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
module Web.Lyeit.Config ( runConfigM , readConfig , config ) where import Control.Monad.Reader (asks, runReaderT) import Data.Aeson (decode) import qualified Data.ByteString.Lazy as BSL import Data.Maybe (fromMaybe) import Prelude hiding (FilePath) import System.Directory (getHomeDirectory) import qualified System.FilePath as FP import Web.Scotty (ActionM) import Web.Lyeit.Type runConfigM :: Config -> ConfigM a -> ActionM a runConfigM = flip runReaderT config :: (Config -> a) -> ConfigM a config = asks readConfig :: FullPath -> IO Config readConfig (FullPath full) = do contents <- BSL.readFile full let c = fromMaybe (error "failed to decode config file of JSON") $ decode contents (FullPath dfull) <- tildaToHome $ document_root_full c (FullPath tfull) <- tildaToHome $ template_path c return $ c { document_root_full = FullPath $ normalise dfull , document_root_show = normalise $ document_root_show c , template_path = FullPath $ normalise tfull } normalise :: String -> String normalise = FP.dropTrailingPathSeparator . FP.normalise tildaToHome :: FullPath -> IO FullPath tildaToHome (FullPath path) = do home <- getHomeDirectory return $ FullPath $ FP.normalise $ replace '~' home path where replace _ _ [] = [] replace from to (s:ss) = if s == from then to ++ replace from to ss else s : replace from to ss
daimatz/Lyeit
src/Web/Lyeit/Config.hs
bsd-3-clause
1,579
0
13
458
456
241
215
38
3
-- | Maximum Flow algorithm -- -- We are given a flow network @G=(V,E)@ with source @s@ and sink @t@ -- where each edge @(u,v)@ in @E@ has a nonnegative capacity -- @c(u,v)>=0@, and we wish to find a flow of maximum value from @s@ -- to @t@. -- -- A flow in @G=(V,E)@ is a real-valued function @f:VxV->R@ that -- satisfies: -- -- @ -- For all u,v in V, f(u,v)\<=c(u,v) -- For all u,v in V, f(u,v)=-f(v,u) -- For all u in V-{s,t}, Sum{f(u,v):v in V } = 0 -- @ -- -- The value of a flow f is defined as @|f|=Sum {f(s,v)|v in V}@, i.e., -- the total net flow out of the source. -- -- In this module we implement the Edmonds-Karp algorithm, which is -- the Ford-Fulkerson method but using the shortest path from @s@ to -- @t@ as the augmenting path along which the flow is incremented. module Data.Graph.Inductive.Query.MaxFlow( getRevEdges, augmentGraph, updAdjList, updateFlow, mfmg, mf, maxFlowgraph, maxFlow ) where import Data.List import Data.Graph.Inductive.Basic import Data.Graph.Inductive.Graph --import Data.Graph.Inductive.Tree import Data.Graph.Inductive.Query.BFS -- | -- @ -- i 0 -- For each edge a--->b this function returns edge b--->a . -- i -- Edges a\<--->b are ignored -- j -- @ getRevEdges :: (Num b) => [Edge] -> [LEdge b] getRevEdges [] = [] getRevEdges ((u,v):es) | notElem (v,u) es = (v,u,0):getRevEdges es | otherwise = getRevEdges (delete (v,u) es) -- | -- @ -- i 0 -- For each edge a--->b insert into graph the edge a\<---b . Then change the -- i (i,0,i) -- label of every edge from a---->b to a------->b -- @ -- -- where label (x,y,z)=(Max Capacity, Current flow, Residual capacity) augmentGraph :: (DynGraph gr, Num b) => gr a b -> gr a (b,b,b) augmentGraph g = emap (\i->(i,0,i)) (insEdges (getRevEdges (edges g)) g) -- | Given a successor or predecessor list for node @u@ and given node @v@, find -- the label corresponding to edge @(u,v)@ and update the flow and -- residual capacity of that edge's label. Then return the updated -- list. updAdjList::(Num b) => Adj (b,b,b) -> Node -> b -> Bool -> Adj (b,b,b) updAdjList s v cf fwd = rs ++ ((x,y+cf',z-cf'),w) : rs' where (rs, ((x,y,z),w):rs') = break ((v==) . snd) s cf' = if fwd then cf else negate cf -- | Update flow and residual capacity along augmenting path from @s@ to @t@ in -- graph @@G. For a path @[u,v,w,...]@ find the node @u@ in @G@ and -- its successor and predecessor list, then update the corresponding -- edges @(u,v)@ and @(v,u)@ on those lists by using the minimum -- residual capacity of the path. updateFlow :: (DynGraph gr, Num b) => Path -> b -> gr a (b,b,b) -> gr a (b,b,b) updateFlow [] _ g = g updateFlow [_] _ g = g updateFlow (u:v:vs) cf g = case match u g of (Nothing,g') -> g' (Just (p,u',l,s),g') -> (p',u',l,s') & g2 where g2 = updateFlow (v:vs) cf g' s' = updAdjList s v cf True p' = updAdjList p v cf False -- | Compute the flow from @s@ to @t@ on a graph whose edges are labeled with -- @(x,y,z)=(max capacity,current flow,residual capacity)@ and all -- edges are of the form @a\<---->b@. First compute the residual -- graph, that is, delete those edges whose residual capacity is -- zero. Then compute the shortest augmenting path from @s@ to @t@, -- and finally update the flow and residual capacity along that path -- by using the minimum capacity of that path. Repeat this process -- until no shortest path from @s@ to @t@ exist. mfmg :: (DynGraph gr, Num b, Ord b) => gr a (b,b,b) -> Node -> Node -> gr a (b,b,b) mfmg g s t | null augPath = g | otherwise = mfmg (updateFlow augPath minC g) s t where minC = minimum (map ((\(_,_,z)->z).snd)(tail augLPath)) augPath = map fst augLPath LP augLPath = lesp s t gf gf = elfilter (\(_,_,z)->z/=0) g -- | Compute the flow from s to t on a graph whose edges are labeled with -- @x@, which is the max capacity and where not all edges need to be -- of the form a\<---->b. Return the flow as a grap whose edges are -- labeled with (x,y,z)=(max capacity,current flow,residual -- capacity) and all edges are of the form a\<---->b mf :: (DynGraph gr, Num b, Ord b) => gr a b -> Node -> Node -> gr a (b,b,b) mf g s t = mfmg (augmentGraph g) s t -- | Compute the maximum flow from s to t on a graph whose edges are labeled -- with x, which is the max capacity and where not all edges need to -- be of the form a\<---->b. Return the flow as a graph whose edges -- are labeled with (y,x) = (current flow, max capacity). maxFlowgraph :: (DynGraph gr, Num b, Ord b) => gr a b -> Node -> Node -> gr a (b,b) maxFlowgraph g s t = emap (\(u,v,_)->(v,u)) . elfilter (\(x,_,_) -> x/=0 ) $ mf g s t -- | Compute the value of a maximumflow maxFlow :: (DynGraph gr, Num b, Ord b) => gr a b -> Node -> Node -> b maxFlow g s t = sum (map (fst . edgeLabel) (out (maxFlowgraph g s t) s)) ------------------------------------------------------------------------------ -- Some test cases: clr595 is from the CLR textbook, page 595. The value of -- the maximum flow for s=1 and t=6 (23) coincides with the example but the -- flow itself is slightly different since the textbook does not compute the -- shortest augmenting path from s to t, but just any path. However remember -- that for a given flow graph the maximum flow is not unique. -- (gr595 is defined in GraphData.hs) ------------------------------------------------------------------------------
scolobb/fgl
Data/Graph/Inductive/Query/MaxFlow.hs
bsd-3-clause
5,867
0
14
1,552
1,258
718
540
44
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.SetupWrapper -- Copyright : (c) The University of Glasgow 2006, -- Duncan Coutts 2008 -- -- Maintainer : [email protected] -- Stability : alpha -- Portability : portable -- -- An interface to building and installing Cabal packages. -- If the @Built-Type@ field is specified as something other than -- 'Custom', and the current version of Cabal is acceptable, this performs -- setup actions directly. Otherwise it builds the setup script and -- runs it with the given arguments. module Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions, ) where import qualified Distribution.Make as Make import qualified Distribution.Simple as Simple import Distribution.Version ( Version(..), VersionRange, anyVersion , intersectVersionRanges, orLaterVersion , withinRange ) import Distribution.InstalledPackageInfo (installedPackageId) import Distribution.Package ( InstalledPackageId(..), PackageIdentifier(..), PackageName(..), Package(..), packageName , packageVersion, Dependency(..) ) import Distribution.PackageDescription ( GenericPackageDescription(packageDescription) , PackageDescription(..), specVersion , BuildType(..), knownBuildTypes ) import Distribution.PackageDescription.Parse ( readPackageDescription ) import Distribution.Simple.Configure ( configCompilerEx ) import Distribution.Compiler ( buildCompilerId ) import Distribution.Simple.Compiler ( CompilerFlavor(GHC), Compiler(compilerId) , PackageDB(..), PackageDBStack ) import Distribution.Simple.PreProcess ( runSimplePreProcessor, ppUnlit ) import Distribution.Simple.Program ( ProgramConfiguration, emptyProgramConfiguration , getProgramSearchPath, getDbProgramOutput, runDbProgram, ghcProgram ) import Distribution.Simple.Program.Find ( programSearchPathAsPATHVar ) import Distribution.Simple.Program.Run ( getEffectiveEnvironment ) import Distribution.Simple.BuildPaths ( defaultDistPref, exeExtension ) import Distribution.Simple.Command ( CommandUI(..), commandShowOptions ) import Distribution.Simple.Program.GHC ( GhcMode(..), GhcOptions(..), renderGhcOptions ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (PackageIndex) import Distribution.Client.Config ( defaultCabalDir ) import Distribution.Client.IndexUtils ( getInstalledPackages ) import Distribution.Client.JobControl ( Lock, criticalSection ) import Distribution.Simple.Setup ( Flag(..) ) import Distribution.Simple.Utils ( die, debug, info, cabalVersion, findPackageDesc, comparing , createDirectoryIfMissingVerbose, installExecutableFile , copyFileVerbose, rewriteFile, intercalate ) import Distribution.Client.Utils ( inDir, tryCanonicalizePath , existsAndIsMoreRecentThan, moreRecentFile ) import Distribution.System ( Platform(..), buildPlatform ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import Distribution.Compat.Exception ( catchIO ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>), (<.>) ) import System.IO ( Handle, hPutStr ) import System.Exit ( ExitCode(..), exitWith ) import System.Process ( runProcess, waitForProcess ) import Control.Applicative ( (<$>), (<*>) ) import Control.Monad ( when, unless ) import Data.List ( foldl1' ) import Data.Maybe ( fromMaybe, isJust ) import Data.Monoid ( mempty ) import Data.Char ( isSpace ) data SetupScriptOptions = SetupScriptOptions { useCabalVersion :: VersionRange, useCompiler :: Maybe Compiler, usePlatform :: Maybe Platform, usePackageDB :: PackageDBStack, usePackageIndex :: Maybe PackageIndex, useProgramConfig :: ProgramConfiguration, useDistPref :: FilePath, useLoggingHandle :: Maybe Handle, useWorkingDir :: Maybe FilePath, forceExternalSetupMethod :: Bool, -- Used only when calling setupWrapper from parallel code to serialise -- access to the setup cache; should be Nothing otherwise. -- -- Note: setup exe cache ------------------------ -- When we are installing in parallel, we always use the external setup -- method. Since compiling the setup script each time adds noticeable -- overhead, we use a shared setup script cache -- ('~/.cabal/setup-exe-cache'). For each (compiler, platform, Cabal -- version) combination the cache holds a compiled setup script -- executable. This only affects the Simple build type; for the Custom, -- Configure and Make build types we always compile the setup script anew. setupCacheLock :: Maybe Lock } defaultSetupScriptOptions :: SetupScriptOptions defaultSetupScriptOptions = SetupScriptOptions { useCabalVersion = anyVersion, useCompiler = Nothing, usePlatform = Nothing, usePackageDB = [GlobalPackageDB, UserPackageDB], usePackageIndex = Nothing, useProgramConfig = emptyProgramConfiguration, useDistPref = defaultDistPref, useLoggingHandle = Nothing, useWorkingDir = Nothing, forceExternalSetupMethod = False, setupCacheLock = Nothing } setupWrapper :: Verbosity -> SetupScriptOptions -> Maybe PackageDescription -> CommandUI flags -> (Version -> flags) -> [String] -> IO () setupWrapper verbosity options mpkg cmd flags extraArgs = do pkg <- maybe getPkg return mpkg let setupMethod = determineSetupMethod options' buildType' options' = options { useCabalVersion = intersectVersionRanges (useCabalVersion options) (orLaterVersion (specVersion pkg)) } buildType' = fromMaybe Custom (buildType pkg) mkArgs cabalLibVersion = commandName cmd : commandShowOptions cmd (flags cabalLibVersion) ++ extraArgs checkBuildType buildType' setupMethod verbosity options' (packageId pkg) buildType' mkArgs where getPkg = findPackageDesc (fromMaybe "." (useWorkingDir options)) >>= readPackageDescription verbosity >>= return . packageDescription checkBuildType (UnknownBuildType name) = die $ "The build-type '" ++ name ++ "' is not known. Use one of: " ++ intercalate ", " (map display knownBuildTypes) ++ "." checkBuildType _ = return () -- | Decide if we're going to be able to do a direct internal call to the -- entry point in the Cabal library or if we're going to have to compile -- and execute an external Setup.hs script. -- determineSetupMethod :: SetupScriptOptions -> BuildType -> SetupMethod determineSetupMethod options buildType' | forceExternalSetupMethod options = externalSetupMethod | isJust (useLoggingHandle options) || buildType' == Custom = externalSetupMethod | cabalVersion `withinRange` useCabalVersion options = internalSetupMethod | otherwise = externalSetupMethod type SetupMethod = Verbosity -> SetupScriptOptions -> PackageIdentifier -> BuildType -> (Version -> [String]) -> IO () -- ------------------------------------------------------------ -- * Internal SetupMethod -- ------------------------------------------------------------ internalSetupMethod :: SetupMethod internalSetupMethod verbosity options _ bt mkargs = do let args = mkargs cabalVersion debug verbosity $ "Using internal setup method with build-type " ++ show bt ++ " and args:\n " ++ show args inDir (useWorkingDir options) $ buildTypeAction bt args buildTypeAction :: BuildType -> ([String] -> IO ()) buildTypeAction Simple = Simple.defaultMainArgs buildTypeAction Configure = Simple.defaultMainWithHooksArgs Simple.autoconfUserHooks buildTypeAction Make = Make.defaultMainArgs buildTypeAction Custom = error "buildTypeAction Custom" buildTypeAction (UnknownBuildType _) = error "buildTypeAction UnknownBuildType" -- ------------------------------------------------------------ -- * External SetupMethod -- ------------------------------------------------------------ externalSetupMethod :: SetupMethod externalSetupMethod verbosity options pkg bt mkargs = do debug verbosity $ "Using external setup method with build-type " ++ show bt createDirectoryIfMissingVerbose verbosity True setupDir (cabalLibVersion, mCabalLibInstalledPkgId, options') <- cabalLibVersionToUse debug verbosity $ "Using Cabal library version " ++ display cabalLibVersion path <- if useCachedSetupExecutable then getCachedSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId else compileSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId False invokeSetupScript options' path (mkargs cabalLibVersion) where workingDir = case fromMaybe "" (useWorkingDir options) of [] -> "." dir -> dir setupDir = workingDir </> useDistPref options </> "setup" setupVersionFile = setupDir </> "setup" <.> "version" setupHs = setupDir </> "setup" <.> "hs" setupProgFile = setupDir </> "setup" <.> exeExtension useCachedSetupExecutable = (bt == Simple || bt == Configure || bt == Make) maybeGetInstalledPackages :: SetupScriptOptions -> Compiler -> ProgramConfiguration -> IO PackageIndex maybeGetInstalledPackages options' comp conf = case usePackageIndex options' of Just index -> return index Nothing -> getInstalledPackages verbosity comp (usePackageDB options') conf cabalLibVersionToUse :: IO (Version, (Maybe InstalledPackageId) ,SetupScriptOptions) cabalLibVersionToUse = do savedVer <- savedVersion case savedVer of Just version | version `withinRange` useCabalVersion options -> do updateSetupScript version bt -- Does the previously compiled setup executable still exist and -- is it up-to date? useExisting <- canUseExistingSetup version if useExisting then return (version, Nothing, options) else installedVersion _ -> installedVersion where -- This check duplicates the checks in 'getCachedSetupExecutable' / -- 'compileSetupExecutable'. Unfortunately, we have to perform it twice -- because the selected Cabal version may change as a result of this -- check. canUseExistingSetup :: Version -> IO Bool canUseExistingSetup version = if useCachedSetupExecutable then do (_, cachedSetupProgFile) <- cachedSetupDirAndProg options version doesFileExist cachedSetupProgFile else (&&) <$> setupProgFile `existsAndIsMoreRecentThan` setupHs <*> setupProgFile `existsAndIsMoreRecentThan` setupVersionFile installedVersion :: IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedVersion = do (comp, conf, options') <- configureCompiler options (version, mipkgid, options'') <- installedCabalVersion options' comp conf updateSetupScript version bt writeFile setupVersionFile (show version ++ "\n") return (version, mipkgid, options'') savedVersion :: IO (Maybe Version) savedVersion = do versionString <- readFile setupVersionFile `catchIO` \_ -> return "" case reads versionString of [(version,s)] | all isSpace s -> return (Just version) _ -> return Nothing -- | Update a Setup.hs script, creating it if necessary. updateSetupScript :: Version -> BuildType -> IO () updateSetupScript _ Custom = do useHs <- doesFileExist customSetupHs useLhs <- doesFileExist customSetupLhs unless (useHs || useLhs) $ die "Using 'build-type: Custom' but there is no Setup.hs or Setup.lhs script." let src = (if useHs then customSetupHs else customSetupLhs) srcNewer <- src `moreRecentFile` setupHs when srcNewer $ if useHs then copyFileVerbose verbosity src setupHs else runSimplePreProcessor ppUnlit src setupHs verbosity where customSetupHs = workingDir </> "Setup.hs" customSetupLhs = workingDir </> "Setup.lhs" updateSetupScript cabalLibVersion _ = rewriteFile setupHs (buildTypeScript cabalLibVersion) buildTypeScript :: Version -> String buildTypeScript cabalLibVersion = case bt of Simple -> "import Distribution.Simple; main = defaultMain\n" Configure -> "import Distribution.Simple; main = defaultMainWithHooks " ++ if cabalLibVersion >= Version [1,3,10] [] then "autoconfUserHooks\n" else "defaultUserHooks\n" Make -> "import Distribution.Make; main = defaultMain\n" Custom -> error "buildTypeScript Custom" UnknownBuildType _ -> error "buildTypeScript UnknownBuildType" installedCabalVersion :: SetupScriptOptions -> Compiler -> ProgramConfiguration -> IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedCabalVersion options' _ _ | packageName pkg == PackageName "Cabal" = return (packageVersion pkg, Nothing, options') installedCabalVersion options' compiler conf = do index <- maybeGetInstalledPackages options' compiler conf let cabalDep = Dependency (PackageName "Cabal") (useCabalVersion options') options'' = options' { usePackageIndex = Just index } case PackageIndex.lookupDependency index cabalDep of [] -> die $ "The package '" ++ display (packageName pkg) ++ "' requires Cabal library version " ++ display (useCabalVersion options) ++ " but no suitable version is installed." pkgs -> let ipkginfo = head . snd . bestVersion fst $ pkgs in return (packageVersion ipkginfo ,Just . installedPackageId $ ipkginfo, options'') bestVersion :: (a -> Version) -> [a] -> a bestVersion f = firstMaximumBy (comparing (preference . f)) where -- Like maximumBy, but picks the first maximum element instead of the -- last. In general, we expect the preferred version to go first in the -- list. For the default case, this has the effect of choosing the version -- installed in the user package DB instead of the global one. See #1463. -- -- Note: firstMaximumBy could be written as just -- `maximumBy cmp . reverse`, but the problem is that the behaviour of -- maximumBy is not fully specified in the case when there is not a single -- greatest element. firstMaximumBy :: (a -> a -> Ordering) -> [a] -> a firstMaximumBy _ [] = error "Distribution.Client.firstMaximumBy: empty list" firstMaximumBy cmp xs = foldl1' maxBy xs where maxBy x y = case cmp x y of { GT -> x; EQ -> x; LT -> y; } preference version = (sameVersion, sameMajorVersion ,stableVersion, latestVersion) where sameVersion = version == cabalVersion sameMajorVersion = majorVersion version == majorVersion cabalVersion majorVersion = take 2 . versionBranch stableVersion = case versionBranch version of (_:x:_) -> even x _ -> False latestVersion = version configureCompiler :: SetupScriptOptions -> IO (Compiler, ProgramConfiguration, SetupScriptOptions) configureCompiler options' = do (comp, conf) <- case useCompiler options' of Just comp -> return (comp, useProgramConfig options') Nothing -> do (comp, _, conf) <- configCompilerEx (Just GHC) Nothing Nothing (useProgramConfig options') verbosity return (comp, conf) -- Whenever we need to call configureCompiler, we also need to access the -- package index, so let's cache it here. index <- maybeGetInstalledPackages options' comp conf return (comp, conf, options' { useCompiler = Just comp, usePackageIndex = Just index, useProgramConfig = conf }) -- | Path to the setup exe cache directory and path to the cached setup -- executable. cachedSetupDirAndProg :: SetupScriptOptions -> Version -> IO (FilePath, FilePath) cachedSetupDirAndProg options' cabalLibVersion = do cabalDir <- defaultCabalDir let setupCacheDir = cabalDir </> "setup-exe-cache" cachedSetupProgFile = setupCacheDir </> ("setup-" ++ buildTypeString ++ "-" ++ cabalVersionString ++ "-" ++ platformString ++ "-" ++ compilerVersionString) <.> exeExtension return (setupCacheDir, cachedSetupProgFile) where buildTypeString = show bt cabalVersionString = "Cabal-" ++ (display cabalLibVersion) compilerVersionString = display $ fromMaybe buildCompilerId (fmap compilerId . useCompiler $ options') platformString = display $ fromMaybe buildPlatform (usePlatform options') -- | Look up the setup executable in the cache; update the cache if the setup -- executable is not found. getCachedSetupExecutable :: SetupScriptOptions -> Version -> Maybe InstalledPackageId -> IO FilePath getCachedSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId = do (setupCacheDir, cachedSetupProgFile) <- cachedSetupDirAndProg options' cabalLibVersion cachedSetupExists <- doesFileExist cachedSetupProgFile if cachedSetupExists then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else criticalSection' $ do -- The cache may have been populated while we were waiting. cachedSetupExists' <- doesFileExist cachedSetupProgFile if cachedSetupExists' then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else do debug verbosity $ "Setup executable not found in the cache." src <- compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId True createDirectoryIfMissingVerbose verbosity True setupCacheDir installExecutableFile verbosity src cachedSetupProgFile return cachedSetupProgFile where criticalSection' = fromMaybe id (fmap criticalSection $ setupCacheLock options') -- | If the Setup.hs is out of date wrt the executable then recompile it. -- Currently this is GHC only. It should really be generalised. -- compileSetupExecutable :: SetupScriptOptions -> Version -> Maybe InstalledPackageId -> Bool -> IO FilePath compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId forceCompile = do setupHsNewer <- setupHs `moreRecentFile` setupProgFile cabalVersionNewer <- setupVersionFile `moreRecentFile` setupProgFile let outOfDate = setupHsNewer || cabalVersionNewer when (outOfDate || forceCompile) $ do debug verbosity "Setup executable needs to be updated, compiling..." (compiler, conf, options'') <- configureCompiler options' let cabalPkgid = PackageIdentifier (PackageName "Cabal") cabalLibVersion let ghcOptions = mempty { ghcOptVerbosity = Flag verbosity , ghcOptMode = Flag GhcModeMake , ghcOptInputFiles = [setupHs] , ghcOptOutputFile = Flag setupProgFile , ghcOptObjDir = Flag setupDir , ghcOptHiDir = Flag setupDir , ghcOptSourcePathClear = Flag True , ghcOptSourcePath = [workingDir] , ghcOptPackageDBs = usePackageDB options'' , ghcOptPackages = maybe [] (\ipkgid -> [(ipkgid, cabalPkgid)]) maybeCabalLibInstalledPkgId } let ghcCmdLine = renderGhcOptions compiler ghcOptions case useLoggingHandle options of Nothing -> runDbProgram verbosity ghcProgram conf ghcCmdLine -- If build logging is enabled, redirect compiler output to the log file. (Just logHandle) -> do output <- getDbProgramOutput verbosity ghcProgram conf ghcCmdLine hPutStr logHandle output return setupProgFile invokeSetupScript :: SetupScriptOptions -> FilePath -> [String] -> IO () invokeSetupScript options' path args = do info verbosity $ unwords (path : args) case useLoggingHandle options' of Nothing -> return () Just logHandle -> info verbosity $ "Redirecting build log to " ++ show logHandle -- Since useWorkingDir can change the relative path, the path argument must -- be turned into an absolute path. On some systems, runProcess will take -- path as relative to the new working directory instead of the current -- working directory. path' <- tryCanonicalizePath path searchpath <- programSearchPathAsPATHVar (getProgramSearchPath (useProgramConfig options')) env <- getEffectiveEnvironment [("PATH", Just searchpath)] process <- runProcess path' args (useWorkingDir options') env Nothing (useLoggingHandle options') (useLoggingHandle options') exitCode <- waitForProcess process unless (exitCode == ExitSuccess) $ exitWith exitCode
fpco/cabal
cabal-install/Distribution/Client/SetupWrapper.hs
bsd-3-clause
23,082
7
22
6,565
4,126
2,208
1,918
380
27
{-# LANGUAGE CPP, DeriveDataTypeable, FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses, NoImplicitPrelude, OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables, TemplateHaskell #-} -- | Extensions to ClassyPrelude that are useful to most modules & plugins in Dash -- This module should NOT import from any Dash modules and anything -- exported here should be used in at least two Dash modules module FreeAgent.AgentPrelude ( module BasicPrelude , Semigroup(..) , forM_, forM , Generic , Path.FilePath , (</>) , P.show , tshow , Time.UTCTime(..) , Time.Day(..) , FilePathS , debug, dbg, err , convert , ExceptT, runExceptT , convEither, convExceptT , tryAny , catchAny , tryAnyConvT , Convertible(..) , def , deriveSerializers , fqName, typeName, proxyFqName , qdebug, qinfo, qwarn, qerror , qdebugNS , logDebug, logInfo, logWarn, logError , Proxy(..) , deriveSafeStore , deriveSafeStoreVersion , deriveSerializersVersion , getCurrentTime , NFData(..), genericRnf , (!??) , zeroDate ) where import BasicPrelude hiding (FilePath, forM, forM_, handle, init, show, (</>), (<>)) import qualified Prelude as P import Control.DeepSeq.Generics (NFData (..), genericRnf) import Control.Error (ExceptT, hoistEither, runExceptT) import Control.Monad.Logger (logDebug, logError, logInfo, logWarn) import Control.Monad.Logger.Quote (qdebug, qdebugNS, qerror, qinfo, qwarn) import Control.Monad.Trans.Control (MonadBaseControl) import Data.Binary as Binary (Binary (..)) import Data.Convertible (Convertible (..), convert) import Data.Convertible.Instances.Text () import Data.Default (def) import Data.Typeable import GHC.Generics (Generic) import Language.Haskell.TH (Dec, Name, Q) import Language.Haskell.TH.Lib (conT) import Data.Aeson (FromJSON (..), ToJSON) import Data.Foldable (forM_) import Data.SafeCopy (Version, base, deriveSafeCopy, extension) import Data.Semigroup (Semigroup (..)) import qualified Data.Text as Text import qualified Data.Time.Calendar as Time import qualified Data.Time.Clock as Time import Data.Traversable (forM) import FileLocation (dbg, debug, err) import Filesystem.Path ((</>)) import qualified Filesystem.Path.CurrentOS as Path import Control.Exception.Enclosed (catchAny, tryAny) #if __GLASGOW_HASKELL__ < 708 data Proxy a = Proxy deriving Typeable #endif type FilePathS = P.FilePath tshow :: (Show a) => a -> Text tshow = Text.pack . P.show typeName :: (Typeable a) => a -> Text typeName typee = Text.pack . P.show $ typeOf typee fqName :: (Typeable a) => a -> Text fqName typee = modName ++ "." ++ typeName typee where modName = Text.pack . tyConModule . typeRepTyCon $ typeOf typee proxyFqName :: (Typeable a) => Proxy a -> Text proxyFqName typee = modName ++ "." ++ name where name = Text.pack . P.show $ subtype subtype = let (_ , [t]) = (splitTyConApp $ typeOf typee) in t modName = Text.pack . tyConModule $ typeRepTyCon subtype convEither :: Convertible e f => Either e a -> Either f a convEither (Right result) = Right result convEither (Left reason) = Left $ convert reason convExceptT :: (Convertible e f, Monad m) => Either e a -> ExceptT f m a convExceptT = hoistEither . convEither -- | Template haskell function to create the Serialize and SafeCopy -- instances for a given type - use this one to specify a later version -- (also will require a migration instance - see SafeCopy docs for more info ) -- -- > data MyDataV1 = MyDataV1 Int -- > data MyData = MyData Int String -- > deriveSafeStore ''MyDataV1 -- > deriveSafeStoreVersion 2 ''MyData deriveSafeStoreVersion :: Version a -> Name -> Q [Dec] deriveSafeStoreVersion ver name = case ver of 1 -> deriveSafeCopy 1 'base name _ -> deriveSafeCopy ver 'extension name -- | Template haskell function to create the Serialize and SafeCopy -- instances for a given type -- -- > data MyData = MyData Int -- > deriveSafeStore ''MyData deriveSafeStore :: Name -> Q [Dec] deriveSafeStore = deriveSafeCopy 1 'base -- | Same as 'deriveSerializers' except that the 'SafeCopy' instance will be -- for an extension of the provided version. This would also require -- a migration from the previous verison. See the SafeCopy documentation -- for more details. deriveSerializersVersion :: Version a -> Name -> Q [Dec] deriveSerializersVersion ver name = do sc <- case ver of 1 -> deriveSafeCopy 1 'base name _ -> deriveSafeCopy ver 'extension name gen <- [d| instance Binary $(conT name) instance FromJSON $(conT name) instance ToJSON $(conT name) instance NFData $(conT name) where rnf = genericRnf |] return $ sc ++ gen -- | TemplateHaskell function to generate required serializers and related -- instances for Actions/Results. -- This includes Cereal, SafeCopy, Binary and NFData. deriveSerializers :: Name -> Q [Dec] deriveSerializers name = -- Originally we called deriveSerializersVersion here but this created -- random linking errors in hdevtools and other tools due (I suspect) -- to stage restriction. A little redundancy is preferable to separate -- modules. do sc <- deriveSafeCopy 1 'base name gen <- [d| instance Binary $(conT name) instance FromJSON $(conT name) instance ToJSON $(conT name) instance NFData $(conT name) where rnf = genericRnf |] return $ sc ++ gen (!??) :: Applicative m => m (Maybe a) -> e -> m (Either e a) (!??) ma e = toeither <$> ma where toeither Nothing = Left e toeither (Just a) = Right a tryAnyConvT :: (MonadBaseControl IO io, Convertible SomeException e) => io a -> ExceptT e io a tryAnyConvT ma = lift (tryAny ma) >>= convExceptT getCurrentTime :: MonadIO io => io Time.UTCTime getCurrentTime = liftIO Time.getCurrentTime zeroDate :: Time.UTCTime zeroDate = convert (0::Int)
jeremyjh/free-agent
core/src/FreeAgent/AgentPrelude.hs
bsd-3-clause
6,773
0
13
1,992
1,403
821
582
125
2
{-# LANGUAGE ExistentialQuantification, Rank2Types, PatternGuards #-} module Util where import Control.Arrow import Control.Monad import Control.Monad.Trans.State import Control.Exception import Data.Char import Data.Function import Data.List import Data.Ord import System.Directory import System.Exit import System.FilePath import System.IO import System.IO.Unsafe import Unsafe.Coerce import Data.Data import Data.Generics.Uniplate.Operations import Language.Haskell.Exts.Extension import GHC.IO.Handle(hDuplicate,hDuplicateTo) --------------------------------------------------------------------- -- SYSTEM.DIRECTORY getDirectoryContentsRecursive :: FilePath -> IO [FilePath] getDirectoryContentsRecursive dir = do xs <- getDirectoryContents dir (dirs,files) <- partitionM doesDirectoryExist [dir </> x | x <- xs, not $ isBadDir x] rest <- concatMapM getDirectoryContentsRecursive $ sort dirs return $ sort files ++ rest where isBadDir x = "." `isPrefixOf` x || "_" `isPrefixOf` x --------------------------------------------------------------------- -- CONTROL.MONAD partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a]) partitionM f [] = return ([], []) partitionM f (x:xs) = do res <- f x (as,bs) <- partitionM f xs return ([x | res]++as, [x | not res]++bs) concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b] concatMapM f = liftM concat . mapM f concatM :: Monad m => [m [a]] -> m [a] concatM = liftM concat . sequence concatZipWithM :: Monad m => (a -> b -> m [c]) -> [a] -> [b] -> m [c] concatZipWithM f xs ys = liftM concat $ zipWithM f xs ys listM' :: Monad m => [a] -> m [a] listM' x = length x `seq` return x --------------------------------------------------------------------- -- PRELUDE notNull = not . null headDef :: a -> [a] -> a headDef x [] = x headDef x (y:ys) = y isLeft_ Left{} = True; isLeft_ _ = False isRight_ = not . isLeft_ unzipEither :: [Either a b] -> ([a], [b]) unzipEither (x:xs) = case x of Left y -> (y:a,b) Right y -> (a,y:b) where (a,b) = unzipEither xs unzipEither [] = ([], []) for = flip map --------------------------------------------------------------------- -- DATA.STRING limit :: Int -> String -> String limit n s = if null post then s else pre ++ "..." where (pre,post) = splitAt n s ltrim :: String -> String ltrim = dropWhile isSpace rtrim :: String -> String rtrim = reverse . ltrim . reverse trimBy :: (a -> Bool) -> [a] -> [a] trimBy f = reverse . dropWhile f . reverse . dropWhile f --------------------------------------------------------------------- -- DATA.LIST groupSortFst :: Ord a => [(a,b)] -> [(a,[b])] groupSortFst = map (fst . head &&& map snd) . groupBy ((==) `on` fst) . sortBy (comparing fst) disjoint :: Eq a => [a] -> [a] -> Bool disjoint xs = null . intersect xs unsnoc :: [a] -> ([a],a) unsnoc [] = error "Unsnoc on empty list" unsnoc xs = (init xs, last xs) revTake :: Int -> [a] -> [a] revTake i = reverse . take i . reverse concatUnzip :: [([a], [b])] -> ([a], [b]) concatUnzip = (concat *** concat) . unzip --------------------------------------------------------------------- -- DATA.TUPLE swap :: (a,b) -> (b,a) swap (a,b) = (b,a) fst3 :: (a,b,c) -> a fst3 (a,b,c) = a snd3 :: (a,b,c) -> b snd3 (a,b,c) = b thd3 :: (a,b,c) -> c thd3 (a,b,c) = c concat3 :: [([a],[b],[c])] -> ([a],[b],[c]) concat3 xs = (concat a, concat b, concat c) where (a,b,c) = unzip3 xs concat2 :: [([a],[b])] -> ([a],[b]) concat2 xs = (concat a, concat b) where (a,b) = unzip xs --------------------------------------------------------------------- -- SYSTEM.IO -- | An 'Encoding' represents how characters are stored in a file. Created with -- 'defaultEncoding' or 'readEncoding' and used with 'useEncoding'. data Encoding = Encoding_Internal (Maybe (Handle -> IO ())) -- | The system default encoding. defaultEncoding :: Encoding defaultEncoding = Encoding_Internal Nothing -- | Apply an encoding to a 'Handle'. useEncoding :: Handle -> Encoding -> IO () useEncoding h (Encoding_Internal x) = maybe (return ()) ($ h) x readFileEncoding :: Encoding -> FilePath -> IO String readFileEncoding enc file = do h <- if file == "-" then return stdin else openFile file ReadMode useEncoding h enc hGetContents h -- | Create an encoding from a string, or throw an error if the encoding is not known. -- Accepts many encodings including @locale@, @utf-8@ and all those supported by the -- GHC @mkTextEncoding@ function. readEncoding :: String -> IO Encoding -- GHC's mkTextEncoding function is fairly poor - it doesn't support lots of fun things, -- so we fake them up, and then try mkTextEncoding last readEncoding "" = return defaultEncoding readEncoding enc | Just e <- lookup (f enc) [(f a, b) | (as,b) <- encs, a <- as] = return $ wrap e | otherwise = do res <- try $ mkTextEncoding enc :: IO (Either SomeException TextEncoding) case res of Right e -> return $ wrap e Left _ -> do let (a,b) = splitAt 2 $ map (head . fst) encs putStr $ unlines ["Error: Unknown text encoding argument, " ++ enc ,"Possible values:" ," " ++ unwords a ," " ++ unwords b ," and anything accepted by System.IO.mkTextEncoding"] exitWith $ ExitFailure 1 where f = map toLower . filter (`notElem` "-_ ") wrap = Encoding_Internal . Just . flip hSetEncoding encs = let a*b = (words a, b) in ["ISO8859-1 8859-1 ISO8859 8859 LATIN LATIN1" * latin1 ,"LOCALE" * localeEncoding ,"UTF-8" * utf8 ,"UTF-8BOM" * utf8_bom ,"UTF-16" * utf16 ,"UTF-16LE" * utf16le ,"UTF-16BE" * utf16be ,"UTF-32" * utf16 ,"UTF-32LE" * utf16le ,"UTF-32BE" * utf16be] exitMessage :: String -> a exitMessage msg = unsafePerformIO $ do putStrLn msg exitWith $ ExitFailure 1 -- FIXME: This could use a lot more bracket calls! captureOutput :: IO () -> IO String captureOutput act = do tmp <- getTemporaryDirectory (f,h) <- openTempFile tmp "hlint" sto <- hDuplicate stdout ste <- hDuplicate stderr hDuplicateTo h stdout hDuplicateTo h stderr hClose h act hDuplicateTo sto stdout hDuplicateTo ste stderr res <- readFile' f removeFile f return res -- FIXME: Should use strict ByteString readFile' :: FilePath -> IO String readFile' x = listM' =<< readFile x --------------------------------------------------------------------- -- DATA.GENERICS data Box = forall a . Data a => Box a gzip :: Data a => (forall b . Data b => b -> b -> c) -> a -> a -> Maybe [c] gzip f x y | toConstr x /= toConstr y = Nothing | otherwise = Just $ zipWith op (gmapQ Box x) (gmapQ Box y) where op (Box x) (Box y) = f x (unsafeCoerce y) --------------------------------------------------------------------- -- DATA.GENERICS.UNIPLATE.OPERATIONS descendIndex :: Uniplate a => (Int -> a -> a) -> a -> a descendIndex f x = flip evalState 0 $ flip descendM x $ \y -> do i <- get modify (+1) return $ f i y universeParent :: Uniplate a => a -> [(Maybe a, a)] universeParent x = (Nothing,x) : f x where f :: Uniplate a => a -> [(Maybe a, a)] f x = concat [(Just x, y) : f y | y <- children x] universeParentBi :: Biplate a b => a -> [(Maybe b, b)] universeParentBi = concatMap universeParent . childrenBi --------------------------------------------------------------------- -- LANGUAGE.HASKELL.EXTS.EXTENSION defaultExtensions :: [Extension] defaultExtensions = [e | e@EnableExtension{} <- knownExtensions] \\ map EnableExtension badExtensions badExtensions = [Arrows -- steals proc ,TransformListComp -- steals the group keyword ,XmlSyntax, RegularPatterns -- steals a-b ,UnboxedTuples -- breaks (#) lens operator ,QuasiQuotes -- breaks [x| ...], making whitespace free list comps break ]
bergmark/hlint
src/Util.hs
bsd-3-clause
8,198
0
19
1,950
2,855
1,510
1,345
-1
-1
---------------------------------------------------------------------------- -- | -- Module : Data.Filesystem -- Copyright : (c) Sergey Vinokurov 2018 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] ---------------------------------------------------------------------------- {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef mingw32_HOST_OS #define WINDOWS 1 #endif module Data.Filesystem ( findRecurCollect , findRecursive ) where import Control.Concurrent.Async.Lifted import Control.Concurrent.STM import Control.Concurrent.STM.TMQueue import Control.Monad.Base import Control.Monad.Catch import Control.Monad.Trans.Control import Data.Foldable.Ext import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.NBSem import Data.Path import Data.Semigroup as Semigroup import Data.Set (Set) import qualified Data.Set as S import qualified Data.Streaming.Filesystem as Streaming import qualified Data.Text as T import GHC.Conc (getNumCapabilities) import GHC.Stack.Ext (WithCallStack) import qualified System.FilePath as FilePath #ifdef WINDOWS #else import qualified Control.Exception as Exception import System.Posix.Files as Posix #endif import Data.Path.Internal import Data.CompiledRegex {-# INLINABLE findRecursive #-} findRecursive :: forall a m. (WithCallStack, MonadBaseControl IO m, MonadMask m) => Int -- ^ Extra search threads to run in parallel -> (FullPath 'Dir -> Bool) -- ^ Whether to visit directory. Unvisited directories will not be collected -> (FullPath 'File -> m (Maybe a)) -- ^ What to do with a file -> (FullPath 'Dir -> m (Maybe a)) -- ^ What to do with a directory -> (a -> m ()) -- ^ Consume output -> Set (FullPath 'Dir) -- ^ Dirs to search non-recursively -> Set (FullPath 'Dir) -- ^ Dirs to search recursively -> m () findRecursive extraJobs dirVisitPred filePred dirPred consume shallowDirs recursiveDirs = do sem <- newNBSem extraJobs findRecursive' sem where findRecursive' :: NBSem -> m () findRecursive' sem = foldr (goDirRec (const False)) (foldr (goDirRec dirVisitPred) (pure ()) recursiveDirs) shallowDirs where goDirRec :: (FullPath 'Dir -> Bool) -> FullPath 'Dir -> m () -> m () goDirRec dirPred' = goDirAsyncOrSync . (T.unpack . unFullPath) where goDirAsyncOrSync :: FilePath -> m () -> m () goDirAsyncOrSync root next = do acquired <- tryAcquireNBSem sem if acquired then withAsync (goDir root `finally` releaseNBSem sem) $ \yAsync -> next *> wait yAsync else goDir root *> next goDir :: FilePath -> m () goDir root = bracket (liftBase (Streaming.openDirStream root)) (liftBase . Streaming.closeDirStream) goDirStream where goDirStream :: Streaming.DirStream -> m () goDirStream stream = go where go :: m () go = do x <- liftBase $ Streaming.readDirStream stream for_ x $ \y -> do let y' :: FilePath y' = root FilePath.</> y let doFile = (filePred y'' >>= traverse_ consume) *> go where y'' :: FullPath 'File y'' = FullPath $ T.pack y' doDir = if dirPred' y'' then (dirPred y'' >>= traverse_ consume) *> goDirAsyncOrSync y' go else go where y'' :: FullPath 'Dir y'' = FullPath $ T.pack y' #ifdef WINDOWS ft <- liftBase $ Streaming.getFileType y' case ft of Streaming.FTOther -> go Streaming.FTFile -> doFile Streaming.FTFileSym -> doFile Streaming.FTDirectory -> doDir Streaming.FTDirectorySym -> doDir #else status <- liftBase $ Posix.getSymbolicLinkStatus y' if | Posix.isRegularFile status -> doFile | Posix.isDirectory status -> doDir | Posix.isSymbolicLink status -> do status' <- liftBase $ Exception.try $ Posix.getFileStatus y' case status' of Left (_ :: Exception.IOException) -> go Right status'' | Posix.isRegularFile status'' -> doFile | Posix.isDirectory status'' -> doDir | otherwise -> go | otherwise -> go #endif class IncrementalContainer big small | big -> small where incrementalAdd :: small -> big -> big instance Ord a => IncrementalContainer (Set a) a where {-# INLINE incrementalAdd #-} incrementalAdd = S.insert instance (Ord k, Semigroup v) => IncrementalContainer (Map k v) (k, v) where {-# INLINE incrementalAdd #-} incrementalAdd = uncurry (M.insertWith (Semigroup.<>)) {-# INLINABLE findRecurCollect #-} findRecurCollect :: forall big small m. (WithCallStack, MonadBaseControl IO m, MonadMask m, IncrementalContainer big small) => Set (BaseName 'Dir) -> CompiledRegex -> Set (FullPath 'Dir) -- Shallow paths -> Set (FullPath 'Dir) -- Recursive paths -> big -- ^ Initial value -> (FullPath 'File -> m (Maybe small)) -> (FullPath 'Dir -> m (Maybe small)) -> m big findRecurCollect ignoredDirs ignoredGlobsRE shallowPaths recursivePaths initialValue consumeFile consumeDir = do n <- liftBase getNumCapabilities results <- liftBase newTMQueueIO let collect :: small -> m () collect = liftBase . atomically . writeTMQueue results shouldVisit :: FullPath 'Dir -> Bool shouldVisit path = takeFileName path `S.notMember` ignoredDirs && not (reMatches ignoredGlobsRE (unFullPath path)) consume :: big -> IO big consume !xs = do res <- atomically $ readTMQueue results case res of Nothing -> pure xs Just res' -> consume $ incrementalAdd res' xs consumeFile' :: FullPath 'File -> m (Maybe small) consumeFile' path | reMatches ignoredGlobsRE (unFullPath path) = pure Nothing | otherwise = consumeFile path -- Reserve 1 capability for synchronous processing extraJobs = n - 1 doFind = findRecursive extraJobs shouldVisit consumeFile' consumeDir collect shallowPaths recursivePaths withAsync (doFind `finally` liftBase (atomically (closeTMQueue results))) $ \searchAsync -> liftBase (consume initialValue) <* (wait searchAsync :: m ())
sergv/tags-server
src/Data/Filesystem.hs
bsd-3-clause
7,703
10
37
2,739
1,543
809
734
-1
-1
{- | Definitions of the PlotWithGnuplot class. -} {-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances, ExistentialQuantification #-} {-# LANGUAGE TypeOperators, FlexibleContexts, GADTs, ScopedTypeVariables, DeriveDataTypeable #-} module Graphics.Gnewplot.Types where import Control.Monad import Data.List semiColonConcat = concat . intersperse "; " quote :: String -> String quote = show type GnuplotCmd = [PlotLine] data PlotLine = PL {plotData :: String, plotTitle :: String, plotWith :: String, cleanUp :: IO () } | SPL {plotData :: String, plotTitle :: String, plotWith :: String, cleanUp :: IO () } | TopLevelGnuplotCmd String String instance Show PlotLine where show (PL d t w _ ) = "PL "++show d++" "++show t ++" "++show w show (TopLevelGnuplotCmd a b) = "TopLevelGnuplotCmd "++ show a ++ " "++show b plOnly pls = [pl | pl@(PL _ _ _ _) <- pls] splOnly pls = [pl | pl@(SPL _ _ _ _) <- pls] tlOnlyUnset pls = [s2 | pl@(TopLevelGnuplotCmd s1 s2) <- pls] tlOnly pls = [s1 | pl@(TopLevelGnuplotCmd s1 s2) <- pls] hasPl pls = not $ null $ plOnly pls hasSpl pls = not $ null $ splOnly pls cleanupCmds :: [GnuplotCmd] -> IO () cleanupCmds cmds = forM_ cmds $ \plines -> sequence_ $ map cleanUp $ plOnly plines ++ splOnly plines setWith :: String -> GnuplotCmd -> GnuplotCmd setWith sty = map f where f pl@(PL _ _ _ _) = pl {plotWith = sty } f tlcmd = tlcmd addData :: String -> GnuplotCmd -> GnuplotCmd addData s = map f where f pl@(PL _ _ _ _) = pl {plotData = plotData pl++s } f tlcmd = tlcmd showPlotCmd :: GnuplotCmd -> String showPlotCmd [] = "" showPlotCmd [TopLevelGnuplotCmd s s2] = s ++ "\n"++ s2 showPlotCmd plines | hasPl plines = tls++"\nplot "++(intercalate ", " $ map p $ plOnly $ plines)++"\n"++untls | hasSpl plines = tls++"\nsplot "++(intercalate ", " $ map s $ splOnly $ plines)++"\n"++untls where s (SPL dat tit wth _) = dat++title tit++withStr wth p (PL dat tit wth _) = dat++title tit++withStr wth tls = unlines $ tlOnly plines untls = unlines $ tlOnlyUnset plines title "" = " notitle" title tit = " title '"++tit++"'" withStr "" = "" withStr s = " with "++s showMultiPlot :: [(Rectangle, GnuplotCmd)] -> String showMultiPlot rpls = "set multiplot\n" ++ concatMap pl rpls ++"\nunset multiplot\n" where pl (r@(Rect (x0,y0) (x1,y1)), plines)=concat ["#"++show r++"\n", "set origin ", show x0, ",", show y0, "\n", "set size ", show (x1-x0), ",", show (y1-y0), "\n", showPlotCmd plines] -- | coordinates for a rectangle data Rectangle = Rect (Double, Double) (Double,Double) deriving Show unitRect = Rect (0,0) (1,1) rectTopLeft (Rect (x1,y1) (x2,y2)) = (x1+0.035,y2-0.010) -- | the main class - implement either getGnuplotCmd or muliplot class PlotWithGnuplot a where getGnuplotCmd :: a -> IO GnuplotCmd getGnuplotCmd a = (snd . head) `fmap` multiPlot unitRect a multiPlot :: Rectangle -> a -> IO [(Rectangle, GnuplotCmd)] multiPlot r a = (\x->[(r, x)]) `fmap` getGnuplotCmd a instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (Either a b) where multiPlot r (Left xs) = multiPlot r xs multiPlot r (Right xs) = multiPlot r xs -- | An existential box for anythign plottable data GnuplotBox = forall a. PlotWithGnuplot a => GnuplotBox a instance PlotWithGnuplot GnuplotBox where multiPlot r (GnuplotBox x) = multiPlot r x instance PlotWithGnuplot [GnuplotBox] where getGnuplotCmd xs = concat `fmap` mapM getGnuplotCmd xs -- | the empty (blank) plot data Noplot = Noplot instance PlotWithGnuplot Noplot where getGnuplotCmd _ = return [PL "x" "" "lines lc rgb \"white\"" (return () ), TopLevelGnuplotCmd "unset border; unset tics" "set border; set tics"] -- | Gnuplot's test plot data GnuplotTest = GnuplotTest instance PlotWithGnuplot (GnuplotTest) where multiPlot r _ = do return $ [(r, [TopLevelGnuplotCmd "test" ""])]
glutamate/gnewplot
Graphics/Gnewplot/Types.hs
bsd-3-clause
4,489
0
13
1,348
1,489
783
706
83
3
module HSlippyMap ( Tile (..), Lat, Long, X, Y, ZLevel, tilesFromBBox, tileFromLatLong, tileFromXY ) where type Lat = Float type Long = Float type X = Integer type Y = Integer type ZLevel = Integer data Tile = Tile { tlat :: Lat, tlong :: Long, tx :: X, ty :: Y, tz :: ZLevel } instance Show Tile where show (Tile lat long x y z) = "http://tile.openstreetmap.org/" ++ show z ++ "/" ++ show x ++ "/" ++ show y ++ ".png" -- if not same z-level == Nothing tilesFromBBox :: Tile -> Tile -> Maybe [Tile] tilesFromBBox min max | (tz min) == (tz max) = Just $ concat $ map (\(x,y) -> map (\y'-> Tile (tlat min) (tlong min) x y' z) y) [(x,[(minimum [tymin, tymax])..(maximum [tymin,tymax])]) | x <- [(minimum [txmin, txmax])..(maximum [txmin, txmax])]] | otherwise = Nothing where txmax = tx max txmin = tx min tymax = ty max tymin = ty min z = tz min tileFromLatLong :: Lat -> Long -> ZLevel -> Tile tileFromLatLong lat lon z = Tile lat lon x y z where x = long2tilex lon z y = lat2tiley lat z tileFromXY :: X -> Y -> ZLevel -> Tile tileFromXY x y z = Tile lat lon x y z where lat = tilex2long x z lon = tiley2lat y z long2tilex lon z = floor((lon + 180) / 360 * (2** fromInteger z::Long)) lat2tiley lat z = floor((1.0 - log( tan(lat * pi/180.0) + 1.0 / cos(lat * pi/180.0)) / pi) / 2.0 * (2 ** fromInteger z::Long)) tilex2long x z = (fromInteger x::Long) / (2.0 ** fromInteger z::Long) * 360.0 - 180 tiley2lat y z = 180.0 / pi * atan(0.5 * (exp n - exp(-n))) where n = pi - 2.0 * pi * (fromInteger y::Long) / (2.0 ** fromInteger z::Long)
j4/HSlippyMap
HSlippyMap.hs
bsd-3-clause
1,688
0
19
465
803
429
374
42
1
{-# LANGUAGE UnliftedFFITypes #-} {-# LANGUAGE BangPatterns #-} module Slogger where import Control.Monad.Logger import qualified Data.IntMap as IM import GHC.Conc.Sync (ThreadId(..), myThreadId) import System.IO.Unsafe (unsafePerformIO) type ThreadInt = Int data ThreadLogInfo = ThreadLogInfo { parentIds :: [Int] , nextId :: Int } data LogId = LogId ThreadInt Int -- Yuck, I know! sloggerMap :: IORef (IM.IntMap (IORef ThreadInfo)) sloggerMap = unsafePerformIO (newIORef IM.empty) {-# NOINLINE sloggerMap #-} getThreadLogInfoRef :: IO (IORef ThreadInfo) getThreadLogInfoRef = do tid <- threadIdToInt <$> myThreadId mp <- readIORef sloggerMap minfo <- IM.lookup tid mp case minfo of Just info -> return info Nothing -> do info <- newIORef (ThreadLogInfo [] 0) atomicModifyIORef sloggerMap $ \mp' -> let (mexisting, mp'') = IM.insertLookupWithKey (\_ _ exising -> existing) tid info mp' in (mp'', fromMaybe info mexisting) pushParentLogId :: IO popParentLogId :: LogId -> IO getFreshLogIds :: IO (LogId, Maybe LogId) getFreshLogIds = do ref <- getThreadLogInfoRef readIORef ref threadIdToInt :: ThreadId -> ThreadInt threadIdToInt !(ThreadId tid) = getThreadId tid -- Copied from GHC.Conc.Sync foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt log :: LogLevel -> -- openForAppending :: FilePath -> IO Handle -- openForAppending fp = do -- h <- openBinaryFile fp AppendMode -- hSetBuffering h (BlockBuffering Nothing) -- return h -- openForReading :: FilePath -> IO Handle -- openForReading fp = do -- h <- openBinaryFile fp ReadMode -- hSetBuffering h (BlockBuffering Nothing) -- return h -- withFileForAppending :: FilePath -> (Handle -> IO a) -> IO a -- withFileForAppending fp f = do -- h <- openForAppending fp -- f h `finally` hClose h -- withFileForReading :: FilePath -> (Handle -> IO a) -> IO a -- withFileForReading fp f = do -- h <- openForReading fp -- f h `finally` hClose h
mgsloan/slogger
deadcode/OldSlogger.hs
bsd-3-clause
2,112
1
21
486
415
230
185
-1
-1
{- (c) Galois, 2006 (c) University of Glasgow, 2007 -} {-# LANGUAGE CPP, NondecreasingIndentation, RecordWildCards #-} module Coverage (addTicksToBinds, hpcInitCode) where #ifdef GHCI import qualified GHCi import GHCi.RemoteTypes import Data.Array import ByteCodeTypes import GHC.Stack.CCS #endif import Type import HsSyn import Module import Outputable import DynFlags import Control.Monad import SrcLoc import ErrUtils import NameSet hiding (FreeVars) import Name import Bag import CostCentre import CoreSyn import Id import VarSet import Data.List import FastString import HscTypes import TyCon import UniqSupply import BasicTypes import MonadUtils import Maybes import CLabel import Util import Data.Time import System.Directory import Trace.Hpc.Mix import Trace.Hpc.Util import Data.Map (Map) import qualified Data.Map as Map {- ************************************************************************ * * * The main function: addTicksToBinds * * ************************************************************************ -} addTicksToBinds :: HscEnv -> Module -> ModLocation -- ... off the current module -> NameSet -- Exported Ids. When we call addTicksToBinds, -- isExportedId doesn't work yet (the desugarer -- hasn't set it), so we have to work from this set. -> [TyCon] -- Type constructor in this module -> LHsBinds Id -> IO (LHsBinds Id, HpcInfo, Maybe ModBreaks) addTicksToBinds hsc_env mod mod_loc exports tyCons binds | let dflags = hsc_dflags hsc_env passes = coveragePasses dflags, not (null passes), Just orig_file <- ml_hs_file mod_loc = do if "boot" `isSuffixOf` orig_file then return (binds, emptyHpcInfo False, Nothing) else do us <- mkSplitUniqSupply 'C' -- for cost centres let orig_file2 = guessSourceFile binds orig_file tickPass tickish (binds,st) = let env = TTE { fileName = mkFastString orig_file2 , declPath = [] , tte_dflags = dflags , exports = exports , inlines = emptyVarSet , inScope = emptyVarSet , blackList = Map.fromList [ (getSrcSpan (tyConName tyCon),()) | tyCon <- tyCons ] , density = mkDensity tickish dflags , this_mod = mod , tickishType = tickish } (binds',_,st') = unTM (addTickLHsBinds binds) env st in (binds', st') initState = TT { tickBoxCount = 0 , mixEntries = [] , uniqSupply = us } (binds1,st) = foldr tickPass (binds, initState) passes let tickCount = tickBoxCount st entries = reverse $ mixEntries st hashNo <- writeMixEntries dflags mod tickCount entries orig_file2 modBreaks <- mkModBreaks hsc_env mod tickCount entries when (dopt Opt_D_dump_ticked dflags) $ log_action dflags dflags NoReason SevDump noSrcSpan defaultDumpStyle (pprLHsBinds binds1) return (binds1, HpcInfo tickCount hashNo, Just modBreaks) | otherwise = return (binds, emptyHpcInfo False, Nothing) guessSourceFile :: LHsBinds Id -> FilePath -> FilePath guessSourceFile binds orig_file = -- Try look for a file generated from a .hsc file to a -- .hs file, by peeking ahead. let top_pos = catMaybes $ foldrBag (\ (L pos _) rest -> srcSpanFileName_maybe pos : rest) [] binds in case top_pos of (file_name:_) | ".hsc" `isSuffixOf` unpackFS file_name -> unpackFS file_name _ -> orig_file mkModBreaks :: HscEnv -> Module -> Int -> [MixEntry_] -> IO ModBreaks #ifndef GHCI mkModBreaks _hsc_env _mod _count _entries = return emptyModBreaks #else mkModBreaks hsc_env mod count entries | HscInterpreted <- hscTarget (hsc_dflags hsc_env) = do breakArray <- GHCi.newBreakArray hsc_env (length entries) ccs <- mkCCSArray hsc_env mod count entries let locsTicks = listArray (0,count-1) [ span | (span,_,_,_) <- entries ] varsTicks = listArray (0,count-1) [ vars | (_,_,vars,_) <- entries ] declsTicks = listArray (0,count-1) [ decls | (_,decls,_,_) <- entries ] return emptyModBreaks { modBreaks_flags = breakArray , modBreaks_locs = locsTicks , modBreaks_vars = varsTicks , modBreaks_decls = declsTicks , modBreaks_ccs = ccs } | otherwise = return emptyModBreaks mkCCSArray :: HscEnv -> Module -> Int -> [MixEntry_] -> IO (Array BreakIndex (RemotePtr GHC.Stack.CCS.CostCentre)) mkCCSArray hsc_env modul count entries = do if interpreterProfiled dflags then do let module_str = moduleNameString (moduleName modul) costcentres <- GHCi.mkCostCentres hsc_env module_str (map mk_one entries) return (listArray (0,count-1) costcentres) else do return (listArray (0,-1) []) where dflags = hsc_dflags hsc_env mk_one (srcspan, decl_path, _, _) = (name, src) where name = concat (intersperse "." decl_path) src = showSDoc dflags (ppr srcspan) #endif writeMixEntries :: DynFlags -> Module -> Int -> [MixEntry_] -> FilePath -> IO Int writeMixEntries dflags mod count entries filename | not (gopt Opt_Hpc dflags) = return 0 | otherwise = do let hpc_dir = hpcDir dflags mod_name = moduleNameString (moduleName mod) hpc_mod_dir | moduleUnitId mod == mainUnitId = hpc_dir | otherwise = hpc_dir ++ "/" ++ unitIdString (moduleUnitId mod) tabStop = 8 -- <tab> counts as a normal char in GHC's -- location ranges. createDirectoryIfMissing True hpc_mod_dir modTime <- getModificationUTCTime filename let entries' = [ (hpcPos, box) | (span,_,_,box) <- entries, hpcPos <- [mkHpcPos span] ] when (length entries' /= count) $ do panic "the number of .mix entries are inconsistent" let hashNo = mixHash filename modTime tabStop entries' mixCreate hpc_mod_dir mod_name $ Mix filename modTime (toHash hashNo) tabStop entries' return hashNo -- ----------------------------------------------------------------------------- -- TickDensity: where to insert ticks data TickDensity = TickForCoverage -- for Hpc | TickForBreakPoints -- for GHCi | TickAllFunctions -- for -prof-auto-all | TickTopFunctions -- for -prof-auto-top | TickExportedFunctions -- for -prof-auto-exported | TickCallSites -- for stack tracing deriving Eq mkDensity :: TickishType -> DynFlags -> TickDensity mkDensity tickish dflags = case tickish of HpcTicks -> TickForCoverage SourceNotes -> TickForCoverage Breakpoints -> TickForBreakPoints ProfNotes -> case profAuto dflags of ProfAutoAll -> TickAllFunctions ProfAutoTop -> TickTopFunctions ProfAutoExports -> TickExportedFunctions ProfAutoCalls -> TickCallSites _other -> panic "mkDensity" -- | Decide whether to add a tick to a binding or not. shouldTickBind :: TickDensity -> Bool -- top level? -> Bool -- exported? -> Bool -- simple pat bind? -> Bool -- INLINE pragma? -> Bool shouldTickBind density top_lev exported _simple_pat inline = case density of TickForBreakPoints -> False -- we never add breakpoints to simple pattern bindings -- (there's always a tick on the rhs anyway). TickAllFunctions -> not inline TickTopFunctions -> top_lev && not inline TickExportedFunctions -> exported && not inline TickForCoverage -> True TickCallSites -> False shouldTickPatBind :: TickDensity -> Bool -> Bool shouldTickPatBind density top_lev = case density of TickForBreakPoints -> False TickAllFunctions -> True TickTopFunctions -> top_lev TickExportedFunctions -> False TickForCoverage -> False TickCallSites -> False -- ----------------------------------------------------------------------------- -- Adding ticks to bindings addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id) addTickLHsBinds = mapBagM addTickLHsBind addTickLHsBind :: LHsBind Id -> TM (LHsBind Id) addTickLHsBind (L pos bind@(AbsBinds { abs_binds = binds, abs_exports = abs_exports })) = do withEnv add_exports $ do withEnv add_inlines $ do binds' <- addTickLHsBinds binds return $ L pos $ bind { abs_binds = binds' } where -- in AbsBinds, the Id on each binding is not the actual top-level -- Id that we are defining, they are related by the abs_exports -- field of AbsBinds. So if we're doing TickExportedFunctions we need -- to add the local Ids to the set of exported Names so that we know to -- tick the right bindings. add_exports env = env{ exports = exports env `extendNameSetList` [ idName mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , idName pid `elemNameSet` (exports env) ] } add_inlines env = env{ inlines = inlines env `extendVarSetList` [ mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , isAnyInlinePragma (idInlinePragma pid) ] } addTickLHsBind (L pos bind@(AbsBindsSig { abs_sig_bind = val_bind , abs_sig_export = poly_id })) | L _ FunBind { fun_id = L _ mono_id } <- val_bind = do withEnv (add_export mono_id) $ do withEnv (add_inlines mono_id) $ do val_bind' <- addTickLHsBind val_bind return $ L pos $ bind { abs_sig_bind = val_bind' } | otherwise = pprPanic "addTickLHsBind" (ppr bind) where -- see AbsBinds comments add_export mono_id env | idName poly_id `elemNameSet` exports env = env { exports = exports env `extendNameSet` idName mono_id } | otherwise = env add_inlines mono_id env | isAnyInlinePragma (idInlinePragma poly_id) = env { inlines = inlines env `extendVarSet` mono_id } | otherwise = env addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do let name = getOccString id decl_path <- getPathEntry density <- getDensity inline_ids <- liftM inlines getEnv let inline = isAnyInlinePragma (idInlinePragma id) || id `elemVarSet` inline_ids -- See Note [inline sccs] tickish <- tickishType `liftM` getEnv if inline && tickish == ProfNotes then return (L pos funBind) else do (fvs, mg@(MG { mg_alts = matches' })) <- getFreeVars $ addPathEntry name $ addTickMatchGroup False (fun_matches funBind) blackListed <- isBlackListed pos exported_names <- liftM exports getEnv -- We don't want to generate code for blacklisted positions -- We don't want redundant ticks on simple pattern bindings -- We don't want to tick non-exported bindings in TickExportedFunctions let simple = isSimplePatBind funBind toplev = null decl_path exported = idName id `elemNameSet` exported_names tick <- if not blackListed && shouldTickBind density toplev exported simple inline then bindTick density name pos fvs else return Nothing let mbCons = maybe Prelude.id (:) return $ L pos $ funBind { fun_matches = mg { mg_alts = matches' } , fun_tick = tick `mbCons` fun_tick funBind } where -- a binding is a simple pattern binding if it is a funbind with -- zero patterns isSimplePatBind :: HsBind a -> Bool isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0 -- TODO: Revisit this addTickLHsBind (L pos (pat@(PatBind { pat_lhs = lhs, pat_rhs = rhs }))) = do let name = "(...)" (fvs, rhs') <- getFreeVars $ addPathEntry name $ addTickGRHSs False False rhs let pat' = pat { pat_rhs = rhs'} -- Should create ticks here? density <- getDensity decl_path <- getPathEntry let top_lev = null decl_path if not (shouldTickPatBind density top_lev) then return (L pos pat') else do -- Allocate the ticks rhs_tick <- bindTick density name pos fvs let patvars = map getOccString (collectPatBinders lhs) patvar_ticks <- mapM (\v -> bindTick density v pos fvs) patvars -- Add to pattern let mbCons = maybe id (:) rhs_ticks = rhs_tick `mbCons` fst (pat_ticks pat') patvar_tickss = zipWith mbCons patvar_ticks (snd (pat_ticks pat') ++ repeat []) return $ L pos $ pat' { pat_ticks = (rhs_ticks, patvar_tickss) } -- Only internal stuff, not from source, uses VarBind, so we ignore it. addTickLHsBind var_bind@(L _ (VarBind {})) = return var_bind addTickLHsBind patsyn_bind@(L _ (PatSynBind {})) = return patsyn_bind bindTick :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) bindTick density name pos fvs = do decl_path <- getPathEntry let toplev = null decl_path count_entries = toplev || density == TickAllFunctions top_only = density /= TickAllFunctions box_label = if toplev then TopLevelBox [name] else LocalBox (decl_path ++ [name]) -- allocATickBox box_label count_entries top_only pos fvs -- Note [inline sccs] -- -- It should be reasonable to add ticks to INLINE functions; however -- currently this tickles a bug later on because the SCCfinal pass -- does not look inside unfoldings to find CostCentres. It would be -- difficult to fix that, because SCCfinal currently works on STG and -- not Core (and since it also generates CostCentres for CAFs, -- changing this would be difficult too). -- -- Another reason not to add ticks to INLINE functions is that this -- sometimes handy for avoiding adding a tick to a particular function -- (see #6131) -- -- So for now we do not add any ticks to INLINE functions at all. -- ----------------------------------------------------------------------------- -- Decorate an LHsExpr with ticks -- selectively add ticks to interesting expressions addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExpr e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | isGoodBreakExpr e0 -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- Add a tick to an expression which is the RHS of an equation or a binding. -- We always consider these to be breakpoints, unless the expression is a 'let' -- (because the body will definitely have a tick somewhere). ToDo: perhaps -- we should treat 'case' and 'if' the same way? addTickLHsExprRHS :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprRHS e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- The inner expression of an evaluation context: -- let binds in [], ( [] ) -- we never tick these if we're doing HPC, but otherwise -- we treat it like an ordinary expression. addTickLHsExprEvalInner :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprEvalInner e = do d <- getDensity case d of TickForCoverage -> addTickLHsExprNever e _otherwise -> addTickLHsExpr e -- | A let body is treated differently from addTickLHsExprEvalInner -- above with TickForBreakPoints, because for breakpoints we always -- want to tick the body, even if it is not a redex. See test -- break012. This gives the user the opportunity to inspect the -- values of the let-bound variables. addTickLHsExprLetBody :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprLetBody e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it _other -> addTickLHsExprEvalInner e where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- version of addTick that does not actually add a tick, -- because the scope of this tick is completely subsumed by -- another. addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprNever (L pos e0) = do e1 <- addTickHsExpr e0 return $ L pos e1 -- general heuristic: expressions which do not denote values are good -- break points isGoodBreakExpr :: HsExpr Id -> Bool isGoodBreakExpr (HsApp {}) = True isGoodBreakExpr (HsAppTypeOut {}) = True isGoodBreakExpr (OpApp {}) = True isGoodBreakExpr _other = False isCallSite :: HsExpr Id -> Bool isCallSite HsApp{} = True isCallSite HsAppTypeOut{} = True isCallSite OpApp{} = True isCallSite _ = False addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprOptAlt oneOfMany (L pos e0) = ifDensity TickForCoverage (allocTickBox (ExpBox oneOfMany) False False pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addBinTickLHsExpr boxLabel (L pos e0) = ifDensity TickForCoverage (allocBinTickBox boxLabel pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) -- ----------------------------------------------------------------------------- -- Decorate the body of an HsExpr with ticks. -- (Whether to put a tick around the whole expression was already decided, -- in the addTickLHsExpr family of functions.) addTickHsExpr :: HsExpr Id -> TM (HsExpr Id) addTickHsExpr e@(HsVar (L _ id)) = do freeVar id; return e addTickHsExpr (HsUnboundVar {}) = panic "addTickHsExpr.HsUnboundVar" addTickHsExpr e@(HsIPVar _) = return e addTickHsExpr e@(HsOverLit _) = return e addTickHsExpr e@(HsOverLabel _) = return e addTickHsExpr e@(HsLit _) = return e addTickHsExpr (HsLam matchgroup) = liftM HsLam (addTickMatchGroup True matchgroup) addTickHsExpr (HsLamCase mgs) = liftM HsLamCase (addTickMatchGroup True mgs) addTickHsExpr (HsApp e1 e2) = liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (HsAppTypeOut e ty) = liftM2 HsAppTypeOut (addTickLHsExprNever e) (return ty) addTickHsExpr (OpApp e1 e2 fix e3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsExprNever e2) (return fix) (addTickLHsExpr e3) addTickHsExpr (NegApp e neg) = liftM2 NegApp (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan neg) addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprEvalInner e) addTickHsExpr (SectionL e1 e2) = liftM2 SectionL (addTickLHsExpr e1) (addTickLHsExprNever e2) addTickHsExpr (SectionR e1 e2) = liftM2 SectionR (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (ExplicitTuple es boxity) = liftM2 ExplicitTuple (mapM addTickTupArg es) (return boxity) addTickHsExpr (HsCase e mgs) = liftM2 HsCase (addTickLHsExpr e) -- not an EvalInner; e might not necessarily -- be evaluated. (addTickMatchGroup False mgs) addTickHsExpr (HsIf cnd e1 e2 e3) = liftM3 (HsIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsExprOptAlt True e2) (addTickLHsExprOptAlt True e3) addTickHsExpr (HsMultiIf ty alts) = do { let isOneOfMany = case alts of [_] -> False; _ -> True ; alts' <- mapM (liftL $ addTickGRHS isOneOfMany False) alts ; return $ HsMultiIf ty alts' } addTickHsExpr (HsLet (L l binds) e) = bindLocals (collectLocalBinders binds) $ liftM2 (HsLet . L l) (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsExprLetBody e) addTickHsExpr (HsDo cxt (L l stmts) srcloc) = do { (stmts', _) <- addTickLStmts' forQual stmts (return ()) ; return (HsDo cxt (L l stmts') srcloc) } where forQual = case cxt of ListComp -> Just $ BinBox QualBinBox _ -> Nothing addTickHsExpr (ExplicitList ty wit es) = liftM3 ExplicitList (return ty) (addTickWit wit) (mapM (addTickLHsExpr) es) where addTickWit Nothing = return Nothing addTickWit (Just fln) = do fln' <- addTickSyntaxExpr hpcSrcSpan fln return (Just fln') addTickHsExpr (ExplicitPArr ty es) = liftM2 ExplicitPArr (return ty) (mapM (addTickLHsExpr) es) addTickHsExpr (HsStatic e) = HsStatic <$> addTickLHsExpr e addTickHsExpr expr@(RecordCon { rcon_flds = rec_binds }) = do { rec_binds' <- addTickHsRecordBinds rec_binds ; return (expr { rcon_flds = rec_binds' }) } addTickHsExpr expr@(RecordUpd { rupd_expr = e, rupd_flds = flds }) = do { e' <- addTickLHsExpr e ; flds' <- mapM addTickHsRecField flds ; return (expr { rupd_expr = e', rupd_flds = flds' }) } addTickHsExpr (ExprWithTySig e ty) = liftM2 ExprWithTySig (addTickLHsExprNever e) -- No need to tick the inner expression -- for expressions with signatures (return ty) addTickHsExpr (ArithSeq ty wit arith_seq) = liftM3 ArithSeq (return ty) (addTickWit wit) (addTickArithSeqInfo arith_seq) where addTickWit Nothing = return Nothing addTickWit (Just fl) = do fl' <- addTickSyntaxExpr hpcSrcSpan fl return (Just fl') -- We might encounter existing ticks (multiple Coverage passes) addTickHsExpr (HsTick t e) = liftM (HsTick t) (addTickLHsExprNever e) addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e) addTickHsExpr (HsTickPragma _ _ _ (L pos e0)) = do e2 <- allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 return $ unLoc e2 addTickHsExpr (PArrSeq ty arith_seq) = liftM2 PArrSeq (return ty) (addTickArithSeqInfo arith_seq) addTickHsExpr (HsSCC src nm e) = liftM3 HsSCC (return src) (return nm) (addTickLHsExpr e) addTickHsExpr (HsCoreAnn src nm e) = liftM3 HsCoreAnn (return src) (return nm) (addTickLHsExpr e) addTickHsExpr e@(HsBracket {}) = return e addTickHsExpr e@(HsTcBracketOut {}) = return e addTickHsExpr e@(HsRnBracketOut {}) = return e addTickHsExpr e@(HsSpliceE {}) = return e addTickHsExpr (HsProc pat cmdtop) = liftM2 HsProc (addTickLPat pat) (liftL (addTickHsCmdTop) cmdtop) addTickHsExpr (HsWrap w e) = liftM2 HsWrap (return w) (addTickHsExpr e) -- Explicitly no tick on inside addTickHsExpr (ExprWithTySigOut e ty) = liftM2 ExprWithTySigOut (addTickLHsExprNever e) -- No need to tick the inner expression (return ty) -- for expressions with signatures -- Others should never happen in expression content. addTickHsExpr e = pprPanic "addTickHsExpr" (ppr e) addTickTupArg :: LHsTupArg Id -> TM (LHsTupArg Id) addTickTupArg (L l (Present e)) = do { e' <- addTickLHsExpr e ; return (L l (Present e')) } addTickTupArg (L l (Missing ty)) = return (L l (Missing ty)) addTickMatchGroup :: Bool{-is lambda-} -> MatchGroup Id (LHsExpr Id) -> TM (MatchGroup Id (LHsExpr Id)) addTickMatchGroup is_lam mg@(MG { mg_alts = L l matches }) = do let isOneOfMany = matchesOneOfMany matches matches' <- mapM (liftL (addTickMatch isOneOfMany is_lam)) matches return $ mg { mg_alts = L l matches' } addTickMatch :: Bool -> Bool -> Match Id (LHsExpr Id) -> TM (Match Id (LHsExpr Id)) addTickMatch isOneOfMany isLambda (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickGRHSs isOneOfMany isLambda gRHSs return $ Match mf pats opSig gRHSs' addTickGRHSs :: Bool -> Bool -> GRHSs Id (LHsExpr Id) -> TM (GRHSs Id (LHsExpr Id)) addTickGRHSs isOneOfMany isLambda (GRHSs guarded (L l local_binds)) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL (addTickGRHS isOneOfMany isLambda)) guarded return $ GRHSs guarded' (L l local_binds') where binders = collectLocalBinders local_binds addTickGRHS :: Bool -> Bool -> GRHS Id (LHsExpr Id) -> TM (GRHS Id (LHsExpr Id)) addTickGRHS isOneOfMany isLambda (GRHS stmts expr) = do (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickGRHSBody isOneOfMany isLambda expr) return $ GRHS stmts' expr' addTickGRHSBody :: Bool -> Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickGRHSBody isOneOfMany isLambda expr@(L pos e0) = do d <- getDensity case d of TickForCoverage -> addTickLHsExprOptAlt isOneOfMany expr TickAllFunctions | isLambda -> addPathEntry "\\" $ allocTickBox (ExpBox False) True{-count-} False{-not top-} pos $ addTickHsExpr e0 _otherwise -> addTickLHsExprRHS expr addTickLStmts :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM [ExprLStmt Id] addTickLStmts isGuard stmts = do (stmts, _) <- addTickLStmts' isGuard stmts (return ()) return stmts addTickLStmts' :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM a -> TM ([ExprLStmt Id], a) addTickLStmts' isGuard lstmts res = bindLocals (collectLStmtsBinders lstmts) $ do { lstmts' <- mapM (liftL (addTickStmt isGuard)) lstmts ; a <- res ; return (lstmts', a) } addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id (LHsExpr Id) -> TM (Stmt Id (LHsExpr Id)) addTickStmt _isGuard (LastStmt e noret ret) = do liftM3 LastStmt (addTickLHsExpr e) (pure noret) (addTickSyntaxExpr hpcSrcSpan ret) addTickStmt _isGuard (BindStmt pat e bind fail ty) = do liftM5 BindStmt (addTickLPat pat) (addTickLHsExprRHS e) (addTickSyntaxExpr hpcSrcSpan bind) (addTickSyntaxExpr hpcSrcSpan fail) (return ty) addTickStmt isGuard (BodyStmt e bind' guard' ty) = do liftM4 BodyStmt (addTick isGuard e) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickStmt _isGuard (LetStmt (L l binds)) = do liftM (LetStmt . L l) (addTickHsLocalBinds binds) addTickStmt isGuard (ParStmt pairs mzipExpr bindExpr ty) = do liftM4 ParStmt (mapM (addTickStmtAndBinders isGuard) pairs) (unLoc <$> addTickLHsExpr (L hpcSrcSpan mzipExpr)) (addTickSyntaxExpr hpcSrcSpan bindExpr) (return ty) addTickStmt isGuard (ApplicativeStmt args mb_join body_ty) = do args' <- mapM (addTickApplicativeArg isGuard) args return (ApplicativeStmt args' mb_join body_ty) addTickStmt isGuard stmt@(TransStmt { trS_stmts = stmts , trS_by = by, trS_using = using , trS_ret = returnExpr, trS_bind = bindExpr , trS_fmap = liftMExpr }) = do t_s <- addTickLStmts isGuard stmts t_y <- fmapMaybeM addTickLHsExprRHS by t_u <- addTickLHsExprRHS using t_f <- addTickSyntaxExpr hpcSrcSpan returnExpr t_b <- addTickSyntaxExpr hpcSrcSpan bindExpr L _ t_m <- addTickLHsExpr (L hpcSrcSpan liftMExpr) return $ stmt { trS_stmts = t_s, trS_by = t_y, trS_using = t_u , trS_ret = t_f, trS_bind = t_b, trS_fmap = t_m } addTickStmt isGuard stmt@(RecStmt {}) = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addTick isGuard e | Just fn <- isGuard = addBinTickLHsExpr fn e | otherwise = addTickLHsExprRHS e addTickApplicativeArg :: Maybe (Bool -> BoxLabel) -> (SyntaxExpr Id, ApplicativeArg Id Id) -> TM (SyntaxExpr Id, ApplicativeArg Id Id) addTickApplicativeArg isGuard (op, arg) = liftM2 (,) (addTickSyntaxExpr hpcSrcSpan op) (addTickArg arg) where addTickArg (ApplicativeArgOne pat expr) = ApplicativeArgOne <$> addTickLPat pat <*> addTickLHsExpr expr addTickArg (ApplicativeArgMany stmts ret pat) = ApplicativeArgMany <$> addTickLStmts isGuard stmts <*> (unLoc <$> addTickLHsExpr (L hpcSrcSpan ret)) <*> addTickLPat pat addTickStmtAndBinders :: Maybe (Bool -> BoxLabel) -> ParStmtBlock Id Id -> TM (ParStmtBlock Id Id) addTickStmtAndBinders isGuard (ParStmtBlock stmts ids returnExpr) = liftM3 ParStmtBlock (addTickLStmts isGuard stmts) (return ids) (addTickSyntaxExpr hpcSrcSpan returnExpr) addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id) addTickHsLocalBinds (HsValBinds binds) = liftM HsValBinds (addTickHsValBinds binds) addTickHsLocalBinds (HsIPBinds binds) = liftM HsIPBinds (addTickHsIPBinds binds) addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds addTickHsValBinds :: HsValBindsLR Id a -> TM (HsValBindsLR Id b) addTickHsValBinds (ValBindsOut binds sigs) = liftM2 ValBindsOut (mapM (\ (rec,binds') -> liftM2 (,) (return rec) (addTickLHsBinds binds')) binds) (return sigs) addTickHsValBinds _ = panic "addTickHsValBinds" addTickHsIPBinds :: HsIPBinds Id -> TM (HsIPBinds Id) addTickHsIPBinds (IPBinds ipbinds dictbinds) = liftM2 IPBinds (mapM (liftL (addTickIPBind)) ipbinds) (return dictbinds) addTickIPBind :: IPBind Id -> TM (IPBind Id) addTickIPBind (IPBind nm e) = liftM2 IPBind (return nm) (addTickLHsExpr e) -- There is no location here, so we might need to use a context location?? addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id) addTickSyntaxExpr pos syn@(SyntaxExpr { syn_expr = x }) = do L _ x' <- addTickLHsExpr (L pos x) return $ syn { syn_expr = x' } -- we do not walk into patterns. addTickLPat :: LPat Id -> TM (LPat Id) addTickLPat pat = return pat addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id) addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) = liftM4 HsCmdTop (addTickLHsCmd cmd) (return tys) (return ty) (return syntaxtable) addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id) addTickLHsCmd (L pos c0) = do c1 <- addTickHsCmd c0 return $ L pos c1 addTickHsCmd :: HsCmd Id -> TM (HsCmd Id) addTickHsCmd (HsCmdLam matchgroup) = liftM HsCmdLam (addTickCmdMatchGroup matchgroup) addTickHsCmd (HsCmdApp c e) = liftM2 HsCmdApp (addTickLHsCmd c) (addTickLHsExpr e) {- addTickHsCmd (OpApp e1 c2 fix c3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsCmd c2) (return fix) (addTickLHsCmd c3) -} addTickHsCmd (HsCmdPar e) = liftM HsCmdPar (addTickLHsCmd e) addTickHsCmd (HsCmdCase e mgs) = liftM2 HsCmdCase (addTickLHsExpr e) (addTickCmdMatchGroup mgs) addTickHsCmd (HsCmdIf cnd e1 c2 c3) = liftM3 (HsCmdIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsCmd c2) (addTickLHsCmd c3) addTickHsCmd (HsCmdLet (L l binds) c) = bindLocals (collectLocalBinders binds) $ liftM2 (HsCmdLet . L l) (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsCmd c) addTickHsCmd (HsCmdDo (L l stmts) srcloc) = do { (stmts', _) <- addTickLCmdStmts' stmts (return ()) ; return (HsCmdDo (L l stmts') srcloc) } addTickHsCmd (HsCmdArrApp e1 e2 ty1 arr_ty lr) = liftM5 HsCmdArrApp (addTickLHsExpr e1) (addTickLHsExpr e2) (return ty1) (return arr_ty) (return lr) addTickHsCmd (HsCmdArrForm e fix cmdtop) = liftM3 HsCmdArrForm (addTickLHsExpr e) (return fix) (mapM (liftL (addTickHsCmdTop)) cmdtop) addTickHsCmd (HsCmdWrap w cmd) = liftM2 HsCmdWrap (return w) (addTickHsCmd cmd) -- Others should never happen in a command context. --addTickHsCmd e = pprPanic "addTickHsCmd" (ppr e) addTickCmdMatchGroup :: MatchGroup Id (LHsCmd Id) -> TM (MatchGroup Id (LHsCmd Id)) addTickCmdMatchGroup mg@(MG { mg_alts = L l matches }) = do matches' <- mapM (liftL addTickCmdMatch) matches return $ mg { mg_alts = L l matches' } addTickCmdMatch :: Match Id (LHsCmd Id) -> TM (Match Id (LHsCmd Id)) addTickCmdMatch (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickCmdGRHSs gRHSs return $ Match mf pats opSig gRHSs' addTickCmdGRHSs :: GRHSs Id (LHsCmd Id) -> TM (GRHSs Id (LHsCmd Id)) addTickCmdGRHSs (GRHSs guarded (L l local_binds)) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL addTickCmdGRHS) guarded return $ GRHSs guarded' (L l local_binds') where binders = collectLocalBinders local_binds addTickCmdGRHS :: GRHS Id (LHsCmd Id) -> TM (GRHS Id (LHsCmd Id)) -- The *guards* are *not* Cmds, although the body is -- C.f. addTickGRHS for the BinBox stuff addTickCmdGRHS (GRHS stmts cmd) = do { (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickLHsCmd cmd) ; return $ GRHS stmts' expr' } addTickLCmdStmts :: [LStmt Id (LHsCmd Id)] -> TM [LStmt Id (LHsCmd Id)] addTickLCmdStmts stmts = do (stmts, _) <- addTickLCmdStmts' stmts (return ()) return stmts addTickLCmdStmts' :: [LStmt Id (LHsCmd Id)] -> TM a -> TM ([LStmt Id (LHsCmd Id)], a) addTickLCmdStmts' lstmts res = bindLocals binders $ do lstmts' <- mapM (liftL addTickCmdStmt) lstmts a <- res return (lstmts', a) where binders = collectLStmtsBinders lstmts addTickCmdStmt :: Stmt Id (LHsCmd Id) -> TM (Stmt Id (LHsCmd Id)) addTickCmdStmt (BindStmt pat c bind fail ty) = do liftM5 BindStmt (addTickLPat pat) (addTickLHsCmd c) (return bind) (return fail) (return ty) addTickCmdStmt (LastStmt c noret ret) = do liftM3 LastStmt (addTickLHsCmd c) (pure noret) (addTickSyntaxExpr hpcSrcSpan ret) addTickCmdStmt (BodyStmt c bind' guard' ty) = do liftM4 BodyStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickCmdStmt (LetStmt (L l binds)) = do liftM (LetStmt . L l) (addTickHsLocalBinds binds) addTickCmdStmt stmt@(RecStmt {}) = do { stmts' <- addTickLCmdStmts (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTickCmdStmt ApplicativeStmt{} = panic "ToDo: addTickCmdStmt ApplicativeLastStmt" -- Others should never happen in a command context. addTickCmdStmt stmt = pprPanic "addTickHsCmd" (ppr stmt) addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id) addTickHsRecordBinds (HsRecFields fields dd) = do { fields' <- mapM addTickHsRecField fields ; return (HsRecFields fields' dd) } addTickHsRecField :: LHsRecField' id (LHsExpr Id) -> TM (LHsRecField' id (LHsExpr Id)) addTickHsRecField (L l (HsRecField id expr pun)) = do { expr' <- addTickLHsExpr expr ; return (L l (HsRecField id expr' pun)) } addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id) addTickArithSeqInfo (From e1) = liftM From (addTickLHsExpr e1) addTickArithSeqInfo (FromThen e1 e2) = liftM2 FromThen (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromTo e1 e2) = liftM2 FromTo (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromThenTo e1 e2 e3) = liftM3 FromThenTo (addTickLHsExpr e1) (addTickLHsExpr e2) (addTickLHsExpr e3) liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a) liftL f (L loc a) = do a' <- f a return $ L loc a' data TickTransState = TT { tickBoxCount:: Int , mixEntries :: [MixEntry_] , uniqSupply :: UniqSupply } data TickTransEnv = TTE { fileName :: FastString , density :: TickDensity , tte_dflags :: DynFlags , exports :: NameSet , inlines :: VarSet , declPath :: [String] , inScope :: VarSet , blackList :: Map SrcSpan () , this_mod :: Module , tickishType :: TickishType } -- deriving Show data TickishType = ProfNotes | HpcTicks | Breakpoints | SourceNotes deriving (Eq) coveragePasses :: DynFlags -> [TickishType] coveragePasses dflags = ifa (hscTarget dflags == HscInterpreted) Breakpoints $ ifa (gopt Opt_Hpc dflags) HpcTicks $ ifa (gopt Opt_SccProfilingOn dflags && profAuto dflags /= NoProfAuto) ProfNotes $ ifa (debugLevel dflags > 0) SourceNotes [] where ifa f x xs | f = x:xs | otherwise = xs -- | Tickishs that only make sense when their source code location -- refers to the current file. This might not always be true due to -- LINE pragmas in the code - which would confuse at least HPC. tickSameFileOnly :: TickishType -> Bool tickSameFileOnly HpcTicks = True tickSameFileOnly _other = False type FreeVars = OccEnv Id noFVs :: FreeVars noFVs = emptyOccEnv -- Note [freevars] -- For breakpoints we want to collect the free variables of an -- expression for pinning on the HsTick. We don't want to collect -- *all* free variables though: in particular there's no point pinning -- on free variables that are will otherwise be in scope at the GHCi -- prompt, which means all top-level bindings. Unfortunately detecting -- top-level bindings isn't easy (collectHsBindsBinders on the top-level -- bindings doesn't do it), so we keep track of a set of "in-scope" -- variables in addition to the free variables, and the former is used -- to filter additions to the latter. This gives us complete control -- over what free variables we track. data TM a = TM { unTM :: TickTransEnv -> TickTransState -> (a,FreeVars,TickTransState) } -- a combination of a state monad (TickTransState) and a writer -- monad (FreeVars). instance Functor TM where fmap = liftM instance Applicative TM where pure a = TM $ \ _env st -> (a,noFVs,st) (<*>) = ap instance Monad TM where (TM m) >>= k = TM $ \ env st -> case m env st of (r1,fv1,st1) -> case unTM (k r1) env st1 of (r2,fv2,st2) -> (r2, fv1 `plusOccEnv` fv2, st2) instance HasDynFlags TM where getDynFlags = TM $ \ env st -> (tte_dflags env, noFVs, st) instance MonadUnique TM where getUniqueSupplyM = TM $ \_ st -> (uniqSupply st, noFVs, st) getUniqueM = TM $ \_ st -> let (u, us') = takeUniqFromSupply (uniqSupply st) in (u, noFVs, st { uniqSupply = us' }) getState :: TM TickTransState getState = TM $ \ _ st -> (st, noFVs, st) setState :: (TickTransState -> TickTransState) -> TM () setState f = TM $ \ _ st -> ((), noFVs, f st) getEnv :: TM TickTransEnv getEnv = TM $ \ env st -> (env, noFVs, st) withEnv :: (TickTransEnv -> TickTransEnv) -> TM a -> TM a withEnv f (TM m) = TM $ \ env st -> case m (f env) st of (a, fvs, st') -> (a, fvs, st') getDensity :: TM TickDensity getDensity = TM $ \env st -> (density env, noFVs, st) ifDensity :: TickDensity -> TM a -> TM a -> TM a ifDensity d th el = do d0 <- getDensity; if d == d0 then th else el getFreeVars :: TM a -> TM (FreeVars, a) getFreeVars (TM m) = TM $ \ env st -> case m env st of (a, fv, st') -> ((fv,a), fv, st') freeVar :: Id -> TM () freeVar id = TM $ \ env st -> if id `elemVarSet` inScope env then ((), unitOccEnv (nameOccName (idName id)) id, st) else ((), noFVs, st) addPathEntry :: String -> TM a -> TM a addPathEntry nm = withEnv (\ env -> env { declPath = declPath env ++ [nm] }) getPathEntry :: TM [String] getPathEntry = declPath `liftM` getEnv getFileName :: TM FastString getFileName = fileName `liftM` getEnv isGoodSrcSpan' :: SrcSpan -> Bool isGoodSrcSpan' pos@(RealSrcSpan _) = srcSpanStart pos /= srcSpanEnd pos isGoodSrcSpan' (UnhelpfulSpan _) = False isGoodTickSrcSpan :: SrcSpan -> TM Bool isGoodTickSrcSpan pos = do file_name <- getFileName tickish <- tickishType `liftM` getEnv let need_same_file = tickSameFileOnly tickish same_file = Just file_name == srcSpanFileName_maybe pos return (isGoodSrcSpan' pos && (not need_same_file || same_file)) ifGoodTickSrcSpan :: SrcSpan -> TM a -> TM a -> TM a ifGoodTickSrcSpan pos then_code else_code = do good <- isGoodTickSrcSpan pos if good then then_code else else_code bindLocals :: [Id] -> TM a -> TM a bindLocals new_ids (TM m) = TM $ \ env st -> case m env{ inScope = inScope env `extendVarSetList` new_ids } st of (r, fv, st') -> (r, fv `delListFromOccEnv` occs, st') where occs = [ nameOccName (idName id) | id <- new_ids ] isBlackListed :: SrcSpan -> TM Bool isBlackListed pos = TM $ \ env st -> case Map.lookup pos (blackList env) of Nothing -> (False,noFVs,st) Just () -> (True,noFVs,st) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocTickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocTickBox boxLabel countEntries topOnly pos m = ifGoodTickSrcSpan pos (do (fvs, e) <- getFreeVars m env <- getEnv tickish <- mkTickish boxLabel countEntries topOnly pos fvs (declPath env) return (L pos (HsTick tickish (L pos e))) ) (do e <- m return (L pos e) ) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocATickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) allocATickBox boxLabel countEntries topOnly pos fvs = ifGoodTickSrcSpan pos (do let mydecl_path = case boxLabel of TopLevelBox x -> x LocalBox xs -> xs _ -> panic "allocATickBox" tickish <- mkTickish boxLabel countEntries topOnly pos fvs mydecl_path return (Just tickish) ) (return Nothing) mkTickish :: BoxLabel -> Bool -> Bool -> SrcSpan -> OccEnv Id -> [String] -> TM (Tickish Id) mkTickish boxLabel countEntries topOnly pos fvs decl_path = do let ids = filter (not . isUnliftedType . idType) $ occEnvElts fvs -- unlifted types cause two problems here: -- * we can't bind them at the GHCi prompt -- (bindLocalsAtBreakpoint already fliters them out), -- * the simplifier might try to substitute a literal for -- the Id, and we can't handle that. me = (pos, decl_path, map (nameOccName.idName) ids, boxLabel) cc_name | topOnly = head decl_path | otherwise = concat (intersperse "." decl_path) dflags <- getDynFlags env <- getEnv case tickishType env of HpcTicks -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me : mixEntries st } return $ HpcTick (this_mod env) c ProfNotes -> do ccUnique <- getUniqueM let cc = mkUserCC (mkFastString cc_name) (this_mod env) pos ccUnique count = countEntries && gopt Opt_ProfCountEntries dflags return $ ProfNote cc count True{-scopes-} Breakpoints -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me:mixEntries st } return $ Breakpoint c ids SourceNotes | RealSrcSpan pos' <- pos -> return $ SourceNote pos' cc_name _otherwise -> panic "mkTickish: bad source span!" allocBinTickBox :: (Bool -> BoxLabel) -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocBinTickBox boxLabel pos m = do env <- getEnv case tickishType env of HpcTicks -> do e <- liftM (L pos) m ifGoodTickSrcSpan pos (mkBinTickBoxHpc boxLabel pos e) (return e) _other -> allocTickBox (ExpBox False) False False pos m mkBinTickBoxHpc :: (Bool -> BoxLabel) -> SrcSpan -> LHsExpr Id -> TM (LHsExpr Id) mkBinTickBoxHpc boxLabel pos e = TM $ \ env st -> let meT = (pos,declPath env, [],boxLabel True) meF = (pos,declPath env, [],boxLabel False) meE = (pos,declPath env, [],ExpBox False) c = tickBoxCount st mes = mixEntries st in ( L pos $ HsTick (HpcTick (this_mod env) c) $ L pos $ HsBinTick (c+1) (c+2) e -- notice that F and T are reversed, -- because we are building the list in -- reverse... , noFVs , st {tickBoxCount=c+3 , mixEntries=meF:meT:meE:mes} ) mkHpcPos :: SrcSpan -> HpcPos mkHpcPos pos@(RealSrcSpan s) | isGoodSrcSpan' pos = toHpcPos (srcSpanStartLine s, srcSpanStartCol s, srcSpanEndLine s, srcSpanEndCol s - 1) -- the end column of a SrcSpan is one -- greater than the last column of the -- span (see SrcLoc), whereas HPC -- expects to the column range to be -- inclusive, hence we subtract one above. mkHpcPos _ = panic "bad source span; expected such spans to be filtered out" hpcSrcSpan :: SrcSpan hpcSrcSpan = mkGeneralSrcSpan (fsLit "Haskell Program Coverage internals") matchesOneOfMany :: [LMatch Id body] -> Bool matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1 where matchCount (L _ (Match _ _pats _ty (GRHSs grhss _binds))) = length grhss type MixEntry_ = (SrcSpan, [String], [OccName], BoxLabel) -- For the hash value, we hash everything: the file name, -- the timestamp of the original source file, the tab stop, -- and the mix entries. We cheat, and hash the show'd string. -- This hash only has to be hashed at Mix creation time, -- and is for sanity checking only. mixHash :: FilePath -> UTCTime -> Int -> [MixEntry] -> Int mixHash file tm tabstop entries = fromIntegral $ hashString (show $ Mix file tm 0 tabstop entries) {- ************************************************************************ * * * initialisation * * ************************************************************************ Each module compiled with -fhpc declares an initialisation function of the form `hpc_init_<module>()`, which is emitted into the _stub.c file and annotated with __attribute__((constructor)) so that it gets executed at startup time. The function's purpose is to call hs_hpc_module to register this module with the RTS, and it looks something like this: static void hpc_init_Main(void) __attribute__((constructor)); static void hpc_init_Main(void) {extern StgWord64 _hpc_tickboxes_Main_hpc[]; hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);} -} hpcInitCode :: Module -> HpcInfo -> SDoc hpcInitCode _ (NoHpcInfo {}) = Outputable.empty hpcInitCode this_mod (HpcInfo tickCount hashNo) = vcat [ text "static void hpc_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hpc_init_" <> ppr this_mod <> text "(void)" , braces (vcat [ text "extern StgWord64 " <> tickboxes <> text "[]" <> semi, text "hs_hpc_module" <> parens (hcat (punctuate comma [ doubleQuotes full_name_str, int tickCount, -- really StgWord32 int hashNo, -- really StgWord32 tickboxes ])) <> semi ]) ] where tickboxes = ppr (mkHpcTicksLabel $ this_mod) module_name = hcat (map (text.charToC) $ bytesFS (moduleNameFS (Module.moduleName this_mod))) package_name = hcat (map (text.charToC) $ bytesFS (unitIdFS (moduleUnitId this_mod))) full_name_str | moduleUnitId this_mod == mainUnitId = module_name | otherwise = package_name <> char '/' <> module_name
tjakway/ghcjvm
compiler/deSugar/Coverage.hs
bsd-3-clause
51,909
0
25
15,476
13,575
6,864
6,711
954
8
module Main where import Graphics.Formats.OFF.Simple import Control.Arrow import Data.Vector ( Vector ) import qualified Data.Vector as V import Test.HUnit ( assertFailure, (@?=) ) import Test.Framework import Test.Framework.Providers.HUnit import System.FilePath import TestData samplePrefix = "samples" fileMatches :: FilePath -> OFF -> Test fileMatches file off = testCase file $ do eoff <- readOFFFile (samplePrefix </> file) case eoff of Left err -> assertFailure (show err) Right off' -> off' @?= off makeOFF :: ([(Double, Double, Double)], [[Int]]) -> OFF makeOFF (vs, fs) = OFF { vertices = V.fromList vs , faces = V.map (flip Face Nothing) $ V.fromList (map V.fromList fs) } makeOFFC :: ( [(Double, Double, Double)] , [([Int], (Double, Double, Double))]) -> OFF makeOFFC (vs, fs) = OFF { vertices = V.fromList vs , faces = V.map (uncurry Face) $ V.fromList (map (first V.fromList . second Just) fs) } tests = [ "cube.off" `fileMatches` makeOFF cubeData , "cube.offc" `fileMatches` makeOFFC cubecData , "dodec.off" `fileMatches` makeOFF dodecData , "mushroom.off" `fileMatches` makeOFFC mushroomData , "tetra.off" `fileMatches` makeOFF tetraData , "tetra.offc" `fileMatches` makeOFFC tetracData ] main :: IO () main = defaultMain tests
acfoltzer/off-simple
tests/Main.hs
bsd-3-clause
1,385
0
14
322
476
268
208
36
2
{-# LANGUAGE FlexibleContexts, RankNTypes #-} module EC2Tests.AddressTests ( runAddressTests ) where import Data.Text (Text) import Test.Hspec import Cloud.AWS.EC2 import Cloud.AWS.EC2.Types import Util import EC2Tests.Util region :: Text region = "ap-northeast-1" runAddressTests :: IO () runAddressTests = hspec $ do describe "describeAddresses" $ do it "doesn't throw any exception" $ do testEC2 region (describeAddresses [] [] []) `miss` anyConnectionException describe "{allocate,release}Address" $ do it "doesn't throw any exception" $ do testEC2' region (do addr <- allocateAddress False releaseAddress (Just $ allocateAddressPublicIp addr) Nothing addr2 <- allocateAddress True releaseAddress Nothing (allocateAddressAllocationId addr2) ) `miss` anyConnectionException describe "[dis]associateAddress" $ do context "with EC2" $ do it "doesn't throw any exception" $ do testEC2' region ( withInstance testRunInstancesRequest $ \Instance{instanceId = inst} -> withAddress False $ \AllocateAddress{allocateAddressPublicIp = ip} -> do waitForInstanceState InstanceStateRunning inst associateAddress $ AssociateAddressRequestEc2 ip inst disassociateAddress $ DisassociateAddressRequestEc2 ip ) `miss` anyConnectionException context "with VPC" $ do it "doesn't throw any exception" $ do testEC2' region ( withSubnet "10.0.0.0/24" $ \Subnet{subnetId = subnet, subnetVpcId = vpc} -> setupNetworkInterface vpc subnet $ \nic -> withAddress True $ \AllocateAddress{allocateAddressAllocationId = Just alloc} -> do (_, Just assoc) <- associateAddress $ AssociateAddressRequestVpc { associateAddressRequestVpcAllocationId = alloc , associateAddressRequestVpcInstanceId = Nothing , associateAddressRequestVpcNetworkInterfaceId = Just nic , associateAddressRequestVpcPrivateIpAddress = Nothing , associateAddressRequestVpcAllowReassociation = Nothing } disassociateAddress $ DisassociateAddressRequestVpc assoc ) `miss` anyConnectionException where setupNetworkInterface vpc subnet f = withNetworkInterface subnet $ \NetworkInterface{networkInterfaceId = nic} -> withInternetGateway $ \InternetGateway{internetGatewayInternetGatewayId = igw} -> withInternetGatewayAttached igw vpc $ f nic
worksap-ate/aws-sdk
test/EC2Tests/AddressTests.hs
bsd-3-clause
3,003
0
32
1,065
567
284
283
54
1
{-# LANGUAGE OverloadedStrings #-} -- | HTTP\/2 server library. -- -- Example: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > module Main (main) where -- > -- > import qualified Control.Exception as E -- > import Data.ByteString.Builder (byteString) -- > import Network.HTTP.Types (ok200) -- > import Network.Run.TCP (runTCPServer) -- network-run -- > -- > import Network.HTTP2.Server -- > -- > main :: IO () -- > main = runTCPServer Nothing "80" $ \s _peer -> runHTTP2Server s -- > where -- > runHTTP2Server s = E.bracket (allocSimpleConfig s 4096) -- > freeSimpleConfig -- > (\config -> run config server) -- > server _req _aux sendResponse = sendResponse response [] -- > where -- > response = responseBuilder ok200 header body -- > header = [("Content-Type", "text/plain")] -- > body = byteString "Hello, world!\n" module Network.HTTP2.Server ( -- * Runner run -- * Runner arguments , Config(..) , allocSimpleConfig , freeSimpleConfig -- * HTTP\/2 server , Server -- * Request , Request -- ** Accessing request , requestMethod , requestPath , requestAuthority , requestScheme , requestHeaders , requestBodySize , getRequestBodyChunk , getRequestTrailers -- * Aux , Aux , auxTimeHandle -- * Response , Response -- ** Creating response , responseNoBody , responseFile , responseStreaming , responseBuilder -- ** Accessing response , responseBodySize -- ** Trailers maker , TrailersMaker , NextTrailersMaker(..) , defaultTrailersMaker , setResponseTrailersMaker -- * Push promise , PushPromise , pushPromise , promiseRequestPath , promiseResponse , promiseWeight , defaultWeight -- * Types , Path , Authority , Scheme , FileSpec(..) , FileOffset , ByteCount -- * RecvN , defaultReadN -- * Position read for files , PositionReadMaker , PositionRead , Sentinel(..) , defaultPositionReadMaker ) where import Data.ByteString.Builder (Builder) import Data.IORef (readIORef) import qualified Network.HTTP.Types as H import Imports import Network.HPACK import Network.HPACK.Token import Network.HTTP2.Arch import Network.HTTP2.Frame.Types import Network.HTTP2.Server.Run (run) import Network.HTTP2.Server.Types ---------------------------------------------------------------- -- | Getting the method from a request. requestMethod :: Request -> Maybe H.Method requestMethod (Request req) = getHeaderValue tokenMethod vt where (_,vt) = inpObjHeaders req -- | Getting the path from a request. requestPath :: Request -> Maybe Path requestPath (Request req) = getHeaderValue tokenPath vt where (_,vt) = inpObjHeaders req -- | Getting the authority from a request. requestAuthority :: Request -> Maybe Authority requestAuthority (Request req) = getHeaderValue tokenAuthority vt where (_,vt) = inpObjHeaders req -- | Getting the scheme from a request. requestScheme :: Request -> Maybe Scheme requestScheme (Request req) = getHeaderValue tokenScheme vt where (_,vt) = inpObjHeaders req -- | Getting the headers from a request. requestHeaders :: Request -> HeaderTable requestHeaders (Request req) = inpObjHeaders req -- | Getting the body size from a request. requestBodySize :: Request -> Maybe Int requestBodySize (Request req) = inpObjBodySize req -- | Reading a chunk of the request body. -- An empty 'ByteString' returned when finished. getRequestBodyChunk :: Request -> IO ByteString getRequestBodyChunk (Request req) = inpObjBody req -- | Reading request trailers. -- This function must be called after 'getRequestBodyChunk' -- returns an empty. getRequestTrailers :: Request -> IO (Maybe HeaderTable) getRequestTrailers (Request req) = readIORef (inpObjTrailers req) ---------------------------------------------------------------- -- | Creating response without body. responseNoBody :: H.Status -> H.ResponseHeaders -> Response responseNoBody st hdr = Response $ OutObj hdr' OutBodyNone defaultTrailersMaker where hdr' = setStatus st hdr -- | Creating response with file. responseFile :: H.Status -> H.ResponseHeaders -> FileSpec -> Response responseFile st hdr fileSpec = Response $ OutObj hdr' (OutBodyFile fileSpec) defaultTrailersMaker where hdr' = setStatus st hdr -- | Creating response with builder. responseBuilder :: H.Status -> H.ResponseHeaders -> Builder -> Response responseBuilder st hdr builder = Response $ OutObj hdr' (OutBodyBuilder builder) defaultTrailersMaker where hdr' = setStatus st hdr -- | Creating response with streaming. responseStreaming :: H.Status -> H.ResponseHeaders -> ((Builder -> IO ()) -> IO () -> IO ()) -> Response responseStreaming st hdr strmbdy = Response $ OutObj hdr' (OutBodyStreaming strmbdy) defaultTrailersMaker where hdr' = setStatus st hdr ---------------------------------------------------------------- -- | Getter for response body size. This value is available for file body. responseBodySize :: Response -> Maybe Int responseBodySize (Response (OutObj _ (OutBodyFile (FileSpec _ _ len)) _)) = Just (fromIntegral len) responseBodySize _ = Nothing -- | Setting 'TrailersMaker' to 'Response'. setResponseTrailersMaker :: Response -> TrailersMaker -> Response setResponseTrailersMaker (Response rsp) tm = Response rsp { outObjTrailers = tm } ---------------------------------------------------------------- -- | Creating push promise. -- The third argument is traditional, not used. pushPromise :: ByteString -> Response -> Weight -> PushPromise pushPromise path rsp w = PushPromise path rsp w
kazu-yamamoto/http2
Network/HTTP2/Server.hs
bsd-3-clause
5,738
0
13
1,135
1,026
583
443
96
1
{-# LANGUAGE TypeFamilies #-} module Data.Hot.Pidgin.Base where import GHC.Exts (IsList, Item, fromList, toList) data PHot2 a = PHot2 !a !a deriving (Eq, Ord, Show) data PHot3 a = PHot3 !a !a !a deriving (Eq, Ord, Show) data PHot5 a = PHot5 !a !a !a !a !a deriving (Eq, Ord, Show) data PHot10 a = PHot10 !a !a !a !a !a !a !a !a !a !a deriving (Eq, Ord, Show) instance Functor PHot5 where fmap f (PHot5 x1 x2 x3 x4 x5) = PHot5 (f x1) (f x2) (f x3) (f x4) (f x5) instance Functor PHot10 where fmap f (PHot10 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) = PHot10 (f x1) (f x2) (f x3) (f x4) (f x5) (f x6) (f x7) (f x8) (f x9) (f x10) instance IsList (PHot2 a) where type Item (PHot2 a) = a fromList (x1: x2: _) = PHot2 x1 x2 fromList _ = error $ "PHot2 fromList" toList (PHot2 x1 x2) = [x1, x2] instance IsList (PHot3 a) where type Item (PHot3 a) = a fromList (x1: x2: x3: _) = PHot3 x1 x2 x3 fromList _ = error $ "PHot3 fromList" toList (PHot3 x1 x2 x3) = [x1, x2, x3] instance IsList (PHot5 a) where type Item (PHot5 a) = a fromList (x1: x2: x3: x4: x5: _) = PHot5 x1 x2 x3 x4 x5 fromList _ = error $ "PHot5 fromList" toList (PHot5 x1 x2 x3 x4 x5) = [x1, x2, x3, x4, x5]
tserduke/hot
lib/classy/Data/Hot/Pidgin/Base.hs
bsd-3-clause
1,221
0
12
311
681
347
334
72
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} module Language.Haskell.Refact.Utils.ExactPrint ( resequenceAnnotations , uniqueSrcSpan , addAnnKeywords , setOffsets , setOffset , setLocatedOffsets , setLocatedDp , extractAnnsEP , replace , replaceAnnKey , mkKey -- , setColRec , getOriginalPos -- * Operations , transferEntryDP ) where import qualified FastString as GHC import qualified GHC as GHC import qualified Data.Generics as SYB --import qualified GHC.SYB.Utils as SYB -- import Language.Haskell.GHC.ExactPrint.Transform hiding import Language.Haskell.GHC.ExactPrint.Types import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Utils.Monad import Language.Haskell.Refact.Utils.Types import Control.Monad.RWS import Data.List import Data.Maybe import qualified Data.Map as Map -- --------------------------------------------------------------------- resequenceAnnotations :: (SYB.Data t) => GHC.Located t -> RefactGhc (GHC.Located t,Anns) resequenceAnnotations t = do t1 <- insertUniqueSrcSpans t let aa = extractAnnsEP t1 bb = uniqueSpansOnly aa logm $ "resequenceAnnotations:annsEP=" ++ (show aa) -- logm $ "resequenceAnnotations:locatedConstr=" ++ (SYB.showConstr locatedConstructor) return (t1,bb) -- --------------------------------------------------------------------- -- | Replace empty source spans with a unique SrcSpan which is used as -- a key. It doesn't matter what it is. insertUniqueSrcSpans :: (SYB.Data t) => GHC.Located t -> RefactGhc (GHC.Located t) insertUniqueSrcSpans t = SYB.everywhereM (SYB.mkM newSrcSpan) t where newSrcSpan :: GHC.SrcSpan -> RefactGhc GHC.SrcSpan newSrcSpan ss = if ss == GHC.noSrcSpan then uniqueSrcSpan else return ss -- --------------------------------------------------------------------- -- | Filter annotations to get ones corresponding to SrcSpans. uniqueSpansOnly :: Anns -> Anns uniqueSpansOnly ans -- = (Map.filterWithKey (\(AnnKey ss _ _) _ -> isUniqueSrcSpan ss) anns,sks) = (\an -> Map.filterWithKey (\(AnnKey ss _) _ -> isUniqueSrcSpan ss) an) ans -- --------------------------------------------------------------------- -- TODO: do we have to match the filename for GHC compare functions? uniqueSrcSpan :: RefactGhc GHC.SrcSpan uniqueSrcSpan = do s <- get col <- gets rsSrcSpanCol put s { rsSrcSpanCol = col + 1 } let pos = GHC.mkSrcLoc (GHC.mkFastString "HaRe") (-1) col return $ GHC.mkSrcSpan pos pos isUniqueSrcSpan :: GHC.SrcSpan -> Bool isUniqueSrcSpan ss = srcSpanStartLine ss == -1 -- --------------------------------------------------------------------- -- |Get the map of (SrcSpan,AnnConName) with empty annotations extractAnnsEP :: forall t. (SYB.Data t) => t -> Anns extractAnnsEP t = Map.fromList as where sts = extractSrcSpanConName t as :: [(AnnKey, Annotation)] as = map (\k -> (k, annNone)) sts {- ++AZ++ Temporarily commenting this output locFold :: forall r b . (SYB.Data b) => (r -> r -> r) -> (forall a . (SYB.Data a) => GHC.Located a -> r) -> r -> b -> r locFold f g v nil = generic v where generic :: b -> r generic t = if SYB.showConstr (SYB.toConstr t) == "L" -- SYB.toConstr t == locatedConstructor then g (GHC.L (ghead "extractAnns" (SYB.gmapQi 0 getSrcSpan t)) (SYB.gmapQi 1 id t)) `f` SYB.gmapQi 1 generic t else foldr f nil (SYB.gmapQ generic t) getSrcSpan :: forall d. SYB.Data d => d -> [GHC.SrcSpan] getSrcSpan = SYB.mkQ [] getSrcSpan' where getSrcSpan' :: GHC.SrcSpan -> [GHC.SrcSpan] getSrcSpan' ss = [ss] -} extractSrcSpanConName :: forall t. (SYB.Data t) => t -> [AnnKey] extractSrcSpanConName = generic where generic :: (SYB.Data a) => a -> [AnnKey] generic t = if SYB.showConstr (SYB.toConstr t) == "L" -- SYB.toConstr t == locatedConstructor then [ AnnKey (ghead "extractAnns" (SYB.gmapQi 0 getSrcSpan t)) (SYB.gmapQi 1 getConName t) ] ++ SYB.gmapQi 1 extractSrcSpanConName t else concat (SYB.gmapQ extractSrcSpanConName t) getSrcSpan :: forall d. SYB.Data d => d -> [GHC.SrcSpan] getSrcSpan = SYB.mkQ [] getSrcSpan' where getSrcSpan' :: GHC.SrcSpan -> [GHC.SrcSpan] getSrcSpan' ss = [ss] getConName :: forall d. SYB.Data d => d -> AnnConName getConName = annGetConstr -- --------------------------------------------------------------------- addAnnKeywords :: Anns -> AnnConName -> [(KeywordId, DeltaPos)] -> Anns addAnnKeywords ans conName ks = (Map.insert (AnnKey ss conName) (annNone {annsDP = ks})) ans where -- First find the first srcspan having the conName -- MP: First in what sense? AnnKey ss _ = ghead "addAnnKeywords" . filter (\(AnnKey _ s) -> s == conName) $ Map.keys anns anns = ans -- --------------------------------------------------------------------- replaceAnnKey :: (SYB.Data old,SYB.Data new) => Anns -> GHC.Located old -> GHC.Located new -> Anns replaceAnnKey ans old new = case Map.lookup (mkAnnKey old) anns of Nothing -> (const anns ) ans Just v -> (const anns') ans where anns1 = Map.delete (mkAnnKey old) anns anns' = Map.insert (mkAnnKey new) v anns1 where anns = ans -- --------------------------------------------------------------------- -- |Update the DeltaPos for the given annotation keys setOffsets :: Anns -> [(AnnKey,Annotation)] -> Anns setOffsets anne kvs = foldl' setOffset anne kvs -- |Update the DeltaPos for the given annotation key/val setOffset :: Anns -> (AnnKey, Annotation) -> Anns setOffset ans (k, Ann dp cs fcs _ so ca) = case Map.lookup k anne of Nothing -> (Map.insert k (Ann dp cs fcs [] so ca)) ans Just (Ann _ _ _ ks so' ca') -> (Map.insert k (Ann dp cs fcs ks so' ca')) ans where anne = ans -- |Update the DeltaPos for the given annotation keys setLocatedOffsets :: (SYB.Data a) => Anns -> [(GHC.Located a,Annotation)] -> Anns setLocatedOffsets anne kvs = foldl' setLocatedDp anne kvs setLocatedDp :: (SYB.Data a) => Anns -> (GHC.Located a, Annotation) -> Anns setLocatedDp aane (loc, annVal) = setOffset aane (mkKey loc,annVal) -- --------------------------------------------------------------------- {- -- |Update the DeltaPos for the given annotation keys setLocatedAnns :: (SYB.Data a) => Anns -> [(GHC.Located a,Annotation)] -> Anns setLocatedAnns anne kvs = foldl' setLocatedAnn anne kvs setLocatedAnn :: (SYB.Data a) => Anns -> (GHC.Located a, Annotation) -> Anns setLocatedAnn aane (loc, annVal) = setAnn aane (mkKey loc,annVal) -- |Update the DeltaPos for the given annotation key/val setAnn :: Anns -> (AnnKey, Annotation) -> Anns setAnn ans (k, Ann dp cs fcs _ so ca) = case Map.lookup k anne of Nothing -> modifyKeywordDeltas (Map.insert k (Ann dp cs fcs [] so ca)) ans Just (Ann _ _ _ ks so ca) -> modifyKeywordDeltas (Map.insert k (Ann dp cs fcs ks so ca)) ans where anne = getKeywordDeltas ans -} -- --------------------------------------------------------------------- -- | Replaces an old expression with a new expression replace :: AnnKey -> AnnKey -> Anns -> Maybe Anns replace old new ans = do let as = ans oldan <- Map.lookup old as newan <- Map.lookup new as let newan' = Ann { annEntryDelta = annEntryDelta oldan -- , annDelta = annDelta oldan -- , annTrueEntryDelta = annTrueEntryDelta oldan , annPriorComments = annPriorComments oldan , annFollowingComments = annFollowingComments oldan , annsDP = moveAnns (annsDP oldan) (annsDP newan) , annSortKey = annSortKey oldan , annCapturedSpan = annCapturedSpan oldan } return ((\anns -> Map.delete old . Map.insert new newan' $ anns) ans) -- --------------------------------------------------------------------- -- |Take the annEntryDelta associated with the first item and associate it with the second. -- Also transfer the AnnSpanEntry value, and any comments occuring before it. transferEntryDP :: (SYB.Data a, SYB.Data b) => Anns -> GHC.Located a -> GHC.Located b -> Anns transferEntryDP ans a b = (const anns') ans where anns = ans maybeAnns = do -- Maybe monad anA <- Map.lookup (mkKey a) anns anB <- Map.lookup (mkKey b) anns let anB' = Ann { annEntryDelta = annEntryDelta anA -- , annDelta = annDelta anA -- , annTrueEntryDelta = annTrueEntryDelta anA , annPriorComments = annPriorComments anA ++ annPriorComments anB , annFollowingComments = annFollowingComments anA ++ annFollowingComments anB , annsDP = annsDP anB , annSortKey = annSortKey anB , annCapturedSpan = annCapturedSpan anB } return (Map.insert (mkKey b) anB' anns) -- return (error $ "transferEntryDP: (mkKey a,mkKey b,anA,anB,anB')" ++ showGhc (mkKey a,mkKey b,anA,anB,anB') ) anns' = fromMaybe (error $ "transferEntryDP: lookup failed (a,b)=" ++ show (mkKey a,mkKey b)) maybeAnns -- --------------------------------------------------------------------- {- adjustAnnOffset :: ColDelta -> Annotation -> Annotation adjustAnnOffset (ColDelta cd) (Ann (DP (ro,co)) (ColDelta ad) kds) = Ann edp cd' kds' where edp = case ro of 0 -> DP (ro,co) _ -> DP (ro,co - cd) cd' = ColDelta (ad - cd) kds' = fmap adjustEntrySpan kds adjustEntrySpan (AnnSpanEntry,dp) = case dp of DP (0,c) -> (AnnSpanEntry,DP (0,c)) DP (r,c) -> (AnnSpanEntry,DP (r, c - cd)) adjustEntrySpan x = x -} -- --------------------------------------------------------------------- -- ++AZ++:TODO: this is a re-implementation of mkAnnKey in ghc-exactprint mkKey :: (SYB.Data a) => GHC.Located a -> AnnKey mkKey (GHC.L l s) = AnnKey l (annGetConstr s) -- | Shift the first output annotation into the correct place moveAnns :: [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] moveAnns [] xs = xs moveAnns ((_, dp): _) ((kw, _):xs) = (kw,dp) : xs moveAnns _ [] = [] {- -- | Delete an annotation deleteAnnotation :: AnnKey -> KeywordId -> Anns -> Anns deleteAnnotation k kw (anns,sks) = (Map.adjust (\(s@Ann{annsDP}) -> s { annsDP = filter (\x -> fst x /= kw) annsDP}) k anns,sks) deleteAnnotations :: [(AnnKey, KeywordId)] -> Anns -> Anns deleteAnnotations vs anne = foldr (uncurry deleteAnnotation) anne vs -} -- ------------------------- {- -- | Recursively change the col offsets setColRec :: (SYB.Data a) => (ColDelta -> ColDelta) -> a -> (Anns -> Anns) setColRec f loc = transform loc where transform :: SYB.Data a => a -> (Anns -> Anns) transform t = if SYB.showConstr (SYB.toConstr t) == "L" -- SYB.toConstr t == locatedConstructor then setCol f (ghead "hereh" $ SYB.gmapQi 0 getSrcSpan t) (SYB.gmapQi 1 getConName t) . SYB.gmapQi 1 transform t else foldr (.) id (SYB.gmapQ transform t) getSrcSpan :: forall d. SYB.Data d => d -> [GHC.SrcSpan] getSrcSpan = SYB.mkQ [] getSrcSpan' where getSrcSpan' :: GHC.SrcSpan -> [GHC.SrcSpan] getSrcSpan' ss = [ss] getConName :: forall d. SYB.Data d => d -> AnnConName getConName = annGetConstr setCol :: (ColDelta -> ColDelta) -> GHC.SrcSpan -> AnnConName -> (Anns -> Anns) setCol f ss cn anns = let key = AnnKey ss cn -- res = \a -> Map.adjust (\s -> s { annDelta = f (annDelta s) }) key a res = \a -> Map.adjust (\s -> s ) key a in res anns -} -- --------------------------------------------------------------------- getOriginalPos :: (SYB.Data a) => Anns -> GHC.Located a -> KeywordId -> (Pos,DeltaPos) getOriginalPos ann la@(GHC.L ss _) kw = let an = gfromJust ("getOriginalPos" ++ showGhc (ss,kw)) $ getAnnotationEP la ann mdp = lookup kw (annsDP an) in case mdp of Nothing -> ((0,0),DP (0,0)) Just dp@(DP (ro,co)) -> ((ro + srcSpanStartLine ss, co + srcSpanStartColumn ss),dp)
mpickering/HaRe
src/Language/Haskell/Refact/Utils/ExactPrint.hs
bsd-3-clause
12,748
0
15
3,155
2,318
1,241
1,077
149
2
{-# LANGUAGE DeriveDataTypeable, NamedFieldPuns #-} module Args where import Paths_activehs import System.Directory (createDirectoryIfMissing) import System.Console.CmdArgs.Implicit import System.FilePath import Data.Version ------------------ data Args = Args { sourcedir :: String , includedir :: [String] , gendir :: String , exercisedir :: String , templatedir :: String , fileservedir :: String , logdir :: String , hoogledb :: (Maybe String) , mainpage :: String , restartpath :: String , port :: Int , lang :: String , static :: Bool , verbose :: Int , verboseinterpreter :: Bool , recompilecmd :: String , magicname :: String , daemon :: Bool } deriving (Show, Data, Typeable) myargs :: Args myargs = Args { sourcedir = "." &= typDir &= help "Directory of lhs files to serve. Default is '.'" , includedir = [] &= typDir &= help "Additional include directory. You can specify more than one. Empty by default." , gendir = "html" &= typDir &= help "Directory to put generated content to serve. Default is 'html'" , exercisedir = "exercise" &= typDir &= help "Directory to put generated exercises to serve. Default is 'exercise'" , templatedir = "" &= typDir &= help "Directory of html template files for pandoc. Default points to the distribution's directory." , fileservedir = "" &= typDir &= help "Files in this directory will be served as they are (for css and javascript files). Default points to the distribution's directory." , logdir = "log" &= typDir &= help "Directory to put log files in. Default is 'log'." , hoogledb = Nothing &= typFile &= help "Hoogle database file" , mainpage = "Index.xml" &= typ "PATH" &= help "Main web page path" , restartpath = "" &= typ "PATH" &= help "Opening this path in browser restarts the ghci server." , lang = "en" &= typ "LANGUAGE" &= help "Default language. It is 'en' by default." , port = 8000 &= typ "PORT" &= help "Port to listen" , static = False &= help "Do not regenerate pages." , verbose = 2 &= help "Verbose activehs output" , verboseinterpreter = False &= help "Verbose interpreter output in the browser" , recompilecmd = "ghc -O" &= typ "COMMAND" &= help "Command to run before page generation. Default is 'ghc -O'." , magicname = "a9xYf" &= typ "VARNAME" &= help "Magic variable name." , daemon = False &= help "Run as a service." } &= summary ("activehs " ++ showVersion version ++ ", (C) 2010-2012 Péter Diviánszky") &= program "activehs" completeArgs :: Args -> IO Args completeArgs args -- | gendir args == "" = completeArgs (args {gendir = root args </> "html"}) -- | exercisedir args == "" = completeArgs (args {exercisedir = root args </> "exercise"}) | templatedir args == "" = do dir <- getDataDir completeArgs (args {templatedir = dir </> "template"}) | fileservedir args == "" = do dir <- getDataDir completeArgs (args {fileservedir = dir </> "copy"}) completeArgs args = return args createDirs :: Args -> IO () createDirs (Args {sourcedir, gendir, exercisedir, logdir}) = mapM_ f [sourcedir, gendir, exercisedir, logdir] where f "" = return () f path = createDirectoryIfMissing True path getArgs :: IO Args getArgs = do args <- cmdArgs myargs >>= completeArgs createDirs args return args
pgj/ActiveHs
Args.hs
bsd-3-clause
3,936
0
12
1,301
769
414
355
69
2
{-# LANGUAGE OverlappingInstances #-} -- TLM: required by client code {-# LANGUAGE TypeOperators #-} {-# OPTIONS -fno-warn-missing-methods #-} {-# OPTIONS -fno-warn-orphans #-} -- | -- Module : Data.Array.Accelerate.Language -- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller -- [2009..2014] Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- We use the dictionary view of overloaded operations (such as arithmetic and -- bit manipulation) to reify such expressions. With non-overloaded -- operations (such as, the logical connectives) and partially overloaded -- operations (such as comparisons), we use the standard operator names with a -- \'*\' attached. We keep the standard alphanumeric names as they can be -- easily qualified. -- module Data.Array.Accelerate.Language ( -- * Array and scalar expressions Acc, Exp, -- re-exporting from 'Smart' -- * Scalar introduction constant, -- re-exporting from 'Smart' -- * Array construction use, unit, replicate, generate, -- * Shape manipulation reshape, -- * Extraction of subarrays slice, -- * Map-like functions map, zipWith, -- * Reductions fold, fold1, foldSeg, fold1Seg, -- * Scan functions scanl, scanl', scanl1, scanr, scanr', scanr1, -- * Permutations permute, backpermute, -- * Stencil operations stencil, stencil2, -- ** Stencil specification Boundary(..), Stencil, -- ** Common stencil types Stencil3, Stencil5, Stencil7, Stencil9, Stencil3x3, Stencil5x3, Stencil3x5, Stencil5x5, Stencil3x3x3, Stencil5x3x3, Stencil3x5x3, Stencil3x3x5, Stencil5x5x3, Stencil5x3x5, Stencil3x5x5, Stencil5x5x5, -- * Foreign functions foreignAcc, foreignAcc2, foreignAcc3, foreignExp, foreignExp2, foreignExp3, -- * Pipelining (>->), -- * Array-level flow-control acond, awhile, -- * Index construction and destruction indexHead, indexTail, toIndex, fromIndex, intersect, -- * Flow-control cond, while, -- * Array operations with a scalar result (!), (!!), shape, size, shapeSize, -- * Methods of H98 classes that we need to redefine as their signatures change (==*), (/=*), (<*), (<=*), (>*), (>=*), bit, setBit, clearBit, complementBit, testBit, shift, shiftL, shiftR, rotate, rotateL, rotateR, truncate, round, floor, ceiling, even, odd, -- * Standard functions that we need to redefine as their signatures change (&&*), (||*), not, -- * Conversions ord, chr, boolToInt, fromIntegral, -- * Constants ignore -- Instances of Bounded, Enum, Eq, Ord, Bits, Num, Real, Floating, -- Fractional, RealFrac, RealFloat ) where -- standard libraries import Prelude ( Bounded, Enum, Num, Real, Integral, Floating, Fractional, RealFloat, RealFrac, Eq, Ord, Bool, Char, String, (.), ($), error ) import Data.Bits ( Bits((.&.), (.|.), xor, complement) ) import qualified Prelude as P import Text.Printf -- friends import Data.Array.Accelerate.Type import Data.Array.Accelerate.Smart import Data.Array.Accelerate.Array.Sugar hiding ((!), ignore, shape, size, toIndex, fromIndex, intersect) import qualified Data.Array.Accelerate.Array.Sugar as Sugar -- Array introduction -- ------------------ -- | Array inlet: makes an array available for processing using the Accelerate -- language. -- -- Depending upon the backend used to execute array computations, this may -- trigger (asynchronous) data transfer. -- use :: Arrays arrays => arrays -> Acc arrays use = Acc . Use -- | Scalar inlet: injects a scalar (or a tuple of scalars) into a singleton -- array for use in the Accelerate language. -- unit :: Elt e => Exp e -> Acc (Scalar e) unit = Acc . Unit -- | Replicate an array across one or more dimensions as specified by the -- /generalised/ array index provided as the first argument. -- -- For example, assuming 'arr' is a vector (one-dimensional array), -- -- > replicate (lift (Z :. (2::Int) :. All :. (3::Int))) arr -- -- yields a three dimensional array, where 'arr' is replicated twice across the -- first and three times across the third dimension. -- replicate :: (Slice slix, Elt e) => Exp slix -> Acc (Array (SliceShape slix) e) -> Acc (Array (FullShape slix) e) replicate = Acc $$ Replicate -- | Construct a new array by applying a function to each index. -- -- For example, the following will generate a one-dimensional array -- (`Vector`) of three floating point numbers: -- -- > generate (index1 3) (\_ -> 1.2) -- -- Or, equivalently: -- -- > generate (constant (Z :. (3::Int))) (\_ -> 1.2) -- -- Finally, the following will create an array equivalent to '[1..10]': -- -- > generate (index1 10) $ \ ix -> -- > let (Z :. i) = unlift ix -- > in fromIntegral i -- -- [/NOTE:/] -- -- Using 'generate', it is possible to introduce nested data parallelism, which -- will cause the program to fail. -- -- If the index given by the scalar function is then used to dispatch further -- parallel work, whose result is returned into 'Exp' terms by array indexing -- operations such as (`!`) or `the`, the program will fail with the error: -- '.\/Data\/Array\/Accelerate\/Trafo\/Sharing.hs:447 (convertSharingExp): inconsistent valuation \@ shared \'Exp\' tree ...'. -- generate :: (Shape ix, Elt a) => Exp ix -> (Exp ix -> Exp a) -> Acc (Array ix a) generate = Acc $$ Generate -- Shape manipulation -- ------------------ -- | Change the shape of an array without altering its contents. The 'size' of -- the source and result arrays must be identical. -- -- > precondition: size ix == size ix' -- reshape :: (Shape ix, Shape ix', Elt e) => Exp ix -> Acc (Array ix' e) -> Acc (Array ix e) reshape = Acc $$ Reshape -- Extraction of sub-arrays -- ------------------------ -- | Index an array with a /generalised/ array index, supplied as the -- second argument. The result is a new array (possibly a singleton) -- containing the selected dimensions (`All`s) in their entirety. -- -- This can be used to /cut out/ entire dimensions. The opposite of -- `replicate`. For example, if 'mat' is a two dimensional array, the -- following will select a specific row and yield a one dimensional -- result: -- -- > slice mat (lift (Z :. (2::Int) :. All)) -- -- A fully specified index (with no `All`s) would return a single element (zero -- dimensional array). -- slice :: (Slice slix, Elt e) => Acc (Array (FullShape slix) e) -> Exp slix -> Acc (Array (SliceShape slix) e) slice = Acc $$ Slice -- Map-like functions -- ------------------ -- | Apply the given function element-wise to the given array. -- map :: (Shape ix, Elt a, Elt b) => (Exp a -> Exp b) -> Acc (Array ix a) -> Acc (Array ix b) map = Acc $$ Map -- | Apply the given binary function element-wise to the two arrays. The extent of the resulting -- array is the intersection of the extents of the two source arrays. -- zipWith :: (Shape ix, Elt a, Elt b, Elt c) => (Exp a -> Exp b -> Exp c) -> Acc (Array ix a) -> Acc (Array ix b) -> Acc (Array ix c) zipWith = Acc $$$ ZipWith -- Reductions -- ---------- -- | Reduction of the innermost dimension of an array of arbitrary rank. The -- first argument needs to be an /associative/ function to enable an efficient -- parallel implementation. -- fold :: (Shape ix, Elt a) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Array (ix:.Int) a) -> Acc (Array ix a) fold = Acc $$$ Fold -- | Variant of 'fold' that requires the reduced array to be non-empty and -- doesn't need an default value. The first argument needs to be an -- /associative/ function to enable an efficient parallel implementation. -- fold1 :: (Shape ix, Elt a) => (Exp a -> Exp a -> Exp a) -> Acc (Array (ix:.Int) a) -> Acc (Array ix a) fold1 = Acc $$ Fold1 -- | Segmented reduction along the innermost dimension. Performs one individual -- reduction per segment of the source array. These reductions proceed in -- parallel. -- -- The source array must have at least rank 1. The 'Segments' array determines -- the lengths of the logical sub-arrays, each of which is folded separately. -- foldSeg :: (Shape ix, Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Array (ix:.Int) a) -> Acc (Segments i) -> Acc (Array (ix:.Int) a) foldSeg = Acc $$$$ FoldSeg -- | Variant of 'foldSeg' that requires /all/ segments of the reduced array to -- be non-empty and doesn't need a default value. -- -- The source array must have at least rank 1. The 'Segments' array determines -- the lengths of the logical sub-arrays, each of which is folded separately. -- fold1Seg :: (Shape ix, Elt a, Elt i, IsIntegral i) => (Exp a -> Exp a -> Exp a) -> Acc (Array (ix:.Int) a) -> Acc (Segments i) -> Acc (Array (ix:.Int) a) fold1Seg = Acc $$$ Fold1Seg -- Scan functions -- -------------- -- | Data.List style left-to-right scan, but with the additional restriction -- that the first argument needs to be an /associative/ function to enable an -- efficient parallel implementation. The initial value (second argument) may be -- arbitrary. -- scanl :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) scanl = Acc $$$ Scanl -- | Variant of 'scanl', where the final result of the reduction is returned -- separately. Denotationally, we have -- -- > scanl' f e arr = (init res, unit (res!len)) -- > where -- > len = shape arr -- > res = scanl f e arr -- scanl' :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> (Acc (Vector a), Acc (Scalar a)) scanl' = unatup2 . Acc $$$ Scanl' -- | Data.List style left-to-right scan without an initial value (aka inclusive -- scan). Again, the first argument needs to be an /associative/ function. -- Denotationally, we have -- -- > scanl1 f e arr = tail (scanl f e arr) -- scanl1 :: Elt a => (Exp a -> Exp a -> Exp a) -> Acc (Vector a) -> Acc (Vector a) scanl1 = Acc $$ Scanl1 -- | Right-to-left variant of 'scanl'. -- scanr :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> Acc (Vector a) scanr = Acc $$$ Scanr -- | Right-to-left variant of 'scanl''. -- scanr' :: Elt a => (Exp a -> Exp a -> Exp a) -> Exp a -> Acc (Vector a) -> (Acc (Vector a), Acc (Scalar a)) scanr' = unatup2 . Acc $$$ Scanr' -- | Right-to-left variant of 'scanl1'. -- scanr1 :: Elt a => (Exp a -> Exp a -> Exp a) -> Acc (Vector a) -> Acc (Vector a) scanr1 = Acc $$ Scanr1 -- Permutations -- ------------ -- | Forward permutation specified by an index mapping. The result array is -- initialised with the given defaults and any further values that are permuted -- into the result array are added to the current value using the given -- combination function. -- -- The combination function must be /associative/ and /commutative/. Elements -- that are mapped to the magic value 'ignore' by the permutation function are -- dropped. -- permute :: (Shape ix, Shape ix', Elt a) => (Exp a -> Exp a -> Exp a) -- ^combination function -> Acc (Array ix' a) -- ^array of default values -> (Exp ix -> Exp ix') -- ^permutation -> Acc (Array ix a) -- ^array to be permuted -> Acc (Array ix' a) permute = Acc $$$$ Permute -- | Backward permutation specified by an index mapping from the destination -- array specifying which element of the source array to read. -- backpermute :: (Shape ix, Shape ix', Elt a) => Exp ix' -- ^shape of the result array -> (Exp ix' -> Exp ix) -- ^permutation -> Acc (Array ix a) -- ^source array -> Acc (Array ix' a) backpermute = Acc $$$ Backpermute -- Stencil operations -- ------------------ -- Common stencil types -- -- DIM1 stencil type type Stencil3 a = (Exp a, Exp a, Exp a) type Stencil5 a = (Exp a, Exp a, Exp a, Exp a, Exp a) type Stencil7 a = (Exp a, Exp a, Exp a, Exp a, Exp a, Exp a, Exp a) type Stencil9 a = (Exp a, Exp a, Exp a, Exp a, Exp a, Exp a, Exp a, Exp a, Exp a) -- DIM2 stencil type type Stencil3x3 a = (Stencil3 a, Stencil3 a, Stencil3 a) type Stencil5x3 a = (Stencil5 a, Stencil5 a, Stencil5 a) type Stencil3x5 a = (Stencil3 a, Stencil3 a, Stencil3 a, Stencil3 a, Stencil3 a) type Stencil5x5 a = (Stencil5 a, Stencil5 a, Stencil5 a, Stencil5 a, Stencil5 a) -- DIM3 stencil type type Stencil3x3x3 a = (Stencil3x3 a, Stencil3x3 a, Stencil3x3 a) type Stencil5x3x3 a = (Stencil5x3 a, Stencil5x3 a, Stencil5x3 a) type Stencil3x5x3 a = (Stencil3x5 a, Stencil3x5 a, Stencil3x5 a) type Stencil3x3x5 a = (Stencil3x3 a, Stencil3x3 a, Stencil3x3 a, Stencil3x3 a, Stencil3x3 a) type Stencil5x5x3 a = (Stencil5x5 a, Stencil5x5 a, Stencil5x5 a) type Stencil5x3x5 a = (Stencil5x3 a, Stencil5x3 a, Stencil5x3 a, Stencil5x3 a, Stencil5x3 a) type Stencil3x5x5 a = (Stencil3x5 a, Stencil3x5 a, Stencil3x5 a, Stencil3x5 a, Stencil3x5 a) type Stencil5x5x5 a = (Stencil5x5 a, Stencil5x5 a, Stencil5x5 a, Stencil5x5 a, Stencil5x5 a) -- |Map a stencil over an array. In contrast to 'map', the domain of a stencil function is an -- entire /neighbourhood/ of each array element. Neighbourhoods are sub-arrays centred around a -- focal point. They are not necessarily rectangular, but they are symmetric in each dimension -- and have an extent of at least three in each dimensions — due to the symmetry requirement, the -- extent is necessarily odd. The focal point is the array position that is determined by the -- stencil. -- -- For those array positions where the neighbourhood extends past the boundaries of the source -- array, a boundary condition determines the contents of the out-of-bounds neighbourhood -- positions. -- stencil :: (Shape ix, Elt a, Elt b, Stencil ix a stencil) => (stencil -> Exp b) -- ^stencil function -> Boundary a -- ^boundary condition -> Acc (Array ix a) -- ^source array -> Acc (Array ix b) -- ^destination array stencil = Acc $$$ Stencil -- | Map a binary stencil of an array. The extent of the resulting array is the -- intersection of the extents of the two source arrays. -- stencil2 :: (Shape ix, Elt a, Elt b, Elt c, Stencil ix a stencil1, Stencil ix b stencil2) => (stencil1 -> stencil2 -> Exp c) -- ^binary stencil function -> Boundary a -- ^boundary condition #1 -> Acc (Array ix a) -- ^source array #1 -> Boundary b -- ^boundary condition #2 -> Acc (Array ix b) -- ^source array #2 -> Acc (Array ix c) -- ^destination array stencil2 = Acc $$$$$ Stencil2 -- Foreign function calling -- ------------------------ -- | Call a foreign function. The form the function takes is dependent on the backend being used. -- The arguments are passed as either a single array or as a tuple of arrays. In addition a pure -- Accelerate version of the function needs to be provided to support backends other than the one -- being targeted. foreignAcc :: (Arrays acc, Arrays res, Foreign ff) => ff acc res -> (Acc acc -> Acc res) -> Acc acc -> Acc res foreignAcc = Acc $$$ Aforeign -- | Call a foreign function with foreign implementations for two different backends. foreignAcc2 :: (Arrays acc, Arrays res, Foreign ff1, Foreign ff2) => ff1 acc res -> ff2 acc res -> (Acc acc -> Acc res) -> Acc acc -> Acc res foreignAcc2 ff1 = Acc $$$ Aforeign ff1 $$ Acc $$$ Aforeign -- | Call a foreign function with foreign implementations for three different backends. foreignAcc3 :: (Arrays acc, Arrays res, Foreign ff1, Foreign ff2, Foreign ff3) => ff1 acc res -> ff2 acc res -> ff3 acc res -> (Acc acc -> Acc res) -> Acc acc -> Acc res foreignAcc3 ff1 ff2 = Acc $$$ Aforeign ff1 $$ Acc $$$ Aforeign ff2 $$ Acc $$$ Aforeign -- | Call a foreign expression function. The form the function takes is dependent on the -- backend being used. The arguments are passed as either a single scalar element or as a -- tuple of elements. In addition a pure Accelerate version of the function needs to be -- provided to support backends other than the one being targeted. foreignExp :: (Elt e, Elt res, Foreign ff) => ff e res -> (Exp e -> Exp res) -> Exp e -> Exp res foreignExp = Exp $$$ Foreign -- | Call a foreign function with foreign implementations for two different backends. foreignExp2 :: (Elt e, Elt res, Foreign ff1, Foreign ff2) => ff1 e res -> ff2 e res -> (Exp e -> Exp res) -> Exp e -> Exp res foreignExp2 ff1 = Exp $$$ Foreign ff1 $$ Exp $$$ Foreign -- | Call a foreign function with foreign implementations for three different backends. foreignExp3 :: (Elt e, Elt res, Foreign ff1, Foreign ff2, Foreign ff3) => ff1 e res -> ff2 e res -> ff3 e res -> (Exp e -> Exp res) -> Exp e -> Exp res foreignExp3 ff1 ff2 = Exp $$$ Foreign ff1 $$ Exp $$$ Foreign ff2 $$ Exp $$$ Foreign -- Composition of array computations -- --------------------------------- -- | Pipelining of two array computations. -- -- Denotationally, we have -- -- > (acc1 >-> acc2) arrs = let tmp = acc1 arrs in acc2 tmp -- infixl 1 >-> (>->) :: (Arrays a, Arrays b, Arrays c) => (Acc a -> Acc b) -> (Acc b -> Acc c) -> (Acc a -> Acc c) (>->) = Acc $$$ Pipe -- Flow control constructs -- ----------------------- -- | An array-level if-then-else construct. -- acond :: Arrays a => Exp Bool -- ^ if-condition -> Acc a -- ^ then-array -> Acc a -- ^ else-array -> Acc a acond = Acc $$$ Acond -- | An array-level while construct -- awhile :: Arrays a => (Acc a -> Acc (Scalar Bool)) -> (Acc a -> Acc a) -> Acc a -> Acc a awhile = Acc $$$ Awhile -- Shapes and indices -- ------------------ -- | Get the outermost dimension of a shape -- indexHead :: Slice sh => Exp (sh :. Int) -> Exp Int indexHead = Exp . IndexHead -- | Get all but the outermost element of a shape -- indexTail :: Slice sh => Exp (sh :. Int) -> Exp sh indexTail = Exp . IndexTail -- | Map a multi-dimensional index into a linear, row-major representation of an -- array. The first argument is the array shape, the second is the index. -- toIndex :: Shape sh => Exp sh -> Exp sh -> Exp Int toIndex = Exp $$ ToIndex -- | Inverse of 'fromIndex' -- fromIndex :: Shape sh => Exp sh -> Exp Int -> Exp sh fromIndex = Exp $$ FromIndex -- | Intersection of two shapes -- intersect :: Shape sh => Exp sh -> Exp sh -> Exp sh intersect = Exp $$ Intersect -- Flow-control -- ------------ -- | A scalar-level if-then-else construct. -- cond :: Elt t => Exp Bool -- ^ condition -> Exp t -- ^ then-expression -> Exp t -- ^ else-expression -> Exp t cond = Exp $$$ Cond -- | While construct. Continue to apply the given function, starting with the -- initial value, until the test function evaluates to true. -- while :: Elt e => (Exp e -> Exp Bool) -> (Exp e -> Exp e) -> Exp e -> Exp e while = Exp $$$ While -- Array operations with a scalar result -- ------------------------------------- -- |Expression form that extracts a scalar from an array -- infixl 9 ! (!) :: (Shape ix, Elt e) => Acc (Array ix e) -> Exp ix -> Exp e (!) = Exp $$ Index -- |Expression form that extracts a scalar from an array at a linear index -- infixl 9 !! (!!) :: (Shape ix, Elt e) => Acc (Array ix e) -> Exp Int -> Exp e (!!) = Exp $$ LinearIndex -- |Expression form that yields the shape of an array -- shape :: (Shape ix, Elt e) => Acc (Array ix e) -> Exp ix shape = Exp . Shape -- |Expression form that yields the size of an array -- size :: (Shape ix, Elt e) => Acc (Array ix e) -> Exp Int size = shapeSize . shape -- |The total number of elements in an array of the given 'Shape' -- shapeSize :: Shape ix => Exp ix -> Exp Int shapeSize = Exp . ShapeSize -- Instances of all relevant H98 classes -- ------------------------------------- preludeError :: String -> String -> a preludeError x y = error (printf "Prelude.%s applied to EDSL types: use %s instead" x y) instance (Elt t, IsBounded t) => Bounded (Exp t) where minBound = mkMinBound maxBound = mkMaxBound instance (Elt t, IsScalar t) => Enum (Exp t) -- succ = mkSucc -- pred = mkPred -- FIXME: ops instance (Elt t, IsScalar t) => Eq (Exp t) where -- FIXME: instance makes no sense with standard signatures (==) = preludeError "Eq.==" "(==*)" (/=) = preludeError "Eq./=" "(/=*)" instance (Elt t, IsScalar t) => Ord (Exp t) where -- FIXME: instance makes no sense with standard signatures min = mkMin max = mkMax -- compare = error "Prelude.Ord.compare applied to EDSL types" (<) = preludeError "Ord.<" "(<*)" (<=) = preludeError "Ord.<=" "(<=*)" (>) = preludeError "Ord.>" "(>*)" (>=) = preludeError "Ord.>=" "(>=*)" instance (Elt t, IsNum t, IsIntegral t) => Bits (Exp t) where (.&.) = mkBAnd (.|.) = mkBOr xor = mkBXor complement = mkBNot -- FIXME: argh, the rest have fixed types in their signatures -- | @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive, or right by -- @-i@ bits otherwise. Right shifts perform sign extension on signed number -- types; i.e. they fill the top bits with 1 if the @x@ is negative and with 0 -- otherwise. -- shift :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t shift x i = cond (i ==* 0) x $ cond (i <* 0) (x `shiftR` (-i)) (x `shiftL` i) -- | Shift the argument left by the specified number of bits -- (which must be non-negative). -- shiftL :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t shiftL = mkBShiftL -- | Shift the first argument right by the specified number of bits. The result -- is undefined for negative shift amounts and shift amounts greater or equal to -- the 'bitSize'. -- -- Right shifts perform sign extension on signed number types; i.e. they fill -- the top bits with 1 if the @x@ is negative and with 0 otherwise. -- shiftR :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t shiftR = mkBShiftR -- | @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive, or right by -- @-i@ bits otherwise. -- rotate :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t rotate x i = cond (i ==* 0) x $ cond (i <* 0) (x `rotateR` (-i)) (x `rotateL` i) -- | Rotate the argument left by the specified number of bits -- (which must be non-negative). -- rotateL :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t rotateL = mkBRotateL -- | Rotate the argument right by the specified number of bits -- (which must be non-negative). -- rotateR :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t rotateR = mkBRotateR -- | @bit i@ is a value with the @i@th bit set and all other bits clear -- bit :: (Elt t, IsIntegral t) => Exp Int -> Exp t bit x = 1 `shiftL` x -- | @x \`setBit\` i@ is the same as @x .|. bit i@ -- setBit :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t x `setBit` i = x .|. bit i -- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@ -- clearBit :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t x `clearBit` i = x .&. complement (bit i) -- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@ -- complementBit :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp t x `complementBit` i = x `xor` bit i -- | Return 'True' if the @n@th bit of the argument is 1 -- testBit :: (Elt t, IsIntegral t) => Exp t -> Exp Int -> Exp Bool x `testBit` i = (x .&. bit i) /=* 0 instance (Elt t, IsNum t) => Num (Exp t) where (+) = mkAdd (-) = mkSub (*) = mkMul negate = mkNeg abs = mkAbs signum = mkSig fromInteger = constant . P.fromInteger instance (Elt t, IsNum t) => Real (Exp t) -- FIXME: Why did we include this class? We won't need `toRational' until -- we support rational numbers in AP computations. instance (Elt t, IsIntegral t) => Integral (Exp t) where quot = mkQuot rem = mkRem div = mkIDiv mod = mkMod quotRem = mkQuotRem divMod = mkDivMod -- toInteger = -- makes no sense instance (Elt t, IsFloating t) => Floating (Exp t) where pi = mkPi sin = mkSin cos = mkCos tan = mkTan asin = mkAsin acos = mkAcos atan = mkAtan asinh = mkAsinh acosh = mkAcosh atanh = mkAtanh exp = mkExpFloating sqrt = mkSqrt log = mkLog (**) = mkFPow logBase = mkLogBase instance (Elt t, IsFloating t) => Fractional (Exp t) where (/) = mkFDiv recip = mkRecip fromRational = constant . P.fromRational instance (Elt t, IsFloating t) => RealFrac (Exp t) -- FIXME: add other ops instance (Elt t, IsFloating t) => RealFloat (Exp t) where atan2 = mkAtan2 -- FIXME: add other ops -- Methods from H98 classes, where we need other signatures -- -------------------------------------------------------- infix 4 ==*, /=*, <*, <=*, >*, >=* -- |Equality lifted into Accelerate expressions. -- (==*) :: (Elt t, IsScalar t) => Exp t -> Exp t -> Exp Bool (==*) = mkEq -- |Inequality lifted into Accelerate expressions. -- (/=*) :: (Elt t, IsScalar t) => Exp t -> Exp t -> Exp Bool (/=*) = mkNEq -- compare :: a -> a -> Ordering -- we have no enumerations at the moment -- compare = ... -- |Smaller-than lifted into Accelerate expressions. -- (<*) :: (Elt t, IsScalar t) => Exp t -> Exp t -> Exp Bool (<*) = mkLt -- |Greater-or-equal lifted into Accelerate expressions. -- (>=*) :: (Elt t, IsScalar t) => Exp t -> Exp t -> Exp Bool (>=*) = mkGtEq -- |Greater-than lifted into Accelerate expressions. -- (>*) :: (Elt t, IsScalar t) => Exp t -> Exp t -> Exp Bool (>*) = mkGt -- |Smaller-or-equal lifted into Accelerate expressions. -- (<=*) :: (Elt t, IsScalar t) => Exp t -> Exp t -> Exp Bool (<=*) = mkLtEq -- Conversions from the RealFrac class -- -- | @truncate x@ returns the integer nearest @x@ between zero and @x@. -- truncate :: (Elt a, Elt b, IsFloating a, IsIntegral b) => Exp a -> Exp b truncate = mkTruncate -- | @round x@ returns the nearest integer to @x@, or the even integer if @x@ is -- equidistant between two integers. -- round :: (Elt a, Elt b, IsFloating a, IsIntegral b) => Exp a -> Exp b round = mkRound -- | @floor x@ returns the greatest integer not greater than @x@. -- floor :: (Elt a, Elt b, IsFloating a, IsIntegral b) => Exp a -> Exp b floor = mkFloor -- | @ceiling x@ returns the least integer not less than @x@. -- ceiling :: (Elt a, Elt b, IsFloating a, IsIntegral b) => Exp a -> Exp b ceiling = mkCeiling -- | return if the integer is even -- even :: (Elt a, IsIntegral a) => Exp a -> Exp Bool even x = x .&. 1 ==* 0 -- | return if the integer is odd -- odd :: (Elt a, IsIntegral a) => Exp a -> Exp Bool odd x = x .&. 1 ==* 1 -- Non-overloaded standard functions, where we need other signatures -- ----------------------------------------------------------------- -- |Conjunction -- infixr 3 &&* (&&*) :: Exp Bool -> Exp Bool -> Exp Bool (&&*) = mkLAnd -- |Disjunction -- infixr 2 ||* (||*) :: Exp Bool -> Exp Bool -> Exp Bool (||*) = mkLOr -- |Negation -- not :: Exp Bool -> Exp Bool not = mkLNot -- Conversions -- ----------- -- |Convert a character to an 'Int'. -- ord :: Exp Char -> Exp Int ord = mkOrd -- |Convert an 'Int' into a character. -- chr :: Exp Int -> Exp Char chr = mkChr -- |Convert a Boolean value to an 'Int', where 'False' turns into '0' and 'True' -- into '1'. -- boolToInt :: Exp Bool -> Exp Int boolToInt = mkBoolToInt -- |General coercion from integral types -- fromIntegral :: (Elt a, Elt b, IsIntegral a, IsNum b) => Exp a -> Exp b fromIntegral = mkFromIntegral -- Constants -- --------- -- |Magic value identifying elements that are ignored in a forward permutation. -- Note that this currently does not work for singleton arrays. -- ignore :: Shape ix => Exp ix ignore = constant Sugar.ignore
kumasento/accelerate
Data/Array/Accelerate/Language.hs
bsd-3-clause
28,887
0
14
7,224
6,769
3,741
3,028
-1
-1
module Joust ( module Joust.Joust.Types, module Joust.Joust.Simulator ) where import Joust.Joust.Types import Joust.Joust.Simulator
jfischoff/joust
src/Joust.hs
bsd-3-clause
140
0
5
21
32
22
10
5
0
-- | -- Module: Elaboration -- Description: - -- Copyright: (c) 2013 Tom Hawkins & Lee Pike module Language.Atom.Elaboration ( -- UeStateT -- * Atom monad and container. Atom , AtomDB (..) , Global (..) , Rule (..) , StateHierarchy (..) , buildAtom -- * Type Aliases and Utilities , UID , Name , Phase (..) , Path , elaborate , var , var' , array , array' , addName , get , put , allUVs , allUEs ) where import Control.Applicative (Applicative, pure, (<*>)) import Control.Monad (ap) import Control.Monad.Trans import Data.Function (on) import Data.List import Data.Char import qualified Control.Monad.State.Strict as S import Language.Atom.Expressions hiding (typeOf) import Language.Atom.UeMap type UID = Int -- | A name. type Name = String -- | A hierarchical name. type Path = [Name] -- | A phase is either the minimum phase or the exact phase. data Phase = MinPhase Int | ExactPhase Int data Global = Global { gRuleId :: Int , gVarId :: Int , gArrayId :: Int , gState :: [StateHierarchy] , gProbes :: [(String, Hash)] , gPeriod :: Int , gPhase :: Phase } data AtomDB = AtomDB { atomId :: Int , atomName :: Name , atomNames :: [Name] -- Names used at this level. , atomEnable :: Hash -- Enabling condition. , atomSubs :: [AtomDB] -- Sub atoms. , atomPeriod :: Int , atomPhase :: Phase , atomAssigns :: [(MUV, Hash)] , atomActions :: [([String] -> String, [Hash])] , atomAsserts :: [(Name, Hash)] , atomCovers :: [(Name, Hash)] , atomComm :: String } data Rule = Rule { ruleId :: Int , ruleName :: Name , ruleEnable :: Hash , ruleAssigns :: [(MUV, Hash)] , ruleActions :: [([String] -> String, [Hash])] , rulePeriod :: Int , rulePhase :: Phase , ruleComment :: String -- , mathH :: Bool -- Contains a math.h call? } | Assert { ruleName :: Name , ruleEnable :: Hash , ruleAssert :: Hash } | Cover { ruleName :: Name , ruleEnable :: Hash , ruleCover :: Hash } data StateHierarchy = StateHierarchy Name [StateHierarchy] | StateVariable Name Const | StateArray Name [Const] instance Show AtomDB where show = atomName instance Eq AtomDB where (==) = (==) `on` atomId instance Ord AtomDB where compare a b = compare (atomId a) (atomId b) instance Show Rule where show = ruleName elaborateRules:: Hash -> AtomDB -> UeState [Rule] elaborateRules parentEnable atom = if isRule then do r <- rule rs <- rules return $ r : rs else rules where isRule = not $ null (atomAssigns atom) && null (atomActions atom) enable :: UeState Hash enable = do st <- S.get let (h,st') = newUE (uand (recoverUE st parentEnable) (recoverUE st (atomEnable atom))) st S.put st' return h rule :: UeState Rule rule = do h <- enable assigns <- S.foldM (\prs pr -> do pr' <- enableAssign pr return $ pr' : prs) [] (atomAssigns atom) -- st <- S.get return $ Rule { ruleId = atomId atom , ruleName = atomName atom , ruleEnable = h , ruleAssigns = assigns , ruleActions = atomActions atom , rulePeriod = atomPeriod atom , rulePhase = atomPhase atom , ruleComment = atomComm atom } assert :: (Name, Hash) -> UeState Rule assert (name, u) = do h <- enable return $ Assert { ruleName = name , ruleEnable = h , ruleAssert = u } cover :: (Name, Hash) -> UeState Rule cover (name, u) = do h <- enable return $ Cover { ruleName = name , ruleEnable = h , ruleCover = u } rules :: UeState [Rule] rules = do asserts <- S.foldM (\rs e -> do r <- assert e return $ r:rs ) [] (atomAsserts atom) covers <- S.foldM (\rs e -> do r <- cover e return $ r:rs ) [] (atomCovers atom) rules' <- S.foldM (\rs db -> do en <- enable r <- elaborateRules en db return $ r:rs ) [] (atomSubs atom) return $ asserts ++ covers ++ concat rules' enableAssign :: (MUV, Hash) -> UeState (MUV, Hash) enableAssign (uv', ue') = do e <- enable h <- maybeUpdate (MUVRef uv') st <- S.get let (h',st') = newUE (umux (recoverUE st e) (recoverUE st ue') (recoverUE st h)) st S.put st' return (uv', h') reIdRules :: Int -> [Rule] -> [Rule] reIdRules _ [] = [] reIdRules i (a:b) = case a of Rule _ _ _ _ _ _ _ _ -> a { ruleId = i } : reIdRules (i + 1) b _ -> a : reIdRules i b buildAtom :: UeMap -> Global -> Name -> Atom a -> String -> IO (a, AtomSt) buildAtom st g name (Atom f) comm = do let (h,st') = newUE (ubool True) st -- S.put st' f (st', (g { gRuleId = gRuleId g + 1 }, AtomDB { atomId = gRuleId g , atomName = name , atomNames = [] , atomEnable = h , atomSubs = [] , atomPeriod = gPeriod g , atomPhase = gPhase g , atomAssigns = [] , atomActions = [] , atomAsserts = [] , atomCovers = [] , atomComm = comm })) -- S.return db type AtomSt = (UeMap, (Global, AtomDB)) -- | The Atom monad holds variable and rule declarations. data Atom a = Atom (AtomSt -> IO (a, AtomSt)) instance Applicative Atom where pure = return (<*>) = ap instance Functor Atom where fmap = S.liftM instance Monad Atom where return a = Atom (\ s -> return (a, s)) (Atom f1) >>= f2 = Atom f3 where f3 s = do (a, s') <- f1 s let Atom f4 = f2 a f4 s' instance MonadIO Atom where liftIO io = Atom f where f s = do a <- io return (a, s) get :: Atom AtomSt get = Atom (\ s -> return (s, s)) put :: AtomSt -> Atom () put s = Atom (\ _ -> return ((), s)) -- | A Relation is used for relative performance constraints between 'Action's. -- data Relation = Higher UID | Lower UID deriving (Show, Eq) -- XXX elaborate is a bit hacky since we're threading state through this -- function, but I don't want to go change all the UeState monads to UeStateT -- monads. -- | Given a top level name and design, elaborates design and returns a design database. elaborate :: UeMap -> Name -> Atom () -> IO (Maybe ( UeMap , ( StateHierarchy, [Rule], [Name], [Name] , [(Name, Type)]) )) elaborate st name atom = do (_, (st0, (g, atomDB))) <- buildAtom st Global { gRuleId = 0 , gVarId = 0 , gArrayId = 0 , gState = [] , gProbes = [] , gPeriod = 1 , gPhase = MinPhase 0 } name atom "" let (h,st1) = newUE (ubool True) st0 (getRules,st2) = S.runState (elaborateRules h atomDB) st1 rules = reIdRules 0 (reverse getRules) coverageNames = [ name' | Cover name' _ _ <- rules ] assertionNames = [ name' | Assert name' _ _ <- rules ] probeNames = [ (n, typeOf a st2) | (n, a) <- gProbes g ] if (null rules) then do putStrLn "ERROR: Design contains no rules. Nothing to do." return Nothing else do mapM_ (checkEnable st2) rules ok <- mapM checkAssignConflicts rules return (if and ok then Just ( st2 , (trimState $ StateHierarchy name $ gState g, rules, assertionNames , coverageNames, probeNames)) else Nothing) trimState :: StateHierarchy -> StateHierarchy trimState a = case a of StateHierarchy name items -> StateHierarchy name $ filter f $ map trimState items a' -> a' where f (StateHierarchy _ []) = False f _ = True -- | Checks that a rule will not be trivially disabled. checkEnable :: UeMap -> Rule -> IO () checkEnable st rule | ruleEnable rule == (fst $ newUE (ubool False) st) = putStrLn $ "WARNING: Rule will never execute: " ++ show rule | otherwise = return () -- | Check that a variable is assigned more than once in a rule. Will -- eventually be replaced consistent assignment checking. checkAssignConflicts :: Rule -> IO Bool checkAssignConflicts rule@(Rule _ _ _ _ _ _ _ _) = if length vars /= length vars' then do putStrLn $ "ERROR: Rule " ++ show rule ++ " contains multiple assignments to the same variable(s)." return False else do return True where vars = fst $ unzip $ ruleAssigns rule vars' = nub vars checkAssignConflicts _ = return True {- -- | Checks that all array indices are not a function of array variables. checkArrayIndices :: [Rule] -> Rule -> IO Bool checkArrayIndices rules rule = where ues = allUEs rule arrayIndices' = concatMap arrayIndices ues [ (name, ) | (UA _ name _, index) <- concatMap arrayIndices ues, UV (Array (UA _ name' init)) <- allUVs rules index, length init /= 1 ] data UA = UA Int String [Const] deriving (Show, Eq, Ord) data UV = UV UVLocality deriving (Show, Eq, Ord) data UVLocality = Array UA UE | External String Type deriving (Show, Eq, Ord) allUVs :: [Rule] -> UE -> [UV] arrayIndices :: UE -> [(UA, UE)] , ruleEnable :: UE , ruleAssigns :: [(UV, UE)] , ruleActions :: [([String] -> String, [UE])] -} -- | Generic local variable declaration. var :: Expr a => Name -> a -> Atom (V a) var name init' = do name' <- addName name (st, (g, atom)) <- get let uv' = UV (gVarId g) name' c c = constant init' put (st, (g { gVarId = gVarId g + 1, gState = gState g ++ [StateVariable name c] }, atom)) return $ V uv' -- | Generic external variable declaration. var' :: Name -> Type -> V a var' name t = V $ UVExtern name t -- | Generic array declaration. array :: Expr a => Name -> [a] -> Atom (A a) array name [] = error $ "ERROR: arrays can not be empty: " ++ name array name init' = do name' <- addName name (st, (g, atom)) <- get let ua = UA (gArrayId g) name' c c = map constant init' put (st, (g { gArrayId = gArrayId g + 1, gState = gState g ++ [StateArray name c] }, atom)) return $ A ua -- | Generic external array declaration. array' :: Expr a => Name -> Type -> A a array' name t = A $ UAExtern name t addName :: Name -> Atom Name addName name = do (st, (g, atom)) <- get checkName name if elem name (atomNames atom) then error $ "ERROR: Name \"" ++ name ++ "\" not unique in " ++ show atom ++ "." else do put (st, (g, atom { atomNames = name : atomNames atom })) return $ atomName atom ++ "." ++ name -- still accepts some misformed names, like "_.." or "_][" checkName :: Name -> Atom () checkName name = if (\ x -> isAlpha x || x == '_') (head name) && and (map (\ x -> isAlphaNum x || x `elem` "._[]") (tail name)) then return () else error $ "ERROR: Name \"" ++ name ++ "\" is not a valid identifier." {- ruleGraph :: Name -> [Rule] -> [UV] -> IO () ruleGraph name rules uvs = do putStrLn $ "Writing rule graph (" ++ name ++ ".dot)..." writeFile (name ++ ".dot") g --system $ "dot -o " ++ name ++ ".png -Tpng " ++ name ++ ".dot" return () where adminUVs = [ UV (-1) "__clock" (External Word64) , UV (-2) "__coverage_index" (External Word32) , UV (-3) "__coverage[__coverage_index]" (External Word32) ] g = unlines [ "digraph " ++ name ++ "{" , concat [ " r" ++ show (ruleId r) ++ " [label = \"" ++ show r ++ "\" shape = ellipse];\n" | r <- rules ] , concat [ " v" ++ show i ++ " [label = \"" ++ n ++ "\" shape = box];\n" | (UV i n _) <- adminUVs ++ uvs ] , concat [ " r" ++ show (ruleId r) ++ " -> v" ++ show i ++ "\n" | r <- rules, (UV i _ _, _) <- ruleAssigns r ] , concat [ " v" ++ show i ++ " -> r" ++ show (ruleId r) ++ "\n" | r <- rules, (UV i _ _) <- ruleUVRefs r ] , "}" ] ruleUVRefs r = nub $ concatMap uvSet ues where ues = ruleEnable r : snd (unzip (ruleAssigns r)) ++ concat (snd (unzip (ruleActions r))) -} -- | All the variables that directly and indirectly control the value of an expression. allUVs :: UeMap -> [Rule] -> Hash -> [MUV] allUVs st rules ue' = fixedpoint next $ nearestUVs ue' st where assigns = concat [ ruleAssigns r | r@(Rule _ _ _ _ _ _ _ _) <- rules ] previousUVs :: MUV -> [MUV] previousUVs u = concat [ nearestUVs ue_ st | (uv', ue_) <- assigns, u == uv' ] next :: [MUV] -> [MUV] next uvs = sort $ nub $ uvs ++ concatMap previousUVs uvs fixedpoint :: Eq a => (a -> a) -> a -> a fixedpoint f a | a == f a = a | otherwise = fixedpoint f $ f a -- | All primary expressions used in a rule. allUEs :: Rule -> [Hash] allUEs rule = ruleEnable rule : ues where index :: MUV -> [Hash] index (MUVArray _ ue') = [ue'] index _ = [] ues = case rule of Rule _ _ _ _ _ _ _ _ -> concat [ ue' : index uv' | (uv', ue') <- ruleAssigns rule ] ++ concat (snd (unzip (ruleActions rule))) Assert _ _ a -> [a] Cover _ _ a -> [a]
Copilot-Language/atom_for_copilot
Language/Atom/Elaboration.hs
bsd-3-clause
14,093
0
18
4,917
3,999
2,142
1,857
309
4
module Data.Graph.Inductive.Query.ArtPoint( ap ) where import Data.Graph.Inductive.Graph ------------------------------------------------------------------------------ -- Tree for storing the DFS numbers and back edges for each node in the graph. -- Each node in this tree is of the form (v,n,b) where v is the vertex number, -- n is its DFS number and b is the list of nodes (and their DFS numbers) that -- lead to back back edges for that vertex v. ------------------------------------------------------------------------------ data DFSTree a = B (a,a,[(a,a)]) [DFSTree a] deriving (Eq, Show, Read) ------------------------------------------------------------------------------ -- Tree for storing the DFS and low numbers for each node in the graph. -- Each node in this tree is of the form (v,n,l) where v is the vertex number, -- n is its DFS number and l is its low number. ------------------------------------------------------------------------------ data LOWTree a = Brc (a,a,a) [LOWTree a] deriving (Eq, Show, Read) ------------------------------------------------------------------------------ -- Finds the back edges for a given node. ------------------------------------------------------------------------------ getBackEdges :: Node -> [[(Node,Int)]] -> [(Node,Int)] getBackEdges _ [] = [] getBackEdges v ls = map head (filter (elem (v,0)) (tail ls)) ------------------------------------------------------------------------------ -- Builds a DFS tree for a given graph. Each element (v,n,b) in the tree -- contains: the node number v, the DFS number n, and a list of backedges b. ------------------------------------------------------------------------------ dfsTree :: (Graph gr) => Int -> Node -> [Node] -> [[(Node,Int)]] -> gr a b -> ([DFSTree Int],gr a b,Int) dfsTree n _ [] _ g = ([],g,n) dfsTree n _ _ _ g | isEmpty g = ([],g,n) dfsTree n u (v:vs) ls g = case match v g of (Nothing, g1) -> dfsTree n u vs ls g1 (Just c , g1) -> (B (v,n+1,bck) ts:ts', g3, k) where bck = getBackEdges v ls (ts, g2,m) = dfsTree (n+1) v sc ls' g1 (ts',g3,k) = dfsTree m v vs ls g2 ls' = ((v,n+1):sc'):ls sc' = map (\x->(x,0)) sc sc = suc' c ------------------------------------------------------------------------------ -- Finds the minimum between a dfs number and a list of back edges' dfs -- numbers. ------------------------------------------------------------------------------ minbckEdge :: Int -> [(Node,Int)] -> Int minbckEdge n [] = n minbckEdge n bs = min n (minimum (map snd bs)) ------------------------------------------------------------------------------ -- Returns the low number for a node in a subtree. ------------------------------------------------------------------------------ getLow :: LOWTree Int -> Int getLow (Brc (_,_,l) _) = l ------------------------------------------------------------------------------ -- Builds a low tree from a DFS tree. Each element (v,n,low) in the tree -- contains: the node number v, the DFS number n, and the low number low. ------------------------------------------------------------------------------ lowTree :: DFSTree Int -> LOWTree Int lowTree (B (v,n,[] ) [] ) = Brc (v,n,n) [] lowTree (B (v,n,bcks) [] ) = Brc (v,n,minbckEdge n bcks) [] lowTree (B (v,n,bcks) trs) = Brc (v,n,lowv) ts where lowv = min (minbckEdge n bcks) lowChild lowChild = minimum (map getLow ts) ts = map lowTree trs ------------------------------------------------------------------------------ -- Builds a low tree for a given graph. Each element (v,n,low) in the tree -- contains: the node number v, the DFS number n, and the low number low. ------------------------------------------------------------------------------ getLowTree :: (Graph gr) => gr a b -> Node -> LOWTree Int getLowTree g v = lowTree (head dfsf) where (dfsf, _, _) = dfsTree 0 0 [v] [] g ------------------------------------------------------------------------------ -- Tests if a node in a subtree is an articulation point. An non-root node v -- is an articulation point iff there exists at least one child w of v such -- that lowNumber(w) >= dfsNumber(v). The root node is an articulation point -- iff it has two or more children. ------------------------------------------------------------------------------ isap :: LOWTree Int -> Bool isap (Brc (_,_,_) []) = False isap (Brc (_,1,_) ts) = length ts > 1 isap (Brc (_,n,_) ts) = not (null ch) where ch = filter ( >=n) (map getLow ts) ------------------------------------------------------------------------------ -- Finds the articulation points by traversing the low tree. ------------------------------------------------------------------------------ arp :: LOWTree Int -> [Node] arp (Brc (v,1,_) ts) | length ts > 1 = v:concatMap arp ts | otherwise = concatMap arp ts arp (Brc (v,n,l) ts) | isap (Brc (v,n,l) ts) = v:concatMap arp ts | otherwise = concatMap arp ts ------------------------------------------------------------------------------ -- Finds the articulation points of a graph starting at a given node. ------------------------------------------------------------------------------ artpoints :: (Graph gr) => gr a b -> Node -> [Node] artpoints g v = arp (getLowTree g v) {-| Finds the articulation points for a connected undirected graph, by using the low numbers criteria: a) The root node is an articulation point iff it has two or more children. b) An non-root node v is an articulation point iff there exists at least one child w of v such that lowNumber(w) >= dfsNumber(v). -} ap :: (Graph gr) => gr a b -> [Node] ap g = artpoints g v where ((_,v,_,_),_) = matchAny g
antalsz/hs-to-coq
examples/graph/graph/Data/Graph/Inductive/Query/ArtPoint.hs
mit
6,167
0
14
1,410
1,391
768
623
52
2
{-# LANGUAGE RecordWildCards #-} -- | Statsd reporting. module Pos.Infra.Reporting.Statsd ( withStatsd ) where import Universum import Control.Concurrent (killThread) import Pos.Infra.Statistics (StatsdParams (..)) import qualified System.Metrics as Metrics import qualified System.Remote.Monitoring.Statsd as Monitoring withStatsd :: StatsdParams -> Metrics.Store -> IO t -> IO t withStatsd StatsdParams {..} ekgStore act = bracket acquire release (const act) where acquire = liftIO $ Monitoring.forkStatsd statsdOptions ekgStore release = liftIO . killThread . Monitoring.statsdThreadId statsdOptions = Monitoring.defaultStatsdOptions { Monitoring.host = statsdHost , Monitoring.port = statsdPort , Monitoring.flushInterval = statsdInterval , Monitoring.debug = statsdDebug , Monitoring.prefix = statsdPrefix , Monitoring.suffix = statsdSuffix }
input-output-hk/pos-haskell-prototype
infra/src/Pos/Infra/Reporting/Statsd.hs
mit
978
0
9
228
207
122
85
23
1
module Sieve where main = take 3000 (sieve [2..]) sieve (x:xs) = x : sieve (filter (nietVeelvoud x) xs) nietVeelvoud x y = y `mod` x /= 0 {- [/cygdrive/c/docs/helium/helium/demo] time heliumc Sieve.hs Compiling Sieve.hs (3,1): Missing type signature: main :: [Int] (5,1): Missing type signature: sieve :: [Int] -> [Int] (9,1): Missing type signature: nietVeelvoud :: Int -> Int -> Bool Compilation succesful with 3 warnings real 0m2.234s user 0m0.010s sys 0m0.010s real 0m10.685s user 0m0.010s sys 0m0.010s [/cygdrive/c/docs/helium/helium/demo] time lvmrun Sieve LVMfile 13676 bytes -- Splitsing HeliumLang en PreludePrim [/cygdrive/c/docs/helium/helium/demo] time heliumc -b Sieve.hs Compiling Sieve.hs (3,1): Missing type signature: main :: [Int] (5,1): Missing type signature: sieve :: [Int] -> [Int] (9,1): Missing type signature: nietVeelvoud :: Int -> Int -> Bool Compilation succesful with 3 warnings real 0m1.653s user 0m0.010s sys 0m0.010s LVMfile 11.724 bytes [/cygdrive/c/docs/helium/helium/demo] time heliumc -b Sieve.hs Compiling Sieve.hs (3,1): Missing type signature: main :: [Int] (5,1): Missing type signature: sieve :: [Int] -> [Int] (9,1): Missing type signature: nietVeelvoud :: Int -> Int -> Bool Compilation succesful with 3 warnings real 0m1.672s user 0m0.010s sys 0m0.010s real 0m10.165s real 9.644s ! -}
roberth/uu-helium
demo/Sieve.hs
gpl-3.0
1,404
0
10
265
80
43
37
6
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CodeDeploy.UpdateDeploymentGroup -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Changes information about an existing deployment group. -- -- /See:/ <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_UpdateDeploymentGroup.html AWS API Reference> for UpdateDeploymentGroup. module Network.AWS.CodeDeploy.UpdateDeploymentGroup ( -- * Creating a Request updateDeploymentGroup , UpdateDeploymentGroup -- * Request Lenses , udgServiceRoleARN , udgDeploymentConfigName , udgNewDeploymentGroupName , udgEc2TagFilters , udgOnPremisesInstanceTagFilters , udgAutoScalingGroups , udgApplicationName , udgCurrentDeploymentGroupName -- * Destructuring the Response , updateDeploymentGroupResponse , UpdateDeploymentGroupResponse -- * Response Lenses , udgrsHooksNotCleanedUp , udgrsResponseStatus ) where import Network.AWS.CodeDeploy.Types import Network.AWS.CodeDeploy.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents the input of an update deployment group operation. -- -- /See:/ 'updateDeploymentGroup' smart constructor. data UpdateDeploymentGroup = UpdateDeploymentGroup' { _udgServiceRoleARN :: !(Maybe Text) , _udgDeploymentConfigName :: !(Maybe Text) , _udgNewDeploymentGroupName :: !(Maybe Text) , _udgEc2TagFilters :: !(Maybe [EC2TagFilter]) , _udgOnPremisesInstanceTagFilters :: !(Maybe [TagFilter]) , _udgAutoScalingGroups :: !(Maybe [Text]) , _udgApplicationName :: !Text , _udgCurrentDeploymentGroupName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateDeploymentGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udgServiceRoleARN' -- -- * 'udgDeploymentConfigName' -- -- * 'udgNewDeploymentGroupName' -- -- * 'udgEc2TagFilters' -- -- * 'udgOnPremisesInstanceTagFilters' -- -- * 'udgAutoScalingGroups' -- -- * 'udgApplicationName' -- -- * 'udgCurrentDeploymentGroupName' updateDeploymentGroup :: Text -- ^ 'udgApplicationName' -> Text -- ^ 'udgCurrentDeploymentGroupName' -> UpdateDeploymentGroup updateDeploymentGroup pApplicationName_ pCurrentDeploymentGroupName_ = UpdateDeploymentGroup' { _udgServiceRoleARN = Nothing , _udgDeploymentConfigName = Nothing , _udgNewDeploymentGroupName = Nothing , _udgEc2TagFilters = Nothing , _udgOnPremisesInstanceTagFilters = Nothing , _udgAutoScalingGroups = Nothing , _udgApplicationName = pApplicationName_ , _udgCurrentDeploymentGroupName = pCurrentDeploymentGroupName_ } -- | A replacement service role\'s ARN, if you want to change it. udgServiceRoleARN :: Lens' UpdateDeploymentGroup (Maybe Text) udgServiceRoleARN = lens _udgServiceRoleARN (\ s a -> s{_udgServiceRoleARN = a}); -- | The replacement deployment configuration name to use, if you want to -- change it. udgDeploymentConfigName :: Lens' UpdateDeploymentGroup (Maybe Text) udgDeploymentConfigName = lens _udgDeploymentConfigName (\ s a -> s{_udgDeploymentConfigName = a}); -- | The new name of the deployment group, if you want to change it. udgNewDeploymentGroupName :: Lens' UpdateDeploymentGroup (Maybe Text) udgNewDeploymentGroupName = lens _udgNewDeploymentGroupName (\ s a -> s{_udgNewDeploymentGroupName = a}); -- | The replacement set of Amazon EC2 tags to filter on, if you want to -- change them. udgEc2TagFilters :: Lens' UpdateDeploymentGroup [EC2TagFilter] udgEc2TagFilters = lens _udgEc2TagFilters (\ s a -> s{_udgEc2TagFilters = a}) . _Default . _Coerce; -- | The replacement set of on-premises instance tags for filter on, if you -- want to change them. udgOnPremisesInstanceTagFilters :: Lens' UpdateDeploymentGroup [TagFilter] udgOnPremisesInstanceTagFilters = lens _udgOnPremisesInstanceTagFilters (\ s a -> s{_udgOnPremisesInstanceTagFilters = a}) . _Default . _Coerce; -- | The replacement list of Auto Scaling groups to be included in the -- deployment group, if you want to change them. udgAutoScalingGroups :: Lens' UpdateDeploymentGroup [Text] udgAutoScalingGroups = lens _udgAutoScalingGroups (\ s a -> s{_udgAutoScalingGroups = a}) . _Default . _Coerce; -- | The application name corresponding to the deployment group to update. udgApplicationName :: Lens' UpdateDeploymentGroup Text udgApplicationName = lens _udgApplicationName (\ s a -> s{_udgApplicationName = a}); -- | The current name of the existing deployment group. udgCurrentDeploymentGroupName :: Lens' UpdateDeploymentGroup Text udgCurrentDeploymentGroupName = lens _udgCurrentDeploymentGroupName (\ s a -> s{_udgCurrentDeploymentGroupName = a}); instance AWSRequest UpdateDeploymentGroup where type Rs UpdateDeploymentGroup = UpdateDeploymentGroupResponse request = postJSON codeDeploy response = receiveJSON (\ s h x -> UpdateDeploymentGroupResponse' <$> (x .?> "hooksNotCleanedUp" .!@ mempty) <*> (pure (fromEnum s))) instance ToHeaders UpdateDeploymentGroup where toHeaders = const (mconcat ["X-Amz-Target" =# ("CodeDeploy_20141006.UpdateDeploymentGroup" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON UpdateDeploymentGroup where toJSON UpdateDeploymentGroup'{..} = object (catMaybes [("serviceRoleArn" .=) <$> _udgServiceRoleARN, ("deploymentConfigName" .=) <$> _udgDeploymentConfigName, ("newDeploymentGroupName" .=) <$> _udgNewDeploymentGroupName, ("ec2TagFilters" .=) <$> _udgEc2TagFilters, ("onPremisesInstanceTagFilters" .=) <$> _udgOnPremisesInstanceTagFilters, ("autoScalingGroups" .=) <$> _udgAutoScalingGroups, Just ("applicationName" .= _udgApplicationName), Just ("currentDeploymentGroupName" .= _udgCurrentDeploymentGroupName)]) instance ToPath UpdateDeploymentGroup where toPath = const "/" instance ToQuery UpdateDeploymentGroup where toQuery = const mempty -- | Represents the output of an update deployment group operation. -- -- /See:/ 'updateDeploymentGroupResponse' smart constructor. data UpdateDeploymentGroupResponse = UpdateDeploymentGroupResponse' { _udgrsHooksNotCleanedUp :: !(Maybe [AutoScalingGroup]) , _udgrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateDeploymentGroupResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udgrsHooksNotCleanedUp' -- -- * 'udgrsResponseStatus' updateDeploymentGroupResponse :: Int -- ^ 'udgrsResponseStatus' -> UpdateDeploymentGroupResponse updateDeploymentGroupResponse pResponseStatus_ = UpdateDeploymentGroupResponse' { _udgrsHooksNotCleanedUp = Nothing , _udgrsResponseStatus = pResponseStatus_ } -- | If the output contains no data, and the corresponding deployment group -- contained at least one Auto Scaling group, AWS CodeDeploy successfully -- removed all corresponding Auto Scaling lifecycle event hooks from the -- AWS account. If the output does contain data, AWS CodeDeploy could not -- remove some Auto Scaling lifecycle event hooks from the AWS account. udgrsHooksNotCleanedUp :: Lens' UpdateDeploymentGroupResponse [AutoScalingGroup] udgrsHooksNotCleanedUp = lens _udgrsHooksNotCleanedUp (\ s a -> s{_udgrsHooksNotCleanedUp = a}) . _Default . _Coerce; -- | The response status code. udgrsResponseStatus :: Lens' UpdateDeploymentGroupResponse Int udgrsResponseStatus = lens _udgrsResponseStatus (\ s a -> s{_udgrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/UpdateDeploymentGroup.hs
mpl-2.0
8,816
0
13
1,828
1,193
712
481
144
1
{- Copyright 2016 Markus Ongyerth This file is part of Monky. Monky is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Monky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Monky. If not, see <http://www.gnu.org/licenses/>. -} {-| Module : Monky.Examples.Plain Description: Print some constant values Maintainer: ongy Stability: testing Portability: linux -} module Monky.Examples.Plain ( MonkyList(..) , getPlain ) where import Monky.Modules -- |The type for this functionality newtype MonkyList = MonkyList [MonkyOut] instance PollModule MonkyList where getOutput (MonkyList x) = return x instance EvtModule MonkyList where startEvtLoop (MonkyList xs) a = a xs -- |Get a 'MonkyList' for familiar syntax getPlain :: [MonkyOut] -> IO MonkyList getPlain = return . MonkyList
monky-hs/monky
Monky/Examples/Plain.hs
lgpl-3.0
1,289
0
8
256
115
65
50
11
1
module Futhark.Optimise.AlgSimplifyTests ( tests ) where import Test.HUnit hiding (Test) import Test.Framework import Test.Framework.Providers.HUnit import Data.List import qualified Data.HashMap.Lazy as HM import qualified Data.Map as M import Futhark.Representation.AST import Futhark.Analysis.ScalExp import Futhark.Analysis.ScalExpTests (parseScalExp') import Futhark.Analysis.AlgSimplify tests :: [Test] tests = constantFoldTests ++ suffCondTests constantFoldTests :: [Test] constantFoldTests = [ cfoldTest "2+2" "4" , cfoldTest "2-2" "0" , cfoldTest "2*3" "6" , cfoldTest "6/3" "2" -- Simple cases over; let's try some variables. , cfoldTest "0+x" "x" , cfoldTest "x+x" "2*x" -- Sensitive to operand order , cfoldTest "x-0" "x" , cfoldTest "x-x" "0" , cfoldTest "x/x" "1" , cfoldTest "x/1" "x" , cfoldTest "x/x" "1" ] where vars = declareVars [("x", int32)] simplify'' e = simplify' vars e [] scalExp = parseScalExp' vars cfoldTest input expected = testCase ("constant-fold " ++ input) $ simplify'' input @?= scalExp expected suffCondTests :: [Test] suffCondTests = [ suffCondTest "5<n" [["False"]] , suffCondTest "0 <= i && i <= n-1" [["True"]] , suffCondTest "i-(m-1) <= 0" [["9<m"]] ] where suffsort = sort . map sort simplify'' e = simplify' vars e ranges suffCondTest input expected = testCase ("sufficient conditions for " ++ input) $ suffsort (mkSuffConds' vars input ranges) @?= suffsort (map (map simplify'') expected) vars = declareVars [ ("n", int32) , ("m", int32) , ("i", int32) ] ranges = [ ("n", "10", "10") , ("i", "0", "9") ] type RangesRep' = [(String, String, String)] type VarDecls = [(String, PrimType)] type VarInfo = M.Map String (Int, Type) lookupVarName :: String -> VarInfo -> VName lookupVarName s varinfo = case M.lookup s varinfo of Nothing -> error $ "Unknown variable " ++ s Just (x,_) -> ID (nameFromString s, x) declareVars :: VarDecls -> VarInfo declareVars = M.fromList . snd . mapAccumL declare 0 where declare i (name, t) = (i+1, (name, (i, Prim t))) instantiateRanges :: VarInfo -> RangesRep' -> RangesRep instantiateRanges varinfo r = HM.fromList $ snd $ mapAccumL fix 0 r where fix i (name, lower,upper) = (i+1, (lookupVarName name varinfo, (i, fixBound lower, fixBound upper))) fixBound "" = Nothing fixBound s = Just $ parseScalExp' varinfo s simplify' :: VarInfo -> String -> RangesRep' -> ScalExp simplify' varinfo s r = simplify e r' where e = parseScalExp' varinfo s r' = instantiateRanges varinfo r mkSuffConds' :: VarInfo -> String -> RangesRep' -> [[ScalExp]] mkSuffConds' varinfo s r = case mkSuffConds e r' of Left _ -> [[e]] Right sc -> sc where e = simplify (parseScalExp' varinfo s) r' r' = instantiateRanges varinfo r
CulpaBS/wbBach
tests/Futhark/Optimise/AlgSimplifyTests.hs
bsd-3-clause
3,055
0
12
790
965
529
436
79
2
class Functor (BackendScore) => HasBackend where type BackendMusic :: * type BackendNote :: * type BackendScore :: * -> * type BackendContext :: * -> * finalizeExport :: -> BackendScore (BackendNote) -> BackendMusic class (HasBackend) => HasBackendScore s where type BackendScoreEvent s :: * -- BackendScoreEvent a = a -- LyScore a = Chord (Voice (Chord a)) -- TODO aspects should not be in *context* (passed to note) -- They should be given directly to finalize -- ALTERNATIVELY actually pass context (i.e. Ctxt) in BackendContext (what does this mean?) -- LyContext a = (LyPitch = Int, LyArt = (Double x 2), LyDyn = Double, a) exportScore :: -> s -> BackendScore (BackendContext (BackendScoreEvent s)) class (HasBackend) => HasBackendNote a where exportNote :: -> BackendContext a -> BackendNote exportChord :: -> BackendContext [a] -> BackendNote exportChord = error "Not implemented: exportChord" export :: (HasBackendScore s, HasBackendNote (BackendScoreEvent s)) => -> s -> BackendMusic export = finalizeExport . fmap (exportNote) . exportScore b
FranklinChen/music-score
sketch/old/NewExport.hs
bsd-3-clause
1,099
5
12
207
231
125
106
-1
-1
#include "../Prelude.hs" safer x d q = x /= q && x /= q+d && x /= q-d
osa1/chsc
examples/imaginary/Queens-Safer.hs
bsd-3-clause
71
0
11
19
42
21
21
1
1
module Text.HTML.TagSoup.Development.ParserUtils (PState, Parser, Pick, runParser ,(&), (|->), cons, nil, pick ,nullS, headS, tailS ,dropS, spanS, dropWhileS ,spanEndS ) where import Data.List infix 2 |-> infix 3 & --------------------------------------------------------------------- -- DATA TYPES data PState = PState {text :: String, row :: !Int, col :: !Int} type Parser a = PState -> a type Pick a = Parser (Maybe a) runParser :: Parser a -> String -> a runParser p s = p (PState s 1 1) --------------------------------------------------------------------- -- PARSER COMBINATORS {-# INLINE (&) #-} {-# INLINE (|->) #-} {-# INLINE cons #-} {-# INLINE nil #-} {-# INLINE pick #-} (&) :: Parser a -> (a -> b) -> Parser b (&) p f s = f (p s) (|->) :: String -> Parser a -> Pick a (|->) t p s | t `isPrefixOf` text s = Just $ p $ dropS (length t) s | otherwise = Nothing cons :: (Char -> PState -> a) -> Pick a cons f s | not $ nullS s = Just $ f (headS s) (tailS s) cons f _ = Nothing nil :: a -> Pick a nil r s | nullS s = Just r nil r _ = Nothing pick :: [Pick a] -> Parser a pick (x:xs) s = case x s of Nothing -> pick xs s Just y -> y pick _ s = error "No pick alternatives matched" --------------------------------------------------------------------- -- STATE COMBINATORS update x xs r c = case x of '\n' -> PState xs (r+1) 1 '\t' -> PState xs r (c + 8 - mod (c-1) 8) _ -> PState xs r (c+1) nullS :: PState -> Bool nullS = null . text tailS :: PState -> PState tailS (PState (x:xs) r c) = update x xs r c headS :: PState -> Char headS = head . text dropS :: Int -> PState -> PState dropS n (PState (x:xs) r c) | n > 0 = dropS (n-1) (update x xs r c) dropS n s = s spanS :: (Char -> Bool) -> PState -> (String, PState) spanS f (PState (x:xs) r c) | f x = (x:a, b) where (a,b) = spanS f $ update x xs r c spanS f s = ("", s) dropWhileS :: (Char -> Bool) -> PState -> PState dropWhileS f (PState (x:xs) r c) | f x = dropWhileS f $ update x xs r c dropWhileS f s = s -- keep reading until you reach some end text -- (x,y,True ) = spanEnd t s ==> s == x ++ t ++ y -- (x,y,False) = spanEnd t s ==> s == x && y == "" spanEndS :: String -> PState -> (String, PState, Bool) spanEndS t s@(PState xs r c) | t `isPrefixOf` xs = ("", dropS (length t) s, True) spanEndS t s@(PState [] r c) = ("", s, False) spanEndS t s@(PState (x:xs) r c) = (x:r1,r2,r3) where (r1,r2,r3) = spanEndS t $ update x xs r c
silkapp/tagsoup
dead/Old/Development/ParserUtils.hs
bsd-3-clause
2,542
0
13
647
1,156
613
543
64
3
module Main where import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Language import Text.ParserCombinators.Parsec.Pos import qualified Text.ParserCombinators.Parsec.Token as T import Data.Char import Data.List import Data.Maybe import System.IO.Unsafe main = do s <- getContents case (parse mainParser "stdin" s) of Left err -> putStrLn "Error: " >> print err Right hs -> putStrLn hs -- Try to parse HAML, otherwise re-output raw lines mainParser = do whiteSpace ls <- many1 (hamlCode <|> tilEOL) return $ unlines ls -- -- * HAML lexer -- hamlLexer = T.makeTokenParser emptyDef whiteSpace= T.whiteSpace hamlLexer lexeme = T.lexeme hamlLexer symbol = T.symbol hamlLexer natural = T.natural hamlLexer parens = T.parens hamlLexer semi = T.semi hamlLexer squares = T.squares hamlLexer stringLiteral= T.stringLiteral hamlLexer identifier= T.identifier hamlLexer reserved = T.reserved hamlLexer reservedOp= T.reservedOp hamlLexer commaSep1 = T.commaSep1 hamlLexer -- -- * Main HAML parsers -- -- hamlCode is just many identifiers followed by = followed by a hamlBlock -- f a b c = %somehaml hamlCode = try ( do is <- many1 identifier symbol "=" currentPos <- getPosition x <- manyTill1 (lexeme $ hamlBlock) (notSameIndent currentPos) return $ (concat $ intersperse " " is) ++ " = \n" ++ (concat $ (intersperse (indent currentPos ++ "+++\n") $ filter (not . null) $ x)) ) -- A Block may start with some whitespace, then has a valid bit of data hamlBlock = do currentPos <- getPosition bs <- manyTill1 (pTag <|> pText) (notSameIndent currentPos) return $ intercalate (indent currentPos ++ "+++\n") bs pTag = do currentPos <- getPosition try (do t <- lexeme tagParser ts <- (isInline currentPos >> char '/' >> return []) <|> (hamlBlock) return $ intercalate "\n" $ filter (not . null) $ [ (indent currentPos) ++ "((" ++ (if (null ts) then "i" else "") ++ t ++ ")" , if null ts then [] else ts , (indent currentPos) ++ ")\n"] ) pText = lexeme stringParser notSameIndent p = (eof >> return []) <|> (do innerPos <- getPosition case (sourceColumn p) == (sourceColumn innerPos) of True -> pzero False -> return [] ) -- -- * Various little parsers -- tagParser :: CharParser () String tagParser = do t <- optionMaybe tagParser' i <- optionMaybe idParser c <- optionMaybe (many1 classParser) a <- optionMaybe attributesParser if (isJust t || isJust i || isJust c || isJust a) then do return $ "tag \"" ++ (fromMaybe "div" t) ++ "\"" ++ (if not (isJust i || isJust c || isJust a) then "" else concat $ [ "![" , intercalate ", " $ filter (not . null) [ (maybe "" (\i' -> "strAttr \"id\" \"" ++ i' ++ "\"") i) , (maybe "" (\c' -> "strAttr \"class\" \"" ++ (intercalate " " c') ++ "\"") c) , (maybe "" (\kv -> intercalate ", " $ map (\(k,v) -> "strAttr \"" ++ k ++ "\" (" ++ v ++ ")") kv) a) ] , "]"] ) else pzero tagParser' :: CharParser () String tagParser' = do char '%' many1 termChar idParser :: CharParser () String idParser = do char '#' many1 termChar classParser :: CharParser () String classParser = do char '.' many1 termChar attributesParser :: CharParser () [(String, String)] attributesParser = squares (commaSep1 attributeParser) attributeParser :: CharParser () (String, String) attributeParser = do k <- identifier symbol "=" cs <- many1 identifier return (k, intercalate " " cs) stringParser :: CharParser () String stringParser = do currentPos <- getPosition modifier <- optionMaybe (char '=' <|> char '-') whiteSpace c <- alphaNum cs<- tilEOL case modifier of Just '-' -> return $ (indent currentPos) ++ "-" ++ c:cs Just '=' -> return $ (indent currentPos) ++ "(stringToHtml " ++ c:cs ++ ")" Nothing -> return $ (indent currentPos) ++ "(stringToHtml \"" ++ c:cs ++ "\")" -- -- * Utility functions -- isInline p = do p2 <- getPosition case (sourceLine p ) == (sourceLine p2) of True -> return [] False -> pzero isSameIndent p1 p2 = (sourceColumn p1) == (sourceColumn p2) tilEOL = manyTill1 (noneOf "\n") eol eol = newline <|> (eof >> return '\n') termChar = satisfy (\c -> (isAlphaNum c) || (c `elem` termPunctuation) ) termPunctuation = "-_" indent p = take (sourceColumn (p) - 1) (repeat ' ') manyTill1 p e = do ms <- manyTill p e case (null ms) of True -> pzero False -> return ms
abuiles/turbinado-blog
Turbinado/View/HAML/trhaml.hs
bsd-3-clause
6,065
0
29
2,571
1,645
824
821
114
3
--command line parsing, i.e. here the executable loop should be defined
eugenkiss/loopgotowhile
src/Language/LoopGotoWhile/While/CLTool.hs
bsd-3-clause
72
0
2
11
3
2
1
1
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NoMonoLocalBinds #-} {-# LANGUAGE NondecreasingIndentation #-} -- | See <https://github.com/ezyang/ghc-proposals/blob/backpack/proposals/0000-backpack.rst> -- -- WARNING: The contents of this module are HIGHLY experimental. -- We may refactor it under you. module Distribution.Backpack.Configure ( configureComponentLocalBuildInfos, ) where import Prelude () import Distribution.Compat.Prelude hiding ((<>)) import Distribution.Backpack import Distribution.Backpack.FullUnitId import Distribution.Backpack.PreExistingComponent import Distribution.Backpack.ConfiguredComponent import Distribution.Backpack.LinkedComponent import Distribution.Backpack.ReadyComponent import Distribution.Backpack.ComponentsGraph import Distribution.Backpack.Id import Distribution.Simple.Compiler hiding (Flag) import Distribution.Package import qualified Distribution.InstalledPackageInfo as Installed import Distribution.InstalledPackageInfo (InstalledPackageInfo ,emptyInstalledPackageInfo) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (InstalledPackageIndex) import Distribution.PackageDescription as PD hiding (Flag) import Distribution.ModuleName import Distribution.Simple.Setup as Setup import Distribution.Simple.LocalBuildInfo import Distribution.Types.AnnotatedId import Distribution.Types.ComponentRequestedSpec import Distribution.Types.ComponentInclude import Distribution.Verbosity import qualified Distribution.Compat.Graph as Graph import Distribution.Compat.Graph (Graph, IsNode(..)) import Distribution.Utils.LogProgress import Data.Either ( lefts ) import qualified Data.Set as Set import qualified Data.Map as Map import Distribution.Text import Text.PrettyPrint ------------------------------------------------------------------------------ -- Pipeline ------------------------------------------------------------------------------ configureComponentLocalBuildInfos :: Verbosity -> Bool -- use_external_internal_deps -> ComponentRequestedSpec -> Bool -- deterministic -> Flag String -- configIPID -> Flag ComponentId -- configCID -> PackageDescription -> [PreExistingComponent] -> FlagAssignment -- configConfigurationsFlags -> [(ModuleName, Module)] -- configInstantiateWith -> InstalledPackageIndex -> Compiler -> LogProgress ([ComponentLocalBuildInfo], InstalledPackageIndex) configureComponentLocalBuildInfos verbosity use_external_internal_deps enabled deterministic ipid_flag cid_flag pkg_descr prePkgDeps flagAssignment instantiate_with installedPackageSet comp = do -- NB: In single component mode, this returns a *single* component. -- In this graph, the graph is NOT closed. graph0 <- case mkComponentsGraph enabled pkg_descr of Left ccycle -> dieProgress (componentCycleMsg ccycle) Right g -> return (componentsGraphToList g) infoProgress $ hang (text "Source component graph:") 4 (dispComponentsWithDeps graph0) let conf_pkg_map = Map.fromListWith Map.union [(pc_pkgname pkg, Map.singleton (pc_compname pkg) (AnnotatedId { ann_id = pc_cid pkg, ann_pid = packageId pkg, ann_cname = pc_compname pkg })) | pkg <- prePkgDeps] graph1 <- toConfiguredComponents use_external_internal_deps flagAssignment deterministic ipid_flag cid_flag pkg_descr conf_pkg_map (map fst graph0) infoProgress $ hang (text "Configured component graph:") 4 (vcat (map dispConfiguredComponent graph1)) let shape_pkg_map = Map.fromList [ (pc_cid pkg, (pc_open_uid pkg, pc_shape pkg)) | pkg <- prePkgDeps] uid_lookup def_uid | Just pkg <- PackageIndex.lookupUnitId installedPackageSet uid = FullUnitId (Installed.installedComponentId pkg) (Map.fromList (Installed.instantiatedWith pkg)) | otherwise = error ("uid_lookup: " ++ display uid) where uid = unDefUnitId def_uid graph2 <- toLinkedComponents verbosity uid_lookup (package pkg_descr) shape_pkg_map graph1 infoProgress $ hang (text "Linked component graph:") 4 (vcat (map dispLinkedComponent graph2)) let pid_map = Map.fromList $ [ (pc_uid pkg, pc_munged_id pkg) | pkg <- prePkgDeps] ++ [ (Installed.installedUnitId pkg, mungedId pkg) | (_, Module uid _) <- instantiate_with , Just pkg <- [PackageIndex.lookupUnitId installedPackageSet (unDefUnitId uid)] ] subst = Map.fromList instantiate_with graph3 = toReadyComponents pid_map subst graph2 graph4 = Graph.revTopSort (Graph.fromDistinctList graph3) infoProgress $ hang (text "Ready component graph:") 4 (vcat (map dispReadyComponent graph4)) toComponentLocalBuildInfos comp installedPackageSet pkg_descr prePkgDeps graph4 ------------------------------------------------------------------------------ -- ComponentLocalBuildInfo ------------------------------------------------------------------------------ toComponentLocalBuildInfos :: Compiler -> InstalledPackageIndex -- FULL set -> PackageDescription -> [PreExistingComponent] -- external package deps -> [ReadyComponent] -> LogProgress ([ComponentLocalBuildInfo], InstalledPackageIndex) -- only relevant packages toComponentLocalBuildInfos comp installedPackageSet pkg_descr externalPkgDeps graph = do -- Check and make sure that every instantiated component exists. -- We have to do this now, because prior to linking/instantiating -- we don't actually know what the full set of 'UnitId's we need -- are. let -- TODO: This is actually a bit questionable performance-wise, -- since we will pay for the ALL installed packages even if -- they are not related to what we are building. This was true -- in the old configure code. external_graph :: Graph (Either InstalledPackageInfo ReadyComponent) external_graph = Graph.fromDistinctList . map Left $ PackageIndex.allPackages installedPackageSet internal_graph :: Graph (Either InstalledPackageInfo ReadyComponent) internal_graph = Graph.fromDistinctList . map Right $ graph combined_graph = Graph.unionRight external_graph internal_graph Just local_graph = Graph.closure combined_graph (map nodeKey graph) -- The database of transitively reachable installed packages that the -- external components the package (as a whole) depends on. This will be -- used in several ways: -- -- * We'll use it to do a consistency check so we're not depending -- on multiple versions of the same package (TODO: someday relax -- this for private dependencies.) See right below. -- -- * We'll pass it on in the LocalBuildInfo, where preprocessors -- and other things will incorrectly use it to determine what -- the include paths and everything should be. -- packageDependsIndex = PackageIndex.fromList (lefts local_graph) fullIndex = Graph.fromDistinctList local_graph case Graph.broken fullIndex of [] -> return () broken -> -- TODO: ppr this dieProgress . text $ "The following packages are broken because other" ++ " packages they depend on are missing. These broken " ++ "packages must be rebuilt before they can be used.\n" -- TODO: Undupe. ++ unlines [ "installed package " ++ display (packageId pkg) ++ " is broken due to missing package " ++ intercalate ", " (map display deps) | (Left pkg, deps) <- broken ] ++ unlines [ "planned package " ++ display (packageId pkg) ++ " is broken due to missing package " ++ intercalate ", " (map display deps) | (Right pkg, deps) <- broken ] -- In this section, we'd like to look at the 'packageDependsIndex' -- and see if we've picked multiple versions of the same -- installed package (this is bad, because it means you might -- get an error could not match foo-0.1:Type with foo-0.2:Type). -- -- What is pseudoTopPkg for? I have no idea. It was used -- in the very original commit which introduced checking for -- inconsistencies 5115bb2be4e13841ea07dc9166b9d9afa5f0d012, -- and then moved out of PackageIndex and put here later. -- TODO: Try this code without it... -- -- TODO: Move this into a helper function -- -- TODO: This is probably wrong for Backpack let pseudoTopPkg :: InstalledPackageInfo pseudoTopPkg = emptyInstalledPackageInfo { Installed.installedUnitId = mkLegacyUnitId (packageId pkg_descr), Installed.sourcePackageId = packageId pkg_descr, Installed.depends = map pc_uid externalPkgDeps } case PackageIndex.dependencyInconsistencies . PackageIndex.insert pseudoTopPkg $ packageDependsIndex of [] -> return () inconsistencies -> warnProgress $ hang (text "This package indirectly depends on multiple versions of the same" <+> text "package. This is very likely to cause a compile failure.") 2 (vcat [ text "package" <+> disp (packageName user) <+> parens (disp (installedUnitId user)) <+> text "requires" <+> disp inst | (_dep_key, insts) <- inconsistencies , (inst, users) <- insts , user <- users ]) let clbis = mkLinkedComponentsLocalBuildInfo comp graph -- forM clbis $ \(clbi,deps) -> info verbosity $ "UNIT" ++ hashUnitId (componentUnitId clbi) ++ "\n" ++ intercalate "\n" (map hashUnitId deps) return (clbis, packageDependsIndex) -- Build ComponentLocalBuildInfo for each component we are going -- to build. -- -- This conversion is lossy; we lose some invariants from ReadyComponent mkLinkedComponentsLocalBuildInfo :: Compiler -> [ReadyComponent] -> [ComponentLocalBuildInfo] mkLinkedComponentsLocalBuildInfo comp rcs = map go rcs where internalUnits = Set.fromList (map rc_uid rcs) isInternal x = Set.member x internalUnits go rc = case rc_component rc of CLib lib -> let convModuleExport (modname', (Module uid modname)) | this_uid == unDefUnitId uid , modname' == modname = Installed.ExposedModule modname' Nothing | otherwise = Installed.ExposedModule modname' (Just (OpenModule (DefiniteUnitId uid) modname)) convOpenModuleExport (modname', modu@(OpenModule uid modname)) | uid == this_open_uid , modname' == modname = Installed.ExposedModule modname' Nothing | otherwise = Installed.ExposedModule modname' (Just modu) convOpenModuleExport (_, OpenModuleVar _) = error "convOpenModuleExport: top-level modvar" exports = -- Loses invariants case rc_i rc of Left indefc -> map convOpenModuleExport $ Map.toList (indefc_provides indefc) Right instc -> map convModuleExport $ Map.toList (instc_provides instc) insts = case rc_i rc of Left indefc -> [ (m, OpenModuleVar m) | m <- indefc_requires indefc ] Right instc -> [ (m, OpenModule (DefiniteUnitId uid') m') | (m, Module uid' m') <- instc_insts instc ] compat_name = computeCompatPackageName (packageName rc) (libName lib) compat_key = computeCompatPackageKey comp compat_name (packageVersion rc) this_uid in LibComponentLocalBuildInfo { componentPackageDeps = cpds, componentUnitId = this_uid, componentComponentId = this_cid, componentInstantiatedWith = insts, componentIsIndefinite_ = is_indefinite, componentLocalName = cname, componentInternalDeps = internal_deps, componentExeDeps = exe_deps, componentIncludes = includes, componentExposedModules = exports, componentIsPublic = rc_public rc, componentCompatPackageKey = compat_key, componentCompatPackageName = compat_name } CFLib _ -> FLibComponentLocalBuildInfo { componentUnitId = this_uid, componentComponentId = this_cid, componentLocalName = cname, componentPackageDeps = cpds, componentExeDeps = exe_deps, componentInternalDeps = internal_deps, componentIncludes = includes } CExe _ -> ExeComponentLocalBuildInfo { componentUnitId = this_uid, componentComponentId = this_cid, componentLocalName = cname, componentPackageDeps = cpds, componentExeDeps = exe_deps, componentInternalDeps = internal_deps, componentIncludes = includes } CTest _ -> TestComponentLocalBuildInfo { componentUnitId = this_uid, componentComponentId = this_cid, componentLocalName = cname, componentPackageDeps = cpds, componentExeDeps = exe_deps, componentInternalDeps = internal_deps, componentIncludes = includes } CBench _ -> BenchComponentLocalBuildInfo { componentUnitId = this_uid, componentComponentId = this_cid, componentLocalName = cname, componentPackageDeps = cpds, componentExeDeps = exe_deps, componentInternalDeps = internal_deps, componentIncludes = includes } where this_uid = rc_uid rc this_open_uid = rc_open_uid rc this_cid = rc_cid rc cname = componentName (rc_component rc) cpds = rc_depends rc exe_deps = map ann_id $ rc_exe_deps rc is_indefinite = case rc_i rc of Left _ -> True Right _ -> False includes = map (\ci -> (ci_id ci, ci_renaming ci)) $ case rc_i rc of Left indefc -> indefc_includes indefc Right instc -> map (\ci -> ci { ci_ann_id = fmap DefiniteUnitId (ci_ann_id ci) }) (instc_includes instc) internal_deps = filter isInternal (nodeNeighbors rc)
themoritz/cabal
Cabal/Distribution/Backpack/Configure.hs
bsd-3-clause
15,617
0
22
4,619
2,650
1,423
1,227
275
10
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[TcMonoType]{Typechecking user-specified @MonoTypes@} -} {-# LANGUAGE CPP #-} module TcHsType ( tcHsSigType, tcHsDeriv, tcHsVectInst, tcHsInstHead, UserTypeCtxt(..), -- Type checking type and class decls kcLookupKind, kcTyClTyVars, tcTyClTyVars, tcHsConArgType, tcDataKindSig, tcClassSigType, -- Kind-checking types -- No kind generalisation, no checkValidType tcWildcardBinders, kcHsTyVarBndrs, tcHsTyVarBndrs, tcHsLiftedType, tcHsOpenType, tcLHsType, tcCheckLHsType, tcCheckLHsTypeAndGen, tcHsContext, tcInferApps, tcHsArgTys, kindGeneralize, checkKind, -- Sort-checking kinds tcLHsKind, -- Pattern type signatures tcHsPatSigType, tcPatSig ) where #include "HsVersions.h" import HsSyn import TcRnMonad import TcEvidence( HsWrapper ) import TcEnv import TcMType import TcValidity import TcUnify import TcIface import TcType import Type import TypeRep( Type(..) ) -- For the mkNakedXXX stuff import Kind import RdrName( lookupLocalRdrOcc ) import Var import VarSet import TyCon import ConLike import DataCon import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName ) import Class import Name import NameEnv import TysWiredIn import BasicTypes import SrcLoc import DynFlags ( ExtensionFlag( Opt_DataKinds ), getDynFlags ) import Constants ( mAX_CTUPLE_SIZE ) import ErrUtils( MsgDoc ) import Unique import UniqSupply import Outputable import FastString import Util import Data.Maybe( isNothing ) import Control.Monad ( unless, when, zipWithM ) import PrelNames( funTyConKey, allNameStrings ) {- ---------------------------- General notes ---------------------------- Generally speaking we now type-check types in three phases 1. kcHsType: kind check the HsType *includes* performing any TH type splices; so it returns a translated, and kind-annotated, type 2. dsHsType: convert from HsType to Type: perform zonking expand type synonyms [mkGenTyApps] hoist the foralls [tcHsType] 3. checkValidType: check the validity of the resulting type Often these steps are done one after the other (tcHsSigType). But in mutually recursive groups of type and class decls we do 1 kind-check the whole group 2 build TyCons/Classes in a knot-tied way 3 check the validity of types in the now-unknotted TyCons/Classes For example, when we find (forall a m. m a -> m a) we bind a,m to kind varibles and kind-check (m a -> m a). This makes a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in an environment that binds a and m suitably. The kind checker passed to tcHsTyVars needs to look at enough to establish the kind of the tyvar: * For a group of type and class decls, it's just the group, not the rest of the program * For a tyvar bound in a pattern type signature, its the types mentioned in the other type signatures in that bunch of patterns * For a tyvar bound in a RULE, it's the type signatures on other universally quantified variables in the rule Note that this may occasionally give surprising results. For example: data T a b = MkT (a b) Here we deduce a::*->*, b::* But equally valid would be a::(*->*)-> *, b::*->* Validity checking ~~~~~~~~~~~~~~~~~ Some of the validity check could in principle be done by the kind checker, but not all: - During desugaring, we normalise by expanding type synonyms. Only after this step can we check things like type-synonym saturation e.g. type T k = k Int type S a = a Then (T S) is ok, because T is saturated; (T S) expands to (S Int); and then S is saturated. This is a GHC extension. - Similarly, also a GHC extension, we look through synonyms before complaining about the form of a class or instance declaration - Ambiguity checks involve functional dependencies, and it's easier to wait until knots have been resolved before poking into them Also, in a mutually recursive group of types, we can't look at the TyCon until we've finished building the loop. So to keep things simple, we postpone most validity checking until step (3). Knot tying ~~~~~~~~~~ During step (1) we might fault in a TyCon defined in another module, and it might (via a loop) refer back to a TyCon defined in this module. So when we tie a big knot around type declarations with ARecThing, so that the fault-in code can get the TyCon being defined. ************************************************************************ * * Check types AND do validity checking * * ************************************************************************ -} tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type -- NB: it's important that the foralls that come from the top-level -- HsForAllTy in hs_ty occur *first* in the returned type. -- See Note [Scoped] with TcSigInfo tcHsSigType ctxt (L loc hs_ty) = setSrcSpan loc $ addErrCtxt (pprSigCtxt ctxt empty (ppr hs_ty)) $ do { kind <- case expectedKindInCtxt ctxt of Nothing -> newMetaKindVar Just k -> return k -- The kind is checked by checkValidType, and isn't necessarily -- of kind * in a Template Haskell quote eg [t| Maybe |] -- Generalise here: see Note [Kind generalisation] ; ty <- tcCheckHsTypeAndGen hs_ty kind -- Zonk to expose kind information to checkValidType ; ty <- zonkSigType ty ; checkValidType ctxt ty ; return ty } ----------------- tcHsInstHead :: UserTypeCtxt -> LHsType Name -> TcM ([TyVar], ThetaType, Class, [Type]) -- Like tcHsSigType, but for an instance head. tcHsInstHead user_ctxt lhs_ty@(L loc hs_ty) = setSrcSpan loc $ -- The "In the type..." context comes from the caller do { inst_ty <- tc_inst_head hs_ty ; kvs <- zonkTcTypeAndFV inst_ty ; kvs <- kindGeneralize kvs ; inst_ty <- zonkSigType (mkForAllTys kvs inst_ty) ; checkValidInstance user_ctxt lhs_ty inst_ty } tc_inst_head :: HsType Name -> TcM TcType tc_inst_head (HsForAllTy _ _ hs_tvs hs_ctxt hs_ty) = tcHsTyVarBndrs hs_tvs $ \ tvs -> do { ctxt <- tcHsContext hs_ctxt ; ty <- tc_lhs_type hs_ty ekConstraint -- Body for forall has kind Constraint ; return (mkSigmaTy tvs ctxt ty) } tc_inst_head hs_ty = tc_hs_type hs_ty ekConstraint ----------------- tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type], Kind) -- Like tcHsSigType, but for the ...deriving( C t1 ty2 ) clause -- Returns the C, [ty1, ty2, and the kind of C's *next* argument -- E.g. class C (a::*) (b::k->k) -- data T a b = ... deriving( C Int ) -- returns ([k], C, [k, Int], k->k) -- Also checks that (C ty1 ty2 arg) :: Constraint -- if arg has a suitable kind tcHsDeriv hs_ty = do { arg_kind <- newMetaKindVar ; ty <- tcCheckHsTypeAndGen hs_ty (mkArrowKind arg_kind constraintKind) ; ty <- zonkSigType ty ; arg_kind <- zonkSigType arg_kind ; let (tvs, pred) = splitForAllTys ty ; case getClassPredTys_maybe pred of Just (cls, tys) -> return (tvs, cls, tys, arg_kind) Nothing -> failWithTc (ptext (sLit "Illegal deriving item") <+> quotes (ppr hs_ty)) } -- Used for 'VECTORISE [SCALAR] instance' declarations -- tcHsVectInst :: LHsType Name -> TcM (Class, [Type]) tcHsVectInst ty | Just (L _ cls_name, tys) <- splitLHsClassTy_maybe ty = do { (cls, cls_kind) <- tcClass cls_name ; (arg_tys, _res_kind) <- tcInferApps cls_name cls_kind tys ; return (cls, arg_tys) } | otherwise = failWithTc $ ptext (sLit "Malformed instance type") {- These functions are used during knot-tying in type and class declarations, when we have to separate kind-checking, desugaring, and validity checking ************************************************************************ * * The main kind checker: no validity checks here * * ************************************************************************ First a couple of simple wrappers for kcHsType -} tcClassSigType :: LHsType Name -> TcM Type tcClassSigType lhs_ty = do { ty <- tcCheckLHsTypeAndGen lhs_ty liftedTypeKind ; zonkSigType ty } tcHsConArgType :: NewOrData -> LHsType Name -> TcM Type -- Permit a bang, but discard it tcHsConArgType NewType bty = tcHsLiftedType (getBangType bty) -- Newtypes can't have bangs, but we don't check that -- until checkValidDataCon, so do not want to crash here tcHsConArgType DataType bty = tcHsOpenType (getBangType bty) -- Can't allow an unlifted type for newtypes, because we're effectively -- going to remove the constructor while coercing it to a lifted type. -- And newtypes can't be bang'd --------------------------- tcHsArgTys :: SDoc -> [LHsType Name] -> [Kind] -> TcM [TcType] tcHsArgTys what tys kinds = sequence [ addTypeCtxt ty $ tc_lhs_type ty (expArgKind what kind n) | (ty,kind,n) <- zip3 tys kinds [1..] ] tc_hs_arg_tys :: SDoc -> [LHsType Name] -> [Kind] -> TcM [TcType] -- Just like tcHsArgTys but without the addTypeCtxt tc_hs_arg_tys what tys kinds = sequence [ tc_lhs_type ty (expArgKind what kind n) | (ty,kind,n) <- zip3 tys kinds [1..] ] --------------------------- tcHsOpenType, tcHsLiftedType :: LHsType Name -> TcM TcType -- Used for type signatures -- Do not do validity checking tcHsOpenType ty = addTypeCtxt ty $ tc_lhs_type ty ekOpen tcHsLiftedType ty = addTypeCtxt ty $ tc_lhs_type ty ekLifted -- Like tcHsType, but takes an expected kind tcCheckLHsType :: LHsType Name -> Kind -> TcM Type tcCheckLHsType hs_ty exp_kind = addTypeCtxt hs_ty $ tc_lhs_type hs_ty (EK exp_kind expectedKindMsg) tcLHsType :: LHsType Name -> TcM (TcType, TcKind) -- Called from outside: set the context tcLHsType ty = addTypeCtxt ty (tc_infer_lhs_type ty) --------------------------- tcCheckLHsTypeAndGen :: LHsType Name -> Kind -> TcM Type -- Typecheck a type signature, and kind-generalise it -- The result is not necessarily zonked, and has not been checked for validity tcCheckLHsTypeAndGen lhs_ty kind = do { ty <- tcCheckLHsType lhs_ty kind ; kvs <- zonkTcTypeAndFV ty ; kvs <- kindGeneralize kvs ; return (mkForAllTys kvs ty) } tcCheckHsTypeAndGen :: HsType Name -> Kind -> TcM Type -- Input type is HsType, not LHsType; the caller adds the context -- Otherwise same as tcCheckLHsTypeAndGen tcCheckHsTypeAndGen hs_ty kind = do { ty <- tc_hs_type hs_ty (EK kind expectedKindMsg) ; traceTc "tcCheckHsTypeAndGen" (ppr hs_ty) ; kvs <- zonkTcTypeAndFV ty ; kvs <- kindGeneralize kvs ; return (mkForAllTys kvs ty) } {- Like tcExpr, tc_hs_type takes an expected kind which it unifies with the kind it figures out. When we don't know what kind to expect, we use tc_lhs_type_fresh, to first create a new meta kind variable and use that as the expected kind. -} tc_infer_lhs_type :: LHsType Name -> TcM (TcType, TcKind) tc_infer_lhs_type ty = do { kv <- newMetaKindVar ; r <- tc_lhs_type ty (EK kv expectedKindMsg) ; return (r, kv) } tc_lhs_type :: LHsType Name -> ExpKind -> TcM TcType tc_lhs_type (L span ty) exp_kind = setSrcSpan span $ do { traceTc "tc_lhs_type:" (ppr ty $$ ppr exp_kind) ; tc_hs_type ty exp_kind } tc_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [TcType] tc_lhs_types tys_w_kinds = mapM (uncurry tc_lhs_type) tys_w_kinds ------------------------------------------ tc_fun_type :: HsType Name -> LHsType Name -> LHsType Name -> ExpKind -> TcM TcType -- We need to recognise (->) so that we can construct a FunTy, -- *and* we need to do by looking at the Name, not the TyCon -- (see Note [Zonking inside the knot]). For example, -- consider f :: (->) Int Int (Trac #7312) tc_fun_type ty ty1 ty2 exp_kind@(EK _ ctxt) = do { ty1' <- tc_lhs_type ty1 (EK openTypeKind ctxt) ; ty2' <- tc_lhs_type ty2 (EK openTypeKind ctxt) ; checkExpectedKind ty liftedTypeKind exp_kind ; return (mkFunTy ty1' ty2') } ------------------------------------------ tc_hs_type :: HsType Name -> ExpKind -> TcM TcType tc_hs_type (HsParTy ty) exp_kind = tc_lhs_type ty exp_kind tc_hs_type (HsDocTy ty _) exp_kind = tc_lhs_type ty exp_kind tc_hs_type ty@(HsBangTy {}) _ -- While top-level bangs at this point are eliminated (eg !(Maybe Int)), -- other kinds of bangs are not (eg ((!Maybe) Int)). These kinds of -- bangs are invalid, so fail. (#7210) = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty) tc_hs_type (HsRecTy _) _ = panic "tc_hs_type: record" -- Unwrapped by con decls -- Record types (which only show up temporarily in constructor -- signatures) should have been removed by now ---------- Functions and applications tc_hs_type hs_ty@(HsTyVar name) exp_kind = do { (ty, k) <- tcTyVar name ; checkExpectedKind hs_ty k exp_kind ; return ty } tc_hs_type ty@(HsFunTy ty1 ty2) exp_kind = tc_fun_type ty ty1 ty2 exp_kind tc_hs_type hs_ty@(HsOpTy ty1 (_, l_op@(L _ op)) ty2) exp_kind | op `hasKey` funTyConKey = tc_fun_type hs_ty ty1 ty2 exp_kind | otherwise = do { (op', op_kind) <- tcTyVar op ; tys' <- tcCheckApps hs_ty l_op op_kind [ty1,ty2] exp_kind ; return (mkNakedAppTys op' tys') } -- mkNakedAppTys: see Note [Zonking inside the knot] tc_hs_type hs_ty@(HsAppTy ty1 ty2) exp_kind -- | L _ (HsTyVar fun) <- fun_ty -- , fun `hasKey` funTyConKey -- , [fty1,fty2] <- arg_tys -- = tc_fun_type hs_ty fty1 fty2 exp_kind -- | otherwise = do { (fun_ty', fun_kind) <- tc_infer_lhs_type fun_ty ; arg_tys' <- tcCheckApps hs_ty fun_ty fun_kind arg_tys exp_kind ; return (mkNakedAppTys fun_ty' arg_tys') } -- mkNakedAppTys: see Note [Zonking inside the knot] -- This looks fragile; how do we *know* that fun_ty isn't -- a TyConApp, say (which is never supposed to appear in the -- function position of an AppTy)? where (fun_ty, arg_tys) = splitHsAppTys ty1 [ty2] --------- Foralls tc_hs_type hs_ty@(HsForAllTy _ _ hs_tvs context ty) exp_kind@(EK exp_k _) | isConstraintKind exp_k = failWithTc (hang (ptext (sLit "Illegal constraint:")) 2 (ppr hs_ty)) | otherwise = tcHsTyVarBndrs hs_tvs $ \ tvs' -> -- Do not kind-generalise here! See Note [Kind generalisation] do { ctxt' <- tcHsContext context ; ty' <- if null (unLoc context) then -- Plain forall, no context tc_lhs_type ty exp_kind -- Why exp_kind? See Note [Body kind of forall] else -- If there is a context, then this forall is really a -- _function_, so the kind of the result really is * -- The body kind (result of the function can be * or #, hence ekOpen do { checkExpectedKind hs_ty liftedTypeKind exp_kind ; tc_lhs_type ty ekOpen } ; return (mkSigmaTy tvs' ctxt' ty') } --------- Lists, arrays, and tuples tc_hs_type hs_ty@(HsListTy elt_ty) exp_kind = do { tau_ty <- tc_lhs_type elt_ty ekLifted ; checkExpectedKind hs_ty liftedTypeKind exp_kind ; checkWiredInTyCon listTyCon ; return (mkListTy tau_ty) } tc_hs_type hs_ty@(HsPArrTy elt_ty) exp_kind = do { tau_ty <- tc_lhs_type elt_ty ekLifted ; checkExpectedKind hs_ty liftedTypeKind exp_kind ; checkWiredInTyCon parrTyCon ; return (mkPArrTy tau_ty) } -- See Note [Distinguishing tuple kinds] in HsTypes -- See Note [Inferring tuple kinds] tc_hs_type hs_ty@(HsTupleTy HsBoxedOrConstraintTuple hs_tys) exp_kind@(EK exp_k _ctxt) -- (NB: not zonking before looking at exp_k, to avoid left-right bias) | Just tup_sort <- tupKindSort_maybe exp_k = traceTc "tc_hs_type tuple" (ppr hs_tys) >> tc_tuple hs_ty tup_sort hs_tys exp_kind | otherwise = do { traceTc "tc_hs_type tuple 2" (ppr hs_tys) ; (tys, kinds) <- mapAndUnzipM tc_infer_lhs_type hs_tys ; kinds <- mapM zonkTcKind kinds -- Infer each arg type separately, because errors can be -- confusing if we give them a shared kind. Eg Trac #7410 -- (Either Int, Int), we do not want to get an error saying -- "the second argument of a tuple should have kind *->*" ; let (arg_kind, tup_sort) = case [ (k,s) | k <- kinds , Just s <- [tupKindSort_maybe k] ] of ((k,s) : _) -> (k,s) [] -> (liftedTypeKind, BoxedTuple) -- In the [] case, it's not clear what the kind is, so guess * ; sequence_ [ setSrcSpan loc $ checkExpectedKind ty kind (expArgKind (ptext (sLit "a tuple")) arg_kind n) | (ty@(L loc _),kind,n) <- zip3 hs_tys kinds [1..] ] ; finish_tuple hs_ty tup_sort tys exp_kind } tc_hs_type hs_ty@(HsTupleTy hs_tup_sort tys) exp_kind = tc_tuple hs_ty tup_sort tys exp_kind where tup_sort = case hs_tup_sort of -- Fourth case dealt with above HsUnboxedTuple -> UnboxedTuple HsBoxedTuple -> BoxedTuple HsConstraintTuple -> ConstraintTuple _ -> panic "tc_hs_type HsTupleTy" --------- Promoted lists and tuples tc_hs_type hs_ty@(HsExplicitListTy _k tys) exp_kind = do { tks <- mapM tc_infer_lhs_type tys ; let taus = map fst tks ; kind <- unifyKinds (ptext (sLit "In a promoted list")) tks ; checkExpectedKind hs_ty (mkPromotedListTy kind) exp_kind ; return (foldr (mk_cons kind) (mk_nil kind) taus) } where mk_cons k a b = mkTyConApp (promoteDataCon consDataCon) [k, a, b] mk_nil k = mkTyConApp (promoteDataCon nilDataCon) [k] tc_hs_type hs_ty@(HsExplicitTupleTy _ tys) exp_kind = do { tks <- mapM tc_infer_lhs_type tys ; let n = length tys kind_con = promotedTupleTyCon Boxed n ty_con = promotedTupleDataCon Boxed n (taus, ks) = unzip tks tup_k = mkTyConApp kind_con ks ; checkExpectedKind hs_ty tup_k exp_kind ; return (mkTyConApp ty_con (ks ++ taus)) } --------- Constraint types tc_hs_type ipTy@(HsIParamTy n ty) exp_kind = do { ty' <- tc_lhs_type ty ekLifted ; checkExpectedKind ipTy constraintKind exp_kind ; let n' = mkStrLitTy $ hsIPNameFS n ; return (mkClassPred ipClass [n',ty']) } tc_hs_type ty@(HsEqTy ty1 ty2) exp_kind = do { (ty1', kind1) <- tc_infer_lhs_type ty1 ; (ty2', kind2) <- tc_infer_lhs_type ty2 ; checkExpectedKind ty2 kind2 (EK kind1 msg_fn) ; checkExpectedKind ty constraintKind exp_kind ; return (mkNakedTyConApp eqTyCon [kind1, ty1', ty2']) } where msg_fn pkind = ptext (sLit "The left argument of the equality had kind") <+> quotes (pprKind pkind) --------- Misc tc_hs_type (HsKindSig ty sig_k) exp_kind = do { sig_k' <- tcLHsKind sig_k ; checkExpectedKind ty sig_k' exp_kind ; tc_lhs_type ty (EK sig_k' msg_fn) } where msg_fn pkind = ptext (sLit "The signature specified kind") <+> quotes (pprKind pkind) tc_hs_type (HsCoreTy ty) exp_kind = do { checkExpectedKind ty (typeKind ty) exp_kind ; return ty } -- This should never happen; type splices are expanded by the renamer tc_hs_type ty@(HsSpliceTy {}) _exp_kind = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty) tc_hs_type (HsWrapTy {}) _exp_kind = panic "tc_hs_type HsWrapTy" -- We kind checked something twice tc_hs_type hs_ty@(HsTyLit (HsNumTy _ n)) exp_kind = do { checkExpectedKind hs_ty typeNatKind exp_kind ; checkWiredInTyCon typeNatKindCon ; return (mkNumLitTy n) } tc_hs_type hs_ty@(HsTyLit (HsStrTy _ s)) exp_kind = do { checkExpectedKind hs_ty typeSymbolKind exp_kind ; checkWiredInTyCon typeSymbolKindCon ; return (mkStrLitTy s) } tc_hs_type hs_ty@(HsWildCardTy wc) exp_kind = do { let name = wildCardName wc ; (ty, k) <- tcTyVar name ; checkExpectedKind hs_ty k exp_kind ; return ty } --------------------------- tupKindSort_maybe :: TcKind -> Maybe TupleSort tupKindSort_maybe k | isConstraintKind k = Just ConstraintTuple | isLiftedTypeKind k = Just BoxedTuple | otherwise = Nothing tc_tuple :: HsType Name -> TupleSort -> [LHsType Name] -> ExpKind -> TcM TcType tc_tuple hs_ty tup_sort tys exp_kind = do { tau_tys <- tc_hs_arg_tys cxt_doc tys (repeat arg_kind) ; finish_tuple hs_ty tup_sort tau_tys exp_kind } where arg_kind = case tup_sort of BoxedTuple -> liftedTypeKind UnboxedTuple -> openTypeKind ConstraintTuple -> constraintKind cxt_doc = case tup_sort of BoxedTuple -> ptext (sLit "a tuple") UnboxedTuple -> ptext (sLit "an unboxed tuple") ConstraintTuple -> ptext (sLit "a constraint tuple") finish_tuple :: HsType Name -> TupleSort -> [TcType] -> ExpKind -> TcM TcType finish_tuple hs_ty tup_sort tau_tys exp_kind = do { traceTc "finish_tuple" (ppr res_kind $$ ppr exp_kind $$ ppr exp_kind) ; checkExpectedKind hs_ty res_kind exp_kind ; tycon <- case tup_sort of ConstraintTuple | arity > mAX_CTUPLE_SIZE -> failWith (bigConstraintTuple arity) | otherwise -> tcLookupTyCon (cTupleTyConName arity) BoxedTuple -> do { let tc = tupleTyCon Boxed arity ; checkWiredInTyCon tc ; return tc } UnboxedTuple -> return (tupleTyCon Unboxed arity) ; return (mkTyConApp tycon tau_tys) } where arity = length tau_tys res_kind = case tup_sort of UnboxedTuple -> unliftedTypeKind BoxedTuple -> liftedTypeKind ConstraintTuple -> constraintKind bigConstraintTuple :: Arity -> MsgDoc bigConstraintTuple arity = hang (ptext (sLit "Constraint tuple arity too large:") <+> int arity <+> parens (ptext (sLit "max arity =") <+> int mAX_CTUPLE_SIZE)) 2 (ptext (sLit "Instead, use a nested tuple")) --------------------------- tcInferApps :: Outputable a => a -> TcKind -- Function kind -> [LHsType Name] -- Arg types -> TcM ([TcType], TcKind) -- Kind-checked args tcInferApps the_fun fun_kind args = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) fun_kind args ; args' <- tc_lhs_types args_w_kinds ; return (args', res_kind) } tcCheckApps :: Outputable a => HsType Name -- The type being checked (for err messages only) -> a -- The function -> TcKind -> [LHsType Name] -- Fun kind and arg types -> ExpKind -- Expected kind -> TcM [TcType] tcCheckApps hs_ty the_fun fun_kind args exp_kind = do { (arg_tys, res_kind) <- tcInferApps the_fun fun_kind args ; checkExpectedKind hs_ty res_kind exp_kind ; return arg_tys } --------------------------- splitFunKind :: SDoc -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind) splitFunKind the_fun fun_kind args = go 1 fun_kind args where go _ fk [] = return ([], fk) go arg_no fk (arg:args) = do { mb_fk <- matchExpectedFunKind fk ; case mb_fk of Nothing -> failWithTc too_many_args Just (ak,fk') -> do { (aks, rk) <- go (arg_no+1) fk' args ; let exp_kind = expArgKind (quotes the_fun) ak arg_no ; return ((arg, exp_kind) : aks, rk) } } too_many_args = quotes the_fun <+> ptext (sLit "is applied to too many type arguments") --------------------------- tcHsContext :: LHsContext Name -> TcM [PredType] tcHsContext ctxt = mapM tcHsLPredType (unLoc ctxt) tcHsLPredType :: LHsType Name -> TcM PredType tcHsLPredType pred = tc_lhs_type pred ekConstraint --------------------------- tcTyVar :: Name -> TcM (TcType, TcKind) -- See Note [Type checking recursive type and class declarations] -- in TcTyClsDecls tcTyVar name -- Could be a tyvar, a tycon, or a datacon = do { traceTc "lk1" (ppr name) ; thing <- tcLookup name ; case thing of ATyVar _ tv | isKindVar tv -> failWithTc (ptext (sLit "Kind variable") <+> quotes (ppr tv) <+> ptext (sLit "used as a type")) | otherwise -> return (mkTyVarTy tv, tyVarKind tv) AThing kind -> do { tc <- get_loopy_tc name ; inst_tycon (mkNakedTyConApp tc) kind } -- mkNakedTyConApp: see Note [Zonking inside the knot] AGlobal (ATyCon tc) -> inst_tycon (mkTyConApp tc) (tyConKind tc) AGlobal (AConLike (RealDataCon dc)) | Just tc <- promoteDataCon_maybe dc -> do { data_kinds <- xoptM Opt_DataKinds ; unless data_kinds $ promotionErr name NoDataKinds ; inst_tycon (mkTyConApp tc) (tyConKind tc) } | otherwise -> failWithTc (ptext (sLit "Data constructor") <+> quotes (ppr dc) <+> ptext (sLit "comes from an un-promotable type") <+> quotes (ppr (dataConTyCon dc))) APromotionErr err -> promotionErr name err _ -> wrongThingErr "type" thing name } where get_loopy_tc name = do { env <- getGblEnv ; case lookupNameEnv (tcg_type_env env) name of Just (ATyCon tc) -> return tc _ -> return (aThingErr "tcTyVar" name) } inst_tycon :: ([Type] -> Type) -> Kind -> TcM (Type, Kind) -- Instantiate the polymorphic kind -- Lazy in the TyCon inst_tycon mk_tc_app kind | null kvs = return (mk_tc_app [], ki_body) | otherwise = do { traceTc "lk4" (ppr name <+> dcolon <+> ppr kind) ; ks <- mapM (const newMetaKindVar) kvs ; return (mk_tc_app ks, substKiWith kvs ks ki_body) } where (kvs, ki_body) = splitForAllTys kind tcClass :: Name -> TcM (Class, TcKind) tcClass cls -- Must be a class = do { thing <- tcLookup cls ; case thing of AThing kind -> return (aThingErr "tcClass" cls, kind) AGlobal (ATyCon tc) | Just cls <- tyConClass_maybe tc -> return (cls, tyConKind tc) _ -> wrongThingErr "class" thing cls } aThingErr :: String -> Name -> b -- The type checker for types is sometimes called simply to -- do *kind* checking; and in that case it ignores the type -- returned. Which is a good thing since it may not be available yet! aThingErr str x = pprPanic "AThing evaluated unexpectedly" (text str <+> ppr x) {- Note [Zonking inside the knot] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we are checking the argument types of a data constructor. We must zonk the types before making the DataCon, because once built we can't change it. So we must traverse the type. BUT the parent TyCon is knot-tied, so we can't look at it yet. So we must be careful not to use "smart constructors" for types that look at the TyCon or Class involved. * Hence the use of mkNakedXXX functions. These do *not* enforce the invariants (for example that we use (FunTy s t) rather than (TyConApp (->) [s,t])). * Ditto in zonkTcType (which may be applied more than once, eg to squeeze out kind meta-variables), we are careful not to look at the TyCon. * We arrange to call zonkSigType *once* right at the end, and it does establish the invariants. But in exchange we can't look at the result (not even its structure) until we have emerged from the "knot". * TcHsSyn.zonkTcTypeToType also can safely check/establish invariants. This is horribly delicate. I hate it. A good example of how delicate it is can be seen in Trac #7903. -} mkNakedTyConApp :: TyCon -> [Type] -> Type -- Builds a TyConApp -- * without being strict in TyCon, -- * without satisfying the invariants of TyConApp -- A subsequent zonking will establish the invariants mkNakedTyConApp tc tys = TyConApp tc tys mkNakedAppTys :: Type -> [Type] -> Type mkNakedAppTys ty1 [] = ty1 mkNakedAppTys (TyConApp tc tys1) tys2 = mkNakedTyConApp tc (tys1 ++ tys2) mkNakedAppTys ty1 tys2 = foldl AppTy ty1 tys2 zonkSigType :: TcType -> TcM TcType -- Zonk the result of type-checking a user-written type signature -- It may have kind variables in it, but no meta type variables -- Because of knot-typing (see Note [Zonking inside the knot]) -- it may need to establish the Type invariants; -- hence the use of mkTyConApp and mkAppTy zonkSigType ty = go ty where go (TyConApp tc tys) = do tys' <- mapM go tys return (mkTyConApp tc tys') -- Key point: establish Type invariants! -- See Note [Zonking inside the knot] go (LitTy n) = return (LitTy n) go (FunTy arg res) = do arg' <- go arg res' <- go res return (FunTy arg' res') go (AppTy fun arg) = do fun' <- go fun arg' <- go arg return (mkAppTy fun' arg') -- NB the mkAppTy; we might have instantiated a -- type variable to a type constructor, so we need -- to pull the TyConApp to the top. -- The two interesting cases! go (TyVarTy tyvar) | isTcTyVar tyvar = zonkTcTyVar tyvar | otherwise = TyVarTy <$> updateTyVarKindM go tyvar -- Ordinary (non Tc) tyvars occur inside quantified types go (ForAllTy tv ty) = do { tv' <- zonkTcTyVarBndr tv ; ty' <- go ty ; return (ForAllTy tv' ty') } {- Note [Body kind of a forall] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The body of a forall is usually a type, but in principle there's no reason to prohibit *unlifted* types. In fact, GHC can itself construct a function with an unboxed tuple inside a for-all (via CPR analyis; see typecheck/should_compile/tc170). Moreover in instance heads we get forall-types with kind Constraint. Moreover if we have a signature f :: Int# then we represent it as (HsForAll Implicit [] [] Int#). And this must be legal! We can't drop the empty forall until *after* typechecking the body because of kind polymorphism: Typeable :: forall k. k -> Constraint data Apply f t = Apply (f t) -- Apply :: forall k. (k -> *) -> k -> * instance Typeable Apply where ... Then the dfun has type df :: forall k. Typeable ((k->*) -> k -> *) (Apply k) f :: Typeable Apply f :: forall (t:k->*) (a:k). t a -> t a class C a b where op :: a b -> Typeable Apply data T a = MkT (Typeable Apply) | T2 a T :: * -> * MkT :: forall k. (Typeable ((k->*) -> k -> *) (Apply k)) -> T a f :: (forall (k:BOX). forall (t:: k->*) (a:k). t a -> t a) -> Int f :: (forall a. a -> Typeable Apply) -> Int So we *must* keep the HsForAll on the instance type HsForAll Implicit [] [] (Typeable Apply) so that we do kind generalisation on it. Really we should check that it's a type of value kind {*, Constraint, #}, but I'm not doing that yet Example that should be rejected: f :: (forall (a:*->*). a) Int Note [Inferring tuple kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Give a tuple type (a,b,c), which the parser labels as HsBoxedOrConstraintTuple, we try to figure out whether it's a tuple of kind * or Constraint. Step 1: look at the expected kind Step 2: infer argument kinds If after Step 2 it's not clear from the arguments that it's Constraint, then it must be *. Once having decided that we re-check the Check the arguments again to give good error messages in eg. `(Maybe, Maybe)` Note that we will still fail to infer the correct kind in this case: type T a = ((a,a), D a) type family D :: Constraint -> Constraint While kind checking T, we do not yet know the kind of D, so we will default the kind of T to * -> *. It works if we annotate `a` with kind `Constraint`. Note [Desugaring types] ~~~~~~~~~~~~~~~~~~~~~~~ The type desugarer is phase 2 of dealing with HsTypes. Specifically: * It transforms from HsType to Type * It zonks any kinds. The returned type should have no mutable kind or type variables (hence returning Type not TcType): - any unconstrained kind variables are defaulted to AnyK just as in TcHsSyn. - there are no mutable type variables because we are kind-checking a type Reason: the returned type may be put in a TyCon or DataCon where it will never subsequently be zonked. You might worry about nested scopes: ..a:kappa in scope.. let f :: forall b. T '[a,b] -> Int In this case, f's type could have a mutable kind variable kappa in it; and we might then default it to AnyK when dealing with f's type signature. But we don't expect this to happen because we can't get a lexically scoped type variable with a mutable kind variable in it. A delicate point, this. If it becomes an issue we might need to distinguish top-level from nested uses. Moreover * it cannot fail, * it does no unifications * it does no validity checking, except for structural matters, such as (a) spurious ! annotations. (b) a class used as a type Note [Kind of a type splice] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider these terms, each with TH type splice inside: [| e1 :: Maybe $(..blah..) |] [| e2 :: $(..blah..) |] When kind-checking the type signature, we'll kind-check the splice $(..blah..); we want to give it a kind that can fit in any context, as if $(..blah..) :: forall k. k. In the e1 example, the context of the splice fixes kappa to *. But in the e2 example, we'll desugar the type, zonking the kind unification variables as we go. When we encounter the unconstrained kappa, we want to default it to '*', not to AnyK. Help functions for type applications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} addTypeCtxt :: LHsType Name -> TcM a -> TcM a -- Wrap a context around only if we want to show that contexts. -- Omit invisble ones and ones user's won't grok addTypeCtxt (L _ ty) thing = addErrCtxt doc thing where doc = ptext (sLit "In the type") <+> quotes (ppr ty) {- ************************************************************************ * * Type-variable binders * * ************************************************************************ -} tcWildcardBinders :: [Name] -> ([(Name,TcTyVar)] -> TcM a) -> TcM a tcWildcardBinders wcs thing_inside = do { wc_prs <- mapM new_wildcard wcs ; tcExtendTyVarEnv2 wc_prs $ thing_inside wc_prs } where new_wildcard :: Name -> TcM (Name, TcTyVar) new_wildcard name = do { kind <- newMetaKindVar ; tv <- newFlexiTyVar kind ; return (name, tv) } mkKindSigVar :: Name -> TcM KindVar -- Use the specified name; don't clone it mkKindSigVar n = do { mb_thing <- tcLookupLcl_maybe n ; case mb_thing of Just (AThing k) | Just kvar <- getTyVar_maybe k -> return kvar _ -> return $ mkTcTyVar n superKind (SkolemTv False) } kcScopedKindVars :: [Name] -> TcM a -> TcM a -- Given some tyvar binders like [a (b :: k -> *) (c :: k)] -- bind each scoped kind variable (k in this case) to a fresh -- kind skolem variable kcScopedKindVars kv_ns thing_inside = do { kvs <- mapM newSigKindVar kv_ns -- NB: use mutable signature variables ; tcExtendTyVarEnv2 (kv_ns `zip` kvs) thing_inside } -- | Kind-check a 'LHsTyVarBndrs'. If the decl under consideration has a complete, -- user-supplied kind signature (CUSK), generalise the result. Used in 'getInitialKind' -- and in kind-checking. See also Note [Complete user-supplied kind signatures] in -- HsDecls. kcHsTyVarBndrs :: Bool -- ^ True <=> the decl being checked has a CUSK -> LHsTyVarBndrs Name -> TcM (Kind, r) -- ^ the result kind, possibly with other info -> TcM (Kind, r) -- ^ The full kind of the thing being declared, -- with the other info kcHsTyVarBndrs cusk (HsQTvs { hsq_kvs = kv_ns, hsq_tvs = hs_tvs }) thing_inside = do { kvs <- if cusk then mapM mkKindSigVar kv_ns else mapM newSigKindVar kv_ns ; tcExtendTyVarEnv2 (kv_ns `zip` kvs) $ do { nks <- mapM (kc_hs_tv . unLoc) hs_tvs ; (res_kind, stuff) <- tcExtendKindEnv nks thing_inside ; let full_kind = mkArrowKinds (map snd nks) res_kind kvs = filter (not . isMetaTyVar) $ varSetElems $ tyVarsOfType full_kind gen_kind = if cusk then mkForAllTys kvs full_kind else full_kind ; return (gen_kind, stuff) } } where kc_hs_tv :: HsTyVarBndr Name -> TcM (Name, TcKind) kc_hs_tv (UserTyVar n) = do { mb_thing <- tcLookupLcl_maybe n ; kind <- case mb_thing of Just (AThing k) -> return k _ | cusk -> return liftedTypeKind | otherwise -> newMetaKindVar ; return (n, kind) } kc_hs_tv (KindedTyVar (L _ n) k) = do { kind <- tcLHsKind k -- In an associated type decl, the type variable may already -- be in scope; in that case we want to make sure its kind -- matches the one declared here ; mb_thing <- tcLookupLcl_maybe n ; case mb_thing of Nothing -> return () Just (AThing ks) -> checkKind kind ks Just thing -> pprPanic "check_in_scope" (ppr thing) ; return (n, kind) } tcHsTyVarBndrs :: LHsTyVarBndrs Name -> ([TcTyVar] -> TcM r) -> TcM r -- Bind the kind variables to fresh skolem variables -- and type variables to skolems, each with a meta-kind variable kind tcHsTyVarBndrs (HsQTvs { hsq_kvs = kv_ns, hsq_tvs = hs_tvs }) thing_inside = do { kvs <- mapM mkKindSigVar kv_ns ; tcExtendTyVarEnv kvs $ do { tvs <- mapM tcHsTyVarBndr hs_tvs ; traceTc "tcHsTyVarBndrs {" (vcat [ text "Hs kind vars:" <+> ppr kv_ns , text "Hs type vars:" <+> ppr hs_tvs , text "Kind vars:" <+> ppr kvs , text "Type vars:" <+> ppr tvs ]) ; res <- tcExtendTyVarEnv tvs (thing_inside (kvs ++ tvs)) ; traceTc "tcHsTyVarBndrs }" (vcat [ text "Hs kind vars:" <+> ppr kv_ns , text "Hs type vars:" <+> ppr hs_tvs , text "Kind vars:" <+> ppr kvs , text "Type vars:" <+> ppr tvs ]) ; return res } } tcHsTyVarBndr :: LHsTyVarBndr Name -> TcM TcTyVar -- Return a type variable -- initialised with a kind variable. -- Typically the Kind inside the HsTyVarBndr will be a tyvar with a mutable kind -- in it. -- -- If the variable is already in scope return it, instead of introducing a new -- one. This can occur in -- instance C (a,b) where -- type F (a,b) c = ... -- Here a,b will be in scope when processing the associated type instance for F. -- See Note [Associated type tyvar names] in Class tcHsTyVarBndr (L _ hs_tv) = do { let name = hsTyVarName hs_tv ; mb_tv <- tcLookupLcl_maybe name ; case mb_tv of { Just (ATyVar _ tv) -> return tv ; _ -> do { kind <- case hs_tv of UserTyVar {} -> newMetaKindVar KindedTyVar _ kind -> tcLHsKind kind ; return ( mkTcTyVar name kind (SkolemTv False)) } } } ------------------ kindGeneralize :: TyVarSet -> TcM [KindVar] kindGeneralize tkvs = do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked ; quantifyTyVars gbl_tvs (filterVarSet isKindVar tkvs) } -- ToDo: remove the (filter isKindVar) -- Any type variables in tkvs will be in scope, -- and hence in gbl_tvs, so after removing gbl_tvs -- we should only have kind variables left -- -- BUT there is a smelly case (to be fixed when TH is reorganised) -- f t = [| e :: $t |] -- When typechecking the body of the bracket, we typecheck $t to a -- unification variable 'alpha', with no biding forall. We don't -- want to kind-quantify it! {- Note [Kind generalisation] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We do kind generalisation only at the outer level of a type signature. For example, consider T :: forall k. k -> * f :: (forall a. T a -> Int) -> Int When kind-checking f's type signature we generalise the kind at the outermost level, thus: f1 :: forall k. (forall (a:k). T k a -> Int) -> Int -- YES! and *not* at the inner forall: f2 :: (forall k. forall (a:k). T k a -> Int) -> Int -- NO! Reason: same as for HM inference on value level declarations, we want to infer the most general type. The f2 type signature would be *less applicable* than f1, because it requires a more polymorphic argument. Note [Kinds of quantified type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tcTyVarBndrsGen quantifies over a specified list of type variables, *and* over the kind variables mentioned in the kinds of those tyvars. Note that we must zonk those kinds (obviously) but less obviously, we must return type variables whose kinds are zonked too. Example (a :: k7) where k7 := k9 -> k9 We must return [k9, a:k9->k9] and NOT [k9, a:k7] Reason: we're going to turn this into a for-all type, forall k9. forall (a:k7). blah which the type checker will then instantiate, and instantiate does not look through unification variables! Hence using zonked_kinds when forming tvs'. -} -------------------- -- getInitialKind has made a suitably-shaped kind for the type or class -- Unpack it, and attribute those kinds to the type variables -- Extend the env with bindings for the tyvars, taken from -- the kind of the tycon/class. Give it to the thing inside, and -- check the result kind matches kcLookupKind :: Name -> TcM Kind kcLookupKind nm = do { tc_ty_thing <- tcLookup nm ; case tc_ty_thing of AThing k -> return k AGlobal (ATyCon tc) -> return (tyConKind tc) _ -> pprPanic "kcLookupKind" (ppr tc_ty_thing) } kcTyClTyVars :: Name -> LHsTyVarBndrs Name -> TcM a -> TcM a -- Used for the type variables of a type or class decl, -- when doing the initial kind-check. kcTyClTyVars name (HsQTvs { hsq_kvs = kvs, hsq_tvs = hs_tvs }) thing_inside = kcScopedKindVars kvs $ do { tc_kind <- kcLookupKind name ; let (_, mono_kind) = splitForAllTys tc_kind -- if we have a FullKindSignature, the tc_kind may already -- be generalized. The kvs get matched up while kind-checking -- the types in kc_tv, below (arg_ks, _res_k) = splitKindFunTysN (length hs_tvs) mono_kind -- There should be enough arrows, because -- getInitialKinds used the tcdTyVars ; name_ks <- zipWithM kc_tv hs_tvs arg_ks ; tcExtendKindEnv name_ks thing_inside } where -- getInitialKind has already gotten the kinds of these type -- variables, but tiresomely we need to check them *again* -- to match the kind variables they mention against the ones -- we've freshly brought into scope kc_tv :: LHsTyVarBndr Name -> Kind -> TcM (Name, Kind) kc_tv (L _ (UserTyVar n)) exp_k = return (n, exp_k) kc_tv (L _ (KindedTyVar (L _ n) hs_k)) exp_k = do { k <- tcLHsKind hs_k ; checkKind k exp_k ; return (n, exp_k) } ----------------------- tcTyClTyVars :: Name -> LHsTyVarBndrs Name -- LHS of the type or class decl -> ([TyVar] -> Kind -> TcM a) -> TcM a -- Used for the type variables of a type or class decl, -- on the second pass when constructing the final result -- (tcTyClTyVars T [a,b] thing_inside) -- where T : forall k1 k2 (a:k1 -> *) (b:k1). k2 -> * -- calls thing_inside with arguments -- [k1,k2,a,b] (k2 -> *) -- having also extended the type environment with bindings -- for k1,k2,a,b -- -- No need to freshen the k's because they are just skolem -- constants here, and we are at top level anyway. tcTyClTyVars tycon (HsQTvs { hsq_kvs = hs_kvs, hsq_tvs = hs_tvs }) thing_inside = kcScopedKindVars hs_kvs $ -- Bind scoped kind vars to fresh kind univ vars -- There may be fewer of these than the kvs of -- the type constructor, of course do { thing <- tcLookup tycon ; let { kind = case thing of -- The kind of the tycon has been worked out -- by the previous pass, and is fully zonked AThing kind -> kind _ -> panic "tcTyClTyVars" -- We only call tcTyClTyVars during typechecking in -- TcTyClDecls, where the local env is extended with -- the generalized_env (mapping Names to AThings). ; (kvs, body) = splitForAllTys kind ; (kinds, res) = splitKindFunTysN (length hs_tvs) body } ; tvs <- zipWithM tc_hs_tv hs_tvs kinds ; tcExtendTyVarEnv tvs (thing_inside (kvs ++ tvs) res) } where -- In the case of associated types, the renamer has -- ensured that the names are in commmon -- e.g. class C a_29 where -- type T b_30 a_29 :: * -- Here the a_29 is shared tc_hs_tv (L _ (UserTyVar n)) kind = return (mkTyVar n kind) tc_hs_tv (L _ (KindedTyVar (L _ n) hs_k)) kind = do { tc_kind <- tcLHsKind hs_k ; checkKind kind tc_kind ; return (mkTyVar n kind) } ----------------------------------- tcDataKindSig :: Kind -> TcM [TyVar] -- GADT decls can have a (perhaps partial) kind signature -- e.g. data T :: * -> * -> * where ... -- This function makes up suitable (kinded) type variables for -- the argument kinds, and checks that the result kind is indeed *. -- We use it also to make up argument type variables for for data instances. tcDataKindSig kind = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind) ; span <- getSrcSpanM ; us <- newUniqueSupply ; rdr_env <- getLocalRdrEnv ; let uniqs = uniqsFromSupply us occs = [ occ | str <- allNameStrings , let occ = mkOccName tvName str , isNothing (lookupLocalRdrOcc rdr_env occ) ] -- Note [Avoid name clashes for associated data types] ; return [ mk_tv span uniq occ kind | ((kind, occ), uniq) <- arg_kinds `zip` occs `zip` uniqs ] } where (arg_kinds, res_kind) = splitKindFunTys kind mk_tv loc uniq occ kind = mkTyVar (mkInternalName uniq occ loc) kind badKindSig :: Kind -> SDoc badKindSig kind = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind")) 2 (ppr kind) {- Note [Avoid name clashes for associated data types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class C a b where data D b :: * -> * When typechecking the decl for D, we'll invent an extra type variable for D, to fill out its kind. Ideally we don't want this type variable to be 'a', because when pretty printing we'll get class C a b where data D b a0 (NB: the tidying happens in the conversion to IfaceSyn, which happens as part of pretty-printing a TyThing.) That's why we look in the LocalRdrEnv to see what's in scope. This is important only to get nice-looking output when doing ":info C" in GHCi. It isn't essential for correctness. ************************************************************************ * * Scoped type variables * * ************************************************************************ tcAddScopedTyVars is used for scoped type variables added by pattern type signatures e.g. \ ((x::a), (y::a)) -> x+y They never have explicit kinds (because this is source-code only) They are mutable (because they can get bound to a more specific type). Usually we kind-infer and expand type splices, and then tupecheck/desugar the type. That doesn't work well for scoped type variables, because they scope left-right in patterns. (e.g. in the example above, the 'a' in (y::a) is bound by the 'a' in (x::a). The current not-very-good plan is to * find all the types in the patterns * find their free tyvars * do kind inference * bring the kinded type vars into scope * BUT throw away the kind-checked type (we'll kind-check it again when we type-check the pattern) This is bad because throwing away the kind checked type throws away its splices. But too bad for now. [July 03] Historical note: We no longer specify that these type variables must be universally quantified (lots of email on the subject). If you want to put that back in, you need to a) Do a checkSigTyVars after thing_inside b) More insidiously, don't pass in expected_ty, else we unify with it too early and checkSigTyVars barfs Instead you have to pass in a fresh ty var, and unify it with expected_ty afterwards -} tcHsPatSigType :: UserTypeCtxt -> HsWithBndrs Name (LHsType Name) -- The type signature -> TcM ( Type -- The signature , [(Name, TcTyVar)] -- The new bit of type environment, binding -- the scoped type variables , [(Name, TcTyVar)] ) -- The wildcards -- Used for type-checking type signatures in -- (a) patterns e.g f (x::Int) = e -- (b) result signatures e.g. g x :: Int = e -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x tcHsPatSigType ctxt (HsWB { hswb_cts = hs_ty, hswb_kvs = sig_kvs, hswb_tvs = sig_tvs, hswb_wcs = sig_wcs }) = addErrCtxt (pprSigCtxt ctxt empty (ppr hs_ty)) $ tcWildcardBinders sig_wcs $ \ nwc_binds -> do { emitWildcardHoleConstraints nwc_binds ; kvs <- mapM new_kv sig_kvs ; tvs <- mapM new_tv sig_tvs ; let ktv_binds = (sig_kvs `zip` kvs) ++ (sig_tvs `zip` tvs) ; sig_ty <- tcExtendTyVarEnv2 ktv_binds $ tcHsLiftedType hs_ty ; sig_ty <- zonkSigType sig_ty ; checkValidType ctxt sig_ty ; return (sig_ty, ktv_binds, nwc_binds) } where new_kv name = new_tkv name superKind new_tv name = do { kind <- newMetaKindVar ; new_tkv name kind } new_tkv name kind -- See Note [Pattern signature binders] = case ctxt of RuleSigCtxt {} -> return (mkTcTyVar name kind (SkolemTv False)) _ -> newSigTyVar name kind -- See Note [Unifying SigTvs] tcPatSig :: Bool -- True <=> pattern binding -> HsWithBndrs Name (LHsType Name) -> TcSigmaType -> TcM (TcType, -- The type to use for "inside" the signature [(Name, TcTyVar)], -- The new bit of type environment, binding -- the scoped type variables [(Name, TcTyVar)], -- The wildcards HsWrapper) -- Coercion due to unification with actual ty -- Of shape: res_ty ~ sig_ty tcPatSig in_pat_bind sig res_ty = do { (sig_ty, sig_tvs, sig_nwcs) <- tcHsPatSigType PatSigCtxt sig -- sig_tvs are the type variables free in 'sig', -- and not already in scope. These are the ones -- that should be brought into scope ; if null sig_tvs then do { -- Just do the subsumption check and return wrap <- addErrCtxtM (mk_msg sig_ty) $ tcSubType_NC PatSigCtxt res_ty sig_ty ; return (sig_ty, [], sig_nwcs, wrap) } else do -- Type signature binds at least one scoped type variable -- A pattern binding cannot bind scoped type variables -- It is more convenient to make the test here -- than in the renamer { when in_pat_bind (addErr (patBindSigErr sig_tvs)) -- Check that all newly-in-scope tyvars are in fact -- constrained by the pattern. This catches tiresome -- cases like -- type T a = Int -- f :: Int -> Int -- f (x :: T a) = ... -- Here 'a' doesn't get a binding. Sigh ; let bad_tvs = [ tv | (_, tv) <- sig_tvs , not (tv `elemVarSet` exactTyVarsOfType sig_ty) ] ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs) -- Now do a subsumption check of the pattern signature against res_ty ; wrap <- addErrCtxtM (mk_msg sig_ty) $ tcSubType_NC PatSigCtxt res_ty sig_ty -- Phew! ; return (sig_ty, sig_tvs, sig_nwcs, wrap) } } where mk_msg sig_ty tidy_env = do { (tidy_env, sig_ty) <- zonkTidyTcType tidy_env sig_ty ; (tidy_env, res_ty) <- zonkTidyTcType tidy_env res_ty ; let msg = vcat [ hang (ptext (sLit "When checking that the pattern signature:")) 4 (ppr sig_ty) , nest 2 (hang (ptext (sLit "fits the type of its context:")) 2 (ppr res_ty)) ] ; return (tidy_env, msg) } patBindSigErr :: [(Name, TcTyVar)] -> SDoc patBindSigErr sig_tvs = hang (ptext (sLit "You cannot bind scoped type variable") <> plural sig_tvs <+> pprQuotedList (map fst sig_tvs)) 2 (ptext (sLit "in a pattern binding signature")) {- Note [Pattern signature binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T = forall a. T a (a->Int) f (T x (f :: a->Int) = blah) Here * The pattern (T p1 p2) creates a *skolem* type variable 'a_sk', It must be a skolem so that that it retains its identity, and TcErrors.getSkolemInfo can thereby find the binding site for the skolem. * The type signature pattern (f :: a->Int) binds "a" -> a_sig in the envt * Then unificaiton makes a_sig := a_sk That's why we must make a_sig a MetaTv (albeit a SigTv), not a SkolemTv, so that it can unify to a_sk. For RULE binders, though, things are a bit different (yuk). RULE "foo" forall (x::a) (y::[a]). f x y = ... Here this really is the binding site of the type variable so we'd like to use a skolem, so that we get a complaint if we unify two of them together. Note [Unifying SigTvs] ~~~~~~~~~~~~~~~~~~~~~~ ALAS we have no decent way of avoiding two SigTvs getting unified. Consider f (x::(a,b)) (y::c)) = [fst x, y] Here we'd really like to complain that 'a' and 'c' are unified. But for the reasons above we can't make a,b,c into skolems, so they are just SigTvs that can unify. And indeed, this would be ok, f x (y::c) = case x of (x1 :: a1, True) -> [x,y] (x1 :: a2, False) -> [x,y,y] Here the type of x's first component is called 'a1' in one branch and 'a2' in the other. We could try insisting on the same OccName, but they definitely won't have the sane lexical Name. I think we could solve this by recording in a SigTv a list of all the in-scope variables that it should not unify with, but it's fiddly. ************************************************************************ * * Checking kinds * * ************************************************************************ We would like to get a decent error message from (a) Under-applied type constructors f :: (Maybe, Maybe) (b) Over-applied type constructors f :: Int x -> Int x -} -- The ExpKind datatype means "expected kind" and contains -- some info about just why that kind is expected, to improve -- the error message on a mis-match data ExpKind = EK TcKind (TcKind -> SDoc) -- The second arg is function that takes a *tidied* version -- of the first arg, and produces something like -- "Expected kind k" -- "Expected a constraint" -- "The argument of Maybe should have kind k" instance Outputable ExpKind where ppr (EK k f) = f k ekLifted, ekOpen, ekConstraint :: ExpKind ekLifted = EK liftedTypeKind expectedKindMsg ekOpen = EK openTypeKind expectedKindMsg ekConstraint = EK constraintKind expectedKindMsg expectedKindMsg :: TcKind -> SDoc expectedKindMsg pkind | isConstraintKind pkind = ptext (sLit "Expected a constraint") | isOpenTypeKind pkind = ptext (sLit "Expected a type") | otherwise = ptext (sLit "Expected kind") <+> quotes (pprKind pkind) -- Build an ExpKind for arguments expArgKind :: SDoc -> TcKind -> Int -> ExpKind expArgKind exp kind arg_no = EK kind msg_fn where msg_fn pkind = sep [ ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of") <+> exp , nest 2 $ ptext (sLit "should have kind") <+> quotes (pprKind pkind) ] unifyKinds :: SDoc -> [(TcType, TcKind)] -> TcM TcKind unifyKinds fun act_kinds = do { kind <- newMetaKindVar ; let check (arg_no, (ty, act_kind)) = checkExpectedKind ty act_kind (expArgKind (quotes fun) kind arg_no) ; mapM_ check (zip [1..] act_kinds) ; return kind } checkKind :: TcKind -> TcKind -> TcM () checkKind act_kind exp_kind = do { mb_subk <- unifyKindX act_kind exp_kind ; case mb_subk of Just EQ -> return () _ -> unifyKindMisMatch act_kind exp_kind } checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM () -- A fancy wrapper for 'unifyKindX', which tries -- to give decent error messages. -- (checkExpectedKind ty act_kind exp_kind) -- checks that the actual kind act_kind is compatible -- with the expected kind exp_kind -- The first argument, ty, is used only in the error message generation checkExpectedKind ty act_kind (EK exp_kind ek_ctxt) = do { mb_subk <- unifyKindX act_kind exp_kind -- Kind unification only generates definite errors ; case mb_subk of { Just LT -> return () ; -- act_kind is a sub-kind of exp_kind Just EQ -> return () ; -- The two are equal _other -> do { -- So there's an error -- Now to find out what sort exp_kind <- zonkTcKind exp_kind ; act_kind <- zonkTcKind act_kind ; traceTc "checkExpectedKind" (ppr ty $$ ppr act_kind $$ ppr exp_kind) ; env0 <- tcInitTidyEnv ; dflags <- getDynFlags ; let (exp_as, _) = splitKindFunTys exp_kind (act_as, _) = splitKindFunTys act_kind n_exp_as = length exp_as n_act_as = length act_as n_diff_as = n_act_as - n_exp_as (env1, tidy_exp_kind) = tidyOpenKind env0 exp_kind (env2, tidy_act_kind) = tidyOpenKind env1 act_kind occurs_check | Just act_tv <- tcGetTyVar_maybe act_kind = check_occ act_tv exp_kind | Just exp_tv <- tcGetTyVar_maybe exp_kind = check_occ exp_tv act_kind | otherwise = False check_occ tv k = case occurCheckExpand dflags tv k of OC_Occurs -> True _bad -> False err | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty) <+> ptext (sLit "is unlifted") | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty) <+> ptext (sLit "is lifted") | occurs_check -- Must precede the "more args expected" check = ptext (sLit "Kind occurs check") $$ more_info | n_exp_as < n_act_as -- E.g. [Maybe] = vcat [ ptext (sLit "Expecting") <+> speakN n_diff_as <+> ptext (sLit "more argument") <> (if n_diff_as > 1 then char 's' else empty) <+> ptext (sLit "to") <+> quotes (ppr ty) , more_info ] -- Now n_exp_as >= n_act_as. In the next two cases, -- n_exp_as == 0, and hence so is n_act_as | otherwise -- E.g. Monad [Int] = more_info more_info = sep [ ek_ctxt tidy_exp_kind <> comma , nest 2 $ ptext (sLit "but") <+> quotes (ppr ty) <+> ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)] ; traceTc "checkExpectedKind 1" (ppr ty $$ ppr tidy_act_kind $$ ppr tidy_exp_kind $$ ppr env1 $$ ppr env2) ; failWithTcM (env2, err) } } } {- ************************************************************************ * * Sort checking kinds * * ************************************************************************ tcLHsKind converts a user-written kind to an internal, sort-checked kind. It does sort checking and desugaring at the same time, in one single pass. It fails when the kinds are not well-formed (eg. data A :: * Int), or if there are non-promotable or non-fully applied kinds. -} tcLHsKind :: LHsKind Name -> TcM Kind tcLHsKind k = addErrCtxt (ptext (sLit "In the kind") <+> quotes (ppr k)) $ tc_lhs_kind k tc_lhs_kind :: LHsKind Name -> TcM Kind tc_lhs_kind (L span ki) = setSrcSpan span (tc_hs_kind ki) -- The main worker tc_hs_kind :: HsKind Name -> TcM Kind tc_hs_kind (HsTyVar tc) = tc_kind_var_app tc [] tc_hs_kind k@(HsAppTy _ _) = tc_kind_app k [] tc_hs_kind (HsParTy ki) = tc_lhs_kind ki tc_hs_kind (HsFunTy ki1 ki2) = do kappa_ki1 <- tc_lhs_kind ki1 kappa_ki2 <- tc_lhs_kind ki2 return (mkArrowKind kappa_ki1 kappa_ki2) tc_hs_kind (HsListTy ki) = do kappa <- tc_lhs_kind ki checkWiredInTyCon listTyCon return $ mkPromotedListTy kappa tc_hs_kind (HsTupleTy _ kis) = do kappas <- mapM tc_lhs_kind kis checkWiredInTyCon tycon return $ mkTyConApp tycon kappas where tycon = promotedTupleTyCon Boxed (length kis) -- Argument not kind-shaped tc_hs_kind k = pprPanic "tc_hs_kind" (ppr k) -- Special case for kind application tc_kind_app :: HsKind Name -> [LHsKind Name] -> TcM Kind tc_kind_app (HsAppTy ki1 ki2) kis = tc_kind_app (unLoc ki1) (ki2:kis) tc_kind_app (HsTyVar tc) kis = do { arg_kis <- mapM tc_lhs_kind kis ; tc_kind_var_app tc arg_kis } tc_kind_app ki _ = failWithTc (quotes (ppr ki) <+> ptext (sLit "is not a kind constructor")) tc_kind_var_app :: Name -> [Kind] -> TcM Kind -- Special case for * and Constraint kinds -- They are kinds already, so we don't need to promote them tc_kind_var_app name arg_kis | name == liftedTypeKindTyConName || name == constraintKindTyConName = do { unless (null arg_kis) (failWithTc (text "Kind" <+> ppr name <+> text "cannot be applied")) ; thing <- tcLookup name ; case thing of AGlobal (ATyCon tc) -> return (mkTyConApp tc []) _ -> panic "tc_kind_var_app 1" } -- General case tc_kind_var_app name arg_kis = do { thing <- tcLookup name ; case thing of AGlobal (ATyCon tc) -> do { data_kinds <- xoptM Opt_DataKinds ; unless data_kinds $ addErr (dataKindsErr name) ; case promotableTyCon_maybe tc of Just prom_tc | arg_kis `lengthIs` tyConArity prom_tc -> return (mkTyConApp prom_tc arg_kis) Just _ -> tycon_err tc "is not fully applied" Nothing -> tycon_err tc "is not promotable" } -- A lexically scoped kind variable ATyVar _ kind_var | not (isKindVar kind_var) -> failWithTc (ptext (sLit "Type variable") <+> quotes (ppr kind_var) <+> ptext (sLit "used as a kind")) | not (null arg_kis) -- Kind variables always have kind BOX, -- so cannot be applied to anything -> failWithTc (ptext (sLit "Kind variable") <+> quotes (ppr name) <+> ptext (sLit "cannot appear in a function position")) | otherwise -> return (mkAppTys (mkTyVarTy kind_var) arg_kis) -- It is in scope, but not what we expected AThing _ | isTyVarName name -> failWithTc (ptext (sLit "Type variable") <+> quotes (ppr name) <+> ptext (sLit "used in a kind")) | otherwise -> failWithTc (hang (ptext (sLit "Type constructor") <+> quotes (ppr name) <+> ptext (sLit "used in a kind")) 2 (ptext (sLit "inside its own recursive group"))) APromotionErr err -> promotionErr name err _ -> wrongThingErr "promoted type" thing name -- This really should not happen } where tycon_err tc msg = failWithTc (quotes (ppr tc) <+> ptext (sLit "of kind") <+> quotes (ppr (tyConKind tc)) <+> ptext (sLit msg)) dataKindsErr :: Name -> SDoc dataKindsErr name = hang (ptext (sLit "Illegal kind:") <+> quotes (ppr name)) 2 (ptext (sLit "Perhaps you intended to use DataKinds")) promotionErr :: Name -> PromotionErr -> TcM a promotionErr name err = failWithTc (hang (pprPECategory err <+> quotes (ppr name) <+> ptext (sLit "cannot be used here")) 2 (parens reason)) where reason = case err of FamDataConPE -> ptext (sLit "it comes from a data family instance") NoDataKinds -> ptext (sLit "Perhaps you intended to use DataKinds") _ -> ptext (sLit "it is defined and used in the same recursive group") {- ************************************************************************ * * Scoped type variables * * ************************************************************************ -} badPatSigTvs :: TcType -> [TyVar] -> SDoc badPatSigTvs sig_ty bad_tvs = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs, quotes (pprWithCommas ppr bad_tvs), ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty), ptext (sLit "but are actually discarded by a type synonym") ] , ptext (sLit "To fix this, expand the type synonym") , ptext (sLit "[Note: I hope to lift this restriction in due course]") ] unifyKindMisMatch :: TcKind -> TcKind -> TcM a unifyKindMisMatch ki1 ki2 = do ki1' <- zonkTcKind ki1 ki2' <- zonkTcKind ki2 let msg = hang (ptext (sLit "Couldn't match kind")) 2 (sep [quotes (ppr ki1'), ptext (sLit "against"), quotes (ppr ki2')]) failWithTc msg
acowley/ghc
compiler/typecheck/TcHsType.hs
bsd-3-clause
69,518
105
26
20,667
12,299
6,296
6,003
822
8
{- Utility for generating GHCJS.Prim.Internal.Build: Helpers for constructing objects and arrays that can be efficiently inlined as literals. Template Haskell is not available in ghcjs-prim, therefore this module is generated with this external generator. -} module Main where import Control.Monad import Data.List (intercalate) sizes :: [Int] sizes = [1..32] moduleName = "GHCJS.Prim.Internal.Build" main :: IO () main = mapM_ putStr [ genHeader, genExportList, "\n" , genImports, "\n", genDefns, "\n" , genImmutableA, genMutableA , genImmutableO, genMutableO , "\n#endif" ] genHeader = unlines [ "-- helpers for constructing JS objects that can be efficiently inlined as literals" , "-- no Template Haskell available yet, generated by utils/genBuildObject.hs" , "{-# LANGUAGE CPP #-}" , "#ifndef ghcjs_HOST_OS" , "module " ++ moduleName ++ " () where" , "#else" , "{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI, GHCForeignImportPrim #-}" , "module " ++ moduleName ] genExportList = unlines $ (" ( "++e) : map (" , " ++) es ++ [" ) where"] where (e:es) = funs ++ ((\f n -> f ++ show n) <$> funs <*> sizes) funs = ["buildArrayI", "buildArrayM", "buildObjectI", "buildObjectM"] genImports = unlines [ "import GHCJS.Prim" , "import GHC.Prim" , "import Unsafe.Coerce" , "import System.IO.Unsafe" ] genDefns = unlines [ "type O = JSVal -- object" , "type K = JSVal -- key" , "type V = JSVal -- value" , "type J = JSVal -- some JS value" , "type A = JSVal -- array" , "" , "seqTupList :: [(a,b)] -> [(a,b)]" , "seqTupList xs = go xs `seq` xs" , " where go ((x1,x2):xs) = x1 `seq` x2 `seq` go xs" , " go [] = ()" ] genImmutableA = genBuildA "unsafePerformIO (toJSArray xs)" "I" "A" genMutableA = genBuildA "toJSArray xs" "M" "IO A" genImmutableO = genBuildO "I" "O" genMutableO = genBuildO "M" "IO O" genBuildAL :: String -> String -> String -> String genBuildAL body m res = unlines $ [ "foreign import javascript unsafe \"$r = [];\" js_emptyArray" ++ m ++ " :: " ++ res , "" , m' ++ " :: [J] -> " ++ res , m' ++ " xs = " ++ body , "{-# INLINE [1] " ++ m' ++ " #-}" , "{-# RULES \"" ++ m' ++ "/empty\" " ++ m' ++ " [] = js_emptyArray" ++ m ++ " #-}" ] ++ map mkRule sizes where mkRule n = let vars = map (('x':).show) [1..n] in concat [ "{-# RULES \"", m' ,"/", m', show n, "\" forall " , intercalate " " vars, ". ", m' , " [", intercalate "," vars, "]" , " = ", m', show n, " ", intercalate " " vars, " #-}" ] m' = "buildArray" ++ m genBuildA body n res = unlines $ genBuildAL body n res : map (genBuildA' n res) sizes genBuildA' :: String -> String -> Int -> String genBuildA' n res i = genBuild ("buildArray" ++ n ++ show i) imp args sig where args = intercalate " " $ map (('x':).show) [1..i] sig = join (replicate i ("J -> ")) ++ res imp = '[' : intercalate "," (map (('$':).show) [1..i]) ++ "]" genBuildOL :: String -> String -> String genBuildOL m res = unlines $ [ "foreign import javascript unsafe \"h$buildObjectFromTupList($1)\"" , " js_buildObjectFromTupList" ++ m ++ " :: Any -> " ++ res , "foreign import javascript unsafe \"$r = {};\" js_emptyObject" ++ m ++ " :: " ++ res , m' ++ " :: [(K,V)] -> " ++ res , m' ++ " xs = js_buildObjectFromTupList" ++ m ++ " . unsafeCoerce . seqTupList $ xs" , "{-# INLINE [1] " ++ m' ++ " #-}" , "{-# RULES \"" ++ m' ++ "/empty\" " ++ m' ++ " [] = js_emptyObject" ++ m ++ " #-}" ] ++ map mkRule sizes where mkRule n = let varst = map (\i -> let si = show i in "(k"++si++",v"++si++")") [1..n] vars = concatMap (\i -> let si = show i in ['k':si,'v':si]) [1..n] in concat [ "{-# RULES \"", m' ,"/", m', show n, "\" forall " , intercalate " " vars, ". ", m' , " [", intercalate "," varst, "]" , " = ", m', show n, " ", intercalate " " vars, " #-}" ] m' = "buildObject" ++ m genBuildO n res = unlines $ genBuildOL n res : map (genBuildO' n res) sizes genBuildO' :: String -> String -> Int -> String genBuildO' n res i = genBuild ("buildObject" ++ n ++ show i) imp args sig where imp = "h$buildObject(" ++ intercalate "," (map (('$':).show) [1..2*i]) ++ ")" args = intercalate " " $ map (\j -> "k" ++ show j ++ " v" ++ show j) [1..i] sig = join (replicate i "K -> V -> ") ++ res genBuild n imp args sig = unlines [ n ++ " :: " ++ sig , n ++ " " ++ args ++ " =" , " js_" ++ n ++ " " ++ args , "{-# INLINE " ++ n ++ " #-}" , "" , "foreign import javascript unsafe \"" ++ imp ++ "\"" , " js_" ++ n ++ " :: " ++ sig , "" ]
seereason/ghcjs
utils/genBuildObject.hs
mit
4,893
0
19
1,392
1,423
769
654
100
1
-- | Formats on this architecture -- A Format is a combination of width and class -- -- TODO: Signed vs unsigned? -- -- TODO: This module is currenly shared by all architectures because -- NCGMonad need to know about it to make a VReg. It would be better -- to have architecture specific formats, and do the overloading -- properly. eg SPARC doesn't care about FF80. -- module Format ( Format(..), intFormat, floatFormat, isFloatFormat, cmmTypeFormat, formatToWidth, formatInBytes ) where import GhcPrelude import Cmm import Outputable -- It looks very like the old MachRep, but it's now of purely local -- significance, here in the native code generator. You can change it -- without global consequences. -- -- A major use is as an opcode qualifier; thus the opcode -- mov.l a b -- might be encoded -- MOV II32 a b -- where the Format field encodes the ".l" part. -- ToDo: it's not clear to me that we need separate signed-vs-unsigned formats -- here. I've removed them from the x86 version, we'll see what happens --SDM -- ToDo: quite a few occurrences of Format could usefully be replaced by Width data Format = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80 deriving (Show, Eq) -- | Get the integer format of this width. intFormat :: Width -> Format intFormat width = case width of W8 -> II8 W16 -> II16 W32 -> II32 W64 -> II64 other -> sorry $ "The native code generator cannot " ++ "produce code for Format.intFormat " ++ show other ++ "\n\tConsider using the llvm backend with -fllvm" -- | Get the float format of this width. floatFormat :: Width -> Format floatFormat width = case width of W32 -> FF32 W64 -> FF64 W80 -> FF80 other -> pprPanic "Format.floatFormat" (ppr other) -- | Check if a format represents a floating point value. isFloatFormat :: Format -> Bool isFloatFormat format = case format of FF32 -> True FF64 -> True FF80 -> True _ -> False -- | Convert a Cmm type to a Format. cmmTypeFormat :: CmmType -> Format cmmTypeFormat ty | isFloatType ty = floatFormat (typeWidth ty) | otherwise = intFormat (typeWidth ty) -- | Get the Width of a Format. formatToWidth :: Format -> Width formatToWidth format = case format of II8 -> W8 II16 -> W16 II32 -> W32 II64 -> W64 FF32 -> W32 FF64 -> W64 FF80 -> W80 formatInBytes :: Format -> Int formatInBytes = widthInBytes . formatToWidth
shlevy/ghc
compiler/nativeGen/Format.hs
bsd-3-clause
2,833
0
11
954
408
228
180
60
7
{-# LANGUAGE TemplateHaskell #-} module T7667a where import Language.Haskell.TH -- to be correct, this should be ConE, not VarE! false = $( return $ VarE (mkName "False") )
urbanslug/ghc
testsuite/tests/th/T7667a.hs
bsd-3-clause
178
0
10
33
34
20
14
4
1
-- test for bug #1067 import Control.Concurrent import Control.Exception main = do master <- myThreadId test master 10 -- make sure we catch a final NonTermination exception to get -- a consistent result. threadDelay (10 * one_second) test tid 0 = return () test tid n = do e <- try threads case e of Left NonTermination -> test tid (n-1) Right _ -> return () where threads = do sequence $ replicate 3 $ forkIO $ do t <- myThreadId --putStrLn ("Start " ++ show t) threadDelay one_second --putStrLn ("End " ++ show t) throwTo tid NonTermination --putStrLn ("Thrown " ++ show t) threadDelay (10 * one_second) one_second :: Int one_second = 100000
hferreiro/replay
testsuite/tests/concurrent/should_run/conc064.hs
bsd-3-clause
938
3
12
407
211
95
116
19
2
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE ParallelListComp #-} -- On GHC 6.0 and earlier, this parallel list comprehension generated -- an incorrect unused-binding warning. module ShouldCompile where t :: [(Char,Char)] t = [ (a,b) | a <- "foo" | b <- "bar" ]
wxwxwwxxx/ghc
testsuite/tests/rename/should_compile/rn045.hs
bsd-3-clause
258
1
7
45
52
33
19
5
1
dist :: Double -> Double -> Double -> Double -> Double dist x1 y1 x2 y2 = ((x1 - x2)**2+(y1 - y2)**2)**0.5 myif :: Bool -> a -> a -> a myif b f s | b = f | otherwise = s mysgn :: Int -> Int mysgn x | x > 0 = 1 | x < 0 = -1 | otherwise = 0 comp :: (b -> c) -> (a -> b) -> (a -> c) --comp f1 f2 = \x -> f1(f2(x)) comp f1 f2 x = f1(f2(x)) (+--+) :: Int -> Int (+--+) x = 1 fib_rec (a, b, n) | n > 0 = fib_rec(a + b, a, n - 1) | otherwise = (a, b, n) fib n = let (res, _, _) = fib_rec (1, 0, n) in res rec :: a -> (a -> Int -> a) -> Int -> a rec z s n | n == 0 = z | otherwise = s (rec z s (n - 1)) n fac n = rec 1 (*) n fix f = (\x -> f (x x)) (\x -> f (x x))
SergeyKrivohatskiy/fp_haskell
class/class1.hs
mit
674
2
11
208
535
262
273
17
1
{-| Module : RTorrent Copyright : (c) Kai Lindholm, 2014 License : MIT Maintainer : [email protected] Stability : experimental A module that re-exports "Network.RTorrent.RPC" for convenience. -} module Network.RTorrent ( module Network.RTorrent.RPC ) where import Network.RTorrent.RPC
megantti/rtorrent-rpc
Network/RTorrent.hs
mit
308
0
5
58
22
15
7
3
0
module Graphics.Render.Layered( renderLayeredModel ) where import Prelude as P import Graphics.Layered.Layer import Graphics.Layered.Model import Graphics.GPipe import Graphics.Camera2D import Graphics.Light import Control.Applicative import GHC.Float import Data.Vec as Vec renderLayeredModel :: -- | Model to render LayeredModel -- | Floor to render -> Int -- | View camera of player -> Camera2D -- | Dynamic lights -> [Light Float] -- | Ambient RGB color, the fourth component is intensity -> Vec4 Float -- | Viewport size -> Vec2 Int -- | Stream of fragments with RGBA color plus depth info -> [FragmentStream (Color RGBAFormat (Fragment Float), FragmentDepth)] renderLayeredModel m floorNum cam lights ambient size = render (lmodelFloors m !! i) (double2Float $ fromIntegral i * lmodelFloorHeight m) where i = max 0 $ min (P.length (lmodelFloors m) - 1) floorNum render l d = renderLayer l cam (Vec.map double2Float $ lmodelPos m) (double2Float $ lmodelRot m) d lights ambient size renderLayer :: -- | Layer to render Layer -- | View camera of player -> Camera2D -- | World translation of layer -> Vec3 Float -- | World rotation of layer -> Float -- | Local Z depth of layer -> Float -- | Dynamic lights -> [Light Float] -- | Ambient RGB color, the fourth component is intensity -> Vec4 Float -- | Size of viewport -> Vec2 Int -- | Fragment shader with depth info and alpha channel -> [FragmentStream (Color RGBAFormat (Fragment Float), FragmentDepth)] renderLayer l c p r d ls a s = layerRenderer l c p r d ls a s : (concat $ (\cl -> renderLayer cl c p r d ls a s) <$> P.reverse (layerChilds l))
NCrashed/sinister
src/client/Graphics/Render/Layered.hs
mit
1,721
0
18
391
445
237
208
36
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.HTMLTableColElement ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.HTMLTableColElement #else module Graphics.UI.Gtk.WebKit.DOM.HTMLTableColElement #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.HTMLTableColElement #else import Graphics.UI.Gtk.WebKit.DOM.HTMLTableColElement #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/HTMLTableColElement.hs
mit
480
0
5
39
33
26
7
4
0
module Text.LevenshteinDistance (levenshteinDistance) where import Data.Array -- | -- Levenshtein Distance -- Measure similarity between two lists. -- -- >>> levenshteinDistance "hoge" "hoge" -- 0 -- >>> levenshteinDistance [1, 2, 3] [2, 2, 3] -- 1 levenshteinDistance :: Eq a => [a] -> [a] -> Int levenshteinDistance as [] = length as levenshteinDistance [] bs = length bs levenshteinDistance as bs = table ! (lenA, lenB) where arrayA = fromList as arrayB = fromList bs table = makeArray ((0, 0), (lenA, lenB)) f lenA = length as lenB = length bs f (0, b) = b f (a, 0) = a f (a, b) | charA == charB = table ! (a-1, b-1) | otherwise = 1 + minimum [ remove , insert , replace] where remove = table ! (a-1, b) insert = table ! (a, b-1) replace = table ! (a-1, b-1) charA = arrayA ! (a-1) charB = arrayB ! (b-1) fromList :: [a] -> Array Int a fromList ls = array (0, length ls - 1) $ zip [0..] ls makeArray :: Ix i => (i, i) -> (i -> e) -> Array i e makeArray bnds f = array bnds [(i, f i) | i <- range bnds]
ayachigin/LevenshteinDistance
src/Text/LevenshteinDistance.hs
mit
1,218
0
11
415
481
262
219
27
3
{-# LANGUAGE DeriveDataTypeable #-} module SphereHelloApi.Products (getProducts, ProductResponse (..), Product (..)) where import Network.Curl import SphereHelloApi.ApiAccess import SphereHelloApi.Tokens import Text.JSON.Generic getProductsOpts t = -- CurlVerbose True : CurlHttpHeaders ["Authorization: Bearer " ++ access_token t] : method_GET getProducts :: Curl -> ApiConfig -> TokenResponse -> IO ProductResponse getProducts c cfg t = do resp <- do_curl_ c (productsUrl cfg) (getProductsOpts t) :: IO CurlResponse -- putStrLn $ respBody resp return $ decodeJSON (respBody resp) data ProductResponse = ProductResponse { total :: Int , count :: Int , offset :: Int , results :: [Product] } deriving (Eq, Show, Data, Typeable) -- For all the available data see: http://sphere.io/dev/HTTP_API_Projects_Products.html#product-projection data Product = Product { name :: String , description :: String , slug :: String } deriving (Eq, Show, Data, Typeable)
sphereio/sphere-hello-api
haskell/src/SphereHelloApi/Products.hs
mit
1,001
0
10
176
256
144
112
24
1
module Hate.Graphics.Backend.Modern.Types where import Hate.Graphics.Types import Hate.Graphics.Backend.Common.Pipeline -- supposedly needs more vertex streams and pipelines in the future data BackendModern = BackendModern { solidColorPipeline :: Pipeline, texturingPipeline :: Pipeline, globalVertexStream :: VertexStream, screenSize :: (Int, Int) }
bananu7/Hate
src/Hate/Graphics/Backend/Modern/Types.hs
mit
380
0
9
66
63
43
20
8
0
{- Haskell: map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x:xs) = f x : map f xs -or- map f xs = [ f x | x <- xs ] "Any" language: var ys = new List<T>(); for (var x in xs) { ys.Append(f(x)); } C# LINQ: var ys = from x in xs select f(x); Python: var ys = [ f(x) for x in xs ] Haskell: filter p xs = [x | x <- xs, p x] LINQ: var ys = from x in xs where p(x) select x; C#: ys = [ x for x in xs if p(x) ] -} -- Functions with the same pattern/scheme fssum [] = 0 fssum (x:xs) = x + fssum xs fsproduct [] = 1 fsproduct (x:xs) = x * fsproduct xs fsor [] = False fsor (x:xs) = x || fsor xs fsand [] = True fsand (x:xs) = x && fsand xs fslength [] = 0 fslength (_:xs) = 1 + fslength xs -- All use the "foldr" pattern fssum2 = foldr (+) 0 fsproduct2 = foldr (*) 0 fsor2 = foldr (||) False fsand2 = foldr (&&) True fslenght2 = foldr (\_ n -> 1 + n) 0 fsreverse = foldr (\x xs -> xs ++ [x]) [] -- actually, even ++ is a fold -- 1) xs ++ ys = foldr (:) ys xs -- 2) (++) ys xs = foldr (:) ys xs -- 3) (++) ys = foldr (:) ys -- 4) (++) = foldr (:) fsfoldr :: (a -> b -> b) -> b -> [a] -> b fsfoldr _ v [] = v fsfoldr f v (x:xs) = f x (fsfoldr f v xs) {- -- Interesting (although inneficient) implementation of length length = sum . map (\_ -> 1) length [1,2,3..n] sum (map (\_ -> 1) [1,2,3..n]) sum [1,1,1..1] n -} -- the same as . (as used in the length example) compose :: (b -> c) -> (a -> b) -> (a -> c) compose f g = \x -> f (g x) -- Exercise 1 -- Function generators? Meta function? Closures? Lambdas? -- Exercise 2 -- [f x | x <- xs, p x] -- filter p (map f xs) -- Exercise 3 -- fdmap f xs = foldr (\x ys -> f x : ys) [] xs fdmap f xs = foldr g [] xs where g x ys = f x : ys fdfilter p xs = foldr (\x ys -> if p x then x:ys else ys) [] xs -- fdmap (*2) [1,2,3,4] -- fdfilter (/=' ') "Felipo Soranz Programa Em Haskell" -- Exercise 4 -- How many functions of the standard library can be defined as a fold
feliposz/learning-stuff
haskell/c9lectures-ch7.hs
mit
1,943
9
10
501
550
273
277
24
2
module Options where import Options.Applicative ((<>), Parser) import qualified Options.Applicative as P data Options = Opts { inFileOpt :: FilePath , outDirOpt :: FilePath , maxSizeOpt :: Int , cmdOpt :: Command } deriving (Eq, Show) data Command = Roads | RoadLinks | RoadNodes | FerryLinks | FerryNodes deriving (Eq, Ord, Show) getOptions :: IO Options getOptions = P.execParser $ P.info (P.helper <*> parseOptions) $ P.header "gml-explorer" <> P.progDesc "Explore an OS GML file" <> P.fullDesc parseOptions :: Parser Options parseOptions = Opts <$> parseInputFile <*> parseOutputDir <*> parseMaxFileSize <*> parseCommand parseInputFile :: Parser FilePath parseInputFile = P.argument P.str $ P.metavar "INPUT_FILE" <> P.help "File containing OS GML input" parseOutputDir :: Parser FilePath parseOutputDir = P.strOption $ P.metavar "OUTPUT_DIR" <> P.short 'o' <> P.value "out" <> P.showDefault <> P.help "Output directory" parseMaxFileSize :: Parser Int parseMaxFileSize = P.option P.auto $ P.metavar "MAX_FILE_SIZE" <> P.short 's' <> P.value (30 * 1024 * 1024) <> P.showDefault <> P.help "Maximum size of file to output" parseCommand :: Parser Command parseCommand = P.subparser $ command "roads" "Output OS Road geometry" Roads <> command "roadlinks" "Output OS RoadLink geometry" RoadLinks <> command "roadnodes" "Output OS RoadNode geometry" RoadNodes <> command "ferrylinks" "Output OS FerryLink geometry" FerryLinks <> command "ferrynodes" "Output OS FerryNode geometry" FerryNodes command :: String -> String -> Command -> P.Mod P.CommandFields Command command name desc cmd = P.command name (P.info (P.helper <*> P.pure cmd) (P.progDesc desc))
mietek/gml-explorer
src/Options.hs
mit
1,928
0
12
508
506
260
246
64
1
module Workouts_Test where import qualified Workouts as W import Data.Time.Calendar (fromGregorian) import Test.Framework (testGroup, Test) import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test) kDefaultLookback = 36500 workoutsSuite :: Test workoutsSuite = testGroup "Workouts" [ testCase "" $ testComputeRest , testCase "" $ testRankAsc , testCase "" $ testParseDuration "20:00" (Just $ 20 * 60) , testCase "" $ testParseDuration "1:00:00" (Just $ 60 * 60) , testCase "" $ testParseDuration "foo" Nothing , testCase "" $ testParseLookback (Just "xyz") kDefaultLookback , testCase "" $ testParseLookback (Just "12345") 12345 , testCase "" $ testParseLookback (Nothing) kDefaultLookback ] testComputeRest :: Assertion testComputeRest = assertEqual "rest" [0, 0, 0, 9, 0] $ W.computeRest [ (fromGregorian 2000 1 1) , (fromGregorian 2000 1 2) , (fromGregorian 2000 1 3) , (fromGregorian 2000 1 13) , (fromGregorian 2000 1 13) ] testRankAsc :: Assertion testRankAsc = assertEqual "rankAsc" [4, 1, 3, 2] $ W.rankAsc [10, 1, 9, 2] testParseDuration :: String -> Maybe Int -> Assertion testParseDuration input output = assertEqual ("parseDuration: " ++ input) output (W.parseDuration input) testParseLookback :: Maybe String -> Integer -> Assertion testParseLookback input output = assertEqual ("parseLookback: " ++ (show input)) output (W.parseLookback input)
mrjones/workouts
test/Workouts_Test.hs
mit
1,491
0
11
313
473
254
219
36
1
----------------------------------------------------------------------------- -- Copyright : (c) Hanzhong Xu, Meng Meng 2016, -- License : MIT License -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- -- A simple clock ----------------------------------------------------------------------------- {-# LANGUAGE Arrows #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} module Main where import Control.Arrow import Control.Applicative import Control.Monad import Data.AFSM import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.TChan import Control.Concurrent.Timer import Data.IORef import Foreign.C.Types import Foreign.Ptr import Linear import Linear.Affine ( Point(P) ) import Data.Word import Data.StateVar import Data.Monoid import Data.Maybe import Data.Time.Clock import qualified SDL import qualified SDL.Time secondSF :: Int -> SF Int (Int, Bool) secondSF init = simpleSF (\s x -> let s' = mod (s+x) 60000; y = div s' 1000 in (s', (y, y == 0))) (init * 1000) minuteSF :: Int -> SF Bool (Int, Bool) minuteSF = simpleSF (\s x -> if x then let s' = mod (s + 1) 60 in (s', (s', s' == 0)) else (s, (s, False))) hourSF :: Int -> SF Bool (Int, Bool) hourSF = simpleSF (\s x -> if x then let s' = mod (s + 1) 12 in (s', (s', s' == 0)) else (s, (s, False))) clockSF :: (Int, Int, Int) -> SF Int [(Int,Int,Int)] clockSF (h',m',s') = proc ms -> do (s,sb) <- secondSF s' -< ms (m,mb) <- minuteSF m' -< sb (h,hb) <- hourSF h' -< mb returnA -< [(h,m,s)] black, white, red, green, blue :: V4 Word8 black = V4 0 0 0 maxBound white = V4 maxBound maxBound maxBound maxBound red = V4 maxBound 0 0 maxBound green = V4 0 maxBound 0 maxBound blue = V4 0 0 maxBound maxBound timerCallback :: TChan Int -> Word32 -> IO SDL.Time.RetriggerTimer timerCallback ch interval = do atomically $ writeTChan ch $ fromIntegral interval return $ SDL.Time.Reschedule 1000 renderOutput :: SDL.Renderer -> (Int, Int, Int) -> IO () renderOutput renderer (h,m,s) = do putStrLn $ show (h,m,s) SDL.rendererDrawColor renderer $= white SDL.clear renderer SDL.rendererDrawColor renderer $= black SDL.drawRect renderer (Just (SDL.Rectangle (P (V2 50 50)) (V2 200 200))) let x = 150; y = 150; a = (1 - fromIntegral s / 30) * pi; xs = x + round (100 * (sin a)); ys = y + round (100 * (cos a)); b = (1 - fromIntegral m / 30) * pi; xm = x + round (70 * (sin b)); ym = y + round (70 * (cos b)); c = (1 - fromIntegral h / 6 - fromIntegral m / 360) * pi; xh = x + round (40 * (sin c)); yh = y + round (40 * (cos c)); SDL.rendererDrawColor renderer $= red SDL.drawLine renderer (P (V2 x y)) (P (V2 xs ys)) SDL.rendererDrawColor renderer $= green SDL.drawLine renderer (P (V2 x y)) (P (V2 xm ym)) SDL.rendererDrawColor renderer $= blue SDL.drawLine renderer (P (V2 x y)) (P (V2 xh yh)) SDL.present renderer main :: IO () main = do SDL.initializeAll window <- SDL.createWindow "Clock" SDL.defaultWindow { SDL.windowInitialSize = V2 300 300 } renderer <- SDL.createRenderer window (-1) SDL.defaultRenderer time <- getCurrentTime putStrLn $ show time let t = (floor $ toRational $ utctDayTime time); hour = mod ((div t 3600) + 17) 12; minute = div (mod t 3600) 60; second = mod t 60; now = (hour, minute, second); tc <- newBroadcastTChanIO clock <- sf2TSF $ clockSF now (tids, ret) <- clock tc tid <- forkOS $ outputTChan ret (renderOutput renderer) SDL.addTimer 1000 (timerCallback tc) let loop = (do events <- SDL.pollEvents; let Any quit = foldMap (\case SDL.QuitEvent -> Any True SDL.KeyboardEvent e -> if | SDL.keyboardEventKeyMotion e == SDL.Pressed -> case SDL.keysymScancode (SDL.keyboardEventKeysym e) of SDL.ScancodeQ -> Any True _ -> mempty | otherwise -> mempty _ -> mempty) $ map SDL.eventPayload events unless quit $ loop) renderOutput renderer now SDL.showWindow window loop forM_ tids killThread killThread tid SDL.destroyRenderer renderer SDL.destroyWindow window SDL.quit
PseudoPower/AFSM
examples/SF/Clock.hs
mit
4,455
1
28
1,072
1,747
909
838
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} module Common where import Web.Twitter.Conduit import Web.Authenticate.OAuth as OA import qualified Network.URI as URI import Network.HTTP.Conduit import qualified Data.Map as M import qualified Data.ByteString.Char8 as S8 import qualified Data.CaseInsensitive as CI import Control.Applicative import Control.Monad.IO.Class import Control.Monad.Base import Control.Monad.Trans.Resource import System.Environment import Control.Monad.Logger import Control.Lens getOAuthTokens :: IO (OAuth, Credential) getOAuthTokens = do consumerKey <- getEnv' "TWITTER_KEY" consumerSecret <- getEnv' "TWITTER_SECRET" accessToken <- getEnv' "TW_TOKEN" accessSecret <- getEnv' "TW_SECRET" let oauth = twitterOAuth { oauthConsumerKey = consumerKey , oauthConsumerSecret = consumerSecret } cred = Credential [ ("oauth_token", accessToken) , ("oauth_token_secret", accessSecret) ] return (oauth, cred) where getEnv' = (S8.pack <$>) . getEnv getProxyEnv :: IO (Maybe Proxy) getProxyEnv = do env <- M.fromList . over (mapped . _1) CI.mk <$> getEnvironment let u = M.lookup "https_proxy" env <|> M.lookup "http_proxy" env <|> M.lookup "proxy" env >>= URI.parseURI >>= URI.uriAuthority return $ Proxy <$> (S8.pack . URI.uriRegName <$> u) <*> (parsePort . URI.uriPort <$> u) where parsePort :: String -> Int parsePort [] = 8080 parsePort (':':xs) = read xs parsePort xs = error $ "port number parse failed " ++ xs runTwitterFromEnv :: (MonadIO m, MonadBaseControl IO m) => TW (ResourceT m) a -> m a runTwitterFromEnv task = do pr <- liftBase getProxyEnv (oa, cred) <- liftBase getOAuthTokens let env = (setCredential oa cred def) { twProxy = pr } runTW env task runTwitterFromEnv' :: (MonadIO m, MonadBaseControl IO m) => TW (ResourceT (NoLoggingT m)) a -> m a runTwitterFromEnv' = runNoLoggingT . runTwitterFromEnv
DanielTomlinson/Twitter-Stream-Haskell
Common.hs
mit
2,091
0
15
456
600
323
277
51
3
{-# OPTIONS_GHC -fno-warn-unused-binds #-} --TODO module Il.Analyzer (analyzeIl) where import Defs.Structures import Defs.Common import Il.AST import Analyzer hiding (getFunName, getFunArgs, getFunType) import Data.Monoid import Control.Monad.State -- | Runs everything that is needed to analyze a program analyzeIl :: [Function] -> [DSInfo] analyzeIl functions = let dsfs = map generateDSF functions in analyzeDSF dsfs -- | Start the state monad to create a 'DSFun' for function generateDSF :: Function -> DSFun Type generateDSF fn = let (dsus, st) = runState (sumTerms step [getFunBody fn]) (AS []) in let fd = FunDecl (getFunName fn) (getFunType fn) (getFunArgs fn) in DSF fd (getStateCalls st) (generateDSI (getFunName fn) dsus) -- | Analyze a block of terms using the state monad stepBlock :: [Term] -> TermAnalyzer Output stepBlock = sumTerms step -- | Sums the 'DSUse's using the 'step' function and concating the results sumTerms :: (Term -> TermAnalyzer Output) -> [Term] -> TermAnalyzer Output sumTerms f ts = fmap concat (mapM f ts) -- | Function putting a function call in the state putCall :: FunctionName -> [Term] -> TermAnalyzer () putCall name args = do let cleanArgs = map justifyVars args let call = (name, cleanArgs) modify $ \s -> s {getStateCalls = call:getStateCalls s} where justifyVars :: Term -> Maybe VariableName justifyVars (Var v) = Just v -- FIXME should work on function calls returning dses, not only vars justifyVars _ = Nothing -- | Generate 'DSUse's for a single 'Term' step :: Term -> TermAnalyzer Output step (Block body) = stepBlock body step (VarInit _ Ds) = return [] step (InitAssign _ _ Ds) = return [] step (While cond body) = stepBlock [cond,body] step (Funcall name args) = do let opname = case name of -- FIXME nicer with usage of dsinfFunctions from Common F "insert" -> Just InsertVal F "find" -> Just FindByVal F "update" -> Just UpdateByRef F "max" -> Just ExtremalVal F "delete_max" -> Just DeleteExtremalVal _ -> Nothing -- FIXME add reading the function calls argDsus <- stepBlock args funcallDsu <- case opname of Nothing -> do putCall name args return [] Just op -> case head args of -- FIXME dsinfFunctions ds argument recognition Var varname -> return [(varname, DSU op False False)] _ -> error "Not implemented yet" return $ argDsus ++ funcallDsu step (If cond t1 t2) = do dsuCond <- step cond oldState <- get dsuT1 <- step t1 stateT1 <- get put oldState dsuT2 <- step t2 stateT2 <- get put (stateT1 `mappend` stateT2) return $ concat [dsuCond, dsuT1, dsuT2] -- Dummy steps step t = case t of Var _ -> return [] VarInit _ _ -> return [] Inc _ -> return [] Dec _ -> return [] Int _ -> return [] Assign _ t -> step t Lt t1 t2 -> stepBlock [t1, t2] Mul t1 t2 -> stepBlock [t1, t2] s -> error $ "No step for " ++ show s
alistra/data-structure-inferrer
Il/Analyzer.hs
mit
3,183
0
17
893
1,000
489
511
69
16
module Parser (runTerm) where import Syntax import Eval import Control.Arrow ((+++)) import Unbound.Generics.LocallyNameless (bind, string2Name) import Text.Parsec import Text.Parsec.String (Parser) import qualified Text.Parsec.Token as Tok import Text.Parsec.Language (haskellDef) lexer :: Tok.TokenParser () lexer = Tok.makeTokenParser haskellDef reservedOp :: String -> Parser () reservedOp = Tok.reservedOp lexer parens :: Parser a -> Parser a parens = Tok.parens lexer ident :: Parser String ident = Tok.identifier lexer var :: Parser Term var = do x <- ident return $ Var (string2Name x) lambda :: Parser Term lambda = do reservedOp "\\" x <- ident reservedOp "." t <- parseTerm return $ Lam (bind (string2Name x) t) parseTerm :: Parser Term parseTerm = expr `chainl1` pure App expr :: Parser Term expr = parens parseTerm <|> var <|> lambda runTerm :: String -> Either ParseError Term runTerm = (id +++ eval) . parse parseTerm "<from file>"
kellino/TypeSystems
simpleUntyped/Parser.hs
mit
1,018
0
12
214
346
182
164
37
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html module Stratosphere.ResourceProperties.WAFRegionalSizeConstraintSetSizeConstraint where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.WAFRegionalSizeConstraintSetFieldToMatch -- | Full data type definition for WAFRegionalSizeConstraintSetSizeConstraint. -- See 'wafRegionalSizeConstraintSetSizeConstraint' for a more convenient -- constructor. data WAFRegionalSizeConstraintSetSizeConstraint = WAFRegionalSizeConstraintSetSizeConstraint { _wAFRegionalSizeConstraintSetSizeConstraintComparisonOperator :: Val Text , _wAFRegionalSizeConstraintSetSizeConstraintFieldToMatch :: WAFRegionalSizeConstraintSetFieldToMatch , _wAFRegionalSizeConstraintSetSizeConstraintSize :: Val Integer , _wAFRegionalSizeConstraintSetSizeConstraintTextTransformation :: Val Text } deriving (Show, Eq) instance ToJSON WAFRegionalSizeConstraintSetSizeConstraint where toJSON WAFRegionalSizeConstraintSetSizeConstraint{..} = object $ catMaybes [ (Just . ("ComparisonOperator",) . toJSON) _wAFRegionalSizeConstraintSetSizeConstraintComparisonOperator , (Just . ("FieldToMatch",) . toJSON) _wAFRegionalSizeConstraintSetSizeConstraintFieldToMatch , (Just . ("Size",) . toJSON) _wAFRegionalSizeConstraintSetSizeConstraintSize , (Just . ("TextTransformation",) . toJSON) _wAFRegionalSizeConstraintSetSizeConstraintTextTransformation ] -- | Constructor for 'WAFRegionalSizeConstraintSetSizeConstraint' containing -- required fields as arguments. wafRegionalSizeConstraintSetSizeConstraint :: Val Text -- ^ 'wafrscsscComparisonOperator' -> WAFRegionalSizeConstraintSetFieldToMatch -- ^ 'wafrscsscFieldToMatch' -> Val Integer -- ^ 'wafrscsscSize' -> Val Text -- ^ 'wafrscsscTextTransformation' -> WAFRegionalSizeConstraintSetSizeConstraint wafRegionalSizeConstraintSetSizeConstraint comparisonOperatorarg fieldToMatcharg sizearg textTransformationarg = WAFRegionalSizeConstraintSetSizeConstraint { _wAFRegionalSizeConstraintSetSizeConstraintComparisonOperator = comparisonOperatorarg , _wAFRegionalSizeConstraintSetSizeConstraintFieldToMatch = fieldToMatcharg , _wAFRegionalSizeConstraintSetSizeConstraintSize = sizearg , _wAFRegionalSizeConstraintSetSizeConstraintTextTransformation = textTransformationarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-comparisonoperator wafrscsscComparisonOperator :: Lens' WAFRegionalSizeConstraintSetSizeConstraint (Val Text) wafrscsscComparisonOperator = lens _wAFRegionalSizeConstraintSetSizeConstraintComparisonOperator (\s a -> s { _wAFRegionalSizeConstraintSetSizeConstraintComparisonOperator = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-fieldtomatch wafrscsscFieldToMatch :: Lens' WAFRegionalSizeConstraintSetSizeConstraint WAFRegionalSizeConstraintSetFieldToMatch wafrscsscFieldToMatch = lens _wAFRegionalSizeConstraintSetSizeConstraintFieldToMatch (\s a -> s { _wAFRegionalSizeConstraintSetSizeConstraintFieldToMatch = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-size wafrscsscSize :: Lens' WAFRegionalSizeConstraintSetSizeConstraint (Val Integer) wafrscsscSize = lens _wAFRegionalSizeConstraintSetSizeConstraintSize (\s a -> s { _wAFRegionalSizeConstraintSetSizeConstraintSize = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-texttransformation wafrscsscTextTransformation :: Lens' WAFRegionalSizeConstraintSetSizeConstraint (Val Text) wafrscsscTextTransformation = lens _wAFRegionalSizeConstraintSetSizeConstraintTextTransformation (\s a -> s { _wAFRegionalSizeConstraintSetSizeConstraintTextTransformation = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/WAFRegionalSizeConstraintSetSizeConstraint.hs
mit
4,351
0
13
331
442
253
189
42
1
module Fresh.Unify where import Control.Monad (forM_, when, void, unless) import Control.Monad.Error.Class (MonadError(..)) import qualified Data.Map as Map import Data.STRef import qualified Fresh.OrderedSet as OrderedSet import Fresh.Pretty (Pretty(..)) import Fresh.Types import Fresh.InferMonad unchain :: SType s -> Infer s (SType s) unchain t@(SType (TyVar tvar)) = do vt <- readVar tvar case vt of Unbound{} -> return t Link t' -> unchain t' unchain t = return t unify :: SType s -> SType s -> Infer s () unify t1 t2 = do k1 <- getKind t1 k2 <- getKind t2 when (k1 /= k2) $ throwError $ KindMismatchError k1 k2 t1' <- unchain t1 t2' <- unchain t2 pt1 <- purify t1' pt2 <- purify t2' let wrapError :: TypeError -> Infer s () wrapError e = throwError (WrappedError (UnificationError (show $ pretty pt1) (show $ pretty pt2)) e) unify' t1' t2' `catchError` wrapError unify' :: SType s -> SType s -> Infer s () unify' (SType (TyVar tvar1)) (SType (TyVar tvar2)) = do vt1 <- readVar tvar1 vt2 <- readVar tvar2 case (vt1, vt2) of (Unbound _n1 l1, Unbound _n2 l2) -> if l1 < l2 then writeVar tvar2 vt1 else writeVar tvar1 vt2 (Unbound{}, Link lt2) -> varBind tvar1 lt2 (Link lt1, Unbound{}) -> varBind tvar2 lt1 (Link lt1, Link lt2) -> unify' lt1 lt2 unify' (SType (TyVar tvar)) t = varBind tvar t unify' t (SType (TyVar tvar)) = varBind tvar t unify' (SType (TyAST t1)) (SType (TyAST t2)) = unifyAST t1 t2 unifyAST :: TypeAST Level (SType s) -> TypeAST Level (SType s) -> Infer s () unifyAST (TyAp t1 t2) (TyAp t1' t2') = do unify t1 t1' unify t2 t2' unifyAST (TyCon tc1) (TyCon tc2) | tc1 == tc2 = return () unifyAST (TyGenVar g1) (TyGenVar g2) | g1 == g2 = return () unifyAST u1@(TyGen vs1 (QualType ps1 t1)) u2@(TyGen vs2 (QualType ps2 t2)) | length vs1 == length vs2 = do -- TODO: check instance relation (subsumption) ks1 <- mapM getKind vs1 ks2 <- mapM getKind vs2 forM_ (zip ks1 ks2) $ \(k1, k2) -> when (k1 /= k2 ) $ throwError $ KindMismatchError k1 k2 curLevel <- getCurrentLevel skolems <- mapM (\k -> GenVar <$> freshName <*> pure k <*> pure curLevel) ks1 let skolemTs = map (SType . TyAST . TyGenVar) skolems t1' <- substGens vs1 skolemTs t1 t2' <- substGens vs2 skolemTs t2 unify t1' t2' gvs1 <- liftST $ freeGenVars u1 gvs2 <- liftST $ freeGenVars u2 unless (OrderedSet.null $ OrderedSet.fromList skolems `OrderedSet.intersection` (gvs1 `OrderedSet.concatUnion` gvs2) ) $ throwError $ EscapedSkolemError $ concat [ "Type not polymorphic enough to unify" , "\n\t", "Type 1: ", show u1 , "\n\t", "Type 2: ", show u2 ] unifyAST (TyComp CompositeTerminal) (TyComp CompositeTerminal) = return () unifyAST (TyComp c1) (TyComp c2) = do let FlatComposite labels1 mEnd1 = flattenComposite c1 FlatComposite labels2 mEnd2 = flattenComposite c2 common = Map.intersectionWith (,) labels1 labels2 in1only = Map.difference labels1 labels2 in2only = Map.difference labels2 labels1 emptyRow = SType $ TyAST $ TyComp CompositeTerminal -- TODO: wrap errors to say which field failed forM_ (Map.elems common) $ uncurry unify remainderVar <- freshRVar if Map.null in1only && Map.null in2only then case (mEnd1, mEnd2) of (Nothing, Nothing) -> return () (Just e, Nothing) -> unify e emptyRow (Nothing, Just e) -> unify e emptyRow (Just e1, Just e2) -> unify e1 e2 else do let remainderVarT = SType $ TyVar remainderVar unifyRemainder rem' mEnd = -- e1 + r1 = e2 + r2 -- (r + r2) + r1 = (r + r1) + r2 case mEnd of Nothing -> if Map.null rem' then varBind remainderVar emptyRow else traverse purify rem' >>= \pt -> throwError $ RowEndError (show $ fmap pretty pt) Just end -> unify (SType $ TyAST $ TyComp $ unflattenComposite $ FlatComposite rem' $ Just remainderVarT) end unifyRemainder in1only mEnd2 unifyRemainder in2only mEnd1 unifyAST t1 t2 = unifyError (SType $ TyAST t1) (SType $ TyAST t2) unifyError :: SType s -> SType s -> Infer s a unifyError t1 t2 = do pt1 <- purify t1 pt2 <- purify t2 throwError $ UnificationError (show $ pretty pt1) (show $ pretty pt2) varBind :: TypeVar (STRef s) (SType s) -> SType s -> Infer s () varBind tvar t = do tvarK <- getKind tvar tK <- getKind t when (tvarK /= tK) $ throwError $ KindMismatchError tvarK tK vt <- readVar tvar case vt of Link t' -> unify t' t Unbound name l1 -> --writeVar tvar (Link t) case t of (SType (TyVar tvar2)) -> do vt2 <- readVar tvar2 case vt2 of Link t2 -> unify (SType $ TyVar tvar) t2 Unbound _name2 l2 -> do writeVar tvar (Link t) -- adjust the lambda-rank of the unifiable variable when (l2 > l1) (writeVar tvar2 (Unbound _name2 l1)) (SType (TyAST tast)) -> do tvs <- liftST $ freeVars tast when (name `OrderedSet.member` tvs) $ do pt <- purify t throwError $ OccursError (show $ pretty vt) (show $ pretty pt) writeVar tvar (Link t) -- adjust the lambda-rank of the unifiable variables in tp2 adjustLevel l1 t adjustLevel :: Level -> SType s -> Infer s () adjustLevel l (SType (TyVar tvar)) = do tv <- readVar tvar case tv of Link t -> adjustLevel l t Unbound name l' -> when (l' > l) (writeVar tvar (Unbound name l)) adjustLevel l (SType (TyAST t)) = void $ traverse (adjustLevel l) t
sinelaw/fresh
src/Fresh/Unify.hs
gpl-2.0
6,186
0
24
2,032
2,283
1,095
1,188
133
7
-- -- Web redirector -- -- Copyright © 2011-2018 Operational Dynamics Consulting, Pty Ltd -- -- The code in this file, and the program it is a part of, is made available -- to you by its authors as open source software: you can redistribute it -- and/or modify it under the terms of the GNU General Public License version -- 2 ("GPL") as published by the Free Software Foundation. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -- FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. -- -- You should have received a copy of the GPL along with this program. If not, -- see http://www.gnu.org/licenses/. The authors of this program may be -- contacted through http://research.operationaldynamics.com/ -- {-# LANGUAGE OverloadedStrings, FlexibleInstances #-} module Lookup (lookupHash, storeURL) where import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.Maybe (fromMaybe) import Database.Redis import Control.Exception.Lifted (SomeException, bracket) import Control.Monad.Trans (liftIO) import Numeric (showHex) import System.Random (randomRIO) import Data.Locator (toBase62, fromBase62, padWithZeros, hashStringToBase62) -- -- Utility function to extract the reply from the complex type hedis returns. If -- there's an error condition (regardless of whether it is a Left for server -- error or Nothing for a blank value), return an empty string. -- fromReply :: (Either Reply (Maybe S.ByteString)) -> S.ByteString fromReply x' = either first second x' where first :: Reply -> S.ByteString first (Error s') = s' first _ = "" second :: (Maybe S.ByteString) -> S.ByteString second = fromMaybe "" -- -- Process jump hash. This entry point gets us from IO into the Redis monad, -- and deals with connection setup and teardown. -- lookupHash :: S.ByteString -> IO S.ByteString lookupHash x = bracket (connect defaultConnectInfo) (\r -> runRedis r $ quit) (\r -> runRedis r $ queryTarget x) queryTarget :: S.ByteString -> Redis S.ByteString queryTarget x' = let key = S.append "target:" x' in do k <- get key return $ fromReply k -- -- Store a new URL and return the assigned hash. This entry point likewise wraps -- getting us from IO into the Redis monad, and deals with connection setup and -- teardown. -- storeURL :: S.ByteString -> IO S.ByteString storeURL u' = bracket (connect defaultConnectInfo) (\r -> runRedis r $ quit) (\r -> runRedis r $ checkExistingKey u') -- -- Given a URL, generate a hash for it and store at that address. Return the -- hash. Complications: first check to see that we haven't already stored that -- URL; and, when storing, if the key already exists, we need to find choose -- another. -- checkExistingKey :: S.ByteString -> Redis S.ByteString checkExistingKey u' = do h' <- queryInverse y' if S.null h' then storeNewKey u' y' else return h' where y' = hashStringToBase62 27 u' queryInverse :: S.ByteString -> Redis S.ByteString queryInverse y' = let key = S.append "inverse:" y' in do k <- get key return $ fromReply k storeNewKey :: S.ByteString -> S.ByteString -> Redis S.ByteString storeNewKey u' y' = do x' <- findAvailableKey let targetKey = S.append "target:" x' targetValue = u' inverseKey = S.append "inverse:" y' inverseValue = x' set targetKey targetValue set inverseKey inverseValue return x' findAvailableKey :: Redis S.ByteString findAvailableKey = do num <- liftIO $ randomRIO (0, 62^5) let x' = S.pack . padWithZeros 5 . toBase62 $ num v' <- queryTarget x' if S.null v' then return x' else findAvailableKey
oprdyn/redirector
src/Lookup.hs
gpl-2.0
3,873
0
13
833
778
413
365
69
2
{- Chapter 8.9 Exercises -} {- 1. -} data Nat = Zero | Succ Nat deriving Show add :: Nat -> Nat -> Nat add Zero n = n add (Succ m) n = Succ (add m n) {- add (Succ (Succ Zero)) (Succ Zero) = Succ (add (Succ Zero) (Succ Zero)) = Succ (Succ (add Zero (Succ Zero))) = Succ (Succ (Succ Zero)) -} mult :: Nat -> Nat -> Nat mult m Zero = Zero mult m (Succ n) = add m (mult m n) {- 2 x 1: mult (Succ (Succ Zero)) (Succ Zero) = add (Succ (Succ Zero)) (mult (Succ (Succ Zero)) Zero) = add (Succ (Succ Zero)) Zero = Succ (add (Succ Zero) Zero) = Succ (Succ (add Zero Zero)) = Succ (Succ (Zero)) = Succ (Succ Zero) = 2 2 x 3: 2 x (1 + 2) = 2 + (2 * 2) = 2 + (2 + (2 * 1) = 2 + (2 + (2 + (2 * 0)) = 2 + (2 + (2 + 0)) = 6 mult (Succ (Succ Zero)) (Succ (Succ (Succ Zero))) = Succ (Succ (Succ (Succ (Succ (Succ Zero))))) = 6 -} {- 2. :t compare > compare :: Ord a => a -> a -> Ordering compare 3 5 = LT -} data Tree a = Leaf a | Node (Tree a) a (Tree a) t :: Tree Int t = Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9)) -- occurs :: Eq a => a -> Tree a -> Bool -- occurs x (Leaf y) = x == y -- occurs x (Node l y r) = x == y || occurs x l || occurs x r occurs :: Ord a => a -> Tree a -> Bool occurs x (Leaf y) = x == y occurs x (Node l y r) = case compare x y of LT -> occurs x l EQ -> True GT -> occurs x r {- It is more efficient because it only searches the side of the tree that is likely to have the value. -} {- 3. -} data Tree' a = Leaf' a | Node' (Tree' a) (Tree' a) deriving Show countLeaves :: Tree' a -> Int countLeaves (Leaf' a) = 1 countLeaves (Node' l r) = countLeaves l + countLeaves r t' :: Tree' Int t' = Node' (Node' (Leaf' 3) (Leaf' 4)) (Node' (Leaf' 2) (Node' (Leaf' 5) (Leaf' 1))) -- a tree is balanced if the leaves in the left and right subtree -- differs by most one and also the subtrees themselves are balanced. balanced :: Tree' a -> Bool balanced (Leaf' a) = True balanced (Node' l r) = (abs $ (countLeaves l) - (countLeaves r)) <= 1 && balanced l && balanced r {- 4. -} halve :: [a] -> ([a],[a]) halve [] = ([],[]) halve xs = splitAt (length xs `div` 2) xs balance :: [a] -> Tree' a balance [x] = Leaf' x balance xs = Node' (balance a) (balance b) where (a,b) = halve xs {- balance [1,2,3,4,5] = Node' (Node' (Leaf' 1) (Leaf' 2)) (Node' (Leaf' 3) (Node' (Leaf' 4) (Leaf' 5))) balance [3, 2, 4] = Node' (Leaf' 3) (Node' (Leaf' 2) (Leaf' 4)) -} {- 5. -} data Expr = Val Int | Add Expr Expr | Mult Expr Expr folde :: (Int -> a) -> (a -> a -> a) -> Expr -> a folde f g (Val x) = f x folde f g (Add x y) = g (folde f g x) (folde f g y) {- folde (\x -> x+10) (\x y -> x + y) (Val 2) = 12 folde (\x -> x+10) (\x y -> x + y) (Add (Val 2) (Val 3)) = 25 -} {- 6. -} eval' :: Expr -> Int eval' = folde id (+) size :: Expr -> Int size = folde (\x -> 1) (+) {- eval' (Add (Val 3) (Val 4)) = 7 eval' (Add (Add (Val 2) (Val 5)) (Val 10)) = 17 eval' (Add (Add (Val 1) (Val 5)) (Add (Val 4) (Val 6))) = 16 size (Add (Val 3) (Val 4)) = 2 size (Add (Add (Val 2) (Val 5)) (Val 10)) = 3 size (Add (Add (Val 1) (Val 5)) (Add (Val 4) (Val 6))) = 4 -} {- 7. data Maybe a = Nothing | Just a instance Eq a => (Maybe a) where Nothing == Nothing = True (Just x) == (Just y) = x == y _ == _ = False instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = (x == y) && (xs == ys) _ == _ = False -} {- 8. -} type Assoc k v = [(k, v)] find :: Eq k => k -> Assoc k v -> v find k t = head [v | (k',v) <- t, k == k'] data Prop = Const Bool | Var Char | Not Prop | And Prop Prop | Imply Prop Prop | Or Prop Prop | Iff Prop Prop p1 :: Prop p1 = And (Var 'A') (Not (Var 'A')) p2 :: Prop p2 = Imply (And (Var 'A') (Var 'B')) (Var 'A') p3 :: Prop p3 = Imply (Var 'A') (And (Var 'A') (Var 'B')) p4 :: Prop p4 = Imply (And (Var 'A') (Imply (Var 'A') (Var 'B'))) (Var 'B') p5 :: Prop p5 = Or (Var 'A') (Not (Var 'A')) p6 :: Prop p6 = Or (Var 'A') (Not (Var 'B')) p7 :: Prop p7 = Iff (Var 'A') (Var 'A') p8 :: Prop p8 = Imply (And (Var 'A') (Var 'B')) (Or (Var 'A') (Var 'B')) -- DeMorgan's Laws: -- [P ^ (Q V R)] <-> [(P ^ Q) V (P ^ R)] :: Tautology p9 :: Prop p9 = Iff (And (Var 'P') (Or (Var 'Q') (Var 'R'))) (Or (And (Var 'P') (Var 'Q')) (And (Var 'P') (Var 'R'))) -- [P V (Q ^ R)] <-> [(P V Q) ^ (P V R)] :: Tautology p10 :: Prop p10 = Iff (Or (Var 'P') (And (Var 'Q') (Var 'R'))) (And (Or (Var 'P') (Var 'Q')) (Or (Var 'P') (Var 'R'))) type Subst = Assoc Char Bool {- the substitution [('A', False), ('B', True)] assigns the variable A to False and B to True. -} eval :: Subst -> Prop -> Bool eval _ (Const b) = b eval s (Var x) = find x s eval s (Not p) = not (eval s p) eval s (And p q) = eval s p && eval s q eval s (Imply p q) = eval s p <= eval s q eval s (Or p q) = eval s p || eval s q eval s (Iff p q) = eval s p == eval s q {- eval [('A',False),('B',False)] p1 = False eval [('A',False),('B',False)] p2 = True -} vars :: Prop -> [Char] vars (Const _) = [] vars (Var x) = [x] vars (Not p) = vars p vars (And p q) = vars p ++ vars q vars (Imply p q) = vars p ++ vars q vars (Or p q) = vars p ++ vars q vars (Iff p q) = vars p ++ vars q {- vars p1 = "AA" vars p2 = "ABA" vars p3 = "AAB" vars p4 = "AABB" map (3:) [[1],[20]] = [[3,1],[3,20]] -} bools :: Int -> [[Bool]] bools 0 = [[]] bools n = map (False :) bss ++ map (True :) bss where bss = bools (n-1) rmdupes :: Eq a => [a] -> [a] rmdupes [] = [] rmdupes (x:xs) = x : rmdupes (filter (/= x) xs) substs :: Prop -> [Subst] substs p = map (zip vs) (bools (length vs)) where vs = rmdupes (vars p) {- bools 3 = [[False,False,False], [False,False,True], [False,True,False], [False,True,True], [True,False,False], [True,False,True], [True,True,False], [True,True,True]] bools 2 = [[False,False], [False,True], [True,False], [True,True]] substs p2 = map (zip (rmdupes (vars p2))) (bools (length (rmdupes (vars p2)))) = map (zip (rmdupes "ABA")) (bools (length (rmdupes "ABA"))) = map (zip (rmdupes "ABA")) (bools (length "AA")) = map (zip "AB") (bools 2) = map (zip "AB") [[False,False],[False,True],[True,False],[True,True]] = [[('A',False),('B',False)],[('A',False),('B',True)],[('A',True),('B',False)],[('A',True),('B',True)]] -} isTaut :: Prop -> Bool isTaut p = and [eval s p | s <- substs p] {- isTaut p1 = False isTaut p2 = True isTaut p3 = False isTaut p4 = True isTaut p5 True isTaut p6 False isTaut p7 True isTaut p8 True isTaut p9 True isTaut p10 True -} {- 9. -} -- Abstract machine -- data Expr' = Val' Int | Add' Expr' Expr' | Mult' Expr' Expr' -- value :: Expr' -> Int -- value (Val' n) = n -- value (Add' x y) = value x + value y -- value (Mult' x y) = value x * value y value :: Expr -> Int value (Val n) = n value (Add x y) = value x + value y value (Mult x y) = value x * value y {- value (Add (Add (Val 2) (Val 3)) (Val 4)) = value (Add (value (Val 2) (Val 3))) + value (Val 4) = value (Add (Val 2) (Val 3)) + value (Val 4) = value (value (Val 2) + value (Val 3)) + value (Val 4) = (value (Val 2) + value (Val 3)) + value (Val 4) = 2 + value (Val 3) + value (Val 4) = (2 + 3) + value (Val 4) = 5 + value (Val 4) = 5 + 4 = 9 The definition of the value function does not specify if the left argument of an addition should be evaluated before the right. Basically, the order of evalution is determined by Haskell though control structures can be made explict by defining an abstract machine for expressions, which specifies the step-by-step process of their evaluation. -} type Cont = [Op] data Op = EVALADD Expr | EVALMULT Expr | ADD Int | MULT Int eval'' :: Expr -> Cont -> Int eval'' (Val n) c = exec c n eval'' (Add x y) c = eval'' x (EVALADD y : c) eval'' (Mult x y) c = eval'' x (EVALMULT y : c) exec :: Cont -> Int -> Int exec [] n = n exec (EVALADD y : c) n = eval'' y (ADD n : c) exec (EVALMULT y : c) n = eval'' y (MULT n : c) exec (ADD n : c) m = exec c (n + m) exec (MULT n : c) m = exec c (n * m) value' :: Expr -> Int value' e = eval'' e [] {- Need to trace through the following when I have more time: value' (Add (Val 2) (Val 3)) = 5 value' (Mult (Val 2) (Val 3)) = 6 value' (Add (Mult (Val 2) (Val 3)) (Val 4)) = 10 -}
rad1al/hutton_exercises
ch08.hs
gpl-2.0
8,593
30
12
2,414
2,803
1,344
1,459
121
3
module Lamdu.Formatting ( Format(..) , formatTextContents ) where import qualified Control.Lens as Lens import Control.Monad (mplus) import qualified Data.ByteString.Base16 as Hex import qualified Data.Char as Char import qualified Data.Text as Text import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Text.Printf (printf) import Text.Read (readMaybe) import Lamdu.Prelude formatTextContents :: Text -> Text formatTextContents = Text.concatMap escape where escape '\n' = "\n" escape '\\' = "\\\\" escape c | Char.isControl c = Text.pack (Char.showLitChar c "") | otherwise = Text.singleton c class Format a where tryParse :: Text -> Maybe a format :: a -> Text instance Format ByteString where tryParse str = case Text.uncons str of Just ('#', xs) -> Hex.decode (encodeUtf8 xs) ^? Lens._Right _ -> Nothing format bs = Text.cons '#' $ decodeUtf8 (Hex.encode bs) instance Format Double where tryParse str | "." `Text.isPrefixOf` str = readMaybe ('0':Text.unpack str) | "-." `Text.isPrefixOf` str = tryParse (Text.tail str) <&> negate | otherwise = case reads (Text.unpack str) of [(val, "")] -> Just val [(val, ".")] | '.' `notElem` init (Text.unpack str) -> Just val _ -> Nothing format x | fromIntegral i /= x = printf "%f" x & Text.pack | isInfinite x = ["-" | x < 0] ++ ["Inf"] & mconcat | otherwise = Text.pack (show i) where i :: Integer i = truncate x instance Format Int where tryParse str = case reads (Text.unpack str) of [(val, "")] -> Just val _ -> Nothing format = Text.pack . show instance Format Text where tryParse x = mplus (readMaybe (Text.unpack x)) (readMaybe (Text.unpack x ++ "\"")) format text = mconcat ["\"", formatTextContents text, "\""]
Peaker/lamdu
src/Lamdu/Formatting.hs
gpl-3.0
2,035
0
17
629
715
369
346
55
3
{-| Module : Graphics.QML.Transient License : BSD3 Maintainer : [email protected] Stability : experimental Main module that exports everything needed for users of this library. -} module Graphics.QML.Transient ( Build , Qml , React , qml , runQml , reacting , continuously , changes , member , addMember , module Graphics.QML.Transient.Marshal , module Graphics.QML.Transient.Method , module Graphics.QML.Transient.Property , module Graphics.QML.Transient.Signal , module Control.Monad.Transient , module GHC.Generics ) where import Graphics.QML.Transient.Marshal import Graphics.QML.Transient.Method import Graphics.QML.Transient.Property import Graphics.QML.Transient.Signal import Graphics.QML.Transient.Types import Graphics.QML.Transient.Internal import Graphics.QML.Transient.Internal.Types import Control.Monad.Transient import Control.Concurrent import Control.Monad import Control.Monad.Reader import Control.Monad.Writer.Lazy import GHC.Generics import Graphics.QML import Transient.Base runQml :: DocumentPath -> Build r -> IO r -- ^Build and run a QML context object, loading a '.qml' file from the provided 'DocumentPath'. runQml path (Build q) = do ((buildAction, r),ms) <- runWriterT q cls <- newClass ms ctx <- newObject cls () _ <- forkIO.void . runTransient $ runReaderT (unpackQml buildAction) ctx let engineConfig = defaultEngineConfig { initialDocument = path , contextObject = Just $ anyObjRef ctx } runEngineLoop engineConfig pure r member :: String -> Build a -> Build a -- ^Build and embed an object as a member with a given name. member name (Build q) = do ((buildAction, r),ms) <- liftIO $ runWriterT q obj <- liftIO $ (`newObject` ()) =<< newClass ms propertyConst name obj Build . WriterT $ pure ((buildAction, r), [])
marcinmrotek/hsqml-transient
src/Graphics/QML/Transient.hs
gpl-3.0
1,871
0
13
340
455
261
194
51
1
module TB.Transformers.Maybe.Examples ( ) where
adarqui/ToyBox
haskell/ross/transformers/src/TB/Transformers/Maybe/Examples.hs
gpl-3.0
48
0
3
5
11
8
3
1
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} ------------------------------------------------------------------------------ -- | This module defines our application's state type and an alias for its -- handler monad. module Application where ------------------------------------------------------------------------------ import Control.Lens import qualified Data.Text as T import qualified Network.HTTP.Client as C import Snap.Snaplet import Snap.Snaplet.Heist import Snap.Snaplet.Auth import Snap.Snaplet.Session import Snap.Snaplet.AcidState import Reffit.AcidTypes import Util.Mailgun (SigningKey) import Reffit.CrossRef ------------------------------------------------------------------------------ data App = App { _heist :: Snaplet (Heist App) , _sess :: Snaplet SessionManager , _auth :: Snaplet (AuthManager App) , _acid :: Snaplet (Acid PersistentState) , _sign :: SigningKey , _mgr :: C.Manager , _mgKey :: T.Text , _cref :: CrossRef } makeLenses ''App instance HasHeist App where heistLens = subSnaplet heist instance HasAcid App PersistentState where getAcidStore = view (acid.snapletValue) ------------------------------------------------------------------------------ type AppHandler = Handler App App
imalsogreg/reffit
src/Application.hs
gpl-3.0
1,451
0
11
312
233
140
93
30
0
module Main where import Protolude import qualified Client.Main as CMA main :: IO () main = CMA.main
r-raymond/purple-muon
client/Main.hs
gpl-3.0
104
0
6
20
32
20
12
5
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.Compute.Disks.CreateSnapshot -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a snapshot of a specified persistent disk. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.disks.createSnapshot@. module Network.Google.Resource.Compute.Disks.CreateSnapshot ( -- * REST Resource DisksCreateSnapshotResource -- * Creating a Request , disksCreateSnapshot , DisksCreateSnapshot -- * Request Lenses , dcsProject , dcsDisk , dcsZone , dcsPayload ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.disks.createSnapshot@ method which the -- 'DisksCreateSnapshot' request conforms to. type DisksCreateSnapshotResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "disks" :> Capture "disk" Text :> "createSnapshot" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Snapshot :> Post '[JSON] Operation -- | Creates a snapshot of a specified persistent disk. -- -- /See:/ 'disksCreateSnapshot' smart constructor. data DisksCreateSnapshot = DisksCreateSnapshot' { _dcsProject :: !Text , _dcsDisk :: !Text , _dcsZone :: !Text , _dcsPayload :: !Snapshot } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DisksCreateSnapshot' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcsProject' -- -- * 'dcsDisk' -- -- * 'dcsZone' -- -- * 'dcsPayload' disksCreateSnapshot :: Text -- ^ 'dcsProject' -> Text -- ^ 'dcsDisk' -> Text -- ^ 'dcsZone' -> Snapshot -- ^ 'dcsPayload' -> DisksCreateSnapshot disksCreateSnapshot pDcsProject_ pDcsDisk_ pDcsZone_ pDcsPayload_ = DisksCreateSnapshot' { _dcsProject = pDcsProject_ , _dcsDisk = pDcsDisk_ , _dcsZone = pDcsZone_ , _dcsPayload = pDcsPayload_ } -- | Project ID for this request. dcsProject :: Lens' DisksCreateSnapshot Text dcsProject = lens _dcsProject (\ s a -> s{_dcsProject = a}) -- | Name of the persistent disk to snapshot. dcsDisk :: Lens' DisksCreateSnapshot Text dcsDisk = lens _dcsDisk (\ s a -> s{_dcsDisk = a}) -- | The name of the zone for this request. dcsZone :: Lens' DisksCreateSnapshot Text dcsZone = lens _dcsZone (\ s a -> s{_dcsZone = a}) -- | Multipart request metadata. dcsPayload :: Lens' DisksCreateSnapshot Snapshot dcsPayload = lens _dcsPayload (\ s a -> s{_dcsPayload = a}) instance GoogleRequest DisksCreateSnapshot where type Rs DisksCreateSnapshot = Operation type Scopes DisksCreateSnapshot = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient DisksCreateSnapshot'{..} = go _dcsProject _dcsZone _dcsDisk (Just AltJSON) _dcsPayload computeService where go = buildClient (Proxy :: Proxy DisksCreateSnapshotResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Disks/CreateSnapshot.hs
mpl-2.0
3,997
0
18
992
547
324
223
84
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.Gmail.Users.Settings.GetAutoForwarding -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the auto-forwarding setting for the specified account. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.getAutoForwarding@. module Network.Google.Resource.Gmail.Users.Settings.GetAutoForwarding ( -- * REST Resource UsersSettingsGetAutoForwardingResource -- * Creating a Request , usersSettingsGetAutoForwarding , UsersSettingsGetAutoForwarding -- * Request Lenses , usgafUserId ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.settings.getAutoForwarding@ method which the -- 'UsersSettingsGetAutoForwarding' request conforms to. type UsersSettingsGetAutoForwardingResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "settings" :> "autoForwarding" :> QueryParam "alt" AltJSON :> Get '[JSON] AutoForwarding -- | Gets the auto-forwarding setting for the specified account. -- -- /See:/ 'usersSettingsGetAutoForwarding' smart constructor. newtype UsersSettingsGetAutoForwarding = UsersSettingsGetAutoForwarding' { _usgafUserId :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersSettingsGetAutoForwarding' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usgafUserId' usersSettingsGetAutoForwarding :: UsersSettingsGetAutoForwarding usersSettingsGetAutoForwarding = UsersSettingsGetAutoForwarding' { _usgafUserId = "me" } -- | User\'s email address. The special value \"me\" can be used to indicate -- the authenticated user. usgafUserId :: Lens' UsersSettingsGetAutoForwarding Text usgafUserId = lens _usgafUserId (\ s a -> s{_usgafUserId = a}) instance GoogleRequest UsersSettingsGetAutoForwarding where type Rs UsersSettingsGetAutoForwarding = AutoForwarding type Scopes UsersSettingsGetAutoForwarding = '["https://mail.google.com/", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.settings.basic"] requestClient UsersSettingsGetAutoForwarding'{..} = go _usgafUserId (Just AltJSON) gmailService where go = buildClient (Proxy :: Proxy UsersSettingsGetAutoForwardingResource) mempty
rueshyna/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/GetAutoForwarding.hs
mpl-2.0
3,403
0
14
766
310
192
118
55
1
{-# LANGUAGE OverloadedStrings #-} module Web.GZip ( generateGZip ) where import qualified Codec.Compression.GZip as GZ import Control.Monad (mzero) import Control.Monad.IO.Class import qualified Data.ByteString.Lazy as BSL import System.FilePath (takeExtension) import Files import Web import Web.Types import Web.Generate generateGZip :: WebGenerator generateGZip fo@(f, _) = do (b, ext) <- liftIO $ splitWebExtension f b' <- liftIO $ unRawFilePath $ webFileAbs b if takeExtension b' `notElem` [".png"] && ext == ".gz" -- things that don't compress then do f' <- liftIO $ unRawFilePath $ webFileAbs f webRegenerate (BSL.writeFile f' . GZ.compress =<< BSL.readFile b') [] [b] fo else mzero
databrary/databrary
src/Web/GZip.hs
agpl-3.0
740
0
15
145
223
125
98
23
2
module SMTHelper where import Language.SMTLib2 import Language.SMTLib2.Internals isComplexExpr :: SMTExpr a -> Bool isComplexExpr (Const _ _) = False isComplexExpr (Var _ _) = False isComplexExpr _ = True
hguenther/nbis
SMTHelper.hs
agpl-3.0
207
0
7
31
67
36
31
7
1
{-# OPTIONS_GHC -fno-warn-unticked-promoted-constructors #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeInType #-} module P139_read_vect where -- import Data.Singletons -- import Data.Singletons.Sigma data Nat = Z | S Nat deriving Show data Vec (a :: *) (n :: Nat) where V0 :: Vec a Z (:>) :: a -> Vec a n -> Vec a (S n) infixr 5 :> deriving instance Eq a => Eq (Vec a n) deriving instance Show a => Show (Vec a n) data Natty :: Nat -> * where Zy :: Natty Z Sy :: Natty n -> Natty (S n) deriving instance Show (Natty a) ------------------------------------------------------------------------------ -- read a vector of known length readVecLen :: Natty m -> IO (Vec String m) readVecLen Zy = pure V0 readVecLen (Sy k) = do x <- getLine xs <- readVecLen k pure (x :> xs) -- ------------------------------------------------------------------------------ -- -- read a vector of unknown length data VecUnknown (a :: *) :: * where MkVect :: Natty len -> Vec a len -> VecUnknown a deriving instance Show a => Show (VecUnknown a) readVec :: IO (VecUnknown String) readVec = readVec' Zy where readVec' n = do x <- getLine if x == "" then pure (MkVect n V0) else do MkVect len xs <- readVec pure (MkVect (Sy len) (x :> xs)) -- ------------------------------------------------------------------------------ -- dependent pairs : general solution to above -- when needing unknown input to define a dependent type {- -- type of 2nd element computed from value of 1st anyVect :: Sigma Nat (TyCon (Vec String)) anyVect = S (S (S Z)) :&: "Rod" :> "Jane" :> "Freddy" :> V0 sndAnyVect :: Vec String (S (S (S Z))) sndAnyVect = snd anyVect -- ------------------------------------------------------------------------------ {-# TERMINATING #-} readVec' : IO (Σ Nat (λ n -> Vec String n)) readVec' = do x <- getLine if (x == "") then return (_ , []) else do (_ , xs) <- readVec' return (_ , x ∷ xs) ------------------------------------------------------------------------------ exactLength : {a : Set} {m : Nat} -> (len : Nat) -> (input : Vec a m) -> Maybe (Vec a len) exactLength {_} {m} len input with m Data.Nat.≟ len ... | yes p rewrite p = just input ... | no _ = nothing printVecStringString : {len : Nat} -> Vec (String × String) len -> String printVecStringString [] = "[]" printVecStringString ((l , r) ∷ xs) = "(" Data.String.++ l Data.String.++ " , " Data.String.++ r Data.String.++ ")" Data.String.++ " ∷ " Data.String.++ printVecStringString xs zipInputs : IO ⊤ zipInputs = do IO.putStrLn "Enter 1st vector (blank line to end):" (len1 , vec1) <- readVec' IO.putStrLn "Enter 2nd vector (blank line to end):" (len2 , vec2) <- readVec' case exactLength len1 vec2 of λ where nothing -> IO.putStrLn "nothing" (just v) -> let vz = Data.Vec.zip vec1 v in IO.putStrLn (printVecStringString vz) ------------------------------------------------------------------------------ -} main :: IO () main = do putStrLn "--------------------------------------------------" putStrLn "readVecLen 4" putStrLn "enter 4 lines:" vl <- readVecLen (Sy (Sy (Sy (Sy Zy)))) putStrLn "result:" print vl putStrLn "--------------------------------------------------" putStrLn "readVec" putStrLn "enter lines, then a blank line:" vu <- readVec putStrLn "result:" print vu {- IO.putStrLn "--------------------------------------------------" IO.putStrLn "readVec'" IO.putStrLn "enter lines, then a blank line:" (_ , v) <- readVec' IO.putStrLn "result:" IO.putStrLn (printVecString v) IO.putStrLn "--------------------------------------------------" IO.putStrLn "zipInputs" zipInputs -}
haroldcarr/learn-haskell-coq-ml-etc
idris/book/2017-Type_Driven_Development_with_Idris/src/P139_read_vect.hs
unlicense
3,885
0
16
826
555
279
276
-1
-1
module Routes.Install ( buildInstallPage ) where import Control.Monad import Text.Blaze.Html -- local import Session import State import Html.Base import Html.Install buildInstallPage :: ServerT HtmlPage buildInstallPage = do -- see if configuration is available mconf <- runQuery GetConfig case mconf of Just _ -> mzero Nothing -> build' build' :: ServerT HtmlPage build' = do mu <- getSessionUser return $ installPage mu
mcmaniac/blog.nils.cc
src/Routes/Install.hs
apache-2.0
449
0
10
87
115
61
54
17
2
module Tutorial4 where import Data.Machine import System.Directory.Machine import System.Environment (getArgs) import System.IO (IOMode(..), withFile) import System.IO.Machine (byLine, sourceHandle) import qualified Data.Text as T main :: IO () main = do dirs <- getArgs runT_ $ (autoM print) <~ largest <~ (autoM count) <~ files <~ directoryWalk <~ source dirs where count :: FilePath -> IO Int count file = do xs <- withFile file ReadMode $ \h -> runT $ largest <~ (auto T.length) <~ asParts <~ (auto T.words) <~ sourceHandle byLine h return $ head xs
aloiscochard/machines-tutorial
src/Tutorial4.hs
apache-2.0
605
0
18
138
222
118
104
16
1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Text.PrettyPrint.ANSI.Leijen -- Copyright : Daan Leijen (c) 2000, http://www.cs.uu.nl/~daan -- Max Bolingbroke (c) 2008, http://blog.omega-prime.co.uk -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Pretty print module based on Philip Wadler's \"prettier printer\" -- -- @ -- \"A prettier printer\" -- Draft paper, April 1997, revised March 1998. -- <http://cm.bell-labs.com/cm/cs/who/wadler/papers/prettier/prettier.ps> -- @ -- -- PPrint is an implementation of the pretty printing combinators -- described by Philip Wadler (1997). In their bare essence, the -- combinators of Wadler are not expressive enough to describe some -- commonly occurring layouts. The PPrint library adds new primitives -- to describe these layouts and works well in practice. -- -- The library is based on a single way to concatenate documents, -- which is associative and has both a left and right unit. This -- simple design leads to an efficient and short implementation. The -- simplicity is reflected in the predictable behaviour of the -- combinators which make them easy to use in practice. -- -- A thorough description of the primitive combinators and their -- implementation can be found in Philip Wadler's paper -- (1997). Additions and the main differences with his original paper -- are: -- -- * The nil document is called empty. -- -- * The above combinator is called '<$>'. The operator '</>' is used -- for soft line breaks. -- -- * There are three new primitives: 'align', 'fill' and -- 'fillBreak'. These are very useful in practice. -- -- * Lots of other useful combinators, like 'fillSep' and 'list'. -- -- * There are two renderers, 'renderPretty' for pretty printing and -- 'renderCompact' for compact output. The pretty printing algorithm -- also uses a ribbon-width now for even prettier output. -- -- * There are two displayers, 'displayS' for strings and 'displayIO' for -- file based output. -- -- * There is a 'Pretty' class. -- -- * The implementation uses optimised representations and strictness -- annotations. -- -- Full documentation for the original wl-pprint library available at -- <http://www.cs.uu.nl/~daan/download/pprint/pprint.html>. -- -- The library has been extended to allow formatting text for output -- to ANSI style consoles. New combinators allow: -- -- * Control of foreground and background color of text -- -- * The abliity to make parts of the text bold or underlined -- -- This functionality is, as far as possible, portable across platforms -- with their varying terminals. However, one thing to be particularly -- wary of is that console colors will not be displayed on Windows unless -- the 'Doc' value is output using the 'putDoc' function or one of it's -- friends. Rendering the 'Doc' to a 'String' and then outputing /that/ -- will only work on Unix-style operating systems. ----------------------------------------------------------- module Text.PrettyPrint.ANSI.Leijen ( -- * Documents Doc, putDoc, hPutDoc, -- * Basic combinators empty, char, text, (<>), nest, line, linebreak, group, softline, softbreak, hardline, flatAlt, renderSmart, -- * Alignment -- -- The combinators in this section can not be described by Wadler's -- original combinators. They align their output relative to the -- current output position - in contrast to @nest@ which always -- aligns to the current nesting level. This deprives these -- combinators from being \`optimal\'. In practice however they -- prove to be very useful. The combinators in this section should -- be used with care, since they are more expensive than the other -- combinators. For example, @align@ shouldn't be used to pretty -- print all top-level declarations of a language, but using @hang@ -- for let expressions is fine. align, hang, indent, encloseSep, list, tupled, semiBraces, -- * Operators (<+>), (Text.PrettyPrint.ANSI.Leijen.<$>), (</>), (<$$>), (<//>), -- * List combinators hsep, vsep, fillSep, sep, hcat, vcat, fillCat, cat, punctuate, -- * Fillers fill, fillBreak, -- * Bracketing combinators enclose, squotes, dquotes, parens, angles, braces, brackets, -- * Character documents lparen, rparen, langle, rangle, lbrace, rbrace, lbracket, rbracket, squote, dquote, semi, colon, comma, space, dot, backslash, equals, -- * Colorisation combinators black, red, green, yellow, blue, magenta, cyan, white, dullblack, dullred, dullgreen, dullyellow, dullblue, dullmagenta, dullcyan, dullwhite, onblack, onred, ongreen, onyellow, onblue, onmagenta, oncyan, onwhite, ondullblack, ondullred, ondullgreen, ondullyellow, ondullblue, ondullmagenta, ondullcyan, ondullwhite, -- * Emboldening combinators bold, debold, -- * Underlining combinators underline, deunderline, -- * Removing formatting plain, -- * Primitive type documents string, int, integer, float, double, rational, -- * Pretty class Pretty(..), -- * Rendering SimpleDoc(..), renderPretty, renderCompact, displayS, displayIO -- * Undocumented , bool , column, columns, nesting, width ) where import System.IO (Handle,hPutStr,hPutChar,stdout) import System.Console.ANSI (Color(..), ColorIntensity(..), ConsoleLayer(..), Underlining(..), ConsoleIntensity(..), SGR(..), hSetSGR, setSGRCode) import Data.String (IsString(..)) import Data.Maybe (catMaybes) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (Monoid, mappend, mconcat, mempty) #endif infixr 5 </>,<//>,<$>,<$$> infixr 6 <>,<+> ----------------------------------------------------------- -- list, tupled and semiBraces pretty print a list of -- documents either horizontally or vertically aligned. ----------------------------------------------------------- -- | The document @(list xs)@ comma separates the documents @xs@ and -- encloses them in square brackets. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All comma separators are put in front of the elements. list :: [Doc] -> Doc list = encloseSep lbracket rbracket comma -- | The document @(tupled xs)@ comma separates the documents @xs@ and -- encloses them in parenthesis. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All comma separators are put in front of the elements. tupled :: [Doc] -> Doc tupled = encloseSep lparen rparen comma -- | The document @(semiBraces xs)@ separates the documents @xs@ with -- semi colons and encloses them in braces. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All semi colons are put in front of the elements. semiBraces :: [Doc] -> Doc semiBraces = encloseSep lbrace rbrace semi -- | The document @(encloseSep l r sep xs)@ concatenates the documents -- @xs@ separated by @sep@ and encloses the resulting document by @l@ -- and @r@. The documents are rendered horizontally if that fits the -- page. Otherwise they are aligned vertically. All separators are put -- in front of the elements. For example, the combinator 'list' can be -- defined with @encloseSep@: -- -- > list xs = encloseSep lbracket rbracket comma xs -- > test = text "list" <+> (list (map int [10,200,3000])) -- -- Which is layed out with a page width of 20 as: -- -- @ -- list [10,200,3000] -- @ -- -- But when the page width is 15, it is layed out as: -- -- @ -- list [10 -- ,200 -- ,3000] -- @ encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc encloseSep left right sep ds = case ds of [] -> left <> right [d] -> left <> d <> right _ -> align (cat (zipWith (<>) (left : repeat sep) ds) <> right) ----------------------------------------------------------- -- punctuate p [d1,d2,...,dn] => [d1 <> p,d2 <> p, ... ,dn] ----------------------------------------------------------- -- | @(punctuate p xs)@ concatenates all documents in @xs@ with -- document @p@ except for the last document. -- -- > someText = map text ["words","in","a","tuple"] -- > test = parens (align (cat (punctuate comma someText))) -- -- This is layed out on a page width of 20 as: -- -- @ -- (words,in,a,tuple) -- @ -- -- But when the page width is 15, it is layed out as: -- -- @ -- (words, -- in, -- a, -- tuple) -- @ -- -- (If you want put the commas in front of their elements instead of -- at the end, you should use 'tupled' or, in general, 'encloseSep'.) punctuate :: Doc -> [Doc] -> [Doc] punctuate p [] = [] punctuate p [d] = [d] punctuate p (d:ds) = (d <> p) : punctuate p ds ----------------------------------------------------------- -- high-level combinators ----------------------------------------------------------- -- | The document @(sep xs)@ concatenates all documents @xs@ either -- horizontally with @(\<+\>)@, if it fits the page, or vertically with -- @(\<$\>)@. -- -- > sep xs = group (vsep xs) sep :: [Doc] -> Doc sep = group . vsep -- | The document @(fillSep xs)@ concatenates documents @xs@ -- horizontally with @(\<+\>)@ as long as its fits the page, than -- inserts a @line@ and continues doing that for all documents in -- @xs@. -- -- > fillSep xs = foldr (\<\/\>) empty xs fillSep :: [Doc] -> Doc fillSep = fold (</>) -- | The document @(hsep xs)@ concatenates all documents @xs@ -- horizontally with @(\<+\>)@. hsep :: [Doc] -> Doc hsep = fold (<+>) -- | The document @(vsep xs)@ concatenates all documents @xs@ -- vertically with @(\<$\>)@. If a 'group' undoes the line breaks -- inserted by @vsep@, all documents are separated with a space. -- -- > someText = map text (words ("text to lay out")) -- > -- > test = text "some" <+> vsep someText -- -- This is layed out as: -- -- @ -- some text -- to -- lay -- out -- @ -- -- The 'align' combinator can be used to align the documents under -- their first element -- -- > test = text "some" <+> align (vsep someText) -- -- Which is printed as: -- -- @ -- some text -- to -- lay -- out -- @ vsep :: [Doc] -> Doc vsep = fold (Text.PrettyPrint.ANSI.Leijen.<$>) -- | The document @(cat xs)@ concatenates all documents @xs@ either -- horizontally with @(\<\>)@, if it fits the page, or vertically with -- @(\<$$\>)@. -- -- > cat xs = group (vcat xs) cat :: [Doc] -> Doc cat = group . vcat -- | The document @(fillCat xs)@ concatenates documents @xs@ -- horizontally with @(\<\>)@ as long as its fits the page, than inserts -- a @linebreak@ and continues doing that for all documents in @xs@. -- -- > fillCat xs = foldr (\<\/\/\>) empty xs fillCat :: [Doc] -> Doc fillCat = fold (<//>) -- | The document @(hcat xs)@ concatenates all documents @xs@ -- horizontally with @(\<\>)@. hcat :: [Doc] -> Doc hcat = fold (<>) -- | The document @(vcat xs)@ concatenates all documents @xs@ -- vertically with @(\<$$\>)@. If a 'group' undoes the line breaks -- inserted by @vcat@, all documents are directly concatenated. vcat :: [Doc] -> Doc vcat = fold (<$$>) fold :: (Doc -> Doc -> Doc) -> [Doc] -> Doc fold f [] = empty fold f ds = foldr1 f ds -- | The document @(x \<\> y)@ concatenates document @x@ and document -- @y@. It is an associative operation having 'empty' as a left and -- right unit. (infixr 6) (<>) :: Doc -> Doc -> Doc x <> y = x `beside` y -- | The document @(x \<+\> y)@ concatenates document @x@ and @y@ with a -- @space@ in between. (infixr 6) (<+>) :: Doc -> Doc -> Doc x <+> y = x <> space <> y -- | The document @(x \<\/\> y)@ concatenates document @x@ and @y@ with a -- 'softline' in between. This effectively puts @x@ and @y@ either -- next to each other (with a @space@ in between) or underneath each -- other. (infixr 5) (</>) :: Doc -> Doc -> Doc x </> y = x <> softline <> y -- | The document @(x \<\/\/\> y)@ concatenates document @x@ and @y@ with -- a 'softbreak' in between. This effectively puts @x@ and @y@ either -- right next to each other or underneath each other. (infixr 5) (<//>) :: Doc -> Doc -> Doc x <//> y = x <> softbreak <> y -- | The document @(x \<$\> y)@ concatenates document @x@ and @y@ with a -- 'line' in between. (infixr 5) (<$>) :: Doc -> Doc -> Doc x <$> y = x <> line <> y -- | The document @(x \<$$\> y)@ concatenates document @x@ and @y@ with -- a @linebreak@ in between. (infixr 5) (<$$>) :: Doc -> Doc -> Doc x <$$> y = x <> linebreak <> y -- | The document @softline@ behaves like 'space' if the resulting -- output fits the page, otherwise it behaves like 'line'. -- -- > softline = group line softline :: Doc softline = group line -- | The document @softbreak@ behaves like 'empty' if the resulting -- output fits the page, otherwise it behaves like 'line'. -- -- > softbreak = group linebreak softbreak :: Doc softbreak = group linebreak -- | Document @(squotes x)@ encloses document @x@ with single quotes -- \"'\". squotes :: Doc -> Doc squotes = enclose squote squote -- | Document @(dquotes x)@ encloses document @x@ with double quotes -- '\"'. dquotes :: Doc -> Doc dquotes = enclose dquote dquote -- | Document @(braces x)@ encloses document @x@ in braces, \"{\" and -- \"}\". braces :: Doc -> Doc braces = enclose lbrace rbrace -- | Document @(parens x)@ encloses document @x@ in parenthesis, \"(\" -- and \")\". parens :: Doc -> Doc parens = enclose lparen rparen -- | Document @(angles x)@ encloses document @x@ in angles, \"\<\" and -- \"\>\". angles :: Doc -> Doc angles = enclose langle rangle -- | Document @(brackets x)@ encloses document @x@ in square brackets, -- \"[\" and \"]\". brackets :: Doc -> Doc brackets = enclose lbracket rbracket -- | The document @(enclose l r x)@ encloses document @x@ between -- documents @l@ and @r@ using @(\<\>)@. -- -- > enclose l r x = l <> x <> r enclose :: Doc -> Doc -> Doc -> Doc enclose l r x = l <> x <> r -- | The document @lparen@ contains a left parenthesis, \"(\". lparen :: Doc lparen = char '(' -- | The document @rparen@ contains a right parenthesis, \")\". rparen :: Doc rparen = char ')' -- | The document @langle@ contains a left angle, \"\<\". langle :: Doc langle = char '<' -- | The document @rangle@ contains a right angle, \">\". rangle :: Doc rangle = char '>' -- | The document @lbrace@ contains a left brace, \"{\". lbrace :: Doc lbrace = char '{' -- | The document @rbrace@ contains a right brace, \"}\". rbrace :: Doc rbrace = char '}' -- | The document @lbracket@ contains a left square bracket, \"[\". lbracket :: Doc lbracket = char '[' -- | The document @rbracket@ contains a right square bracket, \"]\". rbracket :: Doc rbracket = char ']' -- | The document @squote@ contains a single quote, \"'\". squote :: Doc squote = char '\'' -- | The document @dquote@ contains a double quote, '\"'. dquote :: Doc dquote = char '"' -- | The document @semi@ contains a semi colon, \";\". semi :: Doc semi = char ';' -- | The document @colon@ contains a colon, \":\". colon :: Doc colon = char ':' -- | The document @comma@ contains a comma, \",\". comma :: Doc comma = char ',' -- | The document @space@ contains a single space, \" \". -- -- > x <+> y = x <> space <> y space :: Doc space = char ' ' -- | The document @dot@ contains a single dot, \".\". dot :: Doc dot = char '.' -- | The document @backslash@ contains a back slash, \"\\\". backslash :: Doc backslash = char '\\' -- | The document @equals@ contains an equal sign, \"=\". equals :: Doc equals = char '=' ----------------------------------------------------------- -- Combinators for prelude types ----------------------------------------------------------- -- string is like "text" but replaces '\n' by "line" -- | The document @(string s)@ concatenates all characters in @s@ -- using @line@ for newline characters and @char@ for all other -- characters. It is used instead of 'text' whenever the text contains -- newline characters. string :: String -> Doc string "" = empty string ('\n':s) = line <> string s string s = case (span (/='\n') s) of (xs,ys) -> text xs <> string ys bool :: Bool -> Doc bool b = text (show b) -- | The document @(int i)@ shows the literal integer @i@ using -- 'text'. int :: Int -> Doc int i = text (show i) -- | The document @(integer i)@ shows the literal integer @i@ using -- 'text'. integer :: Integer -> Doc integer i = text (show i) -- | The document @(float f)@ shows the literal float @f@ using -- 'text'. float :: Float -> Doc float f = text (show f) -- | The document @(double d)@ shows the literal double @d@ using -- 'text'. double :: Double -> Doc double d = text (show d) -- | The document @(rational r)@ shows the literal rational @r@ using -- 'text'. rational :: Rational -> Doc rational r = text (show r) ----------------------------------------------------------- -- overloading "pretty" ----------------------------------------------------------- -- | The member @prettyList@ is only used to define the @instance Pretty -- a => Pretty [a]@. In normal circumstances only the @pretty@ function -- is used. class Pretty a where pretty :: a -> Doc prettyList :: [a] -> Doc prettyList = list . map pretty instance Pretty a => Pretty [a] where pretty = prettyList instance Pretty Doc where pretty = id instance Pretty () where pretty () = text "()" instance Pretty Bool where pretty b = bool b instance Pretty Char where pretty c = char c prettyList s = string s instance Pretty Int where pretty i = int i instance Pretty Integer where pretty i = integer i instance Pretty Float where pretty f = float f instance Pretty Double where pretty d = double d --instance Pretty Rational where -- pretty r = rational r instance (Pretty a,Pretty b) => Pretty (a,b) where pretty (x,y) = tupled [pretty x, pretty y] instance (Pretty a,Pretty b,Pretty c) => Pretty (a,b,c) where pretty (x,y,z)= tupled [pretty x, pretty y, pretty z] instance Pretty a => Pretty (Maybe a) where pretty Nothing = empty pretty (Just x) = pretty x ----------------------------------------------------------- -- semi primitive: fill and fillBreak ----------------------------------------------------------- -- | The document @(fillBreak i x)@ first renders document @x@. It -- than appends @space@s until the width is equal to @i@. If the -- width of @x@ is already larger than @i@, the nesting level is -- increased by @i@ and a @line@ is appended. When we redefine @ptype@ -- in the previous example to use @fillBreak@, we get a useful -- variation of the previous output: -- -- > ptype (name,tp) -- > = fillBreak 6 (text name) <+> text "::" <+> text tp -- -- The output will now be: -- -- @ -- let empty :: Doc -- nest :: Int -> Doc -> Doc -- linebreak -- :: Doc -- @ fillBreak :: Int -> Doc -> Doc fillBreak f x = width x (\w -> if (w > f) then nest f linebreak else text (spaces (f - w))) -- | The document @(fill i x)@ renders document @x@. It than appends -- @space@s until the width is equal to @i@. If the width of @x@ is -- already larger, nothing is appended. This combinator is quite -- useful in practice to output a list of bindings. The following -- example demonstrates this. -- -- > types = [("empty","Doc") -- > ,("nest","Int -> Doc -> Doc") -- > ,("linebreak","Doc")] -- > -- > ptype (name,tp) -- > = fill 6 (text name) <+> text "::" <+> text tp -- > -- > test = text "let" <+> align (vcat (map ptype types)) -- -- Which is layed out as: -- -- @ -- let empty :: Doc -- nest :: Int -> Doc -> Doc -- linebreak :: Doc -- @ fill :: Int -> Doc -> Doc fill f d = width d (\w -> if (w >= f) then empty else text (spaces (f - w))) width :: Doc -> (Int -> Doc) -> Doc width d f = column (\k1 -> d <> column (\k2 -> f (k2 - k1))) ----------------------------------------------------------- -- semi primitive: Alignment and indentation ----------------------------------------------------------- -- | The document @(indent i x)@ indents document @x@ with @i@ spaces. -- -- > test = indent 4 (fillSep (map text -- > (words "the indent combinator indents these words !"))) -- -- Which lays out with a page width of 20 as: -- -- @ -- the indent -- combinator -- indents these -- words ! -- @ indent :: Int -> Doc -> Doc indent i d = hang i (text (spaces i) <> d) -- | The hang combinator implements hanging indentation. The document -- @(hang i x)@ renders document @x@ with a nesting level set to the -- current column plus @i@. The following example uses hanging -- indentation for some text: -- -- > test = hang 4 (fillSep (map text -- > (words "the hang combinator indents these words !"))) -- -- Which lays out on a page with a width of 20 characters as: -- -- @ -- the hang combinator -- indents these -- words ! -- @ -- -- The @hang@ combinator is implemented as: -- -- > hang i x = align (nest i x) hang :: Int -> Doc -> Doc hang i d = align (nest i d) -- | The document @(align x)@ renders document @x@ with the nesting -- level set to the current column. It is used for example to -- implement 'hang'. -- -- As an example, we will put a document right above another one, -- regardless of the current nesting level: -- -- > x $$ y = align (x <$> y) -- -- > test = text "hi" <+> (text "nice" $$ text "world") -- -- which will be layed out as: -- -- @ -- hi nice -- world -- @ align :: Doc -> Doc align d = column (\k -> nesting (\i -> nest (k - i) d)) --nesting might be negative :-) ----------------------------------------------------------- -- Primitives ----------------------------------------------------------- -- | The abstract data type @Doc@ represents pretty documents. -- -- @Doc@ is an instance of the 'Show' class. @(show doc)@ pretty -- prints document @doc@ with a page width of 100 characters and a -- ribbon width of 40 characters. -- -- > show (text "hello" <$> text "world") -- -- Which would return the string \"hello\\nworld\", i.e. -- -- @ -- hello -- world -- @ data Doc = Fail | Empty | Char Char -- invariant: char is not '\n' | Text !Int String -- invariant: text doesn't contain '\n' | Line | FlatAlt Doc Doc -- Render the first doc, but when -- flattened, render the second. | Cat Doc Doc | Nest !Int Doc | Union Doc Doc -- invariant: first lines of first doc longer than the first lines of the second doc | Column (Int -> Doc) | Columns (Maybe Int -> Doc) | Nesting (Int -> Doc) | Color ConsoleLayer ColorIntensity -- Introduces coloring /around/ the embedded document Color Doc | Intensify ConsoleIntensity Doc | Italicize Bool Doc | Underline Underlining Doc | RestoreFormat (Maybe (ColorIntensity, Color)) -- Only used during the rendered phase, to signal a SGR should be issued to restore the terminal formatting. (Maybe (ColorIntensity, Color)) -- These are the colors to revert the current forecolor/backcolor to (i.e. those from before the start of the Color block). (Maybe ConsoleIntensity) -- Intensity to revert to. (Maybe Bool) -- Italicization to revert to. (Maybe Underlining) -- Underlining to revert to. -- | The data type @SimpleDoc@ represents rendered documents and is -- used by the display functions. -- -- The @Int@ in @SText@ contains the length of the string. The @Int@ -- in @SLine@ contains the indentation for that line. The library -- provides two default display functions 'displayS' and -- 'displayIO'. You can provide your own display function by writing a -- function from a @SimpleDoc@ to your own output format. data SimpleDoc = SFail | SEmpty | SChar Char SimpleDoc | SText !Int String SimpleDoc | SLine !Int SimpleDoc | SSGR [SGR] SimpleDoc -- MCB: Not in the wl-pprint package that we forked from. I added this when the "pretty" package -- from base gained a Monoid instance (<http://hackage.haskell.org/trac/ghc/ticket/4378>): instance Monoid Doc where mempty = empty mappend = (<>) mconcat = hcat -- MCB: also added when "pretty" got the corresponding instances: instance IsString Doc where fromString = text -- | The empty document is, indeed, empty. Although @empty@ has no -- content, it does have a \'height\' of 1 and behaves exactly like -- @(text \"\")@ (and is therefore not a unit of @\<$\>@). empty :: Doc empty = Empty -- | The document @(char c)@ contains the literal character @c@. The -- character shouldn't be a newline (@'\n'@), the function 'line' -- should be used for line breaks. char :: Char -> Doc char '\n' = line char c = Char c -- | The document @(text s)@ contains the literal string @s@. The -- string shouldn't contain any newline (@'\n'@) characters. If the -- string contains newline characters, the function 'string' should be -- used. text :: String -> Doc text "" = Empty text s = Text (length s) s -- | The @line@ document advances to the next line and indents to the -- current nesting level. Document @line@ behaves like @(text \" \")@ -- if the line break is undone by 'group'. line :: Doc line = FlatAlt Line space -- | The @linebreak@ document advances to the next line and indents to -- the current nesting level. Document @linebreak@ behaves like -- 'empty' if the line break is undone by 'group'. linebreak :: Doc linebreak = FlatAlt Line empty -- | A linebreak that will never be flattened; it is guaranteed to render -- as a newline. hardline :: Doc hardline = Line beside :: Doc -> Doc -> Doc beside x y = Cat x y -- | The document @(nest i x)@ renders document @x@ with the current -- indentation level increased by i (See also 'hang', 'align' and -- 'indent'). -- -- > nest 2 (text "hello" <$> text "world") <$> text "!" -- -- outputs as: -- -- @ -- hello -- world -- ! -- @ nest :: Int -> Doc -> Doc nest i x = Nest i x column, nesting :: (Int -> Doc) -> Doc column f = Column f nesting f = Nesting f columns :: (Maybe Int -> Doc) -> Doc columns f = Columns f -- | The @group@ combinator is used to specify alternative -- layouts. The document @(group x)@ undoes all line breaks in -- document @x@. The resulting line is added to the current line if -- that fits the page. Otherwise, the document @x@ is rendered without -- any changes. group :: Doc -> Doc group x = Union (flatten x) x -- | A document that is normally rendered as the first argument, but -- when flattened, is rendered as the second document. flatAlt :: Doc -> Doc -> Doc flatAlt = FlatAlt flatten :: Doc -> Doc flatten (FlatAlt x y) = y flatten (Cat x y) = Cat (flatten x) (flatten y) flatten (Nest i x) = Nest i (flatten x) flatten Line = Fail flatten (Union x y) = flatten x flatten (Column f) = Column (flatten . f) flatten (Columns f) = Columns (flatten . f) flatten (Nesting f) = Nesting (flatten . f) flatten (Color l i c x) = Color l i c (flatten x) flatten (Intensify i x) = Intensify i (flatten x) flatten (Italicize b x) = Italicize b (flatten x) flatten (Underline u x) = Underline u (flatten x) flatten other = other --Empty,Char,Text,RestoreFormat ----------------------------------------------------------- -- Colors ----------------------------------------------------------- -- | Displays a document with the black forecolor black :: Doc -> Doc -- | Displays a document with the red forecolor red :: Doc -> Doc -- | Displays a document with the green forecolor green :: Doc -> Doc -- | Displays a document with the yellow forecolor yellow :: Doc -> Doc -- | Displays a document with the blue forecolor blue :: Doc -> Doc -- | Displays a document with the magenta forecolor magenta :: Doc -> Doc -- | Displays a document with the cyan forecolor cyan :: Doc -> Doc -- | Displays a document with the white forecolor white :: Doc -> Doc -- | Displays a document with the dull black forecolor dullblack :: Doc -> Doc -- | Displays a document with the dull red forecolor dullred :: Doc -> Doc -- | Displays a document with the dull green forecolor dullgreen :: Doc -> Doc -- | Displays a document with the dull yellow forecolor dullyellow :: Doc -> Doc -- | Displays a document with the dull blue forecolor dullblue :: Doc -> Doc -- | Displays a document with the dull magenta forecolor dullmagenta :: Doc -> Doc -- | Displays a document with the dull cyan forecolor dullcyan :: Doc -> Doc -- | Displays a document with the dull white forecolor dullwhite :: Doc -> Doc (black, dullblack) = colorFunctions Black (red, dullred) = colorFunctions Red (green, dullgreen) = colorFunctions Green (yellow, dullyellow) = colorFunctions Yellow (blue, dullblue) = colorFunctions Blue (magenta, dullmagenta) = colorFunctions Magenta (cyan, dullcyan) = colorFunctions Cyan (white, dullwhite) = colorFunctions White -- | Displays a document with a forecolor given in the first parameter color :: Color -> Doc -> Doc -- | Displays a document with a dull forecolor given in the first parameter dullcolor :: Color -> Doc -> Doc color = Color Foreground Vivid dullcolor = Color Foreground Dull colorFunctions :: Color -> (Doc -> Doc, Doc -> Doc) colorFunctions what = (color what, dullcolor what) -- | Displays a document with the black backcolor onblack :: Doc -> Doc -- | Displays a document with the red backcolor onred :: Doc -> Doc -- | Displays a document with the green backcolor ongreen :: Doc -> Doc -- | Displays a document with the yellow backcolor onyellow :: Doc -> Doc -- | Displays a document with the blue backcolor onblue :: Doc -> Doc -- | Displays a document with the magenta backcolor onmagenta :: Doc -> Doc -- | Displays a document with the cyan backcolor oncyan :: Doc -> Doc -- | Displays a document with the white backcolor onwhite :: Doc -> Doc -- | Displays a document with the dull block backcolor ondullblack :: Doc -> Doc -- | Displays a document with the dull red backcolor ondullred :: Doc -> Doc -- | Displays a document with the dull green backcolor ondullgreen :: Doc -> Doc -- | Displays a document with the dull yellow backcolor ondullyellow :: Doc -> Doc -- | Displays a document with the dull blue backcolor ondullblue :: Doc -> Doc -- | Displays a document with the dull magenta backcolor ondullmagenta :: Doc -> Doc -- | Displays a document with the dull cyan backcolor ondullcyan :: Doc -> Doc -- | Displays a document with the dull white backcolor ondullwhite :: Doc -> Doc (onblack, ondullblack) = oncolorFunctions Black (onred, ondullred) = oncolorFunctions Red (ongreen, ondullgreen) = oncolorFunctions Green (onyellow, ondullyellow) = oncolorFunctions Yellow (onblue, ondullblue) = oncolorFunctions Blue (onmagenta, ondullmagenta) = oncolorFunctions Magenta (oncyan, ondullcyan) = oncolorFunctions Cyan (onwhite, ondullwhite) = oncolorFunctions White -- | Displays a document with a backcolor given in the first parameter oncolor :: Color -> Doc -> Doc -- | Displays a document with a dull backcolor given in the first parameter ondullcolor :: Color -> Doc -> Doc oncolor = Color Background Vivid ondullcolor = Color Background Dull oncolorFunctions :: Color -> (Doc -> Doc, Doc -> Doc) oncolorFunctions what = (oncolor what, ondullcolor what) ----------------------------------------------------------- -- Console Intensity ----------------------------------------------------------- -- | Displays a document in a heavier font weight bold :: Doc -> Doc bold = Intensify BoldIntensity -- | Displays a document in the normal font weight debold :: Doc -> Doc debold = Intensify NormalIntensity -- NB: I don't support FaintIntensity here because it is not widely supported by terminals. ----------------------------------------------------------- -- Italicization ----------------------------------------------------------- {- I'm in two minds about providing these functions, since italicization is so rarely implemented. It is especially bad because "italicization" may cause the meaning of colors to flip, which will look a bit weird, to say the least... -- | Displays a document in italics. This is not widely supported, and it's use is not recommended italicize :: Doc -> Doc italicize = Italicize True -- | Displays a document with no italics deitalicize :: Doc -> Doc deitalicize = Italicize False -} ----------------------------------------------------------- -- Underlining ----------------------------------------------------------- -- | Displays a document with underlining underline :: Doc -> Doc underline = Underline SingleUnderline -- | Displays a document with no underlining deunderline :: Doc -> Doc deunderline = Underline NoUnderline -- NB: I don't support DoubleUnderline here because it is not widely supported by terminals. ----------------------------------------------------------- -- Removing formatting ----------------------------------------------------------- -- | Removes all colorisation, emboldening and underlining from a document plain :: Doc -> Doc plain Fail = Fail plain e@Empty = e plain c@(Char _) = c plain t@(Text _ _) = t plain l@Line = l plain (FlatAlt x y) = FlatAlt (plain x) (plain y) plain (Cat x y) = Cat (plain x) (plain y) plain (Nest i x) = Nest i (plain x) plain (Union x y) = Union (plain x) (plain y) plain (Column f) = Column (plain . f) plain (Columns f) = Columns (plain . f) plain (Nesting f) = Nesting (plain . f) plain (Color _ _ _ x) = plain x plain (Intensify _ x) = plain x plain (Italicize _ x) = plain x plain (Underline _ x) = plain x plain (RestoreFormat _ _ _ _ _) = Empty ----------------------------------------------------------- -- Renderers ----------------------------------------------------------- ----------------------------------------------------------- -- renderPretty: the default pretty printing algorithm ----------------------------------------------------------- -- list of indentation/document pairs; saves an indirection over [(Int,Doc)] data Docs = Nil | Cons !Int Doc Docs -- | This is the default pretty printer which is used by 'show', -- 'putDoc' and 'hPutDoc'. @(renderPretty ribbonfrac width x)@ renders -- document @x@ with a page width of @width@ and a ribbon width of -- @(ribbonfrac * width)@ characters. The ribbon width is the maximal -- amount of non-indentation characters on a line. The parameter -- @ribbonfrac@ should be between @0.0@ and @1.0@. If it is lower or -- higher, the ribbon width will be 0 or @width@ respectively. renderPretty :: Float -> Int -> Doc -> SimpleDoc renderPretty = renderFits fits1 -- | A slightly smarter rendering algorithm with more lookahead. It provides -- provide earlier breaking on deeply nested structures -- For example, consider this python-ish pseudocode: -- @fun(fun(fun(fun(fun([abcdefg, abcdefg])))))@ -- If we put a softbreak (+ nesting 2) after each open parenthesis, and align -- the elements of the list to match the opening brackets, this will render with -- @renderPretty@ and a page width of 20 as: -- @ -- fun(fun(fun(fun(fun([ -- | abcdef, -- | abcdef, -- ] -- ))))) | -- @ -- Where the 20c. boundary has been marked with |. -- Because @renderPretty@ only uses one-line lookahead, it sees that the first -- line fits, and is stuck putting the second and third lines after the 20-c -- mark. In contrast, @renderSmart@ will continue to check that the potential -- document up to the end of the indentation level. Thus, it will format the -- document as: -- -- @ -- fun( | -- fun( | -- fun( | -- fun( | -- fun([ | -- abcdef, -- abcdef, -- ] | -- ))))) | -- @ -- Which fits within the 20c. boundary. renderSmart :: Float -> Int -> Doc -> SimpleDoc renderSmart = renderFits fitsR renderFits :: (Int -> Int -> Int -> SimpleDoc -> Bool) -> Float -> Int -> Doc -> SimpleDoc renderFits fits rfrac w x -- I used to do a @SSGR [Reset]@ here, but if you do that it will result -- in any rendered @Doc@ containing at least some ANSI control codes. This -- may be undesirable if you want to render to non-ANSI devices by simply -- not making use of the ANSI color combinators I provide. -- -- What I "really" want to do here is do an initial Reset iff there is some -- ANSI color within the Doc, but that's a bit fiddly. I'll fix it if someone -- complains! = best 0 0 Nothing Nothing Nothing Nothing Nothing (Cons 0 x Nil) where -- r :: the ribbon width in characters r = max 0 (min w (round (fromIntegral w * rfrac))) -- best :: n = indentation of current line -- k = current column -- (ie. (k >= n) && (k - n == count of inserted characters) best n k mb_fc mb_bc mb_in mb_it mb_un Nil = SEmpty best n k mb_fc mb_bc mb_in mb_it mb_un (Cons i d ds) = case d of Fail -> SFail Empty -> best_typical n k ds Char c -> let k' = k+1 in seq k' (SChar c (best_typical n k' ds)) Text l s -> let k' = k+l in seq k' (SText l s (best_typical n k' ds)) Line -> SLine i (best_typical i i ds) FlatAlt x _ -> best_typical n k (Cons i x ds) Cat x y -> best_typical n k (Cons i x (Cons i y ds)) Nest j x -> let i' = i+j in seq i' (best_typical n k (Cons i' x ds)) Union x y -> nicest n k (best_typical n k (Cons i x ds)) (best_typical n k (Cons i y ds)) Column f -> best_typical n k (Cons i (f k) ds) Columns f -> best_typical n k (Cons i (f (Just w)) ds) Nesting f -> best_typical n k (Cons i (f i) ds) Color l t c x -> SSGR [SetColor l t c] (best n k mb_fc' mb_bc' mb_in mb_it mb_un (Cons i x ds_restore)) where mb_fc' = case l of { Background -> mb_fc; Foreground -> Just (t, c) } mb_bc' = case l of { Background -> Just (t, c); Foreground -> mb_bc } Intensify t x -> SSGR [SetConsoleIntensity t] (best n k mb_fc mb_bc (Just t) mb_it mb_un (Cons i x ds_restore)) Italicize t x -> SSGR [SetItalicized t] (best n k mb_fc mb_bc mb_in (Just t) mb_un (Cons i x ds_restore)) Underline u x -> SSGR [SetUnderlining u] (best n k mb_fc mb_bc mb_in mb_it (Just u) (Cons i x ds_restore)) RestoreFormat mb_fc' mb_bc' mb_in' mb_it' mb_un' -> SSGR sgrs (best n k mb_fc' mb_bc' mb_in' mb_it' mb_un' ds) where -- We need to be able to restore the entire SGR state, hence we carry around what we believe -- that state should be in all the arguments to this function. Note that in some cases we could -- avoid the Reset of the entire state, but not in general. sgrs = Reset : catMaybes [ fmap (uncurry (SetColor Foreground)) mb_fc', fmap (uncurry (SetColor Background)) mb_bc', fmap SetConsoleIntensity mb_in', fmap SetItalicized mb_it', fmap SetUnderlining mb_un' ] where best_typical n' k' ds' = best n' k' mb_fc mb_bc mb_in mb_it mb_un ds' ds_restore = Cons i (RestoreFormat mb_fc mb_bc mb_in mb_it mb_un) ds --nicest :: r = ribbon width, w = page width, -- n = indentation of current line, k = current column -- x and y, the (simple) documents to chose from. -- precondition: first lines of x are longer than the first lines of y. nicest n k x y | fits w (min n k) width x = x | otherwise = y where width = min (w - k) (r - k + n) -- @fits1@ does 1 line lookahead. fits1 :: Int -> Int -> Int -> SimpleDoc -> Bool fits1 _ _ w x | w < 0 = False fits1 _ _ w SFail = False fits1 _ _ w SEmpty = True fits1 p m w (SChar c x) = fits1 p m (w - 1) x fits1 p m w (SText l s x) = fits1 p m (w - l) x fits1 _ _ w (SLine i x) = True fits1 p m w (SSGR _ x) = fits1 p m w x -- @fitsR@ has a little more lookahead: assuming that nesting roughly -- corresponds to syntactic depth, @fitsR@ checks that not only the current line -- fits, but the entire syntactic structure being formatted at this level of -- indentation fits. If we were to remove the second case for @SLine@, we would -- check that not only the current structure fits, but also the rest of the -- document, which would be slightly more intelligent but would have exponential -- runtime (and is prohibitively expensive in practice). -- p = pagewidth -- m = minimum nesting level to fit in -- w = the width in which to fit the first line fitsR :: Int -> Int -> Int -> SimpleDoc -> Bool fitsR p m w x | w < 0 = False fitsR p m w SFail = False fitsR p m w SEmpty = True fitsR p m w (SChar c x) = fitsR p m (w - 1) x fitsR p m w (SText l s x) = fitsR p m (w - l) x fitsR p m w (SLine i x) | m < i = fitsR p m (p - i) x | otherwise = True fitsR p m w (SSGR _ x) = fitsR p m w x ----------------------------------------------------------- -- renderCompact: renders documents without indentation -- fast and fewer characters output, good for machines ----------------------------------------------------------- -- | @(renderCompact x)@ renders document @x@ without adding any -- indentation. Since no \'pretty\' printing is involved, this -- renderer is very fast. The resulting output contains fewer -- characters than a pretty printed version and can be used for output -- that is read by other programs. -- -- This rendering function does not add any colorisation information. renderCompact :: Doc -> SimpleDoc renderCompact x = scan 0 [x] where scan k [] = SEmpty scan k (d:ds) = case d of Fail -> SFail Empty -> scan k ds Char c -> let k' = k+1 in seq k' (SChar c (scan k' ds)) Text l s -> let k' = k+l in seq k' (SText l s (scan k' ds)) FlatAlt x _ -> scan k (x:ds) Line -> SLine 0 (scan 0 ds) Cat x y -> scan k (x:y:ds) Nest j x -> scan k (x:ds) Union x y -> scan k (y:ds) Column f -> scan k (f k:ds) Columns f -> scan k (f Nothing:ds) Nesting f -> scan k (f 0:ds) Color _ _ _ x -> scan k (x:ds) Intensify _ x -> scan k (x:ds) Italicize _ x -> scan k (x:ds) Underline _ x -> scan k (x:ds) RestoreFormat _ _ _ _ _ -> scan k ds ----------------------------------------------------------- -- Displayers: displayS and displayIO ----------------------------------------------------------- -- | @(displayS simpleDoc)@ takes the output @simpleDoc@ from a -- rendering function and transforms it to a 'ShowS' type (for use in -- the 'Show' class). -- -- > showWidth :: Int -> Doc -> String -- > showWidth w x = displayS (renderPretty 0.4 w x) "" -- -- ANSI color information will be discarded by this function unless -- you are running on a Unix-like operating system. This is due to -- a technical limitation in Windows ANSI support. displayS :: SimpleDoc -> ShowS displayS SFail = error $ "@SFail@ can not appear uncaught in a " ++ "rendered @SimpleDoc@" displayS SEmpty = id displayS (SChar c x) = showChar c . displayS x displayS (SText l s x) = showString s . displayS x displayS (SLine i x) = showString ('\n':indentation i) . displayS x displayS (SSGR s x) = showString (setSGRCode s) . displayS x -- | @(displayIO handle simpleDoc)@ writes @simpleDoc@ to the file -- handle @handle@. This function is used for example by 'hPutDoc': -- -- > hPutDoc handle doc = displayIO handle (renderPretty 0.4 100 doc) -- -- Any ANSI colorisation in @simpleDoc@ will be output. displayIO :: Handle -> SimpleDoc -> IO () displayIO handle simpleDoc = display simpleDoc where display SFail = error $ "@SFail@ can not appear uncaught in a " ++ "rendered @SimpleDoc@" display SEmpty = return () display (SChar c x) = do{ hPutChar handle c; display x} display (SText l s x) = do{ hPutStr handle s; display x} display (SLine i x) = do{ hPutStr handle ('\n':indentation i); display x} display (SSGR s x) = do{ hSetSGR handle s; display x} ----------------------------------------------------------- -- default pretty printers: show, putDoc and hPutDoc ----------------------------------------------------------- instance Show Doc where showsPrec d doc = displayS (renderPretty 0.4 80 doc) -- | The action @(putDoc doc)@ pretty prints document @doc@ to the -- standard output, with a page width of 100 characters and a ribbon -- width of 40 characters. -- -- > main :: IO () -- > main = do{ putDoc (text "hello" <+> text "world") } -- -- Which would output -- -- @ -- hello world -- @ -- -- Any ANSI colorisation in @doc@ will be output. putDoc :: Doc -> IO () putDoc doc = hPutDoc stdout doc -- | @(hPutDoc handle doc)@ pretty prints document @doc@ to the file -- handle @handle@ with a page width of 100 characters and a ribbon -- width of 40 characters. -- -- > main = do{ handle <- openFile "MyFile" WriteMode -- > ; hPutDoc handle (vcat (map text -- > ["vertical","text"])) -- > ; hClose handle -- > } -- -- Any ANSI colorisation in @doc@ will be output. hPutDoc :: Handle -> Doc -> IO () hPutDoc handle doc = displayIO handle (renderPretty 0.4 80 doc) ----------------------------------------------------------- -- insert spaces -- "indentation" used to insert tabs but tabs seem to cause -- more trouble than they solve :-) ----------------------------------------------------------- spaces :: Int -> String spaces n | n <= 0 = "" | otherwise = replicate n ' ' indentation :: Int -> String indentation n = spaces n --indentation n | n >= 8 = '\t' : indentation (n-8) -- | otherwise = spaces n -- LocalWords: PPrint combinators Wadler Wadler's encloseSep
hvr/ansi-wl-pprint
Text/PrettyPrint/ANSI/Leijen.hs
bsd-2-clause
48,494
0
19
12,383
7,961
4,488
3,473
480
20
-- http://www.codewars.com/kata/5502c9e7b3216ec63c0001aa module Codewars.Kata.Categorize where import Codewars.Kata.Categorize.Types -- data Membership = Open | Senior deriving (Eq, Show) openOrSenior :: [(Int, Int)] -> [Membership] openOrSenior = map f where f (a, h) | a>=55 && h>7 = Senior | otherwise = Open
Bodigrim/katas
src/haskell/7-Categorize-New-Member.hs
bsd-2-clause
322
0
12
51
88
50
38
7
1
{-# OPTIONS -Wall #-} ----------------------------------------------------------------------------- -- | -- Module : CEquiv.hs (Executable) -- Copyright : (c) 2008 Benedikt Huber -- License : BSD-style -- Maintainer : [email protected] -- -- This module is invoked just like gcc. It preprocesses the two C source files given in the arguments -- and parses them. Then it compares the ASTs. If CTEST_NON_EQUIV is set, the comparison is expected to fail, -- otherwise it is expected that the ASTs are equal. -- -- Tests are logged, and serialized into a result file. -- If the CEquiv finishes without runtime error, it always returns ExitSuccess. -- -- see 'TestEnvironment'. ----------------------------------------------------------------------------- module Main (main) where import Control.Monad.State import System.FilePath (takeBaseName) import Text.PrettyPrint import Language.Data import Language.C.Test.Environment import Language.C.Test.Framework import Language.C.Test.ParseTests import Language.C.Test.TestMonad nonEquivEnvVar :: String nonEquivEnvVar = "CTEST_NON_EQUIV" main :: IO () main = defaultMain usage theEquivTest usage :: Doc usage = text "./Equiv [gcc-opts] file.1.(c|hc|i) file.2.(c|hc|i)" $$ nest 4 (text "Test Driver: Parses two files and compares the ASTs") $$ envHelpDoc [ (nonEquivEnvVar, ("expected that the ASTs aren't equal",Just "False")) ] theEquivTest :: [String] -> TestMonad () theEquivTest args = case mungeCcArgs args of Ignore -> errorOnInit args $ "No C source file found in argument list: `cc " ++ unwords args ++ "'" Unknown err -> errorOnInit args $ "Could not munge CC args: " ++ err ++ " in `cc "++ unwords args ++ "'" Groked [f1,f2] gccArgs -> theEquivTest' f1 f2 gccArgs Groked cFiles _ -> errorOnInit args $ "Expected two C source files, but found " ++ unwords cFiles theEquivTest' :: FilePath -> FilePath -> [String] -> TestMonad () theEquivTest' f1 f2 gccArgs = do dbgMsg $ "Comparing the ASTs of " ++ f1 ++ " and " ++ f2 expectNonEquiv <- liftIO$ getEnvFlag nonEquivEnvVar dbgMsg $ "Expecting that the ASTs " ++ (if expectNonEquiv then " don't match" else "match") ++ ".\n" modify $ setTmpTemplate (takeBaseName f1) (cFile1, preFile1) <- runCPP f1 gccArgs modify $ setTmpTemplate (takeBaseName f2) (cFile2, preFile2) <- runCPP f2 gccArgs modify $ setTestRunResults (emptyTestResults (takeBaseName (f1 ++ " == " ++ f2)) [cFile1,cFile2]) let parseTest1 = initializeTestResult (parseTestTemplate { testName = "01-parse" }) [f1] let parseTest2 = initializeTestResult (parseTestTemplate { testName = "02-parse" }) [f2] modify $ setTmpTemplate (takeBaseName f1) parseResult1 <- runParseTest preFile1 (initPos cFile1) addTestM $ setTestStatus parseTest1 $ either (uncurry testFailWithReport) (testOkNoReport . snd) parseResult1 ast1 <- either (const exitTest) (return . fst) parseResult1 modify $ setTmpTemplate (takeBaseName f2) parseResult2 <- runParseTest preFile2 (initPos cFile2) addTestM $ setTestStatus parseTest2 $ either (uncurry testFailWithReport) (testOkNoReport . snd) parseResult2 ast2 <- either (const exitTest) (return . fst) parseResult2 -- check equiv modify $ setTmpTemplate (takeBaseName f1 ++ "_eq_" ++ takeBaseName f2) equivResult <- runEquivTest ast1 ast2 case expectNonEquiv of False -> let equivTest = initializeTestResult (equivTestTemplate { testName = "03-equiv" }) [] in addTestM . setTestStatus equivTest $ either (uncurry testFailure) testOkNoReport equivResult True -> let equivTest = initializeTestResult (equivTestTemplate { testName = "03-non-equiv" }) [] in addTestM . setTestStatus equivTest $ either (\(_,mReport) -> testOkUntimed mReport) (\_ -> testFailNoReport "ASTs are equivalent") equivResult
micknelso/language-c
test/src/CEquiv.hs
bsd-3-clause
3,993
0
17
814
941
480
461
61
4
module Data.Language.Brainfuck.Parser where import Data.Language.Brainfuck.Types parse :: String -> Either String Program parse s = case go [] (s ++ "]") of Left msg -> Left msg Right (p, []) -> Right (reverse p) Right (_, rest) -> Left ("unexpected input: " ++ rest) where go p ('+':xs) = go (AdjustCellAt 0 1 : p) xs go p ('-':xs) = go (AdjustCellAt 0 (-1) : p) xs go p ('>':xs) = go (AdjustCellPtr 1 : p) xs go p ('<':xs) = go (AdjustCellPtr (-1) : p) xs go p ('.':xs) = go (PutChar : p) xs go p (',':xs) = go (GetChar : p) xs go p ('[':xs) = case go [] xs of Left msg -> Left msg Right (p', rest) -> go (Loop (reverse p') : p) rest go p (']':xs) = Right (p, xs) go p (_ :xs) = go p xs go _ [] = Left "missing ']'"
frerich/brainfuck
src/lib/Data/Language/Brainfuck/Parser.hs
bsd-3-clause
862
0
15
296
459
234
225
19
13
----------------------------------------------------------------------------- -- -- Stg to C-- code generation: expressions -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmExpr ( cgExpr ) where #define FAST_STRING_NOT_NEEDED #include "HsVersions.h" import {-# SOURCE #-} StgCmmBind ( cgBind ) import StgCmmMonad import StgCmmHeap import StgCmmEnv import StgCmmCon import StgCmmProf (saveCurrentCostCentre, restoreCurrentCostCentre, emitSetCCC) import StgCmmLayout import StgCmmPrim import StgCmmHpc import StgCmmTicky import StgCmmUtils import StgCmmClosure import StgSyn import MkGraph import BlockId import Cmm import CmmInfo import CoreSyn import DataCon import ForeignCall import Id import PrimOp import TyCon import Type import CostCentre ( CostCentreStack, currentCCS ) import Maybes import Util import FastString import Outputable import Control.Monad (when,void) ------------------------------------------------------------------------ -- cgExpr: the main function ------------------------------------------------------------------------ cgExpr :: StgExpr -> FCode ReturnKind cgExpr (StgApp fun args) = cgIdApp fun args {- seq# a s ==> a -} cgExpr (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _res_ty) = cgIdApp a [] cgExpr (StgOpApp op args ty) = cgOpApp op args ty cgExpr (StgConApp con args) = cgConApp con args cgExpr (StgSCC cc tick push expr) = do { emitSetCCC cc tick push; cgExpr expr } cgExpr (StgTick m n expr) = do dflags <- getDynFlags emit (mkTickBox dflags m n) cgExpr expr cgExpr (StgLit lit) = do cmm_lit <- cgLit lit emitReturn [CmmLit cmm_lit] cgExpr (StgLet binds expr) = do { cgBind binds; cgExpr expr } cgExpr (StgLetNoEscape _ _ binds expr) = do { u <- newUnique ; let join_id = mkBlockId u ; cgLneBinds join_id binds ; r <- cgExpr expr ; emitLabel join_id ; return r } cgExpr (StgCase expr _live_vars _save_vars bndr _srt alt_type alts) = cgCase expr bndr alt_type alts cgExpr (StgLam {}) = panic "cgExpr: StgLam" ------------------------------------------------------------------------ -- Let no escape ------------------------------------------------------------------------ {- Generating code for a let-no-escape binding, aka join point is very very similar to what we do for a case expression. The duality is between let-no-escape x = b in e and case e of ... -> b That is, the RHS of 'x' (ie 'b') will execute *later*, just like the alternative of the case; it needs to be compiled in an environment in which all volatile bindings are forgotten, and the free vars are bound only to stable things like stack locations.. The 'e' part will execute *next*, just like the scrutinee of a case. -} ------------------------- cgLneBinds :: BlockId -> StgBinding -> FCode () cgLneBinds join_id (StgNonRec bndr rhs) = do { local_cc <- saveCurrentCostCentre -- See Note [Saving the current cost centre] ; (info, fcode) <- cgLetNoEscapeRhs join_id local_cc bndr rhs ; fcode ; addBindC info } cgLneBinds join_id (StgRec pairs) = do { local_cc <- saveCurrentCostCentre ; r <- sequence $ unzipWith (cgLetNoEscapeRhs join_id local_cc) pairs ; let (infos, fcodes) = unzip r ; addBindsC infos ; sequence_ fcodes } ------------------------- cgLetNoEscapeRhs :: BlockId -- join point for successor of let-no-escape -> Maybe LocalReg -- Saved cost centre -> Id -> StgRhs -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeRhs join_id local_cc bndr rhs = do { (info, rhs_code) <- cgLetNoEscapeRhsBody local_cc bndr rhs ; let (bid, _) = expectJust "cgLetNoEscapeRhs" $ maybeLetNoEscape info ; let code = do { body <- getCode rhs_code ; emitOutOfLine bid (body <*> mkBranch join_id) } ; return (info, code) } cgLetNoEscapeRhsBody :: Maybe LocalReg -- Saved cost centre -> Id -> StgRhs -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeRhsBody local_cc bndr (StgRhsClosure cc _bi _ _upd _ args body) = cgLetNoEscapeClosure bndr local_cc cc (nonVoidIds args) body cgLetNoEscapeRhsBody local_cc bndr (StgRhsCon cc con args) = cgLetNoEscapeClosure bndr local_cc cc [] (StgConApp con args) -- For a constructor RHS we want to generate a single chunk of -- code which can be jumped to from many places, which will -- return the constructor. It's easy; just behave as if it -- was an StgRhsClosure with a ConApp inside! ------------------------- cgLetNoEscapeClosure :: Id -- binder -> Maybe LocalReg -- Slot for saved current cost centre -> CostCentreStack -- XXX: *** NOT USED *** why not? -> [NonVoid Id] -- Args (as in \ args -> body) -> StgExpr -- Body (as in above) -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeClosure bndr cc_slot _unused_cc args body = do dflags <- getDynFlags return ( lneIdInfo dflags bndr args , code ) where code = forkLneBody $ do { ; withNewTickyCounterLNE (idName bndr) args $ do ; restoreCurrentCostCentre cc_slot ; arg_regs <- bindArgsToRegs args ; void $ noEscapeHeapCheck arg_regs (tickyEnterLNE >> cgExpr body) } ------------------------------------------------------------------------ -- Case expressions ------------------------------------------------------------------------ {- Note [Compiling case expressions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is quite interesting to decide whether to put a heap-check at the start of each alternative. Of course we certainly have to do so if the case forces an evaluation, or if there is a primitive op which can trigger GC. A more interesting situation is this (a Plan-B situation) !P!; ...P... case x# of 0# -> !Q!; ...Q... default -> !R!; ...R... where !x! indicates a possible heap-check point. The heap checks in the alternatives *can* be omitted, in which case the topmost heapcheck will take their worst case into account. In favour of omitting !Q!, !R!: - *May* save a heap overflow test, if ...P... allocates anything. - We can use relative addressing from a single Hp to get at all the closures so allocated. - No need to save volatile vars etc across heap checks in !Q!, !R! Against omitting !Q!, !R! - May put a heap-check into the inner loop. Suppose the main loop is P -> R -> P -> R... Q is the loop exit, and only it does allocation. This only hurts us if P does no allocation. If P allocates, then there is a heap check in the inner loop anyway. - May do more allocation than reqd. This sometimes bites us badly. For example, nfib (ha!) allocates about 30\% more space if the worst-casing is done, because many many calls to nfib are leaf calls which don't need to allocate anything. We can un-allocate, but that costs an instruction Neither problem hurts us if there is only one alternative. Suppose the inner loop is P->R->P->R etc. Then here is how many heap checks we get in the *inner loop* under various conditions Alooc Heap check in branches (!Q!, !R!)? P Q R yes no (absorb to !P!) -------------------------------------- n n n 0 0 n y n 0 1 n . y 1 1 y . y 2 1 y . n 1 1 Best choices: absorb heap checks from Q and R into !P! iff a) P itself does some allocation or b) P does allocation, or there is exactly one alternative We adopt (b) because that is more likely to put the heap check at the entry to a function, when not many things are live. After a bunch of single-branch cases, we may have lots of things live Hence: two basic plans for case e of r { alts } ------ Plan A: the general case --------- ...save current cost centre... ...code for e, with sequel (SetLocals r) ...restore current cost centre... ...code for alts... ...alts do their own heap checks ------ Plan B: special case when --------- (i) e does not allocate or call GC (ii) either upstream code performs allocation or there is just one alternative Then heap allocation in the (single) case branch is absorbed by the upstream check. Very common example: primops on unboxed values ...code for e, with sequel (SetLocals r)... ...code for alts... ...no heap check... -} ------------------------------------- data GcPlan = GcInAlts -- Put a GC check at the start the case alternatives, [LocalReg] -- which binds these registers | NoGcInAlts -- The scrutinee is a primitive value, or a call to a -- primitive op which does no GC. Absorb the allocation -- of the case alternative(s) into the upstream check ------------------------------------- cgCase :: StgExpr -> Id -> AltType -> [StgAlt] -> FCode ReturnKind cgCase (StgOpApp (StgPrimOp op) args _) bndr (AlgAlt tycon) alts | isEnumerationTyCon tycon -- Note [case on bool] = do { tag_expr <- do_enum_primop op args -- If the binder is not dead, convert the tag to a constructor -- and assign it. ; when (not (isDeadBinder bndr)) $ do { dflags <- getDynFlags ; tmp_reg <- bindArgToReg (NonVoid bndr) ; emitAssign (CmmLocal tmp_reg) (tagToClosure dflags tycon tag_expr) } ; (mb_deflt, branches) <- cgAlgAltRhss (NoGcInAlts,AssignedDirectly) (NonVoid bndr) alts ; emitSwitch tag_expr branches mb_deflt 0 (tyConFamilySize tycon - 1) ; return AssignedDirectly } where do_enum_primop :: PrimOp -> [StgArg] -> FCode CmmExpr do_enum_primop TagToEnumOp [arg] -- No code! = getArgAmode (NonVoid arg) do_enum_primop primop args = do dflags <- getDynFlags tmp <- newTemp (bWord dflags) cgPrimOp [tmp] primop args return (CmmReg (CmmLocal tmp)) {- Note [case on bool] ~~~~~~~~~~~~~~~~~~~ This special case handles code like case a <# b of True -> False -> --> case tagToEnum# (a <$# b) of True -> .. ; False -> ... --> case (a <$# b) of r -> case tagToEnum# r of True -> .. ; False -> ... If we let the ordinary case code handle it, we'll get something like tmp1 = a < b tmp2 = Bool_closure_tbl[tmp1] if (tmp2 & 7 != 0) then ... // normal tagged case but this junk won't optimise away. What we really want is just an inline comparison: if (a < b) then ... So we add a special case to generate tmp1 = a < b if (tmp1 == 0) then ... and later optimisations will further improve this. Now that #6135 has been resolved it should be possible to remove that special case. The idea behind this special case and pre-6135 implementation of Bool-returning primops was that tagToEnum# was added implicitly in the codegen and then optimized away. Now the call to tagToEnum# is explicit in the source code, which allows to optimize it away at the earlier stages of compilation (i.e. at the Core level). -} -- Note [ticket #3132]: we might be looking at a case of a lifted Id -- that was cast to an unlifted type. The Id will always be bottom, -- but we don't want the code generator to fall over here. If we -- just emit an assignment here, the assignment will be -- type-incorrect Cmm. Hence, we emit the usual enter/return code, -- (and because bottom must be untagged, it will be entered and the -- program will crash). -- The Sequel is a type-correct assignment, albeit bogus. -- The (dead) continuation loops; it would be better to invoke some kind -- of panic function here. -- -- However, we also want to allow an assignment to be generated -- in the case when the types are compatible, because this allows -- some slightly-dodgy but occasionally-useful casts to be used, -- such as in RtClosureInspect where we cast an HValue to a MutVar# -- so we can print out the contents of the MutVar#. If we generate -- code that enters the HValue, then we'll get a runtime panic, because -- the HValue really is a MutVar#. The types are compatible though, -- so we can just generate an assignment. cgCase (StgApp v []) bndr alt_type@(PrimAlt _) alts | isUnLiftedType (idType v) || reps_compatible = -- assignment suffices for unlifted types do { dflags <- getDynFlags ; when (not reps_compatible) $ panic "cgCase: reps do not match, perhaps a dodgy unsafeCoerce?" ; v_info <- getCgIdInfo v ; emitAssign (CmmLocal (idToReg dflags (NonVoid bndr))) (idInfoToAmode v_info) ; _ <- bindArgsToRegs [NonVoid bndr] ; cgAlts (NoGcInAlts,AssignedDirectly) (NonVoid bndr) alt_type alts } where reps_compatible = idPrimRep v == idPrimRep bndr cgCase scrut@(StgApp v []) _ (PrimAlt _) _ = -- fail at run-time, not compile-time do { dflags <- getDynFlags ; mb_cc <- maybeSaveCostCentre True ; _ <- withSequel (AssignTo [idToReg dflags (NonVoid v)] False) (cgExpr scrut) ; restoreCurrentCostCentre mb_cc ; emitComment $ mkFastString "should be unreachable code" ; l <- newLabelC ; emitLabel l ; emit (mkBranch l) ; return AssignedDirectly } {- case seq# a s of v (# s', a' #) -> e ==> case a of v (# s', a' #) -> e (taking advantage of the fact that the return convention for (# State#, a #) is the same as the return convention for just 'a') -} cgCase (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _) bndr alt_type alts = -- handle seq#, same return convention as vanilla 'a'. cgCase (StgApp a []) bndr alt_type alts cgCase scrut bndr alt_type alts = -- the general case do { dflags <- getDynFlags ; up_hp_usg <- getVirtHp -- Upstream heap usage ; let ret_bndrs = chooseReturnBndrs bndr alt_type alts alt_regs = map (idToReg dflags) ret_bndrs simple_scrut = isSimpleScrut scrut alt_type do_gc | not simple_scrut = True | isSingleton alts = False | up_hp_usg > 0 = False | otherwise = True -- cf Note [Compiling case expressions] gc_plan = if do_gc then GcInAlts alt_regs else NoGcInAlts ; mb_cc <- maybeSaveCostCentre simple_scrut -- if do_gc then our sequel will be ReturnTo -- - generate code for the sequel now -- - pass info about the sequel to cgAlts for use in the heap check -- else sequel will be AssignTo ; ret_kind <- withSequel (AssignTo alt_regs False) (cgExpr scrut) ; restoreCurrentCostCentre mb_cc ; _ <- bindArgsToRegs ret_bndrs ; cgAlts (gc_plan,ret_kind) (NonVoid bndr) alt_type alts } ----------------- maybeSaveCostCentre :: Bool -> FCode (Maybe LocalReg) maybeSaveCostCentre simple_scrut | simple_scrut = return Nothing | otherwise = saveCurrentCostCentre ----------------- isSimpleScrut :: StgExpr -> AltType -> Bool -- Simple scrutinee, does not block or allocate; hence safe to amalgamate -- heap usage from alternatives into the stuff before the case -- NB: if you get this wrong, and claim that the expression doesn't allocate -- when it does, you'll deeply mess up allocation isSimpleScrut (StgOpApp op _ _) _ = isSimpleOp op isSimpleScrut (StgLit _) _ = True -- case 1# of { 0# -> ..; ... } isSimpleScrut (StgApp _ []) (PrimAlt _) = True -- case x# of { 0# -> ..; ... } isSimpleScrut _ _ = False isSimpleOp :: StgOp -> Bool -- True iff the op cannot block or allocate isSimpleOp (StgFCallOp (CCall (CCallSpec _ _ safe)) _) = not (playSafe safe) isSimpleOp (StgPrimOp op) = not (primOpOutOfLine op) isSimpleOp (StgPrimCallOp _) = False ----------------- chooseReturnBndrs :: Id -> AltType -> [StgAlt] -> [NonVoid Id] -- These are the binders of a case that are assigned -- by the evaluation of the scrutinee -- Only non-void ones come back chooseReturnBndrs bndr (PrimAlt _) _alts = nonVoidIds [bndr] chooseReturnBndrs _bndr (UbxTupAlt _) [(_, ids, _, _)] = nonVoidIds ids -- 'bndr' is not assigned! chooseReturnBndrs bndr (AlgAlt _) _alts = nonVoidIds [bndr] -- Only 'bndr' is assigned chooseReturnBndrs bndr PolyAlt _alts = nonVoidIds [bndr] -- Only 'bndr' is assigned chooseReturnBndrs _ _ _ = panic "chooseReturnBndrs" -- UbxTupALt has only one alternative ------------------------------------- cgAlts :: (GcPlan,ReturnKind) -> NonVoid Id -> AltType -> [StgAlt] -> FCode ReturnKind -- At this point the result of the case are in the binders cgAlts gc_plan _bndr PolyAlt [(_, _, _, rhs)] = maybeAltHeapCheck gc_plan (cgExpr rhs) cgAlts gc_plan _bndr (UbxTupAlt _) [(_, _, _, rhs)] = maybeAltHeapCheck gc_plan (cgExpr rhs) -- Here bndrs are *already* in scope, so don't rebind them cgAlts gc_plan bndr (PrimAlt _) alts = do { dflags <- getDynFlags ; tagged_cmms <- cgAltRhss gc_plan bndr alts ; let bndr_reg = CmmLocal (idToReg dflags bndr) (DEFAULT,deflt) = head tagged_cmms -- PrimAlts always have a DEFAULT case -- and it always comes first tagged_cmms' = [(lit,code) | (LitAlt lit, code) <- tagged_cmms] ; emitCmmLitSwitch (CmmReg bndr_reg) tagged_cmms' deflt ; return AssignedDirectly } cgAlts gc_plan bndr (AlgAlt tycon) alts = do { dflags <- getDynFlags ; (mb_deflt, branches) <- cgAlgAltRhss gc_plan bndr alts ; let fam_sz = tyConFamilySize tycon bndr_reg = CmmLocal (idToReg dflags bndr) -- Is the constructor tag in the node reg? ; if isSmallFamily dflags fam_sz then do let -- Yes, bndr_reg has constr. tag in ls bits tag_expr = cmmConstrTag1 dflags (CmmReg bndr_reg) branches' = [(tag+1,branch) | (tag,branch) <- branches] emitSwitch tag_expr branches' mb_deflt 1 fam_sz return AssignedDirectly else -- No, get tag from info table do dflags <- getDynFlags let -- Note that ptr _always_ has tag 1 -- when the family size is big enough untagged_ptr = cmmRegOffB bndr_reg (-1) tag_expr = getConstrTag dflags (untagged_ptr) emitSwitch tag_expr branches mb_deflt 0 (fam_sz - 1) return AssignedDirectly } cgAlts _ _ _ _ = panic "cgAlts" -- UbxTupAlt and PolyAlt have only one alternative -- Note [alg-alt heap check] -- -- In an algebraic case with more than one alternative, we will have -- code like -- -- L0: -- x = R1 -- goto L1 -- L1: -- if (x & 7 >= 2) then goto L2 else goto L3 -- L2: -- Hp = Hp + 16 -- if (Hp > HpLim) then goto L4 -- ... -- L4: -- call gc() returns to L5 -- L5: -- x = R1 -- goto L1 ------------------- cgAlgAltRhss :: (GcPlan,ReturnKind) -> NonVoid Id -> [StgAlt] -> FCode ( Maybe CmmAGraph , [(ConTagZ, CmmAGraph)] ) cgAlgAltRhss gc_plan bndr alts = do { tagged_cmms <- cgAltRhss gc_plan bndr alts ; let { mb_deflt = case tagged_cmms of ((DEFAULT,rhs) : _) -> Just rhs _other -> Nothing -- DEFAULT is always first, if present ; branches = [ (dataConTagZ con, cmm) | (DataAlt con, cmm) <- tagged_cmms ] } ; return (mb_deflt, branches) } ------------------- cgAltRhss :: (GcPlan,ReturnKind) -> NonVoid Id -> [StgAlt] -> FCode [(AltCon, CmmAGraph)] cgAltRhss gc_plan bndr alts = do dflags <- getDynFlags let base_reg = idToReg dflags bndr cg_alt :: StgAlt -> FCode (AltCon, CmmAGraph) cg_alt (con, bndrs, _uses, rhs) = getCodeR $ maybeAltHeapCheck gc_plan $ do { _ <- bindConArgs con base_reg bndrs ; _ <- cgExpr rhs ; return con } forkAlts (map cg_alt alts) maybeAltHeapCheck :: (GcPlan,ReturnKind) -> FCode a -> FCode a maybeAltHeapCheck (NoGcInAlts,_) code = code maybeAltHeapCheck (GcInAlts regs, AssignedDirectly) code = altHeapCheck regs code maybeAltHeapCheck (GcInAlts regs, ReturnedTo lret off) code = altHeapCheckReturnsTo regs lret off code ----------------------------------------------------------------------------- -- Tail calls ----------------------------------------------------------------------------- cgConApp :: DataCon -> [StgArg] -> FCode ReturnKind cgConApp con stg_args | isUnboxedTupleCon con -- Unboxed tuple: assign and return = do { arg_exprs <- getNonVoidArgAmodes stg_args ; tickyUnboxedTupleReturn (length arg_exprs) ; emitReturn arg_exprs } | otherwise -- Boxed constructors; allocate and return = ASSERT( stg_args `lengthIs` dataConRepRepArity con ) do { (idinfo, fcode_init) <- buildDynCon (dataConWorkId con) False currentCCS con stg_args -- The first "con" says that the name bound to this -- closure is is "con", which is a bit of a fudge, but -- it only affects profiling (hence the False) ; emit =<< fcode_init ; emitReturn [idInfoToAmode idinfo] } cgIdApp :: Id -> [StgArg] -> FCode ReturnKind cgIdApp fun_id [] | isVoidId fun_id = emitReturn [] cgIdApp fun_id args = do dflags <- getDynFlags fun_info <- getCgIdInfo fun_id self_loop_info <- getSelfLoop let cg_fun_id = cg_id fun_info -- NB: use (cg_id fun_info) instead of fun_id, because -- the former may be externalised for -split-objs. -- See Note [Externalise when splitting] in StgCmmMonad fun_arg = StgVarArg cg_fun_id fun_name = idName cg_fun_id fun = idInfoToAmode fun_info lf_info = cg_lf fun_info node_points dflags = nodeMustPointToIt dflags lf_info case (getCallMethod dflags fun_name cg_fun_id lf_info (length args) (cg_loc fun_info) self_loop_info) of -- A value in WHNF, so we can just return it. ReturnIt -> emitReturn [fun] -- ToDo: does ReturnIt guarantee tagged? EnterIt -> ASSERT( null args ) -- Discarding arguments emitEnter fun SlowCall -> do -- A slow function call via the RTS apply routines { tickySlowCall lf_info args ; emitComment $ mkFastString "slowCall" ; slowCall fun args } -- A direct function call (possibly with some left-over arguments) DirectEntry lbl arity -> do { tickyDirectCall arity args ; if node_points dflags then directCall NativeNodeCall lbl arity (fun_arg:args) else directCall NativeDirectCall lbl arity args } -- Let-no-escape call or self-recursive tail-call JumpToIt blk_id lne_regs -> do { adjustHpBackwards -- always do this before a tail-call ; cmm_args <- getNonVoidArgAmodes args ; emitMultiAssign lne_regs cmm_args ; emit (mkBranch blk_id) ; return AssignedDirectly } -- Note [Self-recursive tail calls] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Self-recursive tail calls can be optimized into a local jump in the same -- way as let-no-escape bindings (see Note [What is a non-escaping let] in -- stgSyn/CoreToStg.lhs). Consider this: -- -- foo.info: -- a = R1 // calling convention -- b = R2 -- goto L1 -- L1: ... -- ... -- ... -- L2: R1 = x -- R2 = y -- call foo(R1,R2) -- -- Instead of putting x and y into registers (or other locations required by the -- calling convention) and performing a call we can put them into local -- variables a and b and perform jump to L1: -- -- foo.info: -- a = R1 -- b = R2 -- goto L1 -- L1: ... -- ... -- ... -- L2: a = x -- b = y -- goto L1 -- -- This can be done only when function is calling itself in a tail position -- and only if the call passes number of parameters equal to function's arity. -- Note that this cannot be performed if a function calls itself with a -- continuation. -- -- This in fact implements optimization known as "loopification". It was -- described in "Low-level code optimizations in the Glasgow Haskell Compiler" -- by Krzysztof Woś, though we use different approach. Krzysztof performed his -- optimization at the Cmm level, whereas we perform ours during code generation -- (Stg-to-Cmm pass) essentially making sure that optimized Cmm code is -- generated in the first place. -- -- Implementation is spread across a couple of places in the code: -- -- * FCode monad stores additional information in its reader environment -- (cgd_self_loop field). This information tells us which function can -- tail call itself in an optimized way (it is the function currently -- being compiled), what is the label of a loop header (L1 in example above) -- and information about local registers in which we should arguments -- before making a call (this would be a and b in example above). -- -- * Whenever we are compiling a function, we set that information to reflect -- the fact that function currently being compiled can be jumped to, instead -- of called. We also have to emit a label to which we will be jumping. Both -- things are done in closureCodyBody in StgCmmBind. -- -- * When we began compilation of another closure we remove the additional -- information from the environment. This is done by forkClosureBody -- in StgCmmMonad. Other functions that duplicate the environment - -- forkLneBody, forkAlts, codeOnly - duplicate that information. In other -- words, we only need to clean the environment of the self-loop information -- when compiling right hand side of a closure (binding). -- -- * When compiling a call (cgIdApp) we use getCallMethod to decide what kind -- of call will be generated. getCallMethod decides to generate a self -- recursive tail call when (a) environment stores information about -- possible self tail-call; (b) that tail call is to a function currently -- being compiled; (c) number of passed arguments is equal to function's -- arity. (d) loopification is turned on via -floopification command-line -- option. -- -- * Command line option to control turn loopification on and off is -- implemented in DynFlags -- emitEnter :: CmmExpr -> FCode ReturnKind emitEnter fun = do { dflags <- getDynFlags ; adjustHpBackwards ; sequel <- getSequel ; updfr_off <- getUpdFrameOff ; case sequel of -- For a return, we have the option of generating a tag-test or -- not. If the value is tagged, we can return directly, which -- is quicker than entering the value. This is a code -- size/speed trade-off: when optimising for speed rather than -- size we could generate the tag test. -- -- Right now, we do what the old codegen did, and omit the tag -- test, just generating an enter. Return _ -> do { let entry = entryCode dflags $ closureInfoPtr dflags $ CmmReg nodeReg ; emit $ mkJump dflags NativeNodeCall entry [cmmUntag dflags fun] updfr_off ; return AssignedDirectly } -- The result will be scrutinised in the sequel. This is where -- we generate a tag-test to avoid entering the closure if -- possible. -- -- The generated code will be something like this: -- -- R1 = fun -- copyout -- if (fun & 7 != 0) goto Lcall else goto Lret -- Lcall: -- call [fun] returns to Lret -- Lret: -- fun' = R1 -- copyin -- ... -- -- Note in particular that the label Lret is used as a -- destination by both the tag-test and the call. This is -- becase Lret will necessarily be a proc-point, and we want to -- ensure that we generate only one proc-point for this -- sequence. -- -- Furthermore, we tell the caller that we generated a native -- return continuation by returning (ReturnedTo Lret off), so -- that the continuation can be reused by the heap-check failure -- code in the enclosing case expression. -- AssignTo res_regs _ -> do { lret <- newLabelC ; let (off, _, copyin) = copyInOflow dflags NativeReturn (Young lret) res_regs [] ; lcall <- newLabelC ; updfr_off <- getUpdFrameOff ; let area = Young lret ; let (outArgs, regs, copyout) = copyOutOflow dflags NativeNodeCall Call area [fun] updfr_off [] -- refer to fun via nodeReg after the copyout, to avoid having -- both live simultaneously; this sometimes enables fun to be -- inlined in the RHS of the R1 assignment. ; let entry = entryCode dflags (closureInfoPtr dflags (CmmReg nodeReg)) the_call = toCall entry (Just lret) updfr_off off outArgs regs ; emit $ copyout <*> mkCbranch (cmmIsTagged dflags (CmmReg nodeReg)) lret lcall <*> outOfLine lcall the_call <*> mkLabel lret <*> copyin ; return (ReturnedTo lret off) } }
ekmett/ghc
compiler/codeGen/StgCmmExpr.hs
bsd-3-clause
30,135
8
20
8,286
4,547
2,403
2,144
-1
-1
{-# LANGUAGE BangPatterns, CPP, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- -- The register allocator -- -- (c) The University of Glasgow 2004 -- ----------------------------------------------------------------------------- {- The algorithm is roughly: 1) Compute strongly connected components of the basic block list. 2) Compute liveness (mapping from pseudo register to point(s) of death?). 3) Walk instructions in each basic block. We keep track of (a) Free real registers (a bitmap?) (b) Current assignment of temporaries to machine registers and/or spill slots (call this the "assignment"). (c) Partial mapping from basic block ids to a virt-to-loc mapping. When we first encounter a branch to a basic block, we fill in its entry in this table with the current mapping. For each instruction: (a) For each temporary *read* by the instruction: If the temporary does not have a real register allocation: - Allocate a real register from the free list. If the list is empty: - Find a temporary to spill. Pick one that is not used in this instruction (ToDo: not used for a while...) - generate a spill instruction - If the temporary was previously spilled, generate an instruction to read the temp from its spill loc. (optimisation: if we can see that a real register is going to be used soon, then don't use it for allocation). (b) For each real register clobbered by this instruction: If a temporary resides in it, If the temporary is live after this instruction, Move the temporary to another (non-clobbered & free) reg, or spill it to memory. Mark the temporary as residing in both memory and a register if it was spilled (it might need to be read by this instruction). (ToDo: this is wrong for jump instructions?) We do this after step (a), because if we start with movq v1, %rsi which is an instruction that clobbers %rsi, if v1 currently resides in %rsi we want to get movq %rsi, %freereg movq %rsi, %rsi -- will disappear instead of movq %rsi, %freereg movq %freereg, %rsi (c) Update the current assignment (d) If the instruction is a branch: if the destination block already has a register assignment, Generate a new block with fixup code and redirect the jump to the new block. else, Update the block id->assignment mapping with the current assignment. (e) Delete all register assignments for temps which are read (only) and die here. Update the free register list. (f) Mark all registers clobbered by this instruction as not free, and mark temporaries which have been spilled due to clobbering as in memory (step (a) marks then as in both mem & reg). (g) For each temporary *written* by this instruction: Allocate a real register as for (b), spilling something else if necessary. - except when updating the assignment, drop any memory locations that the temporary was previously in, since they will be no longer valid after this instruction. (h) Delete all register assignments for temps which are written and die here (there should rarely be any). Update the free register list. (i) Rewrite the instruction with the new mapping. (j) For each spilled reg known to be now dead, re-add its stack slot to the free list. -} module RegAlloc.Linear.Main ( regAlloc, module RegAlloc.Linear.Base, module RegAlloc.Linear.Stats ) where #include "HsVersions.h" import RegAlloc.Linear.State import RegAlloc.Linear.Base import RegAlloc.Linear.StackMap import RegAlloc.Linear.FreeRegs import RegAlloc.Linear.Stats import RegAlloc.Linear.JoinToTargets import qualified RegAlloc.Linear.PPC.FreeRegs as PPC import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC import qualified RegAlloc.Linear.X86.FreeRegs as X86 import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64 import TargetReg import RegAlloc.Liveness import Instruction import Reg import BlockId import Cmm hiding (RegSet) import Digraph import DynFlags import Unique import UniqSet import UniqFM import UniqSupply import Outputable import Platform import Data.Maybe import Data.List import Control.Monad -- ----------------------------------------------------------------------------- -- Top level of the register allocator -- Allocate registers regAlloc :: (Outputable instr, Instruction instr) => DynFlags -> LiveCmmDecl statics instr -> UniqSM ( NatCmmDecl statics instr , Maybe Int -- number of extra stack slots required, -- beyond maxSpillSlots , Maybe RegAllocStats) regAlloc _ (CmmData sec d) = return ( CmmData sec d , Nothing , Nothing ) regAlloc _ (CmmProc (LiveInfo info _ _ _) lbl live []) = return ( CmmProc info lbl live (ListGraph []) , Nothing , Nothing ) regAlloc dflags (CmmProc static lbl live sccs) | LiveInfo info entry_ids@(first_id:_) (Just block_live) _ <- static = do -- do register allocation on each component. (final_blocks, stats, stack_use) <- linearRegAlloc dflags entry_ids block_live sccs -- make sure the block that was first in the input list -- stays at the front of the output let ((first':_), rest') = partition ((== first_id) . blockId) final_blocks let max_spill_slots = maxSpillSlots dflags extra_stack | stack_use > max_spill_slots = Just (stack_use - max_spill_slots) | otherwise = Nothing return ( CmmProc info lbl live (ListGraph (first' : rest')) , extra_stack , Just stats) -- bogus. to make non-exhaustive match warning go away. regAlloc _ (CmmProc _ _ _ _) = panic "RegAllocLinear.regAlloc: no match" -- ----------------------------------------------------------------------------- -- Linear sweep to allocate registers -- | Do register allocation on some basic blocks. -- But be careful to allocate a block in an SCC only if it has -- an entry in the block map or it is the first block. -- linearRegAlloc :: (Outputable instr, Instruction instr) => DynFlags -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc dflags entry_ids block_live sccs = case platformArch platform of ArchX86 -> go $ (frInitFreeRegs platform :: X86.FreeRegs) ArchX86_64 -> go $ (frInitFreeRegs platform :: X86_64.FreeRegs) ArchSPARC -> go $ (frInitFreeRegs platform :: SPARC.FreeRegs) ArchSPARC64 -> panic "linearRegAlloc ArchSPARC64" ArchPPC -> go $ (frInitFreeRegs platform :: PPC.FreeRegs) ArchARM _ _ _ -> panic "linearRegAlloc ArchARM" ArchARM64 -> panic "linearRegAlloc ArchARM64" ArchPPC_64 _ -> go $ (frInitFreeRegs platform :: PPC.FreeRegs) ArchAlpha -> panic "linearRegAlloc ArchAlpha" ArchMipseb -> panic "linearRegAlloc ArchMipseb" ArchMipsel -> panic "linearRegAlloc ArchMipsel" ArchJavaScript -> panic "linearRegAlloc ArchJavaScript" ArchUnknown -> panic "linearRegAlloc ArchUnknown" where go f = linearRegAlloc' dflags f entry_ids block_live sccs platform = targetPlatform dflags linearRegAlloc' :: (FR freeRegs, Outputable instr, Instruction instr) => DynFlags -> freeRegs -> [BlockId] -- ^ entry points -> BlockMap RegSet -- ^ live regs on entry to each basic block -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths" -> UniqSM ([NatBasicBlock instr], RegAllocStats, Int) linearRegAlloc' dflags initFreeRegs entry_ids block_live sccs = do us <- getUniqueSupplyM let (_, stack, stats, blocks) = runR dflags mapEmpty initFreeRegs emptyRegMap (emptyStackMap dflags) us $ linearRA_SCCs entry_ids block_live [] sccs return (blocks, stats, getStackUse stack) linearRA_SCCs :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [NatBasicBlock instr] -> [SCC (LiveBasicBlock instr)] -> RegM freeRegs [NatBasicBlock instr] linearRA_SCCs _ _ blocksAcc [] = return $ reverse blocksAcc linearRA_SCCs entry_ids block_live blocksAcc (AcyclicSCC block : sccs) = do blocks' <- processBlock block_live block linearRA_SCCs entry_ids block_live ((reverse blocks') ++ blocksAcc) sccs linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs) = do blockss' <- process entry_ids block_live blocks [] (return []) False linearRA_SCCs entry_ids block_live (reverse (concat blockss') ++ blocksAcc) sccs {- from John Dias's patch 2008/10/16: The linear-scan allocator sometimes allocates a block before allocating one of its predecessors, which could lead to inconsistent allocations. Make it so a block is only allocated if a predecessor has set the "incoming" assignments for the block, or if it's the procedure's entry block. BL 2009/02: Careful. If the assignment for a block doesn't get set for some reason then this function will loop. We should probably do some more sanity checking to guard against this eventuality. -} process :: (FR freeRegs, Instruction instr, Outputable instr) => [BlockId] -> BlockMap RegSet -> [GenBasicBlock (LiveInstr instr)] -> [GenBasicBlock (LiveInstr instr)] -> [[NatBasicBlock instr]] -> Bool -> RegM freeRegs [[NatBasicBlock instr]] process _ _ [] [] accum _ = return $ reverse accum process entry_ids block_live [] next_round accum madeProgress | not madeProgress {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming. pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out." ( text "Unreachable blocks:" $$ vcat (map ppr next_round)) -} = return $ reverse accum | otherwise = process entry_ids block_live next_round [] accum False process entry_ids block_live (b@(BasicBlock id _) : blocks) next_round accum madeProgress = do block_assig <- getBlockAssigR if isJust (mapLookup id block_assig) || id `elem` entry_ids then do b' <- processBlock block_live b process entry_ids block_live blocks next_round (b' : accum) True else process entry_ids block_live blocks (b : next_round) accum madeProgress -- | Do register allocation on this basic block -- processBlock :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ live regs on entry to each basic block -> LiveBasicBlock instr -- ^ block to do register allocation on -> RegM freeRegs [NatBasicBlock instr] -- ^ block with registers allocated processBlock block_live (BasicBlock id instrs) = do initBlock id block_live (instrs', fixups) <- linearRA block_live [] [] id instrs return $ BasicBlock id instrs' : fixups -- | Load the freeregs and current reg assignment into the RegM state -- for the basic block with this BlockId. initBlock :: FR freeRegs => BlockId -> BlockMap RegSet -> RegM freeRegs () initBlock id block_live = do dflags <- getDynFlags let platform = targetPlatform dflags block_assig <- getBlockAssigR case mapLookup id block_assig of -- no prior info about this block: we must consider -- any fixed regs to be allocated, but we can ignore -- virtual regs (presumably this is part of a loop, -- and we'll iterate again). The assignment begins -- empty. Nothing -> do -- pprTrace "initFreeRegs" (text $ show initFreeRegs) (return ()) case mapLookup id block_live of Nothing -> setFreeRegsR (frInitFreeRegs platform) Just live -> setFreeRegsR $ foldr (frAllocateReg platform) (frInitFreeRegs platform) [ r | RegReal r <- nonDetEltsUFM live ] -- See Note [Unique Determinism and code generation] setAssigR emptyRegMap -- load info about register assignments leading into this block. Just (freeregs, assig) -> do setFreeRegsR freeregs setAssigR assig -- | Do allocation for a sequence of instructions. linearRA :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are live on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code. -> BlockId -- ^ id of the current block, for debugging. -> [LiveInstr instr] -- ^ liveness annotated instructions in this block. -> RegM freeRegs ( [instr] -- instructions after register allocation , [NatBasicBlock instr]) -- fresh blocks of fixup code. linearRA _ accInstr accFixup _ [] = return ( reverse accInstr -- instrs need to be returned in the correct order. , accFixup) -- it doesn't matter what order the fixup blocks are returned in. linearRA block_live accInstr accFixups id (instr:instrs) = do (accInstr', new_fixups) <- raInsn block_live accInstr id instr linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs -- | Do allocation for a single instruction. raInsn :: (FR freeRegs, Outputable instr, Instruction instr) => BlockMap RegSet -- ^ map of what vregs are love on entry to each block. -> [instr] -- ^ accumulator for instructions already processed. -> BlockId -- ^ the id of the current block, for debugging -> LiveInstr instr -- ^ the instr to have its regs allocated, with liveness info. -> RegM freeRegs ( [instr] -- new instructions , [NatBasicBlock instr]) -- extra fixup blocks raInsn _ new_instrs _ (LiveInstr ii Nothing) | Just n <- takeDeltaInstr ii = do setDeltaR n return (new_instrs, []) raInsn _ new_instrs _ (LiveInstr ii@(Instr i) Nothing) | isMetaInstr ii = return (i : new_instrs, []) raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live)) = do assig <- getAssigR -- If we have a reg->reg move between virtual registers, where the -- src register is not live after this instruction, and the dst -- register does not already have an assignment, -- and the source register is assigned to a register, not to a spill slot, -- then we can eliminate the instruction. -- (we can't eliminate it if the source register is on the stack, because -- we do not want to use one spill slot for different virtual registers) case takeRegRegMoveInstr instr of Just (src,dst) | src `elementOfUniqSet` (liveDieRead live), isVirtualReg dst, not (dst `elemUFM` assig), isRealReg src || isInReg src assig -> do case src of (RegReal rr) -> setAssigR (addToUFM assig dst (InReg rr)) -- if src is a fixed reg, then we just map dest to this -- reg in the assignment. src must be an allocatable reg, -- otherwise it wouldn't be in r_dying. _virt -> case lookupUFM assig src of Nothing -> panic "raInsn" Just loc -> setAssigR (addToUFM (delFromUFM assig src) dst loc) -- we have eliminated this instruction {- freeregs <- getFreeRegsR assig <- getAssigR pprTrace "raInsn" (text "ELIMINATED: " <> docToSDoc (pprInstr instr) $$ ppr r_dying <+> ppr w_dying $$ text (show freeregs) $$ ppr assig) $ do -} return (new_instrs, []) _ -> genRaInsn block_live new_instrs id instr (nonDetEltsUFM $ liveDieRead live) (nonDetEltsUFM $ liveDieWrite live) -- See Note [Unique Determinism and code generation] raInsn _ _ _ instr = pprPanic "raInsn" (text "no match for:" <> ppr instr) -- ToDo: what can we do about -- -- R1 = x -- jump I64[x] // [R1] -- -- where x is mapped to the same reg as R1. We want to coalesce x and -- R1, but the register allocator doesn't know whether x will be -- assigned to again later, in which case x and R1 should be in -- different registers. Right now we assume the worst, and the -- assignment to R1 will clobber x, so we'll spill x into another reg, -- generating another reg->reg move. isInReg :: Reg -> RegMap Loc -> Bool isInReg src assig | Just (InReg _) <- lookupUFM assig src = True | otherwise = False genRaInsn :: (FR freeRegs, Instruction instr, Outputable instr) => BlockMap RegSet -> [instr] -> BlockId -> instr -> [Reg] -> [Reg] -> RegM freeRegs ([instr], [NatBasicBlock instr]) genRaInsn block_live new_instrs block_id instr r_dying w_dying = do dflags <- getDynFlags let platform = targetPlatform dflags case regUsageOfInstr platform instr of { RU read written -> do let real_written = [ rr | (RegReal rr) <- written ] let virt_written = [ vr | (RegVirtual vr) <- written ] -- we don't need to do anything with real registers that are -- only read by this instr. (the list is typically ~2 elements, -- so using nub isn't a problem). let virt_read = nub [ vr | (RegVirtual vr) <- read ] -- debugging {- freeregs <- getFreeRegsR assig <- getAssigR pprDebugAndThen (defaultDynFlags Settings{ sTargetPlatform=platform }) trace "genRaInsn" (ppr instr $$ text "r_dying = " <+> ppr r_dying $$ text "w_dying = " <+> ppr w_dying $$ text "virt_read = " <+> ppr virt_read $$ text "virt_written = " <+> ppr virt_written $$ text "freeregs = " <+> text (show freeregs) $$ text "assig = " <+> ppr assig) $ do -} -- (a), (b) allocate real regs for all regs read by this instruction. (r_spills, r_allocd) <- allocateRegsAndSpill True{-reading-} virt_read [] [] virt_read -- (c) save any temporaries which will be clobbered by this instruction clobber_saves <- saveClobberedTemps real_written r_dying -- (d) Update block map for new destinations -- NB. do this before removing dead regs from the assignment, because -- these dead regs might in fact be live in the jump targets (they're -- only dead in the code that follows in the current basic block). (fixup_blocks, adjusted_instr) <- joinToTargets block_live block_id instr -- (e) Delete all register assignments for temps which are read -- (only) and die here. Update the free register list. releaseRegs r_dying -- (f) Mark regs which are clobbered as unallocatable clobberRegs real_written -- (g) Allocate registers for temporaries *written* (only) (w_spills, w_allocd) <- allocateRegsAndSpill False{-writing-} virt_written [] [] virt_written -- (h) Release registers for temps which are written here and not -- used again. releaseRegs w_dying let -- (i) Patch the instruction patch_map = listToUFM [ (t, RegReal r) | (t, r) <- zip virt_read r_allocd ++ zip virt_written w_allocd ] patched_instr = patchRegsOfInstr adjusted_instr patchLookup patchLookup x = case lookupUFM patch_map x of Nothing -> x Just y -> y -- (j) free up stack slots for dead spilled regs -- TODO (can't be bothered right now) -- erase reg->reg moves where the source and destination are the same. -- If the src temp didn't die in this instr but happened to be allocated -- to the same real reg as the destination, then we can erase the move anyway. let squashed_instr = case takeRegRegMoveInstr patched_instr of Just (src, dst) | src == dst -> [] _ -> [patched_instr] let code = squashed_instr ++ w_spills ++ reverse r_spills ++ clobber_saves ++ new_instrs -- pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do -- pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do return (code, fixup_blocks) } -- ----------------------------------------------------------------------------- -- releaseRegs releaseRegs :: FR freeRegs => [Reg] -> RegM freeRegs () releaseRegs regs = do dflags <- getDynFlags let platform = targetPlatform dflags assig <- getAssigR free <- getFreeRegsR let loop assig !free [] = do setAssigR assig; setFreeRegsR free; return () loop assig !free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs loop assig !free (r:rs) = case lookupUFM assig r of Just (InBoth real _) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs Just (InReg real) -> loop (delFromUFM assig r) (frReleaseReg platform real free) rs _ -> loop (delFromUFM assig r) free rs loop assig free regs -- ----------------------------------------------------------------------------- -- Clobber real registers -- For each temp in a register that is going to be clobbered: -- - if the temp dies after this instruction, do nothing -- - otherwise, put it somewhere safe (another reg if possible, -- otherwise spill and record InBoth in the assignment). -- - for allocateRegs on the temps *read*, -- - clobbered regs are allocatable. -- -- for allocateRegs on the temps *written*, -- - clobbered regs are not allocatable. -- saveClobberedTemps :: (Instruction instr, FR freeRegs) => [RealReg] -- real registers clobbered by this instruction -> [Reg] -- registers which are no longer live after this insn -> RegM freeRegs [instr] -- return: instructions to spill any temps that will -- be clobbered. saveClobberedTemps [] _ = return [] saveClobberedTemps clobbered dying = do assig <- getAssigR let to_spill = [ (temp,reg) | (temp, InReg reg) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , any (realRegsAlias reg) clobbered , temp `notElem` map getUnique dying ] (instrs,assig') <- clobber assig [] to_spill setAssigR assig' return instrs where clobber assig instrs [] = return (instrs, assig) clobber assig instrs ((temp, reg) : rest) = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let regclass = targetClassOfRealReg platform reg freeRegs_thisClass = frGetFreeRegs platform regclass freeRegs case filter (`notElem` clobbered) freeRegs_thisClass of -- (1) we have a free reg of the right class that isn't -- clobbered by this instruction; use it to save the -- clobbered value. (my_reg : _) -> do setFreeRegsR (frAllocateReg platform my_reg freeRegs) let new_assign = addToUFM assig temp (InReg my_reg) let instr = mkRegRegMoveInstr platform (RegReal reg) (RegReal my_reg) clobber new_assign (instr : instrs) rest -- (2) no free registers: spill the value [] -> do (spill, slot) <- spillR (RegReal reg) temp -- record why this reg was spilled for profiling recordSpill (SpillClobber temp) let new_assign = addToUFM assig temp (InBoth reg slot) clobber new_assign (spill : instrs) rest -- | Mark all these real regs as allocated, -- and kick out their vreg assignments. -- clobberRegs :: FR freeRegs => [RealReg] -> RegM freeRegs () clobberRegs [] = return () clobberRegs clobbered = do dflags <- getDynFlags let platform = targetPlatform dflags freeregs <- getFreeRegsR setFreeRegsR $! foldr (frAllocateReg platform) freeregs clobbered assig <- getAssigR setAssigR $! clobber assig (nonDetUFMToList assig) -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] where -- if the temp was InReg and clobbered, then we will have -- saved it in saveClobberedTemps above. So the only case -- we have to worry about here is InBoth. Note that this -- also catches temps which were loaded up during allocation -- of read registers, not just those saved in saveClobberedTemps. clobber assig [] = assig clobber assig ((temp, InBoth reg slot) : rest) | any (realRegsAlias reg) clobbered = clobber (addToUFM assig temp (InMem slot)) rest clobber assig (_:rest) = clobber assig rest -- ----------------------------------------------------------------------------- -- allocateRegsAndSpill -- Why are we performing a spill? data SpillLoc = ReadMem StackSlot -- reading from register only in memory | WriteNew -- writing to a new variable | WriteMem -- writing to register only in memory -- Note that ReadNew is not valid, since you don't want to be reading -- from an uninitialized register. We also don't need the location of -- the register in memory, since that will be invalidated by the write. -- Technically, we could coalesce WriteNew and WriteMem into a single -- entry as well. -- EZY -- This function does several things: -- For each temporary referred to by this instruction, -- we allocate a real register (spilling another temporary if necessary). -- We load the temporary up from memory if necessary. -- We also update the register assignment in the process, and -- the list of free registers and free stack slots. allocateRegsAndSpill :: (FR freeRegs, Outputable instr, Instruction instr) => Bool -- True <=> reading (load up spilled regs) -> [VirtualReg] -- don't push these out -> [instr] -- spill insns -> [RealReg] -- real registers allocated (accum.) -> [VirtualReg] -- temps to allocate -> RegM freeRegs ( [instr] , [RealReg]) allocateRegsAndSpill _ _ spills alloc [] = return (spills, reverse alloc) allocateRegsAndSpill reading keep spills alloc (r:rs) = do assig <- getAssigR let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig case lookupUFM assig r of -- case (1a): already in a register Just (InReg my_reg) -> allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- case (1b): already in a register (and memory) -- NB1. if we're writing this register, update its assignment to be -- InReg, because the memory value is no longer valid. -- NB2. This is why we must process written registers here, even if they -- are also read by the same instruction. Just (InBoth my_reg _) -> do when (not reading) (setAssigR (addToUFM assig r (InReg my_reg))) allocateRegsAndSpill reading keep spills (my_reg:alloc) rs -- Not already in a register, so we need to find a free one... Just (InMem slot) | reading -> doSpill (ReadMem slot) | otherwise -> doSpill WriteMem Nothing | reading -> pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr r) -- NOTE: if the input to the NCG contains some -- unreachable blocks with junk code, this panic -- might be triggered. Make sure you only feed -- sensible code into the NCG. In CmmPipeline we -- call removeUnreachableBlocks at the end for this -- reason. | otherwise -> doSpill WriteNew -- reading is redundant with reason, but we keep it around because it's -- convenient and it maintains the recursive structure of the allocator. -- EZY allocRegsAndSpill_spill :: (FR freeRegs, Instruction instr, Outputable instr) => Bool -> [VirtualReg] -> [instr] -> [RealReg] -> VirtualReg -> [VirtualReg] -> UniqFM Loc -> SpillLoc -> RegM freeRegs ([instr], [RealReg]) allocRegsAndSpill_spill reading keep spills alloc r rs assig spill_loc = do dflags <- getDynFlags let platform = targetPlatform dflags freeRegs <- getFreeRegsR let freeRegs_thisClass = frGetFreeRegs platform (classOfVirtualReg r) freeRegs case freeRegs_thisClass of -- case (2): we have a free register (my_reg : _) -> do spills' <- loadTemp r spill_loc my_reg spills setAssigR (addToUFM assig r $! newLocation spill_loc my_reg) setFreeRegsR $ frAllocateReg platform my_reg freeRegs allocateRegsAndSpill reading keep spills' (my_reg : alloc) rs -- case (3): we need to push something out to free up a register [] -> do let keep' = map getUnique keep -- the vregs we could kick out that are already in a slot let candidates_inBoth = [ (temp, reg, mem) | (temp, InBoth reg mem) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , temp `notElem` keep' , targetClassOfRealReg platform reg == classOfVirtualReg r ] -- the vregs we could kick out that are only in a reg -- this would require writing the reg to a new slot before using it. let candidates_inReg = [ (temp, reg) | (temp, InReg reg) <- nonDetUFMToList assig -- This is non-deterministic but we do not -- currently support deterministic code-generation. -- See Note [Unique Determinism and code generation] , temp `notElem` keep' , targetClassOfRealReg platform reg == classOfVirtualReg r ] let result -- we have a temporary that is in both register and mem, -- just free up its register for use. | (temp, my_reg, slot) : _ <- candidates_inBoth = do spills' <- loadTemp r spill_loc my_reg spills let assig1 = addToUFM assig temp (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs -- otherwise, we need to spill a temporary that currently -- resides in a register. | (temp_to_push_out, (my_reg :: RealReg)) : _ <- candidates_inReg = do (spill_insn, slot) <- spillR (RegReal my_reg) temp_to_push_out let spill_store = (if reading then id else reverse) [ -- COMMENT (fsLit "spill alloc") spill_insn ] -- record that this temp was spilled recordSpill (SpillAlloc temp_to_push_out) -- update the register assignment let assig1 = addToUFM assig temp_to_push_out (InMem slot) let assig2 = addToUFM assig1 r $! newLocation spill_loc my_reg setAssigR assig2 -- if need be, load up a spilled temp into the reg we've just freed up. spills' <- loadTemp r spill_loc my_reg spills allocateRegsAndSpill reading keep (spill_store ++ spills') (my_reg:alloc) rs -- there wasn't anything to spill, so we're screwed. | otherwise = pprPanic ("RegAllocLinear.allocRegsAndSpill: no spill candidates\n") $ vcat [ text "allocating vreg: " <> text (show r) , text "assignment: " <> ppr assig , text "freeRegs: " <> text (show freeRegs) , text "initFreeRegs: " <> text (show (frInitFreeRegs platform `asTypeOf` freeRegs)) ] result -- | Calculate a new location after a register has been loaded. newLocation :: SpillLoc -> RealReg -> Loc -- if the tmp was read from a slot, then now its in a reg as well newLocation (ReadMem slot) my_reg = InBoth my_reg slot -- writes will always result in only the register being available newLocation _ my_reg = InReg my_reg -- | Load up a spilled temporary if we need to (read from memory). loadTemp :: (Instruction instr) => VirtualReg -- the temp being loaded -> SpillLoc -- the current location of this temp -> RealReg -- the hreg to load the temp into -> [instr] -> RegM freeRegs [instr] loadTemp vreg (ReadMem slot) hreg spills = do insn <- loadR (RegReal hreg) slot recordSpill (SpillLoad $ getUnique vreg) return $ {- COMMENT (fsLit "spill load") : -} insn : spills loadTemp _ _ _ spills = return spills
mettekou/ghc
compiler/nativeGen/RegAlloc/Linear/Main.hs
bsd-3-clause
37,769
0
25
13,350
5,734
2,935
2,799
459
13
{-# LANGUAGE EmptyDataDecls #-} -- | -- Module : Network.TLS.Record.Types -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- -- The Record Protocol takes messages to be transmitted, fragments the -- data into manageable blocks, optionally compresses the data, applies -- a MAC, encrypts, and transmits the result. Received data is -- decrypted, verified, decompressed, reassembled, and then delivered to -- higher-level clients. -- module Network.TLS.Record.Types ( Header(..) , ProtocolType(..) , packetType -- * TLS Records , Record(..) -- * TLS Record fragment and constructors , Fragment , fragmentGetBytes , fragmentPlaintext , fragmentCiphertext , Plaintext , Compressed , Ciphertext -- * manipulate record , onRecordFragment , fragmentCompress , fragmentCipher , fragmentUncipher , fragmentUncompress -- * serialize record , rawToRecord , recordToRaw , recordToHeader ) where import Network.TLS.Struct import Network.TLS.Record.State import Data.ByteString (ByteString) import qualified Data.ByteString as B import Control.Applicative ((<$>)) -- | Represent a TLS record. data Record a = Record !ProtocolType !Version !(Fragment a) deriving (Show,Eq) newtype Fragment a = Fragment { fragmentGetBytes :: ByteString } deriving (Show,Eq) data Plaintext data Compressed data Ciphertext fragmentPlaintext :: ByteString -> Fragment Plaintext fragmentPlaintext bytes = Fragment bytes fragmentCiphertext :: ByteString -> Fragment Ciphertext fragmentCiphertext bytes = Fragment bytes onRecordFragment :: Record a -> (Fragment a -> RecordM (Fragment b)) -> RecordM (Record b) onRecordFragment (Record pt ver frag) f = Record pt ver <$> f frag fragmentMap :: (ByteString -> RecordM ByteString) -> Fragment a -> RecordM (Fragment b) fragmentMap f (Fragment b) = Fragment <$> f b -- | turn a plaintext record into a compressed record using the compression function supplied fragmentCompress :: (ByteString -> RecordM ByteString) -> Fragment Plaintext -> RecordM (Fragment Compressed) fragmentCompress f = fragmentMap f -- | turn a compressed record into a ciphertext record using the cipher function supplied fragmentCipher :: (ByteString -> RecordM ByteString) -> Fragment Compressed -> RecordM (Fragment Ciphertext) fragmentCipher f = fragmentMap f -- | turn a ciphertext fragment into a compressed fragment using the cipher function supplied fragmentUncipher :: (ByteString -> RecordM ByteString) -> Fragment Ciphertext -> RecordM (Fragment Compressed) fragmentUncipher f = fragmentMap f -- | turn a compressed fragment into a plaintext fragment using the decompression function supplied fragmentUncompress :: (ByteString -> RecordM ByteString) -> Fragment Compressed -> RecordM (Fragment Plaintext) fragmentUncompress f = fragmentMap f -- | turn a record into an header and bytes recordToRaw :: Record a -> (Header, ByteString) recordToRaw (Record pt ver (Fragment bytes)) = (Header pt ver (fromIntegral $ B.length bytes), bytes) -- | turn a header and a fragment into a record rawToRecord :: Header -> Fragment a -> Record a rawToRecord (Header pt ver _) fragment = Record pt ver fragment -- | turn a record into a header recordToHeader :: Record a -> Header recordToHeader (Record pt ver (Fragment bytes)) = Header pt ver (fromIntegral $ B.length bytes)
erikd/hs-tls
core/Network/TLS/Record/Types.hs
bsd-3-clause
3,458
0
11
604
748
406
342
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE Rank2Types #-} -- -- Peripheral.hs --- Advanced Timer (TIM1 to TIM8) Peripheral driver. -- Defines peripheral types, instances. -- -- Copyright (C) 2014, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32.Peripheral.ATIM18.Peripheral where import Ivory.Language import Ivory.HW import Ivory.BSP.STM32.Peripheral.ATIM18.Regs -- Convenience type synonyms data ATIM = ATIM { atimRegCR1 :: BitDataReg ATIM_CR1 , atimRegCR2 :: BitDataReg ATIM_CR2 , atimRegSMCR :: BitDataReg ATIM_SMCR , atimRegDIER :: BitDataReg ATIM_DIER , atimRegSR :: BitDataReg ATIM_SR , atimRegEGR :: BitDataReg ATIM_EGR , atimRegCCMR1_OCM :: BitDataReg ATIM_CCMR1_OCM , atimRegCCMR1_ICM :: BitDataReg ATIM_CCMR1_ICM , atimRegCCMR2_OCM :: BitDataReg ATIM_CCMR2_OCM , atimRegCCMR2_ICM :: BitDataReg ATIM_CCMR2_ICM , atimRegCCER :: BitDataReg ATIM_CCER , atimRegCNT :: BitDataReg ATIM_16 , atimRegPSC :: BitDataReg ATIM_PSC , atimRegARR :: BitDataReg ATIM_16 , atimRegCCR1 :: BitDataReg ATIM_16 , atimRegCCR2 :: BitDataReg ATIM_16 , atimRegCCR3 :: BitDataReg ATIM_16 , atimRegCCR4 :: BitDataReg ATIM_16 , atimRegBDTR :: BitDataReg ATIM_BDTR , atimRCCEnable :: forall eff . Ivory eff () , atimRCCDisable :: forall eff . Ivory eff () } -- | Create an ATIM given the base register address. mkATIM :: Integer -> (forall eff . Ivory eff ()) -> (forall eff . Ivory eff ()) -> String -> ATIM mkATIM base rccen rccdis n = ATIM { atimRegCR1 = reg 0x00 "cr1" , atimRegCR2 = reg 0x04 "cr2" , atimRegSMCR = reg 0x08 "smcr" , atimRegDIER = reg 0x0C "dier" , atimRegSR = reg 0x10 "sr" , atimRegEGR = reg 0x14 "egr" , atimRegCCMR1_OCM = reg 0x18 "ccmr1_ocm" -- aliased with icm , atimRegCCMR1_ICM = reg 0x18 "ccmr1_icm" , atimRegCCMR2_OCM = reg 0x1C "ccmr2_ocm" -- aliased with icm , atimRegCCMR2_ICM = reg 0x1C "ccmr2_icm" , atimRegCCER = reg 0x20 "ccer" , atimRegCNT = reg 0x24 "cnt" , atimRegPSC = reg 0x28 "psc" , atimRegARR = reg 0x2C "arr" , atimRegCCR1 = reg 0x34 "ccr1" , atimRegCCR2 = reg 0x38 "ccr2" , atimRegCCR3 = reg 0x3C "ccr3" , atimRegCCR4 = reg 0x40 "ccr4" , atimRegBDTR = reg 0x44 "bdtr" , atimRCCEnable = rccen , atimRCCDisable = rccdis } where reg :: (IvoryIOReg (BitDataRep d)) => Integer -> String -> BitDataReg d reg offs name = mkBitDataRegNamed (base + offs) (n ++ "->" ++ name)
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/ATIM18/Peripheral.hs
bsd-3-clause
2,833
0
11
826
614
347
267
60
1
module HW10Test (hw10Tests) where import Test.Tasty import Test.Tasty.Hspec import Control.Applicative import HW10.AParser hw10Tests :: IO TestTree hw10Tests = do hspecSuite <- testSpec "HW10" hspecTests return $ testGroup "tests" [hspecSuite] data T = T Integer Char deriving (Show, Eq) hspecTests :: SpecWith () hspecTests = describe "Parser" $ do describe "Functor instance" $ it "applies function in a parser context" $ shouldBe (runParser (fmap (+1) posInt) "1") (Just (2, "")) describe "Applicative instance" $ it "Works?" $ do shouldBe (runParser (T <$> posInt <*> char 'a') "1a") (Just (T 1 'a', "")) describe "abParser" $ it "returns (Just (('a','b'), \"cdef\")" $ shouldBe (runParser abParser "abcdef") (Just (('a','b'), "cdef")) describe "abParser_" $ it "returns Just ((), \"cdef\")" $ shouldBe (runParser abParser_ "abcdef") (Just ((), "cdef")) describe "intPair" $ it "parses 2 space-separated ints into a list" $ shouldBe (runParser intPair "12 34") (Just ([12,34], "")) describe "intOrUppercase" $ it "consumes ints or uppercase chars" $ do shouldBe (runParser intOrUppercase "234abcd") (Just ((), "abcd")) shouldBe (runParser intOrUppercase "XYZ") (Just ((), "YZ")) shouldBe (runParser intOrUppercase "foo") Nothing
cgag/cis-194-solutions
test/HW10Test.hs
bsd-3-clause
1,511
0
16
451
465
231
234
42
1
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} -- | -- Module : NXT.Types -- Copyright : Alexander Thiemann <[email protected]> -- License : BSD3 -- -- Maintainer : Alexander Thiemann <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module NXT.Types where import Data.Typeable import Data.List (intercalate) import GHC.Generics import Data.Hashable import Control.Monad.RWS (RWST) type FunM = RWST String [Stmt] Int TopM type TopM = RWST () [FunDefinition] Int IO data Definition = PFun FunDefinition | PConst ConstDefinition | PLib LibCallDefinition deriving (Show) data FunDefinition = FunDefinition { fd_name :: String , fd_type :: String , fd_args :: [Stmt] , fd_body :: [Stmt] } deriving (Show) data ConstDefinition = ConstDefinition { cd_name :: String , cd_value :: T } deriving (Show) data LibCallDefinition = LibCallDefinition { lcd_name :: String , lcd_libType :: NXTType , lcd_libArgs :: [NXTType] } deriving (Show) data Stmt = If T [Stmt] [Stmt] | While T [Stmt] | DeclVar String T | AssignVar T T | Eval T | FunReturn T deriving Show data BinOpT = BAdd | BSub | BMul | BDiv | BEq | BNEq | BLt | BSt | BLEq | BSEq | BAnd | BOr deriving (Show, Eq, Typeable, Enum, Generic) instance Hashable BinOpT data T = Void | FunP String | VarP String | Lit Int | Rat Float | StrLit String | BoolLit Bool | BinOp BinOpT T T | CastOp String T | FunCall String [T] deriving (Typeable, Show) -- | wrapper for types data V a = V T deriving (Typeable) pack :: (Typeable a) => T -> V a pack = V unpack :: V a -> T unpack (V a) = a prettyOp :: BinOpT -> String prettyOp BAdd = "+" prettyOp BSub = "-" prettyOp BMul = "*" prettyOp BDiv = "/" prettyOp BEq = "==" prettyOp BLt = ">" prettyOp BSt = "<" prettyOp BLEq = ">=" prettyOp BSEq = "<=" prettyOp BNEq = "!=" prettyOp BOr = "||" prettyOp BAnd = "&&" prettyV :: V a -> String prettyV = prettyT . unpack prettyT :: T -> String prettyT (Void) = ""; prettyT (VarP p) = p prettyT (FunP f) = f prettyT (Lit i) = show i prettyT (Rat i) = show i prettyT (StrLit str) = show str prettyT (BoolLit True) = "true" prettyT (BoolLit False) = "false" prettyT (CastOp target val) = "(" ++ target ++ "(" ++ (prettyT val) ++ "))" prettyT (BinOp op x y) = "(" ++ (prettyT x) ++ (prettyOp op) ++ (prettyT y) ++ ")" prettyT (FunCall name args) = name ++ "(" ++ (intercalate ", " $ map prettyT args) ++ ")" prettyFD :: FunDefinition -> String prettyFD = prettyFD' True prettyFD' :: Bool -> FunDefinition -> String prettyFD' withBody (FunDefinition name ty args body) = ty ++ " " ++ name ++ "(" ++ arglist ++ ")" ++ bodyStr where bodyStr = if withBody then " { " ++ (concatMap prettyStmt body) ++ " }" else ";" arglist = intercalate ", " $ map (\(DeclVar ty arg) -> (ty ++ " " ++ (prettyT arg))) args prettyStmt :: Stmt -> String prettyStmt (If cond t f) = "if (" ++ (prettyT cond) ++ ") {" ++ (concatMap prettyStmt t) ++ "}" ++ (case f of [] -> "" _ -> " else { " ++ (concatMap prettyStmt f) ++ "}" ) prettyStmt (While cond loop) = "while (" ++ (prettyT cond) ++ ") {" ++ (concatMap prettyStmt loop) ++ "}" prettyStmt (DeclVar ty var@(VarP name)) = ty ++ " " ++ (prettyT var) ++ ";" prettyStmt (AssignVar v@(VarP pointer) val) = (prettyT v) ++ " = " ++ (prettyT val) ++ ";" prettyStmt (Eval something) = (prettyT something) ++ ";" prettyStmt (FunReturn val) = "return " ++ prettyT val ++ ";" prettyStmt _ = error "Error: Invalid syntax tree" data NXTType = NXTString | NXTBool | NXTInt | NXTFloat | NXTVoid deriving (Show, Eq, Enum) toCName :: NXTType -> String toCName NXTString = "string" toCName NXTBool = "bool" toCName NXTInt = "int" toCName NXTFloat = "float" toCName NXTVoid = "void"
agrafix/legoDSL
NXT/Types.hs
bsd-3-clause
3,964
0
14
976
1,420
766
654
131
2
{-# LANGUAGE ExistentialQuantification #-} {- | Module : Verifier.SAW.Cache Copyright : Galois, Inc. 2012-2015 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (language extensions) -} module Verifier.SAW.Cache ( Cache , newCache , newCacheMap , newCacheMap' , newCacheIntMap , newCacheIntMap' , useCache ) where import Control.Monad (liftM) import Control.Monad.Ref import qualified Data.IntMap as IntMap import qualified Data.Map as Map import Prelude hiding (lookup) data Cache r k a = forall t. Cache (r t) (k -> t -> Maybe a) (k -> a -> t -> t) useCache :: MonadRef r m => Cache r k a -> k -> m a -> m a useCache (Cache ref lookup update) k action = do result <- liftM (lookup k) (readRef ref) case result of Just x -> return x Nothing -> do x <- action modifyRef ref (update k x) return x newCache :: (MonadRef r m, Ord k) => m (Cache r k a) newCache = newCacheMap newCacheMap :: (MonadRef r m, Ord k) => m (Cache r k a) newCacheMap = newCacheMap' Map.empty newCacheMap' :: (MonadRef r m, Ord k) => Map.Map k a -> m (Cache r k a) newCacheMap' initialMap = do ref <- newRef initialMap return (Cache ref Map.lookup Map.insert) newCacheIntMap :: (MonadRef r m) => m (Cache r Int a) newCacheIntMap = newCacheIntMap' IntMap.empty newCacheIntMap' :: (MonadRef r m) => IntMap.IntMap a -> m (Cache r Int a) newCacheIntMap' initialMap = do ref <- newRef initialMap return (Cache ref IntMap.lookup IntMap.insert)
iblumenfeld/saw-core
src/Verifier/SAW/Cache.hs
bsd-3-clause
1,539
0
14
329
552
284
268
38
2
module SNEK.Data ( Data , Datum(..) ) where import Data.Map (Map) type Data = [Datum] data Datum = Symbol String | Bool Bool | String String | List [Datum] | Array [Datum] | Dict (Map Datum Datum) deriving (Eq, Ord, Show)
rightfold/snek
src/SNEK/Data.hs
bsd-3-clause
239
0
8
58
100
60
40
13
0
module DyNet.IO ( -- * Types TextFileSaver, TextFileLoader, -- * Initialize saver / loader createSaver, createSaver', createLoader, -- * Operations on saver saveModel, saveParameter, saveLookupParameter, saveModel', saveParameter', saveLookupParameter', -- * Operations on loader populateModel, populateParameter, populateLookupParameter, populateModel', populateParameter', populateLookupParameter', loadParam, loadLookupParam ) where import DyNet.Internal.IO {-| @ createSaver' f = createSaver f False @ -} createSaver' f = createSaver f False {-| @ saveModel' s m = saveModel s m "" @ -} saveModel' s m = saveModel s m "" {-| @ saveParameter' s m = saveParameter s m "" @ -} saveParameter' s m = saveParameter s m "" {-| @ saveLookupParameter' s m = saveLookupParameter s m "" @ -} saveLookupParameter' s m = saveLookupParameter s m "" {-| @ populateModel' s m = populateModel s m "" @ -} populateModel' s m = populateModel s m "" {-| @ populateParameter' s m = populateParameter s m "" @ -} populateParameter' s m = populateParameter s m "" {-| @ populateLookupParameter' s m = populateLookupParameter s m "" @ -} populateLookupParameter' s m = populateLookupParameter s m ""
masashi-y/dynet.hs
src/DyNet/IO.hs
bsd-3-clause
1,319
0
5
320
197
112
85
28
1
module VerificadorCuitCuil where verificarCuil :: Int -> Bool verificarCuil = verificarCuit verificarCuit :: Int -> Bool verificarCuit n | n <= 20000000000 || n > 99999999999 = False | otherwise = digVerif == if calcVerif == 11 then 0 else calcVerif where digVerif = n `mod` 10 x = listaDigitos $ n `div` 10 y = sum $ zipWith (*) x l calcVerif = 11 - y `mod` 11 l = [5,4,3,2,7,6,5,4,3,2] listaDigitos :: Int -> [Int] listaDigitos n | n == 0 = [] | otherwise = listaDigitos (n `div` 10) ++ [n `mod` 10]
jotix/verificadorCuitCuil
src/VerificadorCuitCuil.hs
bsd-3-clause
565
0
10
159
240
135
105
16
2
{-# OPTIONS_GHC -fno-warn-tabs #-} module Padding ( pkcs7Pad , pkcs7Unpad ) where import Common import qualified Data.Vector.Generic as V import Data.Word pkcs7Pad :: Word8 -> ByteVector -> ByteVector pkcs7Pad blockSize bytes | blockSize == 0 = error "block size must be larger than 0" | otherwise = bytes V.++ V.replicate (fromIntegral padding) padding where padding = blockSize - fromIntegral (V.length bytes) `rem` blockSize pkcs7Unpad :: ByteVector -> Maybe ByteVector pkcs7Unpad bytes = if paddingCorrect then Just $ dropFromTail padCount bytes else Nothing where paddingCorrect = padCount > 0 && expPadding == actPadding expPadding = V.replicate padCount $ fromIntegral padCount actPadding = takeFromTail padCount bytes padCount = fromIntegral $ V.last bytes takeFromTail len bytes = V.drop (V.length bytes - len) bytes dropFromTail len bytes = V.take (V.length bytes - len) bytes
andrewcchen/matasano-cryptopals-solutions
modules/Padding.hs
bsd-3-clause
940
0
12
183
277
143
134
21
2
{-# LANGUAGE RankNTypes, GeneralizedNewtypeDeriving, ExistentialQuantification #-} ------------------------------------------------------------------------------ -- File: Haikubot.hs -- Creation Date: Dec 29 2012 [20:19:14] -- Last Modified: Oct 08 2013 [20:44:40] -- Created By: Samuli Thomasson [SimSaladin] samuli.thomassonAtpaivola.fi ------------------------------------------------------------------------------ module Haikubot.Core ( -- * Data Types Config(..) , BotData(..) , ActionData(..) -- ** Connection types , Con(..) , ConId , Connections -- ** Plugin types , HaikuPlugin(..) , PluginAction, PluginResult , Plugin(..) , Plugins -- ** Event results , Res , noop, stop -- * The Monads , Handler , Action , runHandler , runHandler' , runAction -- * Helpers -- ** Handler helpers , getBotData , getConfig -- ** Action helpers , lift , liftHandler , liftIO , getActionData -- , putActionData -- , modifyActionData , getActionCon , getActionMessage , getActionCon' , getActionMessage' ) where import Haikubot.Messages import Data.Text (Text) import qualified Data.Map as Map import Control.Applicative import Control.Monad import Control.Concurrent.MVar import Control.Concurrent.STM import Network (PortID) import System.IO (Handle) import Control.Monad.Error hiding (lift) import Control.Monad.Reader hiding (lift) -- | Settings for Haikubot. data Config = Config { cRootPrefix :: Text -- ^ Prefix to use for root (admin) commands. , cPlugins :: Plugins -- ^ Plugins to use. } -- | Internal data shared by threads. data BotData = BotData { botConfig :: TVar Config , botConnections :: TVar Connections , botInternalChannel :: MVar Text -- ^ Communication channel to the main thread; see @Main.monitor@. } -- | Additional data available n plugins' functions. data ActionData p = ActionData { actionPersist :: p , actionCon :: Maybe Con , actionMessage :: Maybe IrcMessage } -- | A connection to a server. data Con = Con { conSocket :: Handle , conServer :: String , conPort :: PortID , conNick :: Text } -- | Connections are identified by ConIds (Texts). type ConId = Text -- | Connections used by the bot. type Connections = Map.Map ConId Con -- | Results from plugin handlers. On Nothing, continue in event stack, -- otherwise stop. Left values are errors. type Res = Maybe () noop, stop :: Action p Res noop = return Nothing stop = return (Just ()) type PluginAction = forall p. HaikuPlugin p => Action p Res type PluginResult = Either String Res -- | Plugin interface. class HaikuPlugin p where -- | Handle a root command either from command line or from authorized user. handleCmd :: (Text, [Text]) -> Action p Res handleCmd _ = fail "No action" -- | Handle a privmsg. handleIrcMessage :: IrcMessage -> Action p Res handleIrcMessage _ = noop -- | Action to run before haikubot exit. onExit :: Action p () onExit = return () data Plugin = forall a. HaikuPlugin a => MkPlugin a type Plugins = Map.Map Text Plugin -- | Handler monad. newtype Handler a = Handler { runH :: ReaderT BotData IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadReader BotData) -- | The action monad is provided to simplify plugin writing. It's a MaybeT over -- a ReaderT. newtype Action p a = Action { runA :: ErrorT String (ReaderT (ActionData p) Handler) a } deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadPlus, MonadReader (ActionData p), MonadError String) -- | Run a handler with empty connections. runHandler :: Handler a -> Config -> IO a runHandler handler conf = do cons <- atomically $ newTVar Map.empty conf' <- atomically $ newTVar conf chan <- newEmptyMVar runHandler' handler $ BotData conf' cons chan runHandler' :: Handler a -> BotData -> IO a runHandler' handler = runReaderT (runH handler) runAction :: Action p a -> ActionData p -> Handler (Either String a) runAction action = runReaderT (runErrorT (runA action)) -- runAction' action = runAction action $ ActionData () Nothing Nothing getBotData :: Handler BotData getBotData = ask getConfig :: Handler Config getConfig = liftM botConfig ask >>= liftIO . readTVarIO getActionData :: Action plugdata plugdata getActionData = liftM actionPersist ask -- putActionData :: p -> Action p () -- modifyActionData :: (p -> p) -> Action p () -- putActionData x = modify (\y -> y{actionPersist = x}) -- modifyActionData f = modify (\p@ActionData{actionPersist = x} -> p{actionPersist = f x}) getActionCon' :: Action p (Maybe Con) getActionCon' = liftM actionCon ask getActionCon :: Action p Con getActionCon = getActionCon' >>= \x -> case x of Nothing -> fail "No connection available." Just con -> return con getActionMessage' :: Action p (Maybe IrcMessage) getActionMessage' = liftM actionMessage ask getActionMessage :: Action p IrcMessage getActionMessage = getActionMessage' >>= \x -> case x of Nothing -> fail "No message." Just msg -> return msg -- | TODO: somehow use MonadTrans or something? lift :: Handler (Maybe a) -> Action p a lift handler = Action $ ErrorT $ ReaderT (\_ -> fmap (maybe (Left "") Right) handler) liftHandler :: Handler a -> Action p a liftHandler handler = lift (Just <$> handler)
SimSaladin/haikubot
Haikubot/Core.hs
bsd-3-clause
5,533
0
13
1,247
1,207
674
533
110
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Strict #-} module Validate ( validateBatchOpts , Types.BatchOpts , ValidationResult (..) , nThreads , nLoops , propName , propValue , propValRes ) where import ClassyPrelude import Text.XML.HXT.Core import Control.Monad.State import Types data ValidationResult = ValidationResult { valMsgs :: [(RunName, String)] , valErrors :: Bool } deriving Show instance Monoid ValidationResult where mempty = ValidationResult mempty False (ValidationResult msgA errA) `mappend` (ValidationResult msgB errB) = ValidationResult (msgA <> msgB) (errA || errB) data ThreadGroup = ThreadGroup { nThreads :: String , nLoops :: String } deriving Show data Validation = Validation { propName :: String , propValue :: String , propValRes :: Bool } showValidation :: Validation -> String showValidation (Validation pn pv pvr) = pn <> ": " <> pv <> "\t" <> show pvr newtype Validations = Validations [Validation] newtype AggFilename = AggFilename String deriving Show instance Monoid Validations where mempty = Validations mempty (Validations l1) `mappend` (Validations l2) = Validations (l1 `mappend` l2) instance Semigroup Validations showValidations :: Validations -> String showValidations (Validations l) = str <> "\n" where str = intercalate "\n" $ fmap showValidation l getThreadGroup :: ArrowXml a => a XmlTree ThreadGroup getThreadGroup = proc input -> do tg <- hasName "ThreadGroup" -< input loops <- deep (hasAttrValue "name" (isSuffixOf ".loops")) /> getText -< tg threads <- getChildren >>> hasAttrValue "name" (isSuffixOf ".num_threads") /> getText -< tg returnA -< ThreadGroup threads loops threadGroupGold :: ThreadGroup threadGroupGold = ThreadGroup "${users}" "${loopCount}" checkThreadGroup :: Arrow a => a ThreadGroup Validations checkThreadGroup = arr (checkThreadGroup_ threadGroupGold) checkThreadGroup_ :: ThreadGroup -> ThreadGroup -> Validations checkThreadGroup_ (ThreadGroup threadsA loopsA) (ThreadGroup threadsB loopsB) = Validations [ Validation "threadgroup.threads" threadsB (threadsA == threadsB) , Validation "threadgroup.loops" loopsB (loopsA == loopsB) ] getAggFilename :: ArrowXml a => a XmlTree AggFilename getAggFilename = hasName "ResultCollector" /> hasAttrValue "name" (=="filename") /> getText >>> arr AggFilename filenameGold :: AggFilename filenameGold = AggFilename "${outputFile}" checkAggFilename :: Arrow a => a AggFilename Validations checkAggFilename = arr (checkAggFilename_ filenameGold) checkAggFilename_ :: AggFilename -> AggFilename -> Validations checkAggFilename_ (AggFilename a) (AggFilename b) = Validations [ Validation "aggregateReport.outputFile" b (a == b)] checkProperties :: Arrow a => a (ThreadGroup, AggFilename) Validations checkProperties = checkThreadGroup *** checkAggFilename >>> arr combine where combine (a, b) = a <> b getProperties :: ArrowXml a => a XmlTree (ThreadGroup, AggFilename) getProperties = deep getThreadGroup &&& deep getAggFilename checkScript :: MonadIO m => FilePath -> m String checkScript fp = liftIO $ do ctnt <- unpack <$> readFileUtf8 fp r <- runX $ readString [withValidate no, withWarnings no] ctnt >>> getProperties >>> checkProperties return $ foldl' (<>) mempty $ fmap showValidations r validateBatchOpts :: (MonadThrow m, MonadState ValidationResult m, MonadIO m) => BatchOpts UnValidated -> m (BatchOpts Validated) validateBatchOpts (BatchOpts opts) = do res <- runKleisli (checkBatchOpts >>> checkScripts) opts return $ BatchOpts res checkScripts :: (MonadState ValidationResult m, MonadIO m) => Kleisli m [JMeterOpts] [JMeterOpts] checkScripts = (arr (fmap getIt) >>> Kleisli (mapM checkScript') >>> mkValidation >>> Kleisli addCheck) &&& id >>> arr snd where getIt opt = (opt ^. runName, opt ^. jmxPath) checkScript' (rn, fp) = do res <- checkScript fp return (rn, res) mkValidation = arr $ \v -> ValidationResult v False checkBatchOpts :: (MonadState ValidationResult m, MonadThrow m) => Kleisli m [JMeterOpts] [JMeterOpts] checkBatchOpts = Kleisli checkIt where checkRunNames = all (==1) . countRunNames countRunNames opts = foldl' insertName (mempty :: Map RunName Int) opts insertName mp v = alterMap countName (v ^. runName) mp countName Nothing = Just 1 countName (Just n) = Just (n + 1) checkIt opts = case checkRunNames opts of True -> return $ opts False -> throwM $ InvalidBatchOpts "Each test should have a unique name." addCheck :: MonadState ValidationResult m => ValidationResult -> m () addCheck new = do old <- get put (old `mappend` new) -- checkDomains :: ArrowXml a => a XmlTree (Bool, String) -- checkDomains = hasAttrValue "name" (=="HTTPSampler.domain") /> getText >>> arr checkDomain &&& id -- where -- checkDomain d = d == "portal-preprod.usac.org" || d == "${appianHost}" -- checkReferer :: ArrowXml a => a XmlTree (Bool, String) -- checkReferer = hasAttrValue "name" (=="Referer") -- /> hasAttrValue "name" (=="Header.value") -- /> getText -- >>> arr checkDomain &&& id -- where -- checkDomain d = isInfixOf "${appianHost}" d || isInfixOf "portal-preprod.usac.org" d -- checkOrigin :: ArrowXml a => a XmlTree (Bool, String) -- checkOrigin = hasAttrValue "name" (=="Origin") -- /> hasAttrValue "name" (=="Header.value") -- /> getText -- >>> arr (isInfixOf "${appianHost}") &&& id -- where -- checkDomain d = isInfixOf "${appianHost}" d || isInfixOf "portal-preprod.usac.org" d -- checkHost :: ArrowXml a => a XmlTree (Bool, [String]) -- checkHost = deep (checkDomains `orElse` checkReferer `orElse` checkOrigin) >. foldl' red (True, mempty) -- where -- red (aBool, aVal) (bBool, bVal) -- | bBool = (aBool, aVal) -- | otherwise = (bBool, aVal <> pure bVal)
limaner2002/EPC-tools
src/Validate.hs
bsd-3-clause
5,992
1
15
1,076
1,487
780
707
106
3
module Main where import Control.Monad import Text.Printf import System.Environment import System.Exit import Graphics.FDL.Parser import Graphics.FDL.Typer import Graphics.FDL.Backend.GL main :: IO () main = do args <- getArgs (checkMode, sourceFile) <- case args of ["--check", sf] -> return (True, sf) [sf] -> return (False, sf) _ -> putStrLn "Usage: draw [--check] picture.fdl" >> exitFailure source <- readFile sourceFile let (ast, parserErrors) = parseProg source typerResult = typeProg ast when (not $ null parserErrors) $ showParserErrors source parserErrors >> exitFailure case typerResult of TyperErrors es -> showTyperErrors source es >> exitFailure TyperSuccess p -> if checkMode then putStrLn "All good." else compile p >>= run showParserErrors :: String -> [Error Pos] -> IO () showParserErrors src es = mapM_ (showParserError src) es showParserError :: String -> Error Pos -> IO () showParserError src (Inserted text pos _) = showError src "Parse" ("Something seems to be missing, perhaps " ++ text) pos showParserError src (Deleted text pos _) = showError src "Parse" ("Unexpected charater " ++ text) pos showParserError _ (DeletedAtEnd text) = do putStrLn "Unexpected text at the end of the file:" putStrLn text putStrLn "" showTyperErrors :: String -> [TyperError] -> IO () showTyperErrors src es = mapM_ (showTyperError src) es showTyperError :: String -> TyperError -> IO () showTyperError src (TyperError text pos) = showError src "Typer" text pos showError :: String -> String -> String -> Pos -> IO () showError src error msg pos = do putStrLn $ error ++ " error at " ++ showPos pos putStrLn $ msg putStrLn $ lines src !! (posLine pos - 1) putStrLn $ replicate (posCol pos - 1) ' ' ++ "^" putStrLn $ "" showPos :: Pos -> String showPos (Pos _ line col) = printf "line %d column %d" line col
petermarks/FDL
src/Draw.hs
bsd-3-clause
1,973
0
12
453
667
329
338
48
5
module Ex6 where import Prelude hiding (foldr) import Data.Vector partitionAt :: (Show a, Ord a) => Vector a -> Int -> (Vector a, a, Vector a) partitionAt v pivot = let pv = v !? pivot vSplit = remove pivot v part = foldList pv (remove pivot v) in part foldList :: (Show a, Ord a) => Maybe a -> Vector a -> (Vector a, a, Vector a) foldList Nothing l = undefined foldList (Just pv) l = let lists = foldr (\x y -> case (x >= pv) of True -> (fst y, (cons x (snd y))) False -> ((cons x (fst y)), snd y) ) (Data.Vector.empty, Data.Vector.empty) l in ((fst lists), pv, (snd lists)) remove i v = let (l, r) = (Data.Vector.splitAt i v) in l Data.Vector.++ (Data.Vector.tail r)
bobbyrauchenberg/haskellCourse
src/Ex6.hs
bsd-3-clause
1,026
0
19
489
377
199
178
18
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} module ETCS.SDM.SpecialBreaks ( RegenerativeBreak, EddyCurrentBreak, MagneticShoeBreak, EpBreak , SpecialBreakType (..) , SpecialBreakConfiguration (..) , SpecialBreak, _SpecialBreak , sbIsServiceBreak, sbIsEmergencyBreak , SpecialBreakModel, _SpecialBreakModel , sbmRegenerativeBreak, sbmEddyCurrentBreak , sbmMagneticShoeBreak, sbmEpBreak , ActiveBreaks , abRegenerativeBreak, abEddyCurrentBreak , abMagneticShoeBreak, abEpBreak , activeEmergencyBreaks , activeServiceBreaks ) where import Control.Lens import Data.Set (Set) import qualified Data.Set as Set data RegenerativeBreak data EddyCurrentBreak data MagneticShoeBreak data EpBreak -- | the different types of 'SpecialBreak' data SpecialBreakType t where RegenerativeBreak :: SpecialBreakType RegenerativeBreak EddyCurrentBreak :: SpecialBreakType EddyCurrentBreak MagneticShoeBreak :: SpecialBreakType MagneticShoeBreak EpBreak :: SpecialBreakType EpBreak -- | Defines on which kind of breaking a 'SpecialBreak' is active data SpecialBreakConfiguration = AffectsEmergencyBreakOnly | AffectsServiceBreakOnly | AffectsBothBreaks deriving (Show, Read, Eq, Ord) -- | represents the configuration of a 'SpecialBreak' data SpecialBreak t = SpecialBreak { _sbType :: SpecialBreakType t, _sbInterface :: Maybe SpecialBreakConfiguration } -- | the model of a the special break configuration data SpecialBreakModel = SpecialBreakModel { _sbmRegenerativeBreak :: SpecialBreak RegenerativeBreak, _sbmEddyCurrentBreak :: SpecialBreak EddyCurrentBreak, _sbmMagneticShoeBreak :: SpecialBreak MagneticShoeBreak, _sbmEpBreak :: SpecialBreak EpBreak } deriving (Show, Eq) data ActiveBreaks = ActiveBreaks { _abRegenerativeBreak :: Bool, _abEddyCurrentBreak :: Bool, _abMagneticShoeBreak :: Bool, _abEpBreak :: Bool } deriving (Eq, Ord, Show) deriving instance Eq (SpecialBreakType t) deriving instance Ord (SpecialBreakType t) deriving instance Eq (SpecialBreak t) deriving instance Ord (SpecialBreak t) deriving instance Show (SpecialBreak t) deriving instance Show (SpecialBreakType t) makePrisms ''SpecialBreakType makePrisms ''SpecialBreakConfiguration makeLenses ''SpecialBreak makeLenses ''SpecialBreakModel makePrisms ''SpecialBreakModel makeLenses ''ActiveBreaks activeEmergencyBreaks, activeServiceBreaks :: SpecialBreakModel -> ActiveBreaks activeEmergencyBreaks = activeBreaksOn AffectsEmergencyBreakOnly activeServiceBreaks = activeBreaksOn AffectsServiceBreakOnly activeBreaksOn :: SpecialBreakConfiguration -> SpecialBreakModel -> ActiveBreaks activeBreaksOn p m = ActiveBreaks (specialBreakAffected p sbmRegenerativeBreak m) (specialBreakAffected p sbmEddyCurrentBreak m) (specialBreakAffected p sbmMagneticShoeBreak m) (specialBreakAffected p sbmEpBreak m) specialBreakAffected :: SpecialBreakConfiguration -> Lens' SpecialBreakModel (SpecialBreak t) -> SpecialBreakModel -> Bool specialBreakAffected p l a = maybe False (\c -> c == AffectsBothBreaks || c == p) $ a ^. l . sbInterface _SpecialBreak :: Prism' (SpecialBreakType t, Maybe SpecialBreakConfiguration) (SpecialBreak t) _SpecialBreak = prism' fromSpecialBreak toSpecialBreak where fromSpecialBreak sb = (sb ^. sbType, sb ^. sbInterface) toSpecialBreak (t, i) = let sb = SpecialBreak t i in if validSpecialBreakConfiguration sb then Just sb else Nothing validSpecialBreakConfiguration :: SpecialBreak t -> Bool validSpecialBreakConfiguration sb = case sb ^. sbInterface of Nothing -> True Just bc -> Set.member bc . validBreakConfigurations $ sb ^. sbType where validBreakConfigurations :: SpecialBreakType t -> Set SpecialBreakConfiguration validBreakConfigurations RegenerativeBreak = Set.fromList [ AffectsEmergencyBreakOnly, AffectsServiceBreakOnly , AffectsBothBreaks ] validBreakConfigurations EddyCurrentBreak = Set.fromList [ AffectsEmergencyBreakOnly, AffectsServiceBreakOnly , AffectsBothBreaks ] validBreakConfigurations MagneticShoeBreak = Set.fromList [ AffectsEmergencyBreakOnly ] validBreakConfigurations EpBreak = Set.fromList [ AffectsServiceBreakOnly, AffectsBothBreaks ] sbIsServiceBreak :: SpecialBreak t -> Bool sbIsServiceBreak b = let i = (b ^. sbInterface) in (i == Just AffectsServiceBreakOnly) || (i == Just AffectsBothBreaks) sbIsEmergencyBreak :: SpecialBreak t -> Bool sbIsEmergencyBreak b = let i = (b ^. sbInterface) in (i == Just AffectsEmergencyBreakOnly) || (i == Just AffectsBothBreaks)
open-etcs/openetcs-sdm
src/ETCS/SDM/SpecialBreaks.hs
bsd-3-clause
4,991
0
13
992
1,025
549
476
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} -- | Shared types for various stackage packages. module Stack.Types.BuildPlan ( -- * Types BuildPlan (..) , PackagePlan (..) , PackageConstraints (..) , TestState (..) , SystemInfo (..) , Maintainer (..) , ExeName (..) , SimpleDesc (..) , DepInfo (..) , Component (..) , SnapName (..) , MiniBuildPlan (..) , MiniPackageInfo (..) , renderSnapName , parseSnapName ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception (Exception) import Control.Monad.Catch (MonadThrow, throwM) import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, withText, (.!=), (.:), (.:?), (.=)) import Data.Binary as Binary (Binary) import Data.Binary.VersionTagged (BinarySchema (..)) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Hashable (Hashable) import qualified Data.HashMap.Strict as HashMap import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Monoid import Data.Set (Set) import Data.String (IsString, fromString) import Data.Text (Text, pack, unpack) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Text.Read (decimal) import Data.Time (Day) import qualified Data.Traversable as T import Data.Typeable (TypeRep, Typeable, typeOf) import Data.Vector (Vector) import Distribution.System (Arch, OS) import qualified Distribution.Text as DT import qualified Distribution.Version as C import GHC.Generics (Generic) import Prelude -- Fix AMP warning import Safe (readMay) import Stack.Types.FlagName import Stack.Types.PackageName import Stack.Types.Version -- | The name of an LTS Haskell or Stackage Nightly snapshot. data SnapName = LTS !Int !Int | Nightly !Day deriving (Show, Eq, Ord) data BuildPlan = BuildPlan { bpSystemInfo :: SystemInfo , bpTools :: Vector (PackageName, Version) , bpPackages :: Map PackageName PackagePlan , bpGithubUsers :: Map Text (Set Text) } deriving (Show, Eq) instance ToJSON BuildPlan where toJSON BuildPlan {..} = object [ "system-info" .= bpSystemInfo , "tools" .= fmap goTool bpTools , "packages" .= bpPackages , "github-users" .= bpGithubUsers ] where goTool (k, v) = object [ "name" .= k , "version" .= v ] instance FromJSON BuildPlan where parseJSON = withObject "BuildPlan" $ \o -> do bpSystemInfo <- o .: "system-info" bpTools <- o .: "tools" >>= T.mapM goTool bpPackages <- o .: "packages" bpGithubUsers <- o .:? "github-users" .!= mempty return BuildPlan {..} where goTool = withObject "Tool" $ \o -> (,) <$> o .: "name" <*> o .: "version" data PackagePlan = PackagePlan { ppVersion :: Version , ppGithubPings :: Set Text , ppUsers :: Set PackageName , ppConstraints :: PackageConstraints , ppDesc :: SimpleDesc } deriving (Show, Eq) instance ToJSON PackagePlan where toJSON PackagePlan {..} = object [ "version" .= ppVersion , "github-pings" .= ppGithubPings , "users" .= ppUsers , "constraints" .= ppConstraints , "description" .= ppDesc ] instance FromJSON PackagePlan where parseJSON = withObject "PackageBuild" $ \o -> do ppVersion <- o .: "version" ppGithubPings <- o .:? "github-pings" .!= mempty ppUsers <- o .:? "users" .!= mempty ppConstraints <- o .: "constraints" ppDesc <- o .: "description" return PackagePlan {..} display :: DT.Text a => a -> Text display = fromString . DT.display simpleParse :: (MonadThrow m, DT.Text a, Typeable a) => Text -> m a simpleParse orig = withTypeRep $ \rep -> case DT.simpleParse str of Nothing -> throwM (ParseFailedException rep (pack str)) Just v -> return v where str = unpack orig withTypeRep :: Typeable a => (TypeRep -> m a) -> m a withTypeRep f = res where res = f (typeOf (unwrap res)) unwrap :: m a -> a unwrap _ = error "unwrap" data BuildPlanTypesException = ParseSnapNameException Text | ParseFailedException TypeRep Text deriving Typeable instance Exception BuildPlanTypesException instance Show BuildPlanTypesException where show (ParseSnapNameException t) = "Invalid snapshot name: " ++ T.unpack t show (ParseFailedException rep t) = "Unable to parse " ++ show t ++ " as " ++ show rep data PackageConstraints = PackageConstraints { pcVersionRange :: VersionRange , pcMaintainer :: Maybe Maintainer , pcTests :: TestState , pcHaddocks :: TestState , pcBuildBenchmarks :: Bool , pcFlagOverrides :: Map FlagName Bool , pcEnableLibProfile :: Bool } deriving (Show, Eq) instance ToJSON PackageConstraints where toJSON PackageConstraints {..} = object $ addMaintainer [ "version-range" .= display pcVersionRange , "tests" .= pcTests , "haddocks" .= pcHaddocks , "build-benchmarks" .= pcBuildBenchmarks , "flags" .= pcFlagOverrides , "library-profiling" .= pcEnableLibProfile ] where addMaintainer = maybe id (\m -> (("maintainer" .= m):)) pcMaintainer instance FromJSON PackageConstraints where parseJSON = withObject "PackageConstraints" $ \o -> do pcVersionRange <- (o .: "version-range") >>= either (fail . show) return . simpleParse pcTests <- o .: "tests" pcHaddocks <- o .: "haddocks" pcBuildBenchmarks <- o .: "build-benchmarks" pcFlagOverrides <- o .: "flags" pcMaintainer <- o .:? "maintainer" pcEnableLibProfile <- fmap (fromMaybe True) (o .:? "library-profiling") return PackageConstraints {..} data TestState = ExpectSuccess | ExpectFailure | Don'tBuild -- ^ when the test suite will pull in things we don't want deriving (Show, Eq, Ord, Bounded, Enum) testStateToText :: TestState -> Text testStateToText ExpectSuccess = "expect-success" testStateToText ExpectFailure = "expect-failure" testStateToText Don'tBuild = "do-not-build" instance ToJSON TestState where toJSON = toJSON . testStateToText instance FromJSON TestState where parseJSON = withText "TestState" $ \t -> case HashMap.lookup t states of Nothing -> fail $ "Invalid state: " ++ unpack t Just v -> return v where states = HashMap.fromList $ map (\x -> (testStateToText x, x)) [minBound..maxBound] data SystemInfo = SystemInfo { siGhcVersion :: Version , siOS :: OS , siArch :: Arch , siCorePackages :: Map PackageName Version , siCoreExecutables :: Set ExeName } deriving (Show, Eq, Ord) instance ToJSON SystemInfo where toJSON SystemInfo {..} = object [ "ghc-version" .= siGhcVersion , "os" .= display siOS , "arch" .= display siArch , "core-packages" .= siCorePackages , "core-executables" .= siCoreExecutables ] instance FromJSON SystemInfo where parseJSON = withObject "SystemInfo" $ \o -> do let helper name = (o .: name) >>= either (fail . show) return . simpleParse siGhcVersion <- o .: "ghc-version" siOS <- helper "os" siArch <- helper "arch" siCorePackages <- o .: "core-packages" siCoreExecutables <- o .: "core-executables" return SystemInfo {..} newtype Maintainer = Maintainer { unMaintainer :: Text } deriving (Show, Eq, Ord, Hashable, ToJSON, FromJSON, IsString) -- | Name of an executable. newtype ExeName = ExeName { unExeName :: ByteString } deriving (Show, Eq, Ord, Hashable, IsString, Generic) instance Binary ExeName instance ToJSON ExeName where toJSON = toJSON . S8.unpack . unExeName instance FromJSON ExeName where parseJSON = withText "ExeName" $ return . ExeName . encodeUtf8 -- | A simplified package description that tracks: -- -- * Package dependencies -- -- * Build tool dependencies -- -- * Provided executables -- -- It has fully resolved all conditionals data SimpleDesc = SimpleDesc { sdPackages :: Map PackageName DepInfo , sdTools :: Map ExeName DepInfo , sdProvidedExes :: Set ExeName , sdModules :: Set Text -- ^ modules exported by the library } deriving (Show, Eq) instance Monoid SimpleDesc where mempty = SimpleDesc mempty mempty mempty mempty mappend (SimpleDesc a b c d) (SimpleDesc w x y z) = SimpleDesc (Map.unionWith (<>) a w) (Map.unionWith (<>) b x) (c <> y) (d <> z) instance ToJSON SimpleDesc where toJSON SimpleDesc {..} = object [ "packages" .= sdPackages , "tools" .= sdTools , "provided-exes" .= sdProvidedExes , "modules" .= sdModules ] instance FromJSON SimpleDesc where parseJSON = withObject "SimpleDesc" $ \o -> do sdPackages <- o .: "packages" sdTools <- o .: "tools" sdProvidedExes <- o .: "provided-exes" sdModules <- o .: "modules" return SimpleDesc {..} data DepInfo = DepInfo { diComponents :: Set Component , diRange :: VersionRange } deriving (Show, Eq) instance Monoid DepInfo where mempty = DepInfo mempty C.anyVersion DepInfo a x `mappend` DepInfo b y = DepInfo (mappend a b) (C.intersectVersionRanges x y) instance ToJSON DepInfo where toJSON DepInfo {..} = object [ "components" .= diComponents , "range" .= display diRange ] instance FromJSON DepInfo where parseJSON = withObject "DepInfo" $ \o -> do diComponents <- o .: "components" diRange <- o .: "range" >>= either (fail . show) return . simpleParse return DepInfo {..} data Component = CompLibrary | CompExecutable | CompTestSuite | CompBenchmark deriving (Show, Read, Eq, Ord, Enum, Bounded) compToText :: Component -> Text compToText CompLibrary = "library" compToText CompExecutable = "executable" compToText CompTestSuite = "test-suite" compToText CompBenchmark = "benchmark" instance ToJSON Component where toJSON = toJSON . compToText instance FromJSON Component where parseJSON = withText "Component" $ \t -> maybe (fail $ "Invalid component: " ++ unpack t) return (HashMap.lookup t comps) where comps = HashMap.fromList $ map (compToText &&& id) [minBound..maxBound] -- | Convert a 'SnapName' into its short representation, e.g. @lts-2.8@, -- @nightly-2015-03-05@. renderSnapName :: SnapName -> Text renderSnapName (LTS x y) = T.pack $ concat ["lts-", show x, ".", show y] renderSnapName (Nightly d) = T.pack $ "nightly-" ++ show d -- | Parse the short representation of a 'SnapName'. parseSnapName :: MonadThrow m => Text -> m SnapName parseSnapName t0 = case lts <|> nightly of Nothing -> throwM $ ParseSnapNameException t0 Just sn -> return sn where lts = do t1 <- T.stripPrefix "lts-" t0 Right (x, t2) <- Just $ decimal t1 t3 <- T.stripPrefix "." t2 Right (y, "") <- Just $ decimal t3 return $ LTS x y nightly = do t1 <- T.stripPrefix "nightly-" t0 Nightly <$> readMay (T.unpack t1) instance ToJSON a => ToJSON (Map ExeName a) where toJSON = toJSON . Map.mapKeysWith const (S8.unpack . unExeName) instance FromJSON a => FromJSON (Map ExeName a) where parseJSON = fmap (Map.mapKeysWith const (ExeName . encodeUtf8)) . parseJSON -- | A simplified version of the 'BuildPlan' + cabal file. data MiniBuildPlan = MiniBuildPlan { mbpGhcVersion :: !Version , mbpPackages :: !(Map PackageName MiniPackageInfo) } deriving (Generic, Show, Eq) instance Binary.Binary MiniBuildPlan instance BinarySchema MiniBuildPlan where -- Don't forget to update this if you change the datatype in any way! binarySchema _ = 1 -- | Information on a single package for the 'MiniBuildPlan'. data MiniPackageInfo = MiniPackageInfo { mpiVersion :: !Version , mpiFlags :: !(Map FlagName Bool) , mpiPackageDeps :: !(Set PackageName) , mpiToolDeps :: !(Set ByteString) -- ^ Due to ambiguity in Cabal, it is unclear whether this refers to the -- executable name, the package name, or something else. We have to guess -- based on what's available, which is why we store this is an unwrapped -- 'ByteString'. , mpiExes :: !(Set ExeName) -- ^ Executables provided by this package , mpiHasLibrary :: !Bool -- ^ Is there a library present? } deriving (Generic, Show, Eq) instance Binary.Binary MiniPackageInfo
hesselink/stack
src/Stack/Types/BuildPlan.hs
bsd-3-clause
13,963
0
17
4,217
3,523
1,896
1,627
332
2
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : System.Exit.Lens -- Copyright : (C) 2013-14 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : Control.Exception -- -- These prisms can be used with the combinators in "Control.Exception.Lens". ---------------------------------------------------------------------------- module System.Exit.Lens ( AsExitCode(..) , _ExitFailure , _ExitSuccess ) where import Control.Applicative import Control.Exception import Control.Exception.Lens import Control.Lens import System.Exit -- | Exit codes that a program can return with: class AsExitCode p f t where -- | -- @ -- '_ExitCode' :: 'Equality'' 'ExitCode' 'ExitCode' -- '_ExitCode' :: 'Prism'' 'SomeException' 'ExitCode' -- @ _ExitCode :: Optic' p f t ExitCode instance AsExitCode p f ExitCode where _ExitCode = id {-# INLINE _ExitCode #-} instance (Choice p, Applicative f) => AsExitCode p f SomeException where _ExitCode = exception {-# INLINE _ExitCode #-} -- | indicates successful termination; -- -- @ -- '_ExitSuccess' :: 'Prism'' 'ExitCode' () -- '_ExitSuccess' :: 'Prism'' 'SomeException' () -- @ _ExitSuccess :: (AsExitCode p f t, Choice p, Applicative f) => Optic' p f t () _ExitSuccess = _ExitCode . dimap seta (either id id) . right' . rmap (ExitSuccess <$) where seta ExitSuccess = Right () seta t = Left (pure t) {-# INLINE _ExitSuccess #-} -- | indicates program failure with an exit code. The exact interpretation of the code is operating-system dependent. In particular, some values may be prohibited (e.g. 0 on a POSIX-compliant system). -- -- @ -- '_ExitFailure' :: 'Prism'' 'ExitCode' 'Int' -- '_ExitFailure' :: 'Prism'' 'SomeException' 'Int' -- @ _ExitFailure :: (AsExitCode p f t, Choice p, Applicative f) => Optic' p f t Int _ExitFailure = _ExitCode . dimap seta (either id id) . right' . rmap (fmap ExitFailure) where seta (ExitFailure i) = Right i seta t = Left (pure t) {-# INLINE _ExitFailure #-}
hvr/lens
src/System/Exit/Lens.hs
bsd-3-clause
2,242
0
10
420
383
216
167
29
2
module Data.Conduit.Resumable ( -- * Resumable sources -- | Resumable sources are provided by the conduit package itself. -- See 'ResumableSource'. newResumableSource, -- * Resumable sinks -- $sink (+$$), -- ** Combining with resumable sources (+$$+), (+$$++), (+$$+-), -- * Resumable conduits ResumableConduit, newResumableConduit, (=$+), (=$++), (=$+-), ) where import Control.Monad import Control.Monad.Trans.Class (lift) import Data.Conduit import Data.Conduit.Internal import Data.Void -- ResumableSink (same fixity as $$) infixr 0 +$$ infixr 0 +$$+ infixr 0 +$$++ infixr 0 +$$+- -- ResumableConduit right fusion (same fixity as =$ and =$=) infixr 2 =$+ infixr 2 =$++ infixr 2 =$+- ------------------------------------------------------------------------ -- Resumable sources -- ResumableSource is defined in Data.Conduit.Internal: -- data ResumableSource m o = ResumableSource (Source m o) (m ()) -- | Convert a 'Source' into a 'ResumableSource' so it can be used with '$$++'. newResumableSource :: Monad m => Source m o -> ResumableSource m o newResumableSource src = ResumableSource src (return ()) ------------------------------------------------------------------------ -- Resumable sinks -- $sink -- -- There is no \"ResumableSink\" type because 'Sink' does not require finalizer -- support. A 'Sink' is finalized by letting it run to completion with '$$'. -- | Connect a source and a sink, allowing the sink to be fed more data later. -- Return a 'Right' if the sink completes, or a 'Left' if the source is -- exhausted and the sink requests more input. -- -- When you are done with the sink, close it with '$$' so that: -- -- * The sink sees the end of stream. The sink never sees -- 'Data.Conduit.await' return 'Nothing' until you finish the sink -- with '$$'. -- -- * The sink can release system resources. (+$$) :: Monad m => Source m i -> Sink i m r -> m (Either (Sink i m r) r) (+$$) src sink = newResumableSource src +$$+- sink -- | Connect a source to a sink, allowing both to be resumed. (+$$+) :: Monad m => Source m i -> Sink i m r -> m (ResumableSource m i, Either (Sink i m r) r) (+$$+) src sink = newResumableSource src +$$++ sink -- | Like '+$$+', but resume an already-running source. (+$$++) :: Monad m => ResumableSource m i -> Sink i m r -> m (ResumableSource m i, Either (Sink i m r) r) (+$$++) (ResumableSource (ConduitM left0) final0) (ConduitM right0) = goRight final0 left0 right0 where goRight final left right = case right of HaveOutput _ _ o -> absurd o NeedInput rp rc -> goLeft rp rc final left Done r -> return (ResumableSource (ConduitM left) final, Right r) PipeM mp -> mp >>= goRight final left Leftover p i -> goRight final (HaveOutput left final i) p goLeft rp rc final left = case left of HaveOutput left' final' o -> goRight final' left' (rp o) NeedInput _ lc -> recurse (lc ()) Done r -> return ( ResumableSource (ConduitM (Done r)) (return ()) , Left $ ConduitM $ NeedInput rp rc ) PipeM mp -> mp >>= recurse Leftover p _ -> recurse p where recurse = goLeft rp rc final -- | Finish processing a 'ResumableSource', but allow the 'Sink' to be reused. (+$$+-) :: Monad m => ResumableSource m i -> Sink i m r -> m (Either (Sink i m r) r) (+$$+-) rsrc sink = do (ResumableSource _ final, res) <- rsrc +$$++ sink final return res ------------------------------------------------------------------------ -- Resumable conduits data ResumableConduit i m o = ResumableConduit (Pipe i i o () m ()) (m ()) -- | Convert a 'Conduit' into a 'ResumableConduit' so it can be used with '=$++'. newResumableConduit :: Monad m => Conduit i m o -> ResumableConduit i m o newResumableConduit (ConduitM p) = ResumableConduit p (return ()) -- | Fuse a conduit behind a sink, but allow the conduit to be reused after -- the sink returns. -- -- When the source runs out, the stream terminator is sent directly to -- the sink, bypassing the conduit. Some conduits wait for a stream terminator -- before producing their remaining output, so be sure to use '=$+-' -- to \"flush\" this data out. (=$+) :: Monad m => Conduit a m b -> Sink b m r -> Sink a m (ResumableConduit a m b, r) (=$+) conduit sink = newResumableConduit conduit =$++ sink -- | Continue using a conduit after '=$+'. (=$++) :: Monad m => ResumableConduit a m b -> Sink b m r -> Sink a m (ResumableConduit a m b, r) (=$++) = resumeConduit True resumeConduit :: Monad m => Bool -> ResumableConduit a m b -> Sink b m r -> Sink a m (ResumableConduit a m b, r) resumeConduit bypassEOF (ResumableConduit conduit0 final0) (ConduitM sink0) = ConduitM $ goSink final0 conduit0 sink0 where goSink final conduit sink = case sink of HaveOutput _ _ o -> absurd o NeedInput rp rc -> goConduit rp rc final conduit Done r -> Done (ResumableConduit conduit final, r) PipeM mp -> PipeM (liftM recurse mp) Leftover sink' o -> goSink final (HaveOutput conduit final o) sink' where recurse = goSink final conduit goConduit rp rc final conduit = case conduit of HaveOutput conduit' final' o -> goSink final' conduit' (rp o) NeedInput left' lc -> NeedInput (recurse . left') (if bypassEOF then -- Forward EOF to sink, but leave the conduit -- alone so it accepts input from the next source. goSink final conduit . rc else -- Send EOF through the conduit like 'pipe' does. recurse . lc ) Done r -> goSink (return ()) (Done r) (rc r) PipeM mp -> PipeM (liftM recurse mp) Leftover conduit' i -> Leftover (recurse conduit') i where recurse = goConduit rp rc final -- | Finalize a 'ResumableConduit' by using it one more time. It will be -- closed when the sink finishes. (=$+-) :: Monad m => ResumableConduit a m b -> Sink b m r -> Sink a m r (=$+-) rconduit sink = do (ResumableConduit _ final, res) <- resumeConduit False rconduit sink lift final return res
joeyadams/hs-conduit-resumable
Data/Conduit/Resumable.hs
bsd-3-clause
6,873
0
16
2,155
1,617
834
783
113
10
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.MapBufferRange -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/map_buffer_range.txt ARB_map_buffer_range> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.MapBufferRange ( -- * Enums gl_MAP_FLUSH_EXPLICIT_BIT, gl_MAP_INVALIDATE_BUFFER_BIT, gl_MAP_INVALIDATE_RANGE_BIT, gl_MAP_READ_BIT, gl_MAP_UNSYNCHRONIZED_BIT, gl_MAP_WRITE_BIT, -- * Functions glFlushMappedBufferRange, glMapBufferRange ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/MapBufferRange.hs
bsd-3-clause
907
0
4
106
67
52
15
11
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} -- | Opaque type for an operations log that provides fast O(1) -- appends. module Futhark.Util.Log ( Log, toText, ToLog (..), MonadLogger (..), ) where import qualified Control.Monad.RWS.Lazy import qualified Control.Monad.RWS.Strict import Control.Monad.Writer import qualified Data.DList as DL import qualified Data.Text as T -- | An efficiently catenable sequence of log entries. newtype Log = Log {unLog :: DL.DList T.Text} instance Semigroup Log where Log l1 <> Log l2 = Log $ l1 <> l2 instance Monoid Log where mempty = Log mempty -- | Transform a log into text. Every log entry becomes its own line -- (or possibly more, in case of multi-line entries). toText :: Log -> T.Text toText = T.intercalate "\n" . DL.toList . unLog -- | Typeclass for things that can be turned into a single-entry log. class ToLog a where toLog :: a -> Log instance ToLog String where toLog = Log . DL.singleton . T.pack instance ToLog T.Text where toLog = Log . DL.singleton -- | Typeclass for monads that support logging. class (Applicative m, Monad m) => MonadLogger m where -- | Add one log entry. logMsg :: ToLog a => a -> m () logMsg = addLog . toLog -- | Append an entire log. addLog :: Log -> m () instance (Applicative m, Monad m) => MonadLogger (WriterT Log m) where addLog = tell instance (Applicative m, Monad m) => MonadLogger (Control.Monad.RWS.Lazy.RWST r Log s m) where addLog = tell instance (Applicative m, Monad m) => MonadLogger (Control.Monad.RWS.Strict.RWST r Log s m) where addLog = tell
HIPERFIT/futhark
src/Futhark/Util/Log.hs
isc
1,655
0
10
325
438
248
190
36
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} module Internal.Type where #ifdef ghcjs_HOST_OS import Data.JSString import GHCJS.Marshal (FromJSVal (..), ToJSVal (..)) import GHCJS.Types (JSVal) import Internal.FFI (js_isInCurrentDOM) #endif -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- #ifndef ghcjs_HOST_OS type JSVal = () type JSString = String unpack = undefined #endif newtype Elem = Elem JSVal type PropId = JSString type Attribute = (JSString, JSString) class NamedEvent a where eventName :: a -> String data JsEvent = Blur | Change | Click | DblClick | Focus | KeyPress | KeyUp | KeyDown | Load | MouseDown | MouseMove | MouseOut | MouseOver | MouseUp | Submit | Unload | Wheel #ifdef ghcjs_HOST_OS instance FromJSVal Elem where fromJSVal v = do isElem <- js_isInCurrentDOM v return $ if isElem then Just (Elem v) else Nothing instance ToJSVal Elem where toJSVal (Elem val) = return val #endif #ifdef ghcjs_HOST_OS instance NamedEvent String where eventName = Prelude.id #endif instance {-# OVERLAPPABLE #-} Show a => NamedEvent a where eventName = eventName . show instance NamedEvent JSString where eventName x = eventName (unpack x :: String) instance Show JsEvent where show Blur = "blur" show Change = "change" show Click = "click" show DblClick = "dblclick" show Focus = "focus" show KeyDown = "keydown" show KeyPress = "keypress" show KeyUp = "keyup" show Load = "load" show MouseDown = "mousedown" show MouseMove = "mousemove" show MouseOut = "mouseout" show MouseOver = "mouseover" show MouseUp = "mouseup" show Submit = "submit" show Unload = "unload" show Wheel = "wheel" --------------------------------------------------------------------------------
agocorona/ghcjs-perch
src/Internal/Type.hs
mit
2,287
0
12
669
472
265
207
52
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.OpsWorks.DeregisterVolume -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deregisters an Amazon EBS volume. The volume can then be registered by -- another stack. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html Resource Management>. -- -- __Required Permissions__: To use this action, an IAM user must have a -- Manage permissions level for the stack, or an attached policy that -- explicitly grants permissions. For more information on user permissions, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeregisterVolume.html AWS API Reference> for DeregisterVolume. module Network.AWS.OpsWorks.DeregisterVolume ( -- * Creating a Request deregisterVolume , DeregisterVolume -- * Request Lenses , dvVolumeId -- * Destructuring the Response , deregisterVolumeResponse , DeregisterVolumeResponse ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'deregisterVolume' smart constructor. newtype DeregisterVolume = DeregisterVolume' { _dvVolumeId :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeregisterVolume' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvVolumeId' deregisterVolume :: Text -- ^ 'dvVolumeId' -> DeregisterVolume deregisterVolume pVolumeId_ = DeregisterVolume' { _dvVolumeId = pVolumeId_ } -- | The AWS OpsWorks volume ID, which is the GUID that AWS OpsWorks assigned -- to the instance when you registered the volume with the stack, not the -- Amazon EC2 volume ID. dvVolumeId :: Lens' DeregisterVolume Text dvVolumeId = lens _dvVolumeId (\ s a -> s{_dvVolumeId = a}); instance AWSRequest DeregisterVolume where type Rs DeregisterVolume = DeregisterVolumeResponse request = postJSON opsWorks response = receiveNull DeregisterVolumeResponse' instance ToHeaders DeregisterVolume where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.DeregisterVolume" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DeregisterVolume where toJSON DeregisterVolume'{..} = object (catMaybes [Just ("VolumeId" .= _dvVolumeId)]) instance ToPath DeregisterVolume where toPath = const "/" instance ToQuery DeregisterVolume where toQuery = const mempty -- | /See:/ 'deregisterVolumeResponse' smart constructor. data DeregisterVolumeResponse = DeregisterVolumeResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeregisterVolumeResponse' with the minimum fields required to make a request. -- deregisterVolumeResponse :: DeregisterVolumeResponse deregisterVolumeResponse = DeregisterVolumeResponse'
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/DeregisterVolume.hs
mpl-2.0
3,855
0
12
768
407
249
158
57
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.AutoScaling.DescribeScalingProcessTypes -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Describes the scaling process types for use with ResumeProcesses and -- SuspendProcesses. -- -- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeScalingProcessTypes.html AWS API Reference> for DescribeScalingProcessTypes. module Network.AWS.AutoScaling.DescribeScalingProcessTypes ( -- * Creating a Request describeScalingProcessTypes , DescribeScalingProcessTypes -- * Destructuring the Response , describeScalingProcessTypesResponse , DescribeScalingProcessTypesResponse -- * Response Lenses , dsptrsProcesses , dsptrsResponseStatus ) where import Network.AWS.AutoScaling.Types import Network.AWS.AutoScaling.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeScalingProcessTypes' smart constructor. data DescribeScalingProcessTypes = DescribeScalingProcessTypes' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeScalingProcessTypes' with the minimum fields required to make a request. -- describeScalingProcessTypes :: DescribeScalingProcessTypes describeScalingProcessTypes = DescribeScalingProcessTypes' instance AWSRequest DescribeScalingProcessTypes where type Rs DescribeScalingProcessTypes = DescribeScalingProcessTypesResponse request = postQuery autoScaling response = receiveXMLWrapper "DescribeScalingProcessTypesResult" (\ s h x -> DescribeScalingProcessTypesResponse' <$> (x .@? "Processes" .!@ mempty >>= may (parseXMLList "member")) <*> (pure (fromEnum s))) instance ToHeaders DescribeScalingProcessTypes where toHeaders = const mempty instance ToPath DescribeScalingProcessTypes where toPath = const "/" instance ToQuery DescribeScalingProcessTypes where toQuery = const (mconcat ["Action" =: ("DescribeScalingProcessTypes" :: ByteString), "Version" =: ("2011-01-01" :: ByteString)]) -- | /See:/ 'describeScalingProcessTypesResponse' smart constructor. data DescribeScalingProcessTypesResponse = DescribeScalingProcessTypesResponse' { _dsptrsProcesses :: !(Maybe [ProcessType]) , _dsptrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeScalingProcessTypesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsptrsProcesses' -- -- * 'dsptrsResponseStatus' describeScalingProcessTypesResponse :: Int -- ^ 'dsptrsResponseStatus' -> DescribeScalingProcessTypesResponse describeScalingProcessTypesResponse pResponseStatus_ = DescribeScalingProcessTypesResponse' { _dsptrsProcesses = Nothing , _dsptrsResponseStatus = pResponseStatus_ } -- | The names of the process types. dsptrsProcesses :: Lens' DescribeScalingProcessTypesResponse [ProcessType] dsptrsProcesses = lens _dsptrsProcesses (\ s a -> s{_dsptrsProcesses = a}) . _Default . _Coerce; -- | The response status code. dsptrsResponseStatus :: Lens' DescribeScalingProcessTypesResponse Int dsptrsResponseStatus = lens _dsptrsResponseStatus (\ s a -> s{_dsptrsResponseStatus = a});
olorin/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/DescribeScalingProcessTypes.hs
mpl-2.0
4,134
0
15
831
493
294
199
69
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module HERMIT.Libraries.Int where import Control.Arrow import qualified Data.Map as M import HERMIT.GHC hiding (intTy) import HERMIT.Kure import HERMIT.Lemma import HERMIT.Name import HERMIT.Dictionary.Common import HERMIT.Dictionary.GHC {- Defines the following lemmas: forall n m. (m == n) = (n == m) forall n m. (m < n ) = (n > m) forall n m. (m <= n) = (n >= m) forall n m. (m >= n) = (n < m) forall n m. (m <= n) = False => (m == n) = False forall n m. (m == n) = True => (m <= n) = True forall n m. (min n m) = (min m n) forall n m. (max n m) = (max m n) forall n m. (min n m <= n) = True forall n m. (max n m >= n) = True -} lemmas :: LemmaLibrary lemmas = do intTy <- findTypeT "Prelude.Int" nId <- constT $ newIdH "n" intTy mId <- constT $ newIdH "m" intTy let n = varToCoreExpr nId m = varToCoreExpr mId #if __GLASGOW_HASKELL__ > 710 appTo i e = return $ mkCoreApp (text "appTo") (varToCoreExpr i) e #else appTo i e = return $ mkCoreApp (varToCoreExpr i) e #endif appToInt i = appTo i (Type intTy) appToDict e = do let (aTys, _) = splitFunTys (exprType e) case aTys of #if __GLASGOW_HASKELL__ > 710 (ty:_) | isDictTy ty -> return ty >>> buildDictionaryT >>> arr (mkCoreApp (text "appToDict") e) #else (ty:_) | isDictTy ty -> return ty >>> buildDictionaryT >>> arr (mkCoreApp e) #endif _ -> fail "first argument is not a dictionary." appMN e = mkCoreApps e [m,n] appNM e = mkCoreApps e [n,m] mkEL l r = mkL (Equiv l r) mkL cl = Lemma (mkForall [mId,nId] cl) BuiltIn NotUsed mkIL nm al ar cl cr = mkL (Impl nm (Equiv al ar) (Equiv cl cr)) eqE <- findIdT "Data.Eq.==" >>= appToInt >>= appToDict gtE <- findIdT "Data.Ord.>" >>= appToInt >>= appToDict ltE <- findIdT "Data.Ord.<" >>= appToInt >>= appToDict gteE <- findIdT "Data.Ord.>=" >>= appToInt >>= appToDict lteE <- findIdT "Data.Ord.<=" >>= appToInt >>= appToDict minE <- findIdT "Data.Ord.min" >>= appToInt >>= appToDict maxE <- findIdT "Data.Ord.max" >>= appToInt >>= appToDict trueE <- varToCoreExpr <$> findIdT "Data.Bool.True" falseE <- varToCoreExpr <$> findIdT "Data.Bool.False" return $ M.fromList [ ("EqCommutativeInt", mkEL (appMN eqE) (appNM eqE)) , ("LtGtInt", mkEL (appMN ltE) (appNM gtE)) , ("LteGteInt", mkEL (appMN lteE) (appNM gteE)) , ("GteLtInt", mkEL (appMN gteE) (appNM ltE)) , ("LteFalseImpliesEqFalseInt", mkIL "LteFalse" (appMN lteE) falseE (appMN eqE) falseE) , ("EqTrueImpliesLteTrueInt", mkIL "EqTrue" (appMN eqE) trueE (appMN lteE) trueE) , ("MinCommutativeInt", mkEL (appMN minE) (appNM minE)) , ("MaxCommutativeInt", mkEL (appMN maxE) (appNM maxE)) , ("MinLteInt", mkEL (mkCoreApps lteE [appNM minE, n]) trueE) , ("MaxGteInt", mkEL (mkCoreApps gteE [appNM maxE, n]) trueE) ]
conal/hermit
src/HERMIT/Libraries/Int.hs
bsd-2-clause
3,142
0
21
888
871
443
428
50
2
{-# LANGUAGE TupleSections #-} import Control.Monad (void) import qualified Data.MemoCombinators as Memo import qualified Data.Set as S import qualified Data.Tree as T import qualified NLP.Partage.Auto as A import qualified NLP.Partage.AStar as E import qualified NLP.Partage.Auto.WeiTrie as W import qualified NLP.Partage.DAG as DAG import qualified NLP.Partage.Tree.Other as O -- | Memoization for terminals. memoTerm = Memo.list Memo.char -- | Some smart constructors. node x = T.Node (O.NonTerm x) leaf x = T.Node (O.NonTerm x) [] term x = T.Node (O.Term x) [] foot x = T.Node (O.Foot x) [] -- | A sample TAG grammar. trees = [ node "NP" [node "N" [term "acid"]] , node "NP" [node "N" [term "rains"]] , node "NP" [ node "N" [term "acid"] , node "N" [term "rains"] ] , node "N" [ node "N" [term "acid"] , foot "N" ] , node "S" [ leaf "NP" , node "VP" [node "V" [term "rains"]] ] ] main = do let gram = DAG.mkGram (map (,1) trees) dag = DAG.dagGram gram ruleMap = DAG.factGram gram wei = W.fromGram ruleMap auto = E.mkAuto gram recognize s = E.recognizeFromAuto memoTerm auto s . E.Input mapM_ (\i -> print (i, DAG.label i dag, DAG.value i dag, DAG.edges i dag)) (S.toList (DAG.nodeSet dag)) putStrLn "=========" mapM_ print $ A.allEdges $ A.fromWei wei putStrLn "=========" void $ recognize "S" ["acid", "rains"]
kawu/partage
examples/old/acid-rains.hs
bsd-2-clause
1,495
0
13
399
556
295
261
41
1
{-# LANGUAGE DeriveDataTypeable #-} module PTS.Syntax.Constants ( C (C) , int , star , box , triangle , circle ) where import Data.Data import Data.Typeable -- constants newtype C = C Int deriving (Eq, Ord, Data, Typeable, Show) int :: C int = C 0 star :: C star = C 1 box :: C box = C 2 triangle :: C triangle = C 3 circle :: C circle = C 4
Toxaris/pts
src-lib/PTS/Syntax/Constants.hs
bsd-3-clause
365
0
6
96
139
81
58
25
1
{-# LANGUAGE CPP, BangPatterns, PatternGuards #-} {-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Codec.Archive.Tar.Index -- Copyright : (c) 2010-2015 Duncan Coutts -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- Random access to the content of a @.tar@ archive. -- -- This module uses common names and so is designed to be imported qualified: -- -- > import qualified Codec.Archive.Tar.Index as Tar -- ----------------------------------------------------------------------------- module Codec.Archive.Tar.Index ( -- | The @tar@ format does not contain an index of files within the -- archive. Normally, @tar@ file have to be processed linearly. It is -- sometimes useful however to be able to get random access to files -- within the archive. -- -- This module provides an index of a @tar@ file. A linear pass of the -- @tar@ file is needed to 'build' the 'TarIndex', but thereafter you can -- 'lookup' paths in the @tar@ file, and then use 'hReadEntry' to -- seek to the right part of the file and read the entry. -- * Index type TarIndex, -- * Index lookup lookup, TarIndexEntry(..), -- ** I\/O operations TarEntryOffset, hReadEntry, hReadEntryHeader, -- * Index construction build, -- ** Incremental construction -- $incremental-construction IndexBuilder, emptyIndex, addNextEntry, skipNextEntry, finaliseIndex, -- * Serialising indexes serialise, deserialise, -- * Lower level operations with offsets and I\/O on tar files hReadEntryHeaderOrEof, hSeekEntryOffset, hSeekEntryContentOffset, hSeekEndEntryOffset, nextEntryOffset, indexEndEntryOffset, indexNextEntryOffset, #ifdef TESTS prop_lookup, prop_valid, #endif ) where import Data.Typeable (Typeable) import Codec.Archive.Tar.Types as Tar import Codec.Archive.Tar.Read as Tar import qualified Codec.Archive.Tar.Index.StringTable as StringTable import Codec.Archive.Tar.Index.StringTable (StringTable(..)) import qualified Codec.Archive.Tar.Index.IntTrie as IntTrie import Codec.Archive.Tar.Index.IntTrie (IntTrie(..)) import qualified System.FilePath.Posix as FilePath import Data.Monoid (Monoid(..)) #if (MIN_VERSION_base(4,5,0)) import Data.Monoid ((<>)) #endif import Data.Word import Data.Int import Data.Bits import qualified Data.Array.Unboxed as A import Prelude hiding (lookup) import System.IO import Control.Exception (throwIO) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS #if MIN_VERSION_bytestring(0,10,2) import Data.ByteString.Builder as BS #else import Data.ByteString.Lazy.Builder as BS #endif #ifdef TESTS import qualified Prelude import Test.QuickCheck import Control.Applicative ((<$>), (<*>)) import Data.List (nub, sort, stripPrefix, isPrefixOf) import Data.Maybe #endif -- | An index of the entries in a tar file. -- -- This index type is designed to be quite compact and suitable to store either -- on disk or in memory. -- data TarIndex = TarIndex -- As an example of how the mapping works, consider these example files: -- "foo/bar.hs" at offset 0 -- "foo/baz.hs" at offset 1024 -- -- We split the paths into components and enumerate them. -- { "foo" -> TokenId 0, "bar.hs" -> TokenId 1, "baz.hs" -> TokenId 2 } -- -- We convert paths into sequences of 'TokenId's, i.e. -- "foo/bar.hs" becomes [PathComponentId 0, PathComponentId 1] -- "foo/baz.hs" becomes [PathComponentId 0, PathComponentId 2] -- -- We use a trie mapping sequences of 'PathComponentId's to the entry offset: -- { [PathComponentId 0, PathComponentId 1] -> offset 0 -- , [PathComponentId 0, PathComponentId 2] -> offset 1024 } -- The mapping of filepath components as strings to ids. {-# UNPACK #-} !(StringTable PathComponentId) -- Mapping of sequences of filepath component ids to tar entry offsets. {-# UNPACK #-} !(IntTrie PathComponentId TarEntryOffset) -- The offset immediatly after the last entry, where we would append any -- additional entries. {-# UNPACK #-} !TarEntryOffset deriving (Eq, Show, Typeable) -- | The result of 'lookup' in a 'TarIndex'. It can either be a file directly, -- or a directory entry containing further entries (and all subdirectories -- recursively). Note that the subtrees are constructed lazily, so it's -- cheaper if you don't look at them. -- data TarIndexEntry = TarFileEntry {-# UNPACK #-} !TarEntryOffset | TarDir [(FilePath, TarIndexEntry)] deriving (Show, Typeable) newtype PathComponentId = PathComponentId Int deriving (Eq, Ord, Enum, Show, Typeable) -- | An offset within a tar file. Use 'hReadEntry', 'hReadEntryHeader' or -- 'hSeekEntryOffset'. -- -- This is actually a tar \"record\" number, not a byte offset. -- type TarEntryOffset = Word32 -- | Look up a given filepath in the 'TarIndex'. It may return a 'TarFileEntry' -- containing the 'TarEntryOffset' of the file within the tar file, or if -- the filepath identifies a directory then it returns a 'TarDir' containing -- the list of files within that directory. -- -- Given the 'TarEntryOffset' you can then use one of the I\/O operations: -- -- * 'hReadEntry' to read the whole entry; -- -- * 'hReadEntryHeader' to read just the file metadata (e.g. its length); -- lookup :: TarIndex -> FilePath -> Maybe TarIndexEntry lookup (TarIndex pathTable pathTrie _) path = do fpath <- toComponentIds pathTable path tentry <- IntTrie.lookup pathTrie fpath return (mkIndexEntry tentry) where mkIndexEntry (IntTrie.Entry offset) = TarFileEntry offset mkIndexEntry (IntTrie.Completions entries) = TarDir [ (fromComponentId pathTable key, mkIndexEntry entry) | (key, entry) <- entries ] toComponentIds :: StringTable PathComponentId -> FilePath -> Maybe [PathComponentId] toComponentIds table = lookupComponents [] . filter (/= ".") . FilePath.splitDirectories where lookupComponents cs' [] = Just (reverse cs') lookupComponents cs' (c:cs) = case StringTable.lookup table c of Nothing -> Nothing Just cid -> lookupComponents (cid:cs') cs fromComponentId :: StringTable PathComponentId -> PathComponentId -> FilePath fromComponentId table = StringTable.index table -- | Build a 'TarIndex' from a sequence of tar 'Entries'. The 'Entries' are -- assumed to start at offset @0@ within a file. -- build :: Entries e -> Either e TarIndex build = go emptyIndex where go !builder (Next e es) = go (addNextEntry e builder) es go !builder Done = Right $! finaliseIndex builder go !_ (Fail err) = Left err -- $incremental-construction -- If you need more control than 'build' then you can construct the index -- in an acumulator style using the 'IndexBuilder' and operations. -- -- Start with the 'emptyIndex' and use 'addNextEntry' (or 'skipNextEntry') for -- each 'Entry' in the tar file in order. Every entry must added or skipped in -- order, otherwise the resulting 'TarIndex' will report the wrong -- 'TarEntryOffset's. At the end use 'finaliseIndex' to get the 'TarIndex'. -- -- For example, 'build' is simply: -- -- > build = go emptyIndex -- > where -- > go !builder (Next e es) = go (addNextEntry e builder) es -- > go !builder Done = Right $! finaliseIndex builder -- > go !_ (Fail err) = Left err -- | The intermediate type used for incremental construction of a 'TarIndex'. -- data IndexBuilder = IndexBuilder [(FilePath, TarEntryOffset)] {-# UNPACK #-} !TarEntryOffset -- | The initial empty 'IndexBuilder'. -- emptyIndex :: IndexBuilder emptyIndex = IndexBuilder [] 0 -- | Add the next 'Entry' into the 'IndexBuilder'. -- addNextEntry :: Entry -> IndexBuilder -> IndexBuilder addNextEntry entry (IndexBuilder acc nextOffset) = IndexBuilder ((entrypath, nextOffset):acc) (nextEntryOffset entry nextOffset) where !entrypath = entryPath entry -- | Use this function if you want to skip some entries and not add them to the -- final 'TarIndex'. -- skipNextEntry :: Entry -> IndexBuilder -> IndexBuilder skipNextEntry entry (IndexBuilder acc nextOffset) = IndexBuilder acc (nextEntryOffset entry nextOffset) -- | Finish accumulating 'Entry' information and build the compact 'TarIndex' -- lookup structure. -- finaliseIndex :: IndexBuilder -> TarIndex finaliseIndex (IndexBuilder pathsOffsets finalOffset) = TarIndex pathTable pathTrie finalOffset where pathComponents = concatMap (FilePath.splitDirectories . fst) pathsOffsets pathTable = StringTable.construct pathComponents pathTrie = IntTrie.construct [ (cids, offset) | (path, offset) <- pathsOffsets , let Just cids = toComponentIds pathTable path ] -- | This is the offset immediately following the entry most recently added -- to the 'IndexBuilder'. You might use this if you need to know the offsets -- but don't want to use the 'TarIndex' lookup structure. -- Use with 'hSeekEntryOffset'. See also 'nextEntryOffset'. -- indexNextEntryOffset :: IndexBuilder -> TarEntryOffset indexNextEntryOffset (IndexBuilder _ off) = off -- | This is the offset immediately following the last entry in the tar file. -- This can be useful to append further entries into the tar file. -- Use with 'hSeekEntryOffset', or just use 'hSeekEndEntryOffset' directly. -- indexEndEntryOffset :: TarIndex -> TarEntryOffset indexEndEntryOffset (TarIndex _ _ off) = off -- | Calculate the 'TarEntryOffset' of the next entry, given the size and -- offset of the current entry. -- -- This is much like using 'skipNextEntry' and 'indexNextEntryOffset', but without -- using an 'IndexBuilder'. -- nextEntryOffset :: Entry -> TarEntryOffset -> TarEntryOffset nextEntryOffset entry offset = offset + 1 + case entryContent entry of NormalFile _ size -> blocks size OtherEntryType _ _ size -> blocks size _ -> 0 where blocks size = 1 + ((fromIntegral size - 1) `div` 512) ------------------------- -- I/O operations -- -- | Reads an entire 'Entry' at the given 'TarEntryOffset' in the tar file. -- The 'Handle' must be open for reading and be seekable. -- -- This reads the whole entry into memory strictly, not incrementally. For more -- control, use 'hReadEntryHeader' and then read the entry content manually. -- hReadEntry :: Handle -> TarEntryOffset -> IO Entry hReadEntry hnd off = do entry <- hReadEntryHeader hnd off case entryContent entry of NormalFile _ size -> do body <- LBS.hGet hnd (fromIntegral size) return entry { entryContent = NormalFile body size } OtherEntryType c _ size -> do body <- LBS.hGet hnd (fromIntegral size) return entry { entryContent = OtherEntryType c body size } _ -> return entry -- | Read the header for a 'Entry' at the given 'TarEntryOffset' in the tar -- file. The 'entryContent' will contain the correct metadata but an empty file -- content. The 'Handle' must be open for reading and be seekable. -- -- The 'Handle' position is advanced to the beginning of the entry content (if -- any). You must check the 'entryContent' to see if the entry is of type -- 'NormalFile'. If it is, the 'NormalFile' gives the content length and you -- are free to read this much data from the 'Handle'. -- -- > entry <- Tar.hReadEntryHeader hnd -- > case Tar.entryContent entry of -- > Tar.NormalFile _ size -> do content <- BS.hGet hnd size -- > ... -- -- Of course you don't have to read it all in one go (as 'hReadEntry' does), -- you can use any appropriate method to read it incrementally. -- -- In addition to I\/O errors, this can throw a 'FormatError' if the offset is -- wrong, or if the file is not valid tar format. -- -- There is also the lower level operation 'hSeekEntryOffset'. -- hReadEntryHeader :: Handle -> TarEntryOffset -> IO Entry hReadEntryHeader hnd blockOff = do hSeekEntryOffset hnd blockOff header <- LBS.hGet hnd 512 case Tar.read header of Tar.Next entry _ -> return entry Tar.Fail e -> throwIO e Tar.Done -> fail "hReadEntryHeader: impossible" -- | Set the 'Handle' position to the position corresponding to the given -- 'TarEntryOffset'. -- -- This position is where the entry metadata can be read. If you already know -- the entry has a body (and perhaps know it's length), you may wish to seek to -- the body content directly using 'hSeekEntryContentOffset'. -- hSeekEntryOffset :: Handle -> TarEntryOffset -> IO () hSeekEntryOffset hnd blockOff = hSeek hnd AbsoluteSeek (fromIntegral blockOff * 512) -- | Set the 'Handle' position to the entry content position corresponding to -- the given 'TarEntryOffset'. -- -- This position is where the entry content can be read using ordinary I\/O -- operations (though you have to know in advance how big the entry content -- is). This is /only valid/ if you /already know/ the entry has a body (i.e. -- is a normal file). -- hSeekEntryContentOffset :: Handle -> TarEntryOffset -> IO () hSeekEntryContentOffset hnd blockOff = hSeekEntryOffset hnd (blockOff + 1) -- | This is a low level variant on 'hReadEntryHeader', that can be used to -- iterate through a tar file, entry by entry. -- -- It has a few differences compared to 'hReadEntryHeader': -- -- * It returns an indication when the end of the tar file is reached. -- -- * It /does not/ move the 'Handle' position to the beginning of the entry -- content. -- -- * It returns the 'TarEntryOffset' of the next entry. -- -- After this action, the 'Handle' position is not in any useful place. If -- you want to skip to the next entry, take the 'TarEntryOffset' returned and -- use 'hReadEntryHeaderOrEof' again. Or if having inspected the 'Entry' -- header you want to read the entry content (if it has one) then use -- 'hSeekEntryContentOffset' on the original input 'TarEntryOffset'. -- hReadEntryHeaderOrEof :: Handle -> TarEntryOffset -> IO (Maybe (Entry, TarEntryOffset)) hReadEntryHeaderOrEof hnd blockOff = do hSeekEntryOffset hnd blockOff header <- LBS.hGet hnd 1024 case Tar.read header of Tar.Next entry _ -> let !blockOff' = nextEntryOffset entry blockOff in return (Just (entry, blockOff')) Tar.Done -> return Nothing Tar.Fail e -> throwIO e -- | Seek to the end of a tar file, to the position where new entries can -- be appended, and return that 'TarEntryOffset'. -- -- If you have a valid 'TarIndex' for this tar file then you should supply it -- because it allows seeking directly to the correct location. -- -- If you do not have an index, then this becomes an expensive linear -- operation because we have to read each tar entry header from the beginning -- to find the location immediately after the last entry (this is because tar -- files have a variable length trailer and we cannot reliably find that by -- starting at the end). In this mode, it will fail with an exception if the -- file is not in fact in the tar format. -- hSeekEndEntryOffset :: Handle -> Maybe TarIndex -> IO TarEntryOffset hSeekEndEntryOffset hnd (Just index) = do let offset = indexEndEntryOffset index hSeekEntryOffset hnd offset return offset hSeekEndEntryOffset hnd Nothing = do size <- hFileSize hnd if size == 0 then return 0 else seekToEnd 0 where seekToEnd offset = do mbe <- hReadEntryHeaderOrEof hnd offset case mbe of Nothing -> do hSeekEntryOffset hnd offset return offset Just (_, offset') -> seekToEnd offset' ------------------------- -- (de)serialisation -- -- | The 'TarIndex' is compact in memory, and it has a similarly compact -- external representation. -- serialise :: TarIndex -> BS.Builder serialise (TarIndex stringTable intTrie finalOffset) = BS.word32BE 1 -- format version <> BS.word32BE finalOffset <> serialiseStringTable stringTable <> serialiseIntTrie intTrie -- | Read the external representation back into a 'TarIndex'. -- deserialise :: BS.ByteString -> Maybe (TarIndex, BS.ByteString) deserialise bs | BS.length bs >= 8 , let ver = readWord32BE bs 0 , ver == 1 = do let !finalOffset = readWord32BE bs 4 (stringTable, bs') <- deserialiseStringTable (BS.drop 8 bs) (intTrie, bs'') <- deserialiseIntTrie bs' return (TarIndex stringTable intTrie finalOffset, bs'') | otherwise = Nothing serialiseIntTrie :: IntTrie k v -> BS.Builder serialiseIntTrie (IntTrie arr) = let (_, !ixEnd) = A.bounds arr in BS.word32BE (ixEnd+1) <> foldr (\n r -> BS.word32BE n <> r) mempty (A.elems arr) deserialiseIntTrie :: BS.ByteString -> Maybe (IntTrie k v, BS.ByteString) deserialiseIntTrie bs | BS.length bs >= 4 , let lenArr = readWord32BE bs 0 lenTotal = 4 + 4 * fromIntegral lenArr , BS.length bs >= 4 + 4 * fromIntegral lenArr , let !arr = A.array (0, lenArr-1) [ (i, readWord32BE bs off) | (i, off) <- zip [0..lenArr-1] [4,8 .. lenTotal - 4] ] !bs' = BS.drop lenTotal bs = Just (IntTrie arr, bs') | otherwise = Nothing serialiseStringTable :: StringTable id -> BS.Builder serialiseStringTable (StringTable strs arr) = let (_, !ixEnd) = A.bounds arr in BS.word32BE (fromIntegral (BS.length strs)) <> BS.word32BE (fromIntegral ixEnd + 1) <> BS.byteString strs <> foldr (\n r -> BS.word32BE n <> r) mempty (A.elems arr) deserialiseStringTable :: BS.ByteString -> Maybe (StringTable id, BS.ByteString) deserialiseStringTable bs | BS.length bs >= 8 , let lenStrs = fromIntegral (readWord32BE bs 0) lenArr = fromIntegral (readWord32BE bs 4) lenTotal= 8 + lenStrs + 4 * lenArr , BS.length bs >= lenTotal , let strs = BS.take lenStrs (BS.drop 8 bs) arr = A.array (0, lenArr-1) [ (i, readWord32BE bs off) | (i, off) <- zip [0..lenArr-1] [offArrS,offArrS+4 .. offArrE] ] offArrS = 8 + lenStrs offArrE = offArrS + 4 * lenArr - 1 !stringTable = StringTable strs arr !bs' = BS.drop lenTotal bs = Just (stringTable, bs') | otherwise = Nothing readWord32BE :: BS.ByteString -> Int -> Word32 readWord32BE bs i = fromIntegral (BS.index bs (i + 0)) `shiftL` 24 + fromIntegral (BS.index bs (i + 1)) `shiftL` 16 + fromIntegral (BS.index bs (i + 2)) `shiftL` 8 + fromIntegral (BS.index bs (i + 3)) ------------------------- -- Test properties -- #ifdef TESTS -- Not quite the properties of a finite mapping because we also have lookups -- that result in completions. prop_lookup :: ValidPaths -> NonEmptyFilePath -> Bool prop_lookup (ValidPaths paths) (NonEmptyFilePath p) = case (lookup index p, Prelude.lookup p paths) of (Nothing, Nothing) -> True (Just (TarFileEntry offset), Just offset') -> offset == offset' (Just (TarDir entries), Nothing) -> sort (nub (map fst entries)) == sort (nub completions) _ -> False where index = finaliseIndex (IndexBuilder paths 0) completions = [ head (FilePath.splitDirectories completion) | (path,_) <- paths , completion <- maybeToList $ stripPrefix (p ++ "/") path ] prop_valid :: ValidPaths -> Bool prop_valid (ValidPaths paths) | not $ StringTable.prop_valid pathbits = error "TarIndex: bad string table" | not $ IntTrie.prop_lookup intpaths = error "TarIndex: bad int trie" | not $ IntTrie.prop_completions intpaths = error "TarIndex: bad int trie" | not $ prop' = error "TarIndex: bad prop" | otherwise = True where index@(TarIndex pathTable _ _) = finaliseIndex (IndexBuilder paths 0) pathbits = concatMap (FilePath.splitDirectories . fst) paths intpaths = [ (cids, offset) | (path, offset) <- paths , let Just cids = toComponentIds pathTable path ] prop' = flip all paths $ \(file, offset) -> case lookup index file of Just (TarFileEntry offset') -> offset' == offset _ -> False newtype NonEmptyFilePath = NonEmptyFilePath FilePath deriving Show instance Arbitrary NonEmptyFilePath where arbitrary = NonEmptyFilePath . FilePath.joinPath <$> listOf1 (elements ["a", "b", "c", "d"]) newtype ValidPaths = ValidPaths [(FilePath, TarEntryOffset)] deriving Show instance Arbitrary ValidPaths where arbitrary = ValidPaths . makeNoPrefix <$> listOf ((,) <$> arbitraryPath <*> arbitrary) where arbitraryPath = FilePath.joinPath <$> listOf1 (elements ["a", "b", "c", "d"]) makeNoPrefix [] = [] makeNoPrefix ((k,v):kvs) | all (\(k', _) -> not (isPrefixOfOther k k')) kvs = (k,v) : makeNoPrefix kvs | otherwise = makeNoPrefix kvs isPrefixOfOther a b = a `isPrefixOf` b || b `isPrefixOf` a example0 :: Entries () example0 = testEntry "foo-1.0/foo-1.0.cabal" 1500 -- at block 0 `Next` testEntry "foo-1.0/LICENSE" 2000 -- at block 4 `Next` testEntry "foo-1.0/Data/Foo.hs" 1000 -- at block 9 `Next` Done example1 :: Entries () example1 = Next (testEntry "./" 1500) Done <> example0 testEntry :: FilePath -> Int64 -> Entry testEntry name size = simpleEntry path (NormalFile mempty size) where Right path = toTarPath False name #endif #if !(MIN_VERSION_base(4,5,0)) (<>) :: Monoid m => m -> m -> m (<>) = mappend #endif
hvr/tar
Codec/Archive/Tar/Index.hs
bsd-3-clause
22,284
0
17
5,237
4,189
2,261
1,928
232
3
module Main where import Control.Concurrent.Chan (getChanContents, newChan) import Data.Monoid ((<>)) import Options.Applicative (Parser, argument, execParser, fullDesc, header, helper, info, many, metavar, progDesc, str) import System.Exit (exitSuccess) import System.FilePath (splitFileName, takeFileName) import System.FilePath.GlobPattern (GlobPattern, (~~)) import System.FSNotify (Event (..), eventPath, watchTreeChan, withManager) import System.IO (BufferMode (NoBuffering), hSetBuffering, stdout) data Options = Options { paths :: [FilePath] } main :: IO () main = do hSetBuffering stdout NoBuffering getOptions >>= runWatcher exitSuccess getOptions :: IO Options getOptions = execParser opts where opts = info (helper <*> optionsParser) ( fullDesc <> progDesc "Echoes the filenames of modified files to stdout, \ \one file per line." <> header "hobbes - a file activity monitor" ) optionsParser :: Parser Options optionsParser = Options <$> (many . argument str . metavar $ "PATHS..") runWatcher :: Options -> IO () runWatcher (Options ps) = withManager $ \m -> do chan <- newChan mapM_ (watchPath m chan) ps getChanContents chan >>= mapM_ printPath where watchPath manager chan path = let (dir, glob) = splitFileName path in watchTreeChan manager dir (globModified glob) chan globModified :: GlobPattern -> Event -> Bool globModified _ (Removed _ _) = False globModified glob evt = matchesGlob glob evt matchesGlob :: GlobPattern -> Event -> Bool matchesGlob glob = fileMatchesGlob glob . takeFileName . eventPath printPath :: Event -> IO () printPath = putStrLn . eventPath fileMatchesGlob :: GlobPattern -> FilePath -> Bool fileMatchesGlob "" _ = True fileMatchesGlob "." _ = True fileMatchesGlob glob fp = fp ~~ glob
astynax/hobbes
Hobbes.hs
bsd-3-clause
2,208
0
11
724
561
302
259
48
1