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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Tree relabelling example from chapter 12 of Programming in Haskell,
-- Graham Hutton, Cambridge University Press, 2016.
-- The state monad
type State = Int
newtype ST a = S (State -> (a,State))
app :: ST a -> State -> (a,State)
app (S st) x = st x
instance Functor ST where
-- fmap :: (a -> b) -> ST a -> ST b
fmap g st = S (\s -> let (x,s') = app st s in (g x, s'))
instance Applicative ST where
-- pure :: a -> ST a
pure x = S (\s -> (x,s))
-- (<*>) :: ST (a -> b) -> ST a -> ST b
stf <*> stx = S (\s ->
let (f,s') = app stf s
(x,s'') = app stx s' in (f x, s''))
instance Monad ST where
-- (>>=) :: ST a -> (a -> ST b) -> ST b
st >>= f = S (\s -> let (x,s') = app st s in app (f x) s')
-- Relabelling trees
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving Show
tree :: Tree Char
tree = Node (Node (Leaf 'a') (Leaf 'b')) (Leaf 'c')
rlabel :: Tree a -> Int -> (Tree Int, Int)
rlabel (Leaf _) n = (Leaf n, n+1)
rlabel (Node l r) n = (Node l' r', n'')
where
(l',n') = rlabel l n
(r',n'') = rlabel r n'
fresh :: ST Int
fresh = S (\n -> (n, n+1))
alabel :: Tree a -> ST (Tree Int)
alabel (Leaf _) = Leaf <$> fresh
alabel (Node l r) = Node <$> alabel l <*> alabel r
mlabel :: Tree a -> ST (Tree Int)
mlabel (Leaf _) = do n <- fresh
return (Leaf n)
mlabel (Node l r) = do l' <- mlabel l
r' <- mlabel r
return (Node l' r')
| thalerjonathan/phd | coding/learning/haskell/grahambook/Code_Solutions/relabel.hs | gpl-3.0 | 1,543 | 0 | 13 | 533 | 714 | 365 | 349 | 33 | 1 |
module Test.QuickFuzz.Gen.Media
( module Test.QuickFuzz.Gen.Media.Wav
) where
import Test.QuickFuzz.Gen.Media.Wav
| elopez/QuickFuzz | src/Test/QuickFuzz/Gen/Media.hs | gpl-3.0 | 115 | 0 | 5 | 10 | 27 | 20 | 7 | 3 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.InstallPlan
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : duncan@community.haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Package installation plan
--
-----------------------------------------------------------------------------
module Distribution.Client.InstallPlan (
InstallPlan,
ConfiguredPackage(..),
PlanPackage(..),
-- * Operations on 'InstallPlan's
new,
toList,
ready,
processing,
completed,
failed,
remove,
-- ** Query functions
planPlatform,
planCompiler,
-- * Checking validity of plans
valid,
closed,
consistent,
acyclic,
configuredPackageValid,
-- ** Details on invalid plans
PlanProblem(..),
showPlanProblem,
PackageProblem(..),
showPackageProblem,
problems,
configuredPackageProblems
) where
import Distribution.Client.Types
( SourcePackage(packageDescription), ConfiguredPackage(..)
, InstalledPackage, BuildFailure, BuildSuccess, enableStanzas )
import Distribution.Package
( PackageIdentifier(..), PackageName(..), Package(..), packageName
, PackageFixedDeps(..), Dependency(..) )
import Distribution.Version
( Version, withinRange )
import Distribution.PackageDescription
( GenericPackageDescription(genPackageFlags)
, Flag(flagName), FlagName(..) )
import Distribution.Client.PackageUtils
( externalBuildDepends )
import Distribution.PackageDescription.Configuration
( finalizePackageDescription )
import Distribution.Client.PackageIndex
( PackageIndex )
import qualified Distribution.Client.PackageIndex as PackageIndex
import Distribution.Text
( display )
import Distribution.System
( Platform )
import Distribution.Compiler
( CompilerId(..) )
import Distribution.Client.Utils
( duplicates, duplicatesBy, mergeBy, MergeResult(..) )
import Distribution.Simple.Utils
( comparing, intercalate )
import Data.List
( sort, sortBy )
import Data.Maybe
( fromMaybe )
import qualified Data.Graph as Graph
import Data.Graph (Graph)
import Control.Exception
( assert )
-- When cabal tries to install a number of packages, including all their
-- dependencies it has a non-trivial problem to solve.
--
-- The Problem:
--
-- In general we start with a set of installed packages and a set of source
-- packages.
--
-- Installed packages have fixed dependencies. They have already been built and
-- we know exactly what packages they were built against, including their exact
-- versions.
--
-- Source package have somewhat flexible dependencies. They are specified as
-- version ranges, though really they're predicates. To make matters worse they
-- have conditional flexible dependencies. Configuration flags can affect which
-- packages are required and can place additional constraints on their
-- versions.
--
-- These two sets of package can and usually do overlap. There can be installed
-- packages that are also available as source packages which means they could
-- be re-installed if required, though there will also be packages which are
-- not available as source and cannot be re-installed. Very often there will be
-- extra versions available than are installed. Sometimes we may like to prefer
-- installed packages over source ones or perhaps always prefer the latest
-- available version whether installed or not.
--
-- The goal is to calculate an installation plan that is closed, acyclic and
-- consistent and where every configured package is valid.
--
-- An installation plan is a set of packages that are going to be used
-- together. It will consist of a mixture of installed packages and source
-- packages along with their exact version dependencies. An installation plan
-- is closed if for every package in the set, all of its dependencies are
-- also in the set. It is consistent if for every package in the set, all
-- dependencies which target that package have the same version.
-- Note that plans do not necessarily compose. You might have a valid plan for
-- package A and a valid plan for package B. That does not mean the composition
-- is simultaneously valid for A and B. In particular you're most likely to
-- have problems with inconsistent dependencies.
-- On the other hand it is true that every closed sub plan is valid.
data PlanPackage = PreExisting InstalledPackage
| Configured ConfiguredPackage
| Processing ConfiguredPackage
| Installed ConfiguredPackage BuildSuccess
| Failed ConfiguredPackage BuildFailure
instance Package PlanPackage where
packageId (PreExisting pkg) = packageId pkg
packageId (Configured pkg) = packageId pkg
packageId (Processing pkg) = packageId pkg
packageId (Installed pkg _) = packageId pkg
packageId (Failed pkg _) = packageId pkg
instance PackageFixedDeps PlanPackage where
depends (PreExisting pkg) = depends pkg
depends (Configured pkg) = depends pkg
depends (Processing pkg) = depends pkg
depends (Installed pkg _) = depends pkg
depends (Failed pkg _) = depends pkg
data InstallPlan = InstallPlan {
planIndex :: PackageIndex PlanPackage,
planGraph :: Graph,
planGraphRev :: Graph,
planPkgOf :: Graph.Vertex -> PlanPackage,
planVertexOf :: PackageIdentifier -> Graph.Vertex,
planPlatform :: Platform,
planCompiler :: CompilerId
}
invariant :: InstallPlan -> Bool
invariant plan =
valid (planPlatform plan) (planCompiler plan) (planIndex plan)
internalError :: String -> a
internalError msg = error $ "InstallPlan: internal error: " ++ msg
-- | Build an installation plan from a valid set of resolved packages.
--
new :: Platform -> CompilerId -> PackageIndex PlanPackage
-> Either [PlanProblem] InstallPlan
new platform compiler index =
case problems platform compiler index of
[] -> Right InstallPlan {
planIndex = index,
planGraph = graph,
planGraphRev = Graph.transposeG graph,
planPkgOf = vertexToPkgId,
planVertexOf = fromMaybe noSuchPkgId . pkgIdToVertex,
planPlatform = platform,
planCompiler = compiler
}
where (graph, vertexToPkgId, pkgIdToVertex) =
PackageIndex.dependencyGraph index
noSuchPkgId = internalError "package is not in the graph"
probs -> Left probs
toList :: InstallPlan -> [PlanPackage]
toList = PackageIndex.allPackages . planIndex
-- | Remove packages from the install plan. This will result in an
-- error if there are remaining packages that depend on any matching
-- package. This is primarily useful for obtaining an install plan for
-- the dependencies of a package or set of packages without actually
-- installing the package itself, as when doing development.
--
remove :: (PlanPackage -> Bool)
-> InstallPlan
-> Either [PlanProblem] InstallPlan
remove shouldRemove plan =
new (planPlatform plan) (planCompiler plan) newIndex
where
newIndex = PackageIndex.fromList $
filter (not . shouldRemove) (toList plan)
-- | The packages that are ready to be installed. That is they are in the
-- configured state and have all their dependencies installed already.
-- The plan is complete if the result is @[]@.
--
ready :: InstallPlan -> [ConfiguredPackage]
ready plan = assert check readyPackages
where
check = if null readyPackages && null processingPackages
then null configuredPackages
else True
configuredPackages = [ pkg | Configured pkg <- toList plan ]
processingPackages = [ pkg | Processing pkg <- toList plan]
readyPackages = filter (all isInstalled . depends) configuredPackages
isInstalled pkg =
case PackageIndex.lookupPackageId (planIndex plan) pkg of
Just (Configured _) -> False
Just (Processing _) -> False
Just (Failed _ _) -> internalError depOnFailed
Just (PreExisting _) -> True
Just (Installed _ _) -> True
Nothing -> internalError incomplete
incomplete = "install plan is not closed"
depOnFailed = "configured package depends on failed package"
-- | Marks packages in the graph as currently processing (e.g. building).
--
-- * The package must exist in the graph and be in the configured state.
--
processing :: [ConfiguredPackage] -> InstallPlan -> InstallPlan
processing pkgs plan = assert (invariant plan') plan'
where
plan' = plan {
planIndex = PackageIndex.merge (planIndex plan) processingPkgs
}
processingPkgs = PackageIndex.fromList [Processing pkg | pkg <- pkgs]
-- | Marks a package in the graph as completed. Also saves the build result for
-- the completed package in the plan.
--
-- * The package must exist in the graph and be in the processing state.
-- * The package must have had no uninstalled dependent packages.
--
completed :: PackageIdentifier
-> BuildSuccess
-> InstallPlan -> InstallPlan
completed pkgid buildResult plan = assert (invariant plan') plan'
where
plan' = plan {
planIndex = PackageIndex.insert installed (planIndex plan)
}
installed = Installed (lookupProcessingPackage plan pkgid) buildResult
-- | Marks a package in the graph as having failed. It also marks all the
-- packages that depended on it as having failed.
--
-- * The package must exist in the graph and be in the processing
-- state.
--
failed :: PackageIdentifier -- ^ The id of the package that failed to install
-> BuildFailure -- ^ The build result to use for the failed package
-> BuildFailure -- ^ The build result to use for its dependencies
-> InstallPlan
-> InstallPlan
failed pkgid buildResult buildResult' plan = assert (invariant plan') plan'
where
plan' = plan {
planIndex = PackageIndex.merge (planIndex plan) failures
}
pkg = lookupProcessingPackage plan pkgid
failures = PackageIndex.fromList
$ Failed pkg buildResult
: [ Failed pkg' buildResult'
| Just pkg' <- map checkConfiguredPackage
$ packagesThatDependOn plan pkgid ]
-- | Lookup the reachable packages in the reverse dependency graph.
--
packagesThatDependOn :: InstallPlan
-> PackageIdentifier -> [PlanPackage]
packagesThatDependOn plan = map (planPkgOf plan)
. tail
. Graph.reachable (planGraphRev plan)
. planVertexOf plan
-- | Lookup a package that we expect to be in the processing state.
--
lookupProcessingPackage :: InstallPlan
-> PackageIdentifier -> ConfiguredPackage
lookupProcessingPackage plan pkgid =
case PackageIndex.lookupPackageId (planIndex plan) pkgid of
Just (Processing pkg) -> pkg
_ -> internalError $ "not in processing state or no such pkg " ++ display pkgid
-- | Check a package that we expect to be in the configured or failed state.
--
checkConfiguredPackage :: PlanPackage -> Maybe ConfiguredPackage
checkConfiguredPackage (Configured pkg) = Just pkg
checkConfiguredPackage (Failed _ _) = Nothing
checkConfiguredPackage pkg =
internalError $ "not configured or no such pkg " ++ display (packageId pkg)
-- ------------------------------------------------------------
-- * Checking valididy of plans
-- ------------------------------------------------------------
-- | A valid installation plan is a set of packages that is 'acyclic',
-- 'closed' and 'consistent'. Also, every 'ConfiguredPackage' in the
-- plan has to have a valid configuration (see 'configuredPackageValid').
--
-- * if the result is @False@ use 'problems' to get a detailed list.
--
valid :: Platform -> CompilerId -> PackageIndex PlanPackage -> Bool
valid platform comp index = null (problems platform comp index)
data PlanProblem =
PackageInvalid ConfiguredPackage [PackageProblem]
| PackageMissingDeps PlanPackage [PackageIdentifier]
| PackageCycle [PlanPackage]
| PackageInconsistency PackageName [(PackageIdentifier, Version)]
| PackageStateInvalid PlanPackage PlanPackage
showPlanProblem :: PlanProblem -> String
showPlanProblem (PackageInvalid pkg packageProblems) =
"Package " ++ display (packageId pkg)
++ " has an invalid configuration, in particular:\n"
++ unlines [ " " ++ showPackageProblem problem
| problem <- packageProblems ]
showPlanProblem (PackageMissingDeps pkg missingDeps) =
"Package " ++ display (packageId pkg)
++ " depends on the following packages which are missing from the plan "
++ intercalate ", " (map display missingDeps)
showPlanProblem (PackageCycle cycleGroup) =
"The following packages are involved in a dependency cycle "
++ intercalate ", " (map (display.packageId) cycleGroup)
showPlanProblem (PackageInconsistency name inconsistencies) =
"Package " ++ display name
++ " is required by several packages,"
++ " but they require inconsistent versions:\n"
++ unlines [ " package " ++ display pkg ++ " requires "
++ display (PackageIdentifier name ver)
| (pkg, ver) <- inconsistencies ]
showPlanProblem (PackageStateInvalid pkg pkg') =
"Package " ++ display (packageId pkg)
++ " is in the " ++ showPlanState pkg
++ " state but it depends on package " ++ display (packageId pkg')
++ " which is in the " ++ showPlanState pkg'
++ " state"
where
showPlanState (PreExisting _) = "pre-existing"
showPlanState (Configured _) = "configured"
showPlanState (Processing _) = "processing"
showPlanState (Installed _ _) = "installed"
showPlanState (Failed _ _) = "failed"
-- | For an invalid plan, produce a detailed list of problems as human readable
-- error messages. This is mainly intended for debugging purposes.
-- Use 'showPlanProblem' for a human readable explanation.
--
problems :: Platform -> CompilerId
-> PackageIndex PlanPackage -> [PlanProblem]
problems platform comp index =
[ PackageInvalid pkg packageProblems
| Configured pkg <- PackageIndex.allPackages index
, let packageProblems = configuredPackageProblems platform comp pkg
, not (null packageProblems) ]
++ [ PackageMissingDeps pkg missingDeps
| (pkg, missingDeps) <- PackageIndex.brokenPackages index ]
++ [ PackageCycle cycleGroup
| cycleGroup <- PackageIndex.dependencyCycles index ]
++ [ PackageInconsistency name inconsistencies
| (name, inconsistencies) <- PackageIndex.dependencyInconsistencies index ]
++ [ PackageStateInvalid pkg pkg'
| pkg <- PackageIndex.allPackages index
, Just pkg' <- map (PackageIndex.lookupPackageId index) (depends pkg)
, not (stateDependencyRelation pkg pkg') ]
-- | The graph of packages (nodes) and dependencies (edges) must be acyclic.
--
-- * if the result is @False@ use 'PackageIndex.dependencyCycles' to find out
-- which packages are involved in dependency cycles.
--
acyclic :: PackageIndex PlanPackage -> Bool
acyclic = null . PackageIndex.dependencyCycles
-- | An installation plan is closed if for every package in the set, all of
-- its dependencies are also in the set. That is, the set is closed under the
-- dependency relation.
--
-- * if the result is @False@ use 'PackageIndex.brokenPackages' to find out
-- which packages depend on packages not in the index.
--
closed :: PackageIndex PlanPackage -> Bool
closed = null . PackageIndex.brokenPackages
-- | An installation plan is consistent if all dependencies that target a
-- single package name, target the same version.
--
-- This is slightly subtle. It is not the same as requiring that there be at
-- most one version of any package in the set. It only requires that of
-- packages which have more than one other package depending on them. We could
-- actually make the condition even more precise and say that different
-- versions are ok so long as they are not both in the transitive closure of
-- any other package (or equivalently that their inverse closures do not
-- intersect). The point is we do not want to have any packages depending
-- directly or indirectly on two different versions of the same package. The
-- current definition is just a safe aproximation of that.
--
-- * if the result is @False@ use 'PackageIndex.dependencyInconsistencies' to
-- find out which packages are.
--
consistent :: PackageIndex PlanPackage -> Bool
consistent = null . PackageIndex.dependencyInconsistencies
-- | The states of packages have that depend on each other must respect
-- this relation. That is for very case where package @a@ depends on
-- package @b@ we require that @dependencyStatesOk a b = True@.
--
stateDependencyRelation :: PlanPackage -> PlanPackage -> Bool
stateDependencyRelation (PreExisting _) (PreExisting _) = True
stateDependencyRelation (Configured _) (PreExisting _) = True
stateDependencyRelation (Configured _) (Configured _) = True
stateDependencyRelation (Configured _) (Processing _) = True
stateDependencyRelation (Configured _) (Installed _ _) = True
stateDependencyRelation (Processing _) (PreExisting _) = True
stateDependencyRelation (Processing _) (Installed _ _) = True
stateDependencyRelation (Installed _ _) (PreExisting _) = True
stateDependencyRelation (Installed _ _) (Installed _ _) = True
stateDependencyRelation (Failed _ _) (PreExisting _) = True
-- failed can depends on configured because a package can depend on
-- several other packages and if one of the deps fail then we fail
-- but we still depend on the other ones that did not fail:
stateDependencyRelation (Failed _ _) (Configured _) = True
stateDependencyRelation (Failed _ _) (Processing _) = True
stateDependencyRelation (Failed _ _) (Installed _ _) = True
stateDependencyRelation (Failed _ _) (Failed _ _) = True
stateDependencyRelation _ _ = False
-- | A 'ConfiguredPackage' is valid if the flag assignment is total and if
-- in the configuration given by the flag assignment, all the package
-- dependencies are satisfied by the specified packages.
--
configuredPackageValid :: Platform -> CompilerId -> ConfiguredPackage -> Bool
configuredPackageValid platform comp pkg =
null (configuredPackageProblems platform comp pkg)
data PackageProblem = DuplicateFlag FlagName
| MissingFlag FlagName
| ExtraFlag FlagName
| DuplicateDeps [PackageIdentifier]
| MissingDep Dependency
| ExtraDep PackageIdentifier
| InvalidDep Dependency PackageIdentifier
showPackageProblem :: PackageProblem -> String
showPackageProblem (DuplicateFlag (FlagName flag)) =
"duplicate flag in the flag assignment: " ++ flag
showPackageProblem (MissingFlag (FlagName flag)) =
"missing an assignment for the flag: " ++ flag
showPackageProblem (ExtraFlag (FlagName flag)) =
"extra flag given that is not used by the package: " ++ flag
showPackageProblem (DuplicateDeps pkgids) =
"duplicate packages specified as selected dependencies: "
++ intercalate ", " (map display pkgids)
showPackageProblem (MissingDep dep) =
"the package has a dependency " ++ display dep
++ " but no package has been selected to satisfy it."
showPackageProblem (ExtraDep pkgid) =
"the package configuration specifies " ++ display pkgid
++ " but (with the given flag assignment) the package does not actually"
++ " depend on any version of that package."
showPackageProblem (InvalidDep dep pkgid) =
"the package depends on " ++ display dep
++ " but the configuration specifies " ++ display pkgid
++ " which does not satisfy the dependency."
configuredPackageProblems :: Platform -> CompilerId
-> ConfiguredPackage -> [PackageProblem]
configuredPackageProblems platform comp
(ConfiguredPackage pkg specifiedFlags stanzas specifiedDeps) =
[ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ]
++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ]
++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ]
++ [ DuplicateDeps pkgs
| pkgs <- duplicatesBy (comparing packageName) specifiedDeps ]
++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ]
++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ]
++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps
, not (packageSatisfiesDependency pkgid dep) ]
where
mergedFlags = mergeBy compare
(sort $ map flagName (genPackageFlags (packageDescription pkg)))
(sort $ map fst specifiedFlags)
mergedDeps = mergeBy
(\dep pkgid -> dependencyName dep `compare` packageName pkgid)
(sortBy (comparing dependencyName) requiredDeps)
(sortBy (comparing packageName) specifiedDeps)
packageSatisfiesDependency
(PackageIdentifier name version)
(Dependency name' versionRange) = assert (name == name') $
version `withinRange` versionRange
dependencyName (Dependency name _) = name
requiredDeps :: [Dependency]
requiredDeps =
--TODO: use something lower level than finalizePackageDescription
case finalizePackageDescription specifiedFlags
(const True)
platform comp
[]
(enableStanzas stanzas $ packageDescription pkg) of
Right (resolvedPkg, _) -> externalBuildDepends resolvedPkg
Left _ -> error "configuredPackageInvalidDeps internal error"
| jwiegley/ghc-release | libraries/Cabal/cabal-install/Distribution/Client/InstallPlan.hs | gpl-3.0 | 21,843 | 0 | 16 | 4,774 | 3,830 | 2,062 | 1,768 | 319 | 7 |
module Analysis.CriticalPairsSpec (spec) where
import Data.Matrix hiding ((<|>))
import Test.Hspec
import Abstract.Category
import Abstract.Rewriting.DPO
import Analysis.CriticalPairs
import Category.TypedGraphRule ()
import qualified XML.GGXReader as XML
fileName1 = "tests/grammars/teseRodrigo.ggx"
fileName2 = "tests/grammars/secondOrderMatchTest.ggx"
dpoConf :: Category morph => MorphismsConfig morph
dpoConf = MorphismsConfig monic
testCase findConflicts rules expected = show (pairwise (findConflicts dpoConf []) rules) `shouldBe` expected
spec :: Spec
spec = context "Critical Pairs Test" cpaTest
cpaTest :: Spec
cpaTest = do
describe "first-order" $ do
(gg1,_,_) <- runIO $ XML.readGrammar fileName1 False dpoConf
let rules = map snd (productions gg1)
it "delete-use" $
testCase findAllDeleteUse rules $
"( 2 0 0 0 0 0 0 0 )\n"++
"( 0 3 0 0 0 0 0 0 )\n"++
"( 0 2 6 0 0 0 0 0 )\n"++
"( 0 0 0 1 0 0 0 0 )\n"++
"( 0 0 1 0 4 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"
it "produce-dangling" $
testCase findAllProduceDangling rules $
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 1 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"
it "delete-use and produce-dangling" $
testCase findAllDeleteUseAndProduceDangling rules $
"( 2 0 0 0 0 0 0 0 )\n"++
"( 0 3 0 0 0 0 0 0 )\n"++
"( 0 2 6 0 1 0 0 0 )\n"++
"( 0 0 0 1 0 0 0 0 )\n"++
"( 0 0 1 0 4 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"
it "produce-forbid" $
testCase findAllProduceForbid rules $
"( 0 0 0 0 0 0 0 0 )\n"++
"( 2 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 1 0 0 )\n"
describe "second-order" $ do
(_,gg2,_) <- runIO $ XML.readGrammar fileName2 False dpoConf
let rules = map snd (productions gg2)
it "delete-use" $
testCase findAllDeleteUse rules $
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 5 0 0 )\n"++
"( 0 0 0 3 0 )\n"++
"( 0 0 0 0 3 )\n"
it "produce-dangling" $
testCase findAllProduceDangling rules $
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"
it "delete-use and produce-dangling" $
testCase findAllDeleteUseAndProduceDangling rules $
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 5 0 0 )\n"++
"( 0 0 0 3 0 )\n"++
"( 0 0 0 0 3 )\n"
it "produce-forbid" $
testCase findAllProduceForbid rules $
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"++
"( 0 0 0 0 0 )\n"
pairwise :: (a -> a -> [b]) -> [a] -> Matrix Int
pairwise f items =
matrix (length items) (length items) $ \(i,j) ->
length (f (items !! (i-1)) (items !! (j-1)))
| rodrigo-machado/verigraph | tests/Analysis/CriticalPairsSpec.hs | gpl-3.0 | 3,609 | 0 | 19 | 1,468 | 718 | 360 | 358 | 95 | 1 |
{-# LANGUAGE RankNTypes, NoMonomorphismRestriction, ScopedTypeVariables #-}
module CoqTop
( coqtop
, coqtopRaw
) where
import Prelude hiding (catch)
import System.IO
import System.Process
import Control.Concurrent (forkIO, killThread)
import Control.Concurrent.Chan
import Control.Concurrent.MVar
import Control.Exception
import Text.XML.Light.Input
import Text.XML.Light
import Data.List.Split
-- You'll need ezyang's private copy of Coq https://github.com/ezyang/coq
coqtopProcess :: String -> Handle -> CreateProcess
coqtopProcess theory err = CreateProcess
{ cmdspec = RawCommand "coqtop"
[ "-boot"
, "-l"
, theory ++ ".v"
, "-pgip"]
, cwd = Nothing
, env = Nothing
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = UseHandle err
, close_fds = False
, create_group = False
}
onlyOnce :: IO () -> IO (IO ())
onlyOnce m = do
i <- newMVar m
return (modifyMVar_ i (\x -> x >> return (return ())))
coqtopRaw :: String -> IO (String -> IO [Content], IO ())
coqtopRaw theory = do
--hPutStrLn stderr "Starting up coqtop..."
-- XXX We're not really doing good things with warnings.
-- Fortunately, fatal errors DO get put on stdout.
err <- openFile "/dev/null" WriteMode -- XXX gimme a platform independent version!
(Just fin, Just fout, _, pid) <- createProcess (coqtopProcess theory err)
hSetBuffering fin LineBuffering
hSetBuffering fout LineBuffering -- should be good enough to pick up on <ready/>
resultChan <- newChan
-- XXX do we really want to give them the <ready/> marker? (elim
-- keepDelimsR if not)
tout <- forkIO $
-- Lazy IO at its finest
let p (Elem e) | qName (elName e) == "ready" = True
p _ = False
in writeList2Chan resultChan . split (keepDelimsR (whenElt p)) =<< parseXML `fmap` hGetContents fout
_ <- readChan resultChan -- read out the intro message
--hPutStrLn stderr "Ready coqtop"
-- XXX this doesn't do particularly good things if you don't
-- pass it enough information. Correct thing to do is on COQ
-- side say "I want more information!" Nor does it do good things
-- if you give it too much information... (de-synchronization risk)
interactVar <- newMVar (\s -> {- hPutStrLn stderr s >> -} hPutStr fin (s ++ ".\n") >> readChan resultChan)
let run s = withMVar interactVar (\f -> f s)
end <- onlyOnce $ do
-- hPutStrLn stderr "Closing coqtop..."
killThread tout
hClose fin
hClose fout
hClose err
m <- getProcessExitCode pid
maybe (terminateProcess pid) (const (return ())) m
-- We're erring on the safe side here. If no escape of coqtop
-- from bracket is enforced, this is impossible
modifyMVar_ interactVar (\_ -> return (error "coqtopRaw/end: coqtop is dead"))
return (run, end)
coqtop :: String -> ((String -> IO [Content]) -> IO a) -> IO a
coqtop theory inner = bracket (coqtopRaw theory) snd (inner . fst)
| diflying/logitext | CoqTop.hs | bsd-3-clause | 3,124 | 0 | 19 | 822 | 738 | 383 | 355 | 57 | 2 |
{-# LANGUAGE Haskell98, BangPatterns #-}
{-# LINE 1 "Data/ByteString/Search/BoyerMoore.hs" #-}
-- |
-- Module : Data.ByteString.Search.BoyerMoore
-- Copyright : Daniel Fischer
-- Chris Kuklewicz
-- Licence : BSD3
-- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast overlapping Boyer-Moore search of both strict and lazy
-- 'ByteString' values.
--
-- Descriptions of the algorithm can be found at
-- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140>
-- and
-- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm>
--
-- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and
-- Chris Kuklewicz (haskell at list.mightyreason.com).
module Data.ByteString.Search.BoyerMoore
{-# DEPRECATED "Use the new interface instead" #-} (
-- * Overview
-- $overview
-- ** Changes
-- $changes
-- ** Deprecation
-- $deprecation
-- ** Parameter and return types
-- $types
-- ** Lazy ByteStrings
-- $lazy
-- ** Performance
-- $performance
-- ** Complexity
-- $complexity
-- ** Partial application
-- $currying
-- ** Integer overflow
-- $overflow
-- * Functions
matchLL
, matchLS
, matchSL
, matchSS
) where
import Data.ByteString.Search.Internal.BoyerMoore
(matchLS, matchSS)
import Data.ByteString.Lazy.Search.Internal.BoyerMoore
(matchLL, matchSL)
-- $overview
--
-- This module exists only for backwards compatibility. Nevertheless
-- there have been small changes in the behaviour of the functions.
-- The module exports four search functions: 'matchLL', 'matchLS',
-- 'matchSL', and 'matchSS'. All of them return the list of all
-- starting positions of possibly overlapping occurrences of a pattern
-- in a string.
-- $changes
--
-- Formerly, all four functions returned an empty list when passed
-- an empty pattern. Now, in accordance with the functions from the other
-- modules, @matchXY \"\" target = [0 .. 'length' target]@.
-- $deprecation
--
-- This module is /deprecated/. You should use the new interface provided
-- in "Data.ByteString.Search" resp. "Data.ByteString.Lazy.Search".
-- $types
--
-- The first parameter is always the pattern string. The second
-- parameter is always the target string to be searched. The returned
-- list contains the offsets of all /overlapping/ patterns.
--
-- A returned @Int@ or @Int64@ is an index into the target string
-- which is aligned to the head of the pattern string. Strict targets
-- return @Int@ indices and lazy targets return @Int64@ indices. All
-- returned lists are computed and returned in a lazy fashion.
-- $lazy
--
-- 'matchLL' and 'matchLS' take lazy bytestrings as patterns. For
-- performance, if the pattern is not a single strict chunk then all
-- the the pattern chunks will copied into a concatenated strict
-- bytestring. This limits the patterns to a length of (maxBound ::
-- Int).
--
-- 'matchLL' and 'matchSL' take lazy bytestrings as targets.
-- These are written so that while they work they will not retain a
-- reference to all the earlier parts of the the lazy bytestring.
-- This means the garbage collector would be able to keep only a small
-- amount of the target string and free the rest.
-- $currying
--
-- These functions can all be usefully partially applied.
-- Given only a pattern the partially applied version will compute
-- the supporting lookup tables only once, allowing for efficient re-use.
-- Similarly, the partially applied 'matchLL' and 'matchLS' will compute
-- the concatenated pattern only once.
-- $performance
--
-- In general, the Boyer-Moore algorithm is the most efficient method to
-- search for a pattern inside a string. The advantage over other algorithms
-- (e.g. Naïve, Knuth-Morris-Pratt, Horspool, Sunday) can be made
-- arbitrarily large for specially selected patterns and targets, but
-- usually, it's a factor of 2–3 versus Knuth-Morris-Pratt and of
-- 6–10 versus the naïve algorithm. The Horspool and Sunday
-- algorithms, which are simplified variants of the Boyer-Moore algorithm,
-- typically have performance between Boyer-Moore and Knuth-Morris-Pratt,
-- mostly closer to Boyer-Moore. The advantage of the Boyer-moore variants
-- over other algorithms generally becomes larger for longer patterns. For
-- very short patterns (or patterns with a very short period), other
-- algorithms, e.g. "Data.ByteString.Search.DFA" can be faster (my
-- tests suggest that \"very short\" means two, maybe three bytes).
--
-- In general, searching in a strict 'S.ByteString' is slightly faster
-- than searching in a lazy 'L.ByteString', but for long targets the
-- smaller memory footprint of lazy 'L.ByteStrings' can make searching
-- those (sometimes much) faster. On the other hand, there are cases
-- where searching in a strict target is much faster, even for long targets.
--
-- On 32-bit systems, 'Int'-arithmetic is much faster than 'Int64'-arithmetic,
-- so when there are many matches, that can make a significant difference.
--
-- Also, the modification to ameliorate the case of periodic patterns
-- is defeated by chunk-boundaries, so long patterns with a short period
-- and many matches exhibit poor behaviour (consider using @indices@ from
-- "Data.ByteString.Lazy.Search.DFA" or "Data.ByteString.Lazy.Search.KMP"
-- in those cases, the former for medium-length patterns, the latter for
-- long patterns; only 'matchLL' and 'matchSL' suffer from
-- this problem, though).
-- $complexity
--
-- Preprocessing the pattern string is O(@patternLength@). The search
-- performance is O(@targetLength@\/@patternLength@) in the best case,
-- allowing it to go faster than a Knuth-Morris-Pratt algorithm. With
-- a non-periodic pattern the worst case uses O(3\*@targetLength@)
-- comparisons. The periodic pattern worst case is quadratic
-- O(@targetLength@\*@patternLength@) complexity for the original
-- Boyer-Moore algorithm.
--
-- The searching functions in this module contain a modification which
-- drastically improves the performance for periodic patterns.
-- I believe that for strict target strings, the worst case is now
-- /O/(@targetLength@) also for periodic patterns and for lazy target
-- strings, my semi-educated guess is
-- /O/(@targetLength@ * (1 + @patternLength@ \/ @chunkSize@)).
-- $overflow
--
-- The current code uses @Int@ to keep track of the locations in the
-- target string. If the length of the pattern plus the length of any
-- strict chunk of the target string is greater or equal to
-- @'maxBound'::Int@ then this will overflow causing an error. We try
-- to detect this and call 'error' before a segfault occurs.
| phischu/fragnix | tests/packages/scotty/Data.ByteString.Search.BoyerMoore.hs | bsd-3-clause | 7,728 | 0 | 5 | 2,092 | 198 | 181 | 17 | 12 | 0 |
-- | This module provides quickcheck utilities, e.g. arbitrary and show
-- instances, and comparison functions, so we can focus on the actual properties
-- in the 'Tests.Properties' module.
--
{-# LANGUAGE CPP, FlexibleInstances, TypeSynonymInstances, GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Tests.QuickCheckUtils
(
genUnicode
, unsquare
, smallArbitrary
, BigBounded(..)
, BigInt(..)
, NotEmpty(..)
, Small(..)
, small
, Precision(..)
, precision
, integralRandomR
-- , DecodeErr(..)
-- , genDecodeErr
, Stringy(..)
, eq
, eqP
, Encoding(..)
, write_read
) where
import Control.Applicative ((<$>))
import Control.Arrow (first, (***))
import Control.DeepSeq (NFData (..), deepseq)
import Control.Exception (bracket)
import Data.String (IsString, fromString)
-- import Data.Text.Foreign (I16)
-- import Data.Text.Lazy.Builder.RealFloat (FPFormat(..))
import Data.JSString.RealFloat (FPFormat(..))
import Data.Word (Word8, Word16)
import Debug.Trace (trace)
import System.Random (Random(..), RandomGen)
import Test.QuickCheck hiding (Fixed(..), Small (..), (.&.))
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import Test.QuickCheck.Unicode (string)
import Tests.Utils
import qualified Data.JSString as J
import qualified Data.JSString.Internal.Fusion as JF
import qualified Data.JSString.Internal.Fusion.Common as JF
import qualified Data.ByteString as B
import qualified System.IO as IO
genUnicode :: IsString a => Gen a
genUnicode = fromString <$> string
-- | A type representing a number of UTF-16 code units.
newtype I16 = I16 Int
deriving (Bounded, Enum, Eq, Integral, Num, Ord, Read, Real, Show)
instance Random I16 where
randomR = integralRandomR
random = randomR (minBound,maxBound)
instance Arbitrary I16 where
arbitrary = arbitrarySizedIntegral
shrink = shrinkIntegral
instance Arbitrary B.ByteString where
arbitrary = B.pack `fmap` arbitrary
shrink = map B.pack . shrink . B.unpack
-- For tests that have O(n^2) running times or input sizes, resize
-- their inputs to the square root of the originals.
unsquare :: (Arbitrary a, Show a, Testable b) => (a -> b) -> Property
unsquare = forAll smallArbitrary
smallArbitrary :: (Arbitrary a, Show a) => Gen a
smallArbitrary = sized $ \n -> resize (smallish n) arbitrary
where smallish = round . (sqrt :: Double -> Double) . fromIntegral . abs
instance Arbitrary J.JSString where
arbitrary = J.pack `fmap` arbitrary
shrink = map J.pack . shrink . J.unpack
newtype BigInt = Big Integer
deriving (Eq, Show)
instance Arbitrary BigInt where
arbitrary = choose (1::Int,200) >>= \e -> Big <$> choose (10^(e-1),10^e)
shrink (Big a) = [Big (a `div` 2^(l-e)) | e <- shrink l]
where l = truncate (log (fromIntegral a) / log 2 :: Double) :: Integer
newtype BigBounded a = BigBounded a
deriving (Eq, Show)
instance (Bounded a, Random a, Arbitrary a) => Arbitrary (BigBounded a) where
arbitrary = BigBounded <$> choose (minBound, maxBound)
newtype NotEmpty a = NotEmpty { notEmpty :: a }
deriving (Eq, Ord)
instance Show a => Show (NotEmpty a) where
show (NotEmpty a) = show a
instance Functor NotEmpty where
fmap f (NotEmpty a) = NotEmpty (f a)
instance Arbitrary a => Arbitrary (NotEmpty [a]) where
arbitrary = sized (\n -> NotEmpty `fmap` (choose (1,n+1) >>= vector))
shrink = shrinkNotEmpty null
instance Arbitrary (NotEmpty J.JSString) where
arbitrary = (fmap J.pack) `fmap` arbitrary
shrink = shrinkNotEmpty J.null
instance Arbitrary (NotEmpty B.ByteString) where
arbitrary = (fmap B.pack) `fmap` arbitrary
shrink = shrinkNotEmpty B.null
shrinkNotEmpty :: Arbitrary a => (a -> Bool) -> NotEmpty a -> [NotEmpty a]
shrinkNotEmpty isNull (NotEmpty xs) =
[ NotEmpty xs' | xs' <- shrink xs, not (isNull xs') ]
data Small = S0 | S1 | S2 | S3 | S4 | S5 | S6 | S7
| S8 | S9 | S10 | S11 | S12 | S13 | S14 | S15
| S16 | S17 | S18 | S19 | S20 | S21 | S22 | S23
| S24 | S25 | S26 | S27 | S28 | S29 | S30 | S31
deriving (Eq, Ord, Enum, Bounded)
small :: Integral a => Small -> a
small = fromIntegral . fromEnum
intf :: (Int -> Int -> Int) -> Small -> Small -> Small
intf f a b = toEnum ((fromEnum a `f` fromEnum b) `mod` 32)
instance Show Small where
show = show . fromEnum
instance Read Small where
readsPrec n = map (first toEnum) . readsPrec n
instance Num Small where
fromInteger = toEnum . fromIntegral
signum _ = 1
abs = id
(+) = intf (+)
(-) = intf (-)
(*) = intf (*)
instance Real Small where
toRational = toRational . fromEnum
instance Integral Small where
toInteger = toInteger . fromEnum
quotRem a b = (toEnum x, toEnum y)
where (x, y) = fromEnum a `quotRem` fromEnum b
instance Random Small where
randomR = integralRandomR
random = randomR (minBound,maxBound)
instance Arbitrary Small where
arbitrary = choose (minBound, maxBound)
shrink = shrinkIntegral
integralRandomR :: (Integral a, RandomGen g) => (a,a) -> g -> (a,g)
integralRandomR (a,b) g = case randomR (fromIntegral a :: Integer,
fromIntegral b :: Integer) g of
(x,h) -> (fromIntegral x, h)
{-
data DecodeErr = Lenient | Ignore | Strict | Replace
deriving (Show, Eq)
genDecodeErr :: DecodeErr -> Gen J.OnDecodeError
genDecodeErr Lenient = return J.lenientDecode
genDecodeErr Ignore = return J.ignore
genDecodeErr Strict = return J.strictDecode
genDecodeErr Replace = arbitrary
instance Arbitrary DecodeErr where
arbitrary = elements [Lenient, Ignore, Strict, Replace]
-}
class Stringy s where
packS :: String -> s
unpackS :: s -> String
splitAtS :: Int -> s -> (s,s)
packSChunkSize :: Int -> String -> s
packSChunkSize _ = packS
instance Stringy String where
packS = id
unpackS = id
splitAtS = splitAt
instance Stringy (JF.Stream Char) where
packS = JF.streamList
unpackS = JF.unstreamList
splitAtS n s = (JF.take n s, JF.drop n s)
instance Stringy J.JSString where
packS = J.pack
unpackS = J.unpack
splitAtS = J.splitAt
-- Do two functions give the same answer?
eq :: (Eq a, Show a) => (t -> a) -> (t -> a) -> t -> Bool
eq a b s = a s =^= b s
-- What about with the RHS packed?
eqP :: (Eq a, Show a, Stringy s) =>
(String -> a) -> (s -> a) -> String -> Word8 -> Bool
eqP f g s w = eql "orig" (f s) (g t) &&
eql "mini" (f s) (g mini) &&
eql "head" (f sa) (g ta) &&
eql "tail" (f sb) (g tb)
where t = packS s
mini = packSChunkSize 10 s
(sa,sb) = splitAt m s
(ta,tb) = splitAtS m t
l = length s
m | l == 0 = n
| otherwise = n `mod` l
n = fromIntegral w
eql d a b
| a =^= b = True
| otherwise = trace (d ++ ": " ++ show a ++ " /= " ++ show b) False
instance Arbitrary FPFormat where
arbitrary = elements [Exponent, Fixed, Generic]
newtype Precision a = Precision (Maybe Int)
deriving (Eq, Show)
precision :: a -> Precision a -> Maybe Int
precision _ (Precision prec) = prec
arbitraryPrecision :: Int -> Gen (Precision a)
arbitraryPrecision maxDigits = Precision <$> do
n <- choose (-1,maxDigits)
return $ if n == -1
then Nothing
else Just n
instance Arbitrary (Precision Float) where
arbitrary = arbitraryPrecision 11
shrink = map Precision . shrink . precision undefined
instance Arbitrary (Precision Double) where
arbitrary = arbitraryPrecision 22
shrink = map Precision . shrink . precision undefined
-- Work around lack of Show instance for TextEncoding.
data Encoding = E String IO.TextEncoding
instance Show Encoding where show (E n _) = "utf" ++ n
instance Arbitrary Encoding where
arbitrary = oneof . map return $
[ E "8" IO.utf8, E "8_bom" IO.utf8_bom, E "16" IO.utf16
, E "16le" IO.utf16le, E "16be" IO.utf16be, E "32" IO.utf32
, E "32le" IO.utf32le, E "32be" IO.utf32be
]
windowsNewlineMode :: IO.NewlineMode
windowsNewlineMode = IO.NewlineMode
{ IO.inputNL = IO.CRLF, IO.outputNL = IO.CRLF
}
instance Arbitrary IO.NewlineMode where
arbitrary = oneof . map return $
[ IO.noNewlineTranslation, IO.universalNewlineMode, IO.nativeNewlineMode
, windowsNewlineMode
]
instance Arbitrary IO.BufferMode where
arbitrary = oneof [ return IO.NoBuffering,
return IO.LineBuffering,
return (IO.BlockBuffering Nothing),
(IO.BlockBuffering . Just . (+1) . fromIntegral) `fmap`
(arbitrary :: Gen Word16) ]
-- This test harness is complex! What property are we checking?
--
-- Reading after writing a multi-line file should give the same
-- results as were written.
--
-- What do we vary while checking this property?
-- * The lines themselves, scrubbed to contain neither CR nor LF. (By
-- working with a list of lines, we ensure that the data will
-- sometimes contain line endings.)
-- * Encoding.
-- * Newline translation mode.
-- * Buffering.
write_read :: (NFData a, Eq a)
=> ([b] -> a)
-> ((Char -> Bool) -> a -> b)
-> (IO.Handle -> a -> IO ())
-> (IO.Handle -> IO a)
-> Encoding
-> IO.NewlineMode
-> IO.BufferMode
-> [a]
-> Property
write_read unline filt writer reader (E _ _) nl buf ts =
monadicIO $ assert . (==t) =<< run act
where t = unline . map (filt (not . (`elem` "\r\n"))) $ ts
act = withTempFile $ \path h -> do
-- hSetEncoding h enc
IO.hSetNewlineMode h nl
IO.hSetBuffering h buf
() <- writer h t
IO.hClose h
bracket (IO.openFile path IO.ReadMode) IO.hClose $ \h' -> do
-- hSetEncoding h' enc
IO.hSetNewlineMode h' nl
IO.hSetBuffering h' buf
r <- reader h'
r `deepseq` return r
| ghcjs/ghcjs-base | test/Tests/QuickCheckUtils.hs | mit | 10,416 | 0 | 16 | 2,888 | 3,268 | 1,787 | 1,481 | 221 | 2 |
module Foo where
-- | Some documentation
foo :: Int
foo = 23
| snoyberg/doctest-haskell | test/extract/declaration/Foo.hs | mit | 62 | 0 | 4 | 14 | 15 | 10 | 5 | 3 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, ScopedTypeVariables #-}
-- provides Arbitrary instance for Pandoc types
-- from https://github.com/jgm/pandoc/blob/master/tests/Tests/Arbitrary.hs
module Tests.Arbitrary ()
where
import Test.QuickCheck.Gen
import Test.QuickCheck.Arbitrary
import Control.Monad (liftM, liftM2)
import Text.Pandoc.Definition
import Text.Pandoc.Shared (normalize, escapeURI)
import Text.Pandoc.Builder
realString :: Gen String
realString = resize 8 $ listOf $ frequency [ (9, elements [' '..'\127'])
, (1, elements ['\128'..'\9999']) ]
arbAttr :: Gen Attr
arbAttr = do
id' <- elements ["","loc"]
classes <- elements [[],["haskell"],["c","numberLines"]]
keyvals <- elements [[],[("start","22")],[("a","11"),("b_2","a b c")]]
return (id',classes,keyvals)
instance Arbitrary Inlines where
arbitrary = liftM (fromList :: [Inline] -> Inlines) arbitrary
instance Arbitrary Blocks where
arbitrary = liftM (fromList :: [Block] -> Blocks) arbitrary
instance Arbitrary Inline where
arbitrary = resize 3 $ arbInline 2
arbInlines :: Int -> Gen [Inline]
arbInlines n = listOf1 (arbInline n) `suchThat` (not . startsWithSpace)
where startsWithSpace (Space:_) = True
startsWithSpace _ = False
-- restrict to 3 levels of nesting max; otherwise we get
-- bogged down in indefinitely large structures
arbInline :: Int -> Gen Inline
arbInline n = frequency $ [ (60, liftM Str realString)
, (60, return Space)
, (10, liftM2 Code arbAttr realString)
, (5, elements [ RawInline (Format "html") "<a id=\"eek\">"
, RawInline (Format "latex") "\\my{command}" ])
] ++ [ x | x <- nesters, n > 1]
where nesters = [ (10, liftM Emph $ arbInlines (n-1))
, (10, liftM Strong $ arbInlines (n-1))
, (10, liftM Strikeout $ arbInlines (n-1))
, (10, liftM Superscript $ arbInlines (n-1))
, (10, liftM Subscript $ arbInlines (n-1))
, (10, liftM SmallCaps $ arbInlines (n-1))
, (10, do x1 <- arbitrary
x2 <- arbInlines (n-1)
return $ Quoted x1 x2)
, (10, do x1 <- arbitrary
x2 <- realString
return $ Math x1 x2)
, (10, do x1 <- arbInlines (n-1)
x3 <- realString
x2 <- liftM escapeURI realString
return $ Link x1 (x2,x3))
, (10, do x1 <- arbInlines (n-1)
x3 <- realString
x2 <- liftM escapeURI realString
return $ Image x1 (x2,x3))
, (2, liftM2 Cite arbitrary (arbInlines 1))
, (2, liftM Note $ resize 3 $ listOf1 $ arbBlock (n-1))
]
instance Arbitrary Block where
arbitrary = resize 3 $ arbBlock 2
arbBlock :: Int -> Gen Block
arbBlock n = frequency $ [ (10, liftM Plain $ arbInlines (n-1))
, (15, liftM Para $ arbInlines (n-1))
, (5, liftM2 CodeBlock arbAttr realString)
, (2, elements [ RawBlock (Format "html")
"<div>\n*&*\n</div>"
, RawBlock (Format "latex")
"\\begin[opt]{env}\nhi\n{\\end{env}"
])
, (5, do x1 <- choose (1 :: Int, 6)
x2 <- arbInlines (n-1)
return (Header x1 nullAttr x2))
, (2, return HorizontalRule)
] ++ [x | x <- nesters, n > 0]
where nesters = [ (5, liftM BlockQuote $ listOf1 $ arbBlock (n-1))
, (5, do x2 <- arbitrary
x3 <- arbitrary
x1 <- arbitrary `suchThat` (> 0)
x4 <- listOf1 $ listOf1 $ arbBlock (n-1)
return $ OrderedList (x1,x2,x3) x4 )
, (5, liftM BulletList $ (listOf1 $ listOf1 $ arbBlock (n-1)))
, (5, do items <- listOf1 $ do
x1 <- listOf1 $ listOf1 $ arbBlock (n-1)
x2 <- arbInlines (n-1)
return (x2,x1)
return $ DefinitionList items)
, (2, do rs <- choose (1 :: Int, 4)
cs <- choose (1 :: Int, 4)
x1 <- arbInlines (n-1)
x2 <- vector cs
x3 <- vectorOf cs $ elements [0, 0.25]
x4 <- vectorOf cs $ listOf $ arbBlock (n-1)
x5 <- vectorOf rs $ vectorOf cs
$ listOf $ arbBlock (n-1)
return (Table x1 x2 x3 x4 x5))
]
instance Arbitrary Pandoc where
arbitrary = resize 8 $ liftM normalize
$ liftM2 Pandoc arbitrary arbitrary
instance Arbitrary CitationMode where
arbitrary
= do x <- choose (0 :: Int, 2)
case x of
0 -> return AuthorInText
1 -> return SuppressAuthor
2 -> return NormalCitation
_ -> error "FATAL ERROR: Arbitrary instance, logic bug"
instance Arbitrary Citation where
arbitrary
= do x1 <- listOf $ elements $ ['a'..'z'] ++ ['0'..'9'] ++ ['_']
x2 <- arbInlines 1
x3 <- arbInlines 1
x4 <- arbitrary
x5 <- arbitrary
x6 <- arbitrary
return (Citation x1 x2 x3 x4 x5 x6)
instance Arbitrary MathType where
arbitrary
= do x <- choose (0 :: Int, 1)
case x of
0 -> return DisplayMath
1 -> return InlineMath
_ -> error "FATAL ERROR: Arbitrary instance, logic bug"
instance Arbitrary QuoteType where
arbitrary
= do x <- choose (0 :: Int, 1)
case x of
0 -> return SingleQuote
1 -> return DoubleQuote
_ -> error "FATAL ERROR: Arbitrary instance, logic bug"
instance Arbitrary Meta where
arbitrary
= do (x1 :: Inlines) <- arbitrary
(x2 :: [Inlines]) <- liftM (filter (not . isNull)) arbitrary
(x3 :: Inlines) <- arbitrary
return $ setMeta "title" x1
$ setMeta "author" x2
$ setMeta "date" x3
$ nullMeta
instance Arbitrary Alignment where
arbitrary
= do x <- choose (0 :: Int, 3)
case x of
0 -> return AlignLeft
1 -> return AlignRight
2 -> return AlignCenter
3 -> return AlignDefault
_ -> error "FATAL ERROR: Arbitrary instance, logic bug"
instance Arbitrary ListNumberStyle where
arbitrary
= do x <- choose (0 :: Int, 6)
case x of
0 -> return DefaultStyle
1 -> return Example
2 -> return Decimal
3 -> return LowerRoman
4 -> return UpperRoman
5 -> return LowerAlpha
6 -> return UpperAlpha
_ -> error "FATAL ERROR: Arbitrary instance, logic bug"
instance Arbitrary ListNumberDelim where
arbitrary
= do x <- choose (0 :: Int, 3)
case x of
0 -> return DefaultDelim
1 -> return Period
2 -> return OneParen
3 -> return TwoParens
_ -> error "FATAL ERROR: Arbitrary instance, logic bug"
| guoy34/ampersand | src/Database/Design/Ampersand/Test/Parser/ArbitraryPandoc.hs | gpl-3.0 | 8,331 | 0 | 19 | 3,705 | 2,376 | 1,216 | 1,160 | 166 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module SDL.Init
( initialize
, initializeAll
, InitFlag(..)
, quit
, version
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Bitmask (foldFlags)
import Data.Data (Data)
import Data.Typeable
import Data.Word
import Foreign.Marshal.Alloc
import Foreign.Storable
import GHC.Generics
import SDL.Exception
import SDL.Internal.Numbered
import qualified SDL.Raw as Raw
#if !MIN_VERSION_base(4,8,0)
import Data.Foldable
#endif
{-# DEPRECATED InitEverything "Instead of initialize [InitEverything], use initializeAll" #-}
data InitFlag
= InitTimer
| InitAudio
| InitVideo
| InitJoystick
| InitHaptic
| InitGameController
| InitEvents
| InitEverything
deriving (Bounded, Data, Enum, Eq, Generic, Ord, Read, Show, Typeable)
instance ToNumber InitFlag Word32 where
toNumber InitTimer = Raw.SDL_INIT_TIMER
toNumber InitAudio = Raw.SDL_INIT_AUDIO
toNumber InitVideo = Raw.SDL_INIT_VIDEO
toNumber InitJoystick = Raw.SDL_INIT_JOYSTICK
toNumber InitHaptic = Raw.SDL_INIT_HAPTIC
toNumber InitGameController = Raw.SDL_INIT_GAMECONTROLLER
toNumber InitEvents = Raw.SDL_INIT_EVENTS
toNumber InitEverything = Raw.SDL_INIT_EVERYTHING
-- | Initializes SDL and the given subsystems. Do not call any SDL functions
-- prior to this one, unless otherwise documented that you may do so.
--
-- You may call this function again with additional subsystems to initialize.
--
-- Throws 'SDLEx.SDLException' if initialization fails.
initialize :: (Foldable f, Functor m, MonadIO m) => f InitFlag -> m ()
initialize flags =
throwIfNeg_ "SDL.Init.init" "SDL_Init" $
Raw.init (foldFlags toNumber flags)
-- | Equivalent to @'initialize' ['minBound' .. 'maxBound']@.
initializeAll :: (Functor m, MonadIO m) => m ()
initializeAll = initialize [minBound .. maxBound]
-- | Quit and shutdown SDL, freeing any resources that may have been in use.
-- Do not call any SDL functions after you've called this function, unless
-- otherwise documented that you may do so.
quit :: MonadIO m => m ()
quit = Raw.quit
-- | The major, minor, and patch versions of the SDL library linked with.
-- Does not require initialization.
version :: (Integral a, MonadIO m) => m (a, a, a)
version = liftIO $ do
Raw.Version major minor patch <- alloca $ \v -> Raw.getVersion v >> peek v
return (fromIntegral major, fromIntegral minor, fromIntegral patch)
| oldmanmike/sdl2 | src/SDL/Init.hs | bsd-3-clause | 2,566 | 0 | 13 | 409 | 523 | 293 | 230 | 56 | 1 |
module C where
-- Test for refactor of if to case
-- The comments on the then and else legs should be preserved
foo x = case (odd x) of
True -> -- This is an odd result
bob x 1
False -> -- This is an even result
bob x 2
bob x y = x + y
| RefactoringTools/HaRe | test/testdata/Case/CExpected.hs | bsd-3-clause | 290 | 0 | 8 | 113 | 62 | 33 | 29 | 7 | 2 |
module HAD.Y2014.M03.D10.Solution where
import Data.Maybe (listToMaybe)
import Numeric (readDec)
-- $setup
-- >>> import Test.QuickCheck
-- >>> import Control.Applicative
-- | maybeReadPositiveInt Try to parse a positive Int
-- Can be done point-free (and it's probably funnier this way).
--
--
-- Examples:
--
-- prop> (==) <$> Just <*> maybeReadPositiveInt . show $ getNonNegative x
--
-- prop> Nothing == (maybeReadPositiveInt . show . negate . getPositive $ x)
--
-- >>> maybeReadPositiveInt "foo"
-- Nothing
--
-- >>> maybeReadPositiveInt "12 "
-- Nothing
maybeReadPositiveInt :: String -> Maybe Int
maybeReadPositiveInt =
fmap fst . listToMaybe . filter (null . snd) . readDec
| 1HaskellADay/1HAD | exercises/HAD/Y2014/M03/D10/Solution.hs | mit | 689 | 0 | 9 | 110 | 87 | 57 | 30 | 6 | 1 |
{-# LANGUAGE CPP #-}
module Tests.IOThunk where
#ifdef __HASTE__
import Haste
#endif
runTest :: IO ()
runTest = do
x ; x ; x
y ; y ; y
{-# NOINLINE x #-}
x :: IO ()
x = putStrLn "hello!"
y :: IO ()
y = putStrLn "hi!"
| joelburget/haste-compiler | Tests/IOThunk.hs | bsd-3-clause | 224 | 0 | 6 | 56 | 86 | 46 | 40 | 11 | 1 |
module Basics.DetectAESInECB (detectAesEcb) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS (take, drop, length)
import Data.List (nub, minimumBy)
import Data.Ord (comparing)
import Util.Convert (viewS)
detectAesEcb :: [ByteString] -> String
detectAesEcb ciphertext = viewS $ fst $ minimumBy (comparing snd) candidates
where candidates = zip ciphertext $ map (length . nub . blocks) ciphertext
blocks bs | BS.length bs > 3 = BS.take 2 bs : blocks (BS.drop 2 bs)
| otherwise = [bs]
| ilikebits/matasano | src/Basics/DetectAESInECB.hs | isc | 545 | 0 | 12 | 105 | 201 | 108 | 93 | 11 | 1 |
module P030Spec where
import qualified P030 as P
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = -- do
describe "solveBasic" $
it "各桁の数字をN乗した和が自分自身になる数の和" $
map P.solveBasic [1, 2, 4] `shouldBe` [44, 0, 19316]
| yyotti/euler_haskell | test/P030Spec.hs | mit | 289 | 0 | 8 | 55 | 89 | 52 | 37 | 10 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Item
( Building(..)
, BuildingDescription(..)
, Position
, Size
, Speed
, RenderingInfo(..)
, Action(..)
, Unit(..)
, UnitDescription(..)
, buildingDescription
, buildingPosition
, buildingSize
, buildingTexture
, rPosition
, rSize
, rTexture
, unitDescription
, unitPlan
, unitPosition
, unitSize
, unitSpeed
, unitTexture
)
where
import Control.Lens
import Data.Hashable
import Data.Word
import GHC.Generics
import Linear
import SDL
type Position = V2 Float
type Size = Word8
type Speed = Float
data UnitDescription = UnitDescription
{ _unitSpeed :: Speed
, _unitSize :: Size
, _unitTexture :: FilePath
}
deriving (Eq, Generic)
instance Hashable UnitDescription
data Unit = Unit
{ _unitPosition :: Position
, _unitPlan :: [Action]
, _unitDescription :: UnitDescription
}
data BuildingDescription = BuildingDescription
{ _buildingSize :: Size
, _buildingTexture :: FilePath
}
deriving (Eq, Generic)
instance Hashable BuildingDescription
data Building = Building
{ _buildingPosition :: Position
, _buildingDescription :: BuildingDescription
}
data RenderingInfo = RenderingInfo
{ _rPosition :: Position
, _rSize :: Size
, _rTexture :: Texture
}
data Action = MoveTo Position
deriving (Eq)
makeLenses ''Unit
makeLenses ''UnitDescription
makeLenses ''Building
makeLenses ''BuildingDescription
makeLenses ''RenderingInfo
| Unoriginal-War/unoriginal-war | src/Item.hs | mit | 1,571 | 0 | 9 | 369 | 363 | 218 | 145 | 63 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Day10 (day10, day10', run, Chip(..), Destination(..), Expr(..), parseInput, detectBot) where
import Data.Either (rights)
import Data.List (find, nub, sort)
import Data.Map ((!), Map)
import qualified Data.Map as Map
import Text.Parsec ((<|>) , Parsec , ParseError)
import qualified Text.Parsec as P
newtype Chip = Chip Int deriving (Eq, Show)
instance Ord Chip where compare (Chip a) (Chip b) = compare a b
data Destination = RobotDest Int | OutputDest Int deriving (Eq, Ord, Show)
data Expr =
SourceExpr Chip Destination
| BotExpr Int Destination Destination
deriving (Eq, Ord, Show)
parseInput :: String -> [Expr]
parseInput = rights . map (P.parse parseExpr "") . lines
where
parseExpr = parseSource <|> parseBot
parseSource = do
P.try (P.string "value ")
v <- parseInt
P.string " goes to "
d <- parseDestination
return $ SourceExpr (Chip v) d
parseDestination = parseRobot <|> parseOutput
parseRobot = RobotDest <$> (P.try (P.string "bot ") *> parseInt)
parseOutput = OutputDest <$> (P.try (P.string "output ") *> parseInt)
parseBot = do
P.try (P.string "bot ")
n <- parseInt
P.string " gives low to "
d1 <- parseDestination
P.string " and high to "
d2 <- parseDestination
return $ BotExpr n d1 d2
parseInt = read <$> P.many1 P.digit
calculateComparisons :: [Expr] -> Map Int (Chip, Chip)
calculateComparisons es = comparisonMap
where
comparisonMap = Map.fromList . map (\i -> (i, calculateComparisonInner i)) $ allBots es
calculateComparisonMemo bot = comparisonMap ! bot
calculateComparisonInner bot = let (e1, e2) = incomingEdges bot in (calc e1, calc e2)
where
calc :: Expr -> Chip
calc (BotExpr n d1 _) = calculateEdgeWeightInner n (isRobotDestination d1 bot)
calc (SourceExpr c _) = c
calculateEdgeWeightInner source which = let (a, b) = calculateComparisonMemo source in (provide which) a b
where
provide False = max
provide True = min
incomingEdges bot = let (a : b : []) = allIncomingEdges in (a, b)
where
allIncomingEdges = filter isIncomingEdge es
isIncomingEdge (SourceExpr _ d) = isRobotDestination d bot
isIncomingEdge (BotExpr _ d1 d2) = isRobotDestination d1 bot || isRobotDestination d2 bot
isRobotDestination (RobotDest n) bot = n == bot
isRobotDestination _ _ = False
detectBot :: [Expr] -> (Chip, Chip) -> Int
detectBot es (c1, c2) = fst . head . filter (isMatch . snd) . Map.toList . calculateComparisons $ es
where
isMatch (a, b) = (a == c1 && b == c2) || (a == c2 && b == c1)
allBots :: [Expr] -> [Int]
allBots = sort . nub . concatMap getBots
where
getBots (SourceExpr _ d) = getBotsFromDest d
getBots (BotExpr n1 d1 d2) = n1 : (getBotsFromDest d1 ++ getBotsFromDest d2)
getBotsFromDest (RobotDest n) = [n]
getBotsFromDest _ = []
allOutputs :: [Expr] -> [Int]
allOutputs = sort . nub . concatMap getOutputs
where
getOutputs (SourceExpr _ d) = getOutputsFromDes d
getOutputs (BotExpr n1 d1 d2) = n1 : (getOutputsFromDes d1 ++ getOutputsFromDes d2)
getOutputsFromDes (OutputDest n) = [n]
getOutputsFromDes _ = []
calculateOutputs :: [Expr] -> Map Int Chip
calculateOutputs es = Map.fromList . map (\i -> (i, calculateOutput i)) $ allOutputs es
where
bots = calculateComparisons es
calculateOutput output = case incomingEdge output of
(SourceExpr c _) -> c
(BotExpr n d1 d2) -> let (c1, c2) = bots ! n in
if (d1 == OutputDest output) then min c1 c2 else max c1 c2
incomingEdge output = head . filter isIncomingEdge $ es
where
isIncomingEdge (SourceExpr _ d) = isOutputDestination d output
isIncomingEdge (BotExpr _ d1 d2) = isOutputDestination d1 output || isOutputDestination d2 output
isOutputDestination (OutputDest n) output = n == output
isOutputDestination _ _ = False
-- Final, top-level exports
day10 :: String -> Int
day10 = flip detectBot (Chip 61, Chip 17) . parseInput
day10' :: String -> Int
day10' input = product $ map (\i -> extractValue $ outputs ! i) [0..2]
where
outputs = calculateOutputs $ parseInput input
extractValue (Chip n) = n
-- Input
run :: IO ()
run = do
putStrLn "Day 10 results: "
input <- readFile "inputs/day10.txt"
putStrLn $ " " ++ show (day10 input)
putStrLn $ " " ++ show (day10' input)
| brianshourd/adventOfCode2016 | src/Day10.hs | mit | 4,495 | 0 | 15 | 1,077 | 1,675 | 862 | 813 | 92 | 5 |
module Main where
import Data.IORef
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT hiding (exit)
import System.Exit (exitSuccess)
import Hogldev.Pipeline (
Pipeline(..), getTrans,
PersProj(..)
)
import Hogldev.Camera ( Camera(..), cameraOnKeyboard,
initCamera, cameraOnMouse, cameraOnRender
)
import Hogldev.Texture
import LightingTechnique
import Mesh
windowWidth = 1920
windowHeight = 1080
persProjection = PersProj
{ persFOV = 60
, persWidth = fromIntegral windowWidth
, persHeigh = fromIntegral windowHeight
, persZNear = 1
, persZFar = 100
}
dirLight :: DirectionLight
dirLight = DirectionLight
{ ambientColor = Vertex3 1 1 1
, ambientIntensity = 0.2
, diffuseIntensity = 0.8
, diffuseDirection = Vertex3 1.0 0.0 0.0
}
main :: IO ()
main = do
getArgsAndInitialize
initialDisplayMode $= [DoubleBuffered, RGBAMode, WithDepthBuffer]
initialWindowSize $= Size windowWidth windowHeight
initialWindowPosition $= Position 100 100
createWindow "Tutorial 30"
-- frontFace $= CW
-- cullFace $= Just Back
depthFunc $= Just Lequal
gScale <- newIORef 0.0
cameraRef <- newIORef newCamera
bampMapRef <- newIORef True
lightingEffect <- initLightingTechnique
enableLightingTechnique lightingEffect
setLightingTextureUnit lightingEffect 0
setLightingNormalMapTextureUnit lightingEffect 2
setDirectionalLight lightingEffect dirLight
pointerPosition $= mousePos
boxMesh <- loadMesh "assets/box.obj"
Just texture <- textureLoad "assets/bricks.jpg" Texture2D
Just normalMap <- textureLoad "assets/normal_map.jpg" Texture2D
Just trivialNormalMap <- textureLoad "assets/normal_up.jpg" Texture2D
initializeGlutCallbacks boxMesh lightingEffect gScale cameraRef bampMapRef
texture normalMap trivialNormalMap
clearColor $= Color4 0 0 0 0
mainLoop
where
newCamera = initCamera (Just
(Vector3 0.5 1.025 0.25, Vector3 0 (-0.5) 1, Vector3 0 1 0)
) windowWidth windowHeight
mousePos = Position (windowWidth `div` 2) (windowHeight `div` 2)
initializeGlutCallbacks :: Mesh
-> LightingTechnique
-> IORef GLfloat
-> IORef Camera
-> IORef Bool
-> Texture
-> Texture
-> Texture
-> IO ()
initializeGlutCallbacks boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap = do
displayCallback $=
renderSceneCB boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap
idleCallback $= Just (idleCB gScale cameraRef)
specialCallback $= Just (specialKeyboardCB cameraRef)
keyboardCallback $= Just (keyboardCB bampMapRef)
passiveMotionCallback $= Just (passiveMotionCB cameraRef)
keyboardCB :: IORef Bool -> KeyboardCallback
keyboardCB _ 'q' _ = exitSuccess
keyboardCB bumpMapRef 'b' _ = modifyIORef bumpMapRef not
keyboardCB _ _ _ = return ()
specialKeyboardCB :: IORef Camera -> SpecialCallback
specialKeyboardCB cameraRef key _ = cameraRef $~! cameraOnKeyboard key
passiveMotionCB :: IORef Camera -> MotionCallback
passiveMotionCB cameraRef position = cameraRef $~! cameraOnMouse position
idleCB :: IORef GLfloat -> IORef Camera -> IdleCallback
idleCB gScale cameraRef = do
gScale $~! (+ 0.01)
cameraRef $~! cameraOnRender
postRedisplay Nothing
renderSceneCB :: Mesh
-> LightingTechnique
-> IORef GLfloat
-> IORef Camera
-> IORef Bool
-> Texture
-> Texture
-> Texture
-> DisplayCallback
renderSceneCB boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap = do
cameraRef $~! cameraOnRender
gScaleVal <- readIORef gScale
camera <- readIORef cameraRef
bampMapEnabled <- readIORef bampMapRef
clear [ColorBuffer, DepthBuffer]
enableLightingTechnique lightingEffect
textureBind texture (TextureUnit 0)
if bampMapEnabled
then textureBind normalMap (TextureUnit 2)
else textureBind trivialNormalMap (TextureUnit 2)
setLightingWVP lightingEffect $ getTrans
WVPPipeline {
worldInfo = Vector3 0 0 3,
scaleInfo = Vector3 1 1 1,
rotateInfo = Vector3 (-90) gScaleVal 0,
persProj = persProjection,
pipeCamera = camera
}
setLightingWorldMatrix lightingEffect $ getTrans
WPipeline {
worldInfo = Vector3 0 0 3,
scaleInfo = Vector3 1 1 1,
rotateInfo = Vector3 (-90) gScaleVal 0
}
renderMesh boxMesh
swapBuffers
| triplepointfive/hogldev | tutorial30/Tutorial30.hs | mit | 5,066 | 0 | 14 | 1,520 | 1,171 | 580 | 591 | 119 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- |
-- Module: BigE.Runtime.Render
-- Copyright: (c) 2017 Patrik Sandahl
-- Licence: MIT
-- Maintainer: Patrik Sandahl <patrik.sandahl@gmail.com>
-- Stability: experimental
-- Portability: portable
module BigE.Runtime.Render
( Render
, RenderState (..)
, Key (..)
, ModifierKeys (..)
, MouseButton (..)
, WindowSizeCallback
, KeyPressedCallback
, KeyReleasedCallback
, KeyRepeatingCallback
, MousePressedCallback
, MouseReleasedCallback
, runRender
, frameDuration
, displayDimensions
, getAppState
, getAppStateUnsafe
, putAppState
, modifyAppState
, setWindowSizeCallback
, setKeyPressedCallback
, setKeyRepeatingCallback
, setKeyReleasedCallback
, setMousePressedCallback
, setMouseReleasedCallback
, liftIO
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (MonadReader, ReaderT, ask, runReaderT)
import Data.IORef (IORef, modifyIORef, readIORef)
import Data.Maybe (fromJust)
import Graphics.UI.GLFW (Key (..), ModifierKeys (..),
MouseButton (..), Window)
type WindowSizeCallback app = Int -> Int -> Render app ()
type KeyPressedCallback app = Key -> ModifierKeys -> Render app ()
type KeyRepeatingCallback app = Key -> ModifierKeys -> Render app ()
type KeyReleasedCallback app = Key -> ModifierKeys -> Render app ()
type MousePressedCallback app = MouseButton -> ModifierKeys -> (Int, Int) -> Render app ()
type MouseReleasedCallback app = MouseButton -> ModifierKeys -> (Int, Int) -> Render app ()
-- | BigEngine's internal render state.
data RenderState app = RenderState
{ window :: !Window
-- ^ The GLFW window.
, dimensions :: !(Int, Int)
-- ^ The current dimensions for the window (width, height).
, lastTime :: !Double
-- ^ Last taken timestamp value.
, duration :: !Double
-- ^ The duration in (fractional) seconds since previous frame.
, appWindowSizeCallback :: !(Maybe (WindowSizeCallback app))
-- ^ The application's window size change callback.
, appKeyPressedCallback :: !(Maybe (KeyPressedCallback app))
-- ^ The application's key pressed callback.
, appKeyRepeatingCallback :: !(Maybe (KeyRepeatingCallback app))
-- ^ The application's key repeating callback.
, appKeyReleasedCallback :: !(Maybe (KeyReleasedCallback app))
-- ^ The application's key released callback.
, appMousePressedCallback :: !(Maybe (MousePressedCallback app))
-- ^ The applications mouse pressed callback.
, appMouseReleasedCallback :: !(Maybe (MouseReleasedCallback app))
, appState :: !(Maybe app)
-- ^ The user provided application state.
}
-- | The Render monad transform. Just 'StateT' on top of IO.
newtype Render app reply =
Render { extractRender :: ReaderT (IORef (RenderState app)) IO reply }
deriving (Functor, Applicative, Monad, MonadReader (IORef (RenderState app)), MonadIO)
-- | Run the Render monad action.
runRender :: Render app reply -> IORef (RenderState app) -> IO reply
runRender action = runReaderT (extractRender action)
-- | The time in (fractional) seconds since last frame.
frameDuration :: Render app Double
frameDuration = duration <$> (readIORef' =<< ask)
-- | The display dimensions as (width, height).
displayDimensions :: Render app (Int, Int)
displayDimensions = dimensions <$> (readIORef' =<< ask)
-- | Read the app state.
getAppState :: Render app (Maybe app)
getAppState = appState <$> (readIORef' =<< ask)
-- | Read the app state and force away Maybe. Unsafe, but shall normally be
-- ok in eachFrame and teardown callbacks.
getAppStateUnsafe :: Render app app
getAppStateUnsafe = fromJust . appState <$> (readIORef' =<< ask)
-- | Put a new app state.
putAppState :: app -> Render app ()
putAppState app = do
ref <- ask
modifyIORef' ref $ \state -> state { appState = Just app }
-- | Modify the app state.
modifyAppState :: (app -> app) -> Render app ()
modifyAppState g = do
ref <- ask
modifyIORef' ref $ \state ->
maybe state (\appState' -> state { appState = Just (g appState') }) (appState state)
-- | Set (or unset) the 'WindowSizeCallback'.
setWindowSizeCallback :: Maybe (WindowSizeCallback app) -> Render app ()
setWindowSizeCallback val = do
ref <- ask
modifyIORef' ref $ \state -> state { appWindowSizeCallback = val }
-- | Set (or unset) the 'KeyPressedCallback'.
setKeyPressedCallback :: Maybe (KeyPressedCallback app) -> Render app ()
setKeyPressedCallback val = do
ref <- ask
modifyIORef' ref $ \state -> state { appKeyPressedCallback = val }
-- | Set (or unset) the 'KeyRepeatingCallback'.
setKeyRepeatingCallback :: Maybe (KeyRepeatingCallback app) -> Render app ()
setKeyRepeatingCallback val = do
ref <- ask
modifyIORef' ref $ \state -> state { appKeyRepeatingCallback = val }
-- | Set (or unset) the 'KeyReleasedCallback'.
setKeyReleasedCallback :: Maybe (KeyReleasedCallback app) -> Render app ()
setKeyReleasedCallback val = do
ref <- ask
modifyIORef' ref $ \state -> state { appKeyReleasedCallback = val }
-- | Set (or unset) the 'MousePressedCallback'.
setMousePressedCallback :: Maybe (MousePressedCallback app) -> Render app ()
setMousePressedCallback val = do
ref <- ask
modifyIORef' ref $ \state -> state { appMousePressedCallback = val }
-- | Set (or unset) the 'MouseReleasedCallback'.
setMouseReleasedCallback :: Maybe (MouseReleasedCallback app) -> Render app ()
setMouseReleasedCallback val = do
ref <- ask
modifyIORef' ref $ \state -> state { appMouseReleasedCallback = val }
readIORef' :: IORef (RenderState app) -> Render app (RenderState app)
readIORef' = liftIO . readIORef
modifyIORef' :: IORef (RenderState app) -> (RenderState app -> RenderState app) -> Render app ()
modifyIORef' ref = liftIO . modifyIORef ref
| psandahl/big-engine | src/BigE/Runtime/Render.hs | mit | 6,101 | 0 | 16 | 1,340 | 1,409 | 772 | 637 | 123 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Application.Types.Process
( Process(..)
) where
import Prelude hiding (id)
import Data.Aeson.TH (defaultOptions, deriveToJSON)
import Data.Text.Lazy (Text)
data Process = Process
{ id :: Int
, user :: Text
, host :: Text
, db :: Maybe Text
, command :: Text
, time :: Int
, state :: Maybe Text
, info :: Text
}
$(deriveToJSON defaultOptions ''Process)
| ip1981/mywatch | src/Application/Types/Process.hs | mit | 419 | 0 | 9 | 90 | 128 | 79 | 49 | 16 | 0 |
{--
Copyright (c) 2014 Gorka Suárez García
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--}
{- ***************************************************************
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of
these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
*************************************************************** -}
module Problem0001 (main) where
multipleOf :: (Integral a) => a -> a -> Bool
multipleOf a b = (mod a b) == 0
multipleOf3Or5 :: (Integral a) => a -> Bool
multipleOf3Or5 x = (x `multipleOf` 3) || (x `multipleOf` 5)
multiplesOf3And5Under :: (Integral a) => a -> [a]
multiplesOf3And5Under n = takeWhile (< n) multiples
where multiples = [x | x <- [1,2..], multipleOf3Or5 x]
main = do putStr "The sum of all the multiples of 3 or 5 "
putStrLn ("below 1000 is " ++ show result ++ ".")
where result = sum $ multiplesOf3And5Under 1000 | gorkinovich/Haskell | Problems/Problem0001.hs | mit | 1,959 | 0 | 11 | 359 | 217 | 118 | 99 | 11 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
module LL1 where
import Prelude hiding ((*>))
import Control.Monad
import Control.Monad.ST
import Control.Monad.Writer.Strict
import Data.IORef
import Data.STRef
import Data.List
import Data.Maybe
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
whenM :: Monad m => m Bool -> m () -> m ()
whenM mb mf = do
b <- mb
when b mf
---
data Rule t a where
RTag :: t -> Rule t a -> Rule t a
RSeq :: Rule t a -> Rule t a -> Rule t a
RAlt :: Rule t a -> Rule t a -> Rule t a
RTer :: a -> Rule t a
REps :: Rule t a
REof :: Rule t a
RPretty :: Rule t a -> Rule t a
deriving (Ord)
instance (Eq t, Eq a) => Eq (Rule t a) where
(RTag t _) == (RTag t' _) = t == t'
(RSeq a b) == (RSeq a' b') = a == a' && b == b'
(RAlt a b) == (RAlt a' b') = a == a' && b == b'
(RTer x) == (RTer x') = x == x'
(REps) == (REps) = True
(REof) == (REof) = True
_ == _ = False
showRule :: (Show t, Show a) => Rule t a -> String
showRule rule =
case rule of
RTag t a -> show t ++ " -> " ++ go a
otherwise -> go rule
where
go (RPretty (RTer a)) = show a
go (RPretty a) = go a
go (RTag t a) = "{" ++ show t ++ "}"
go (RSeq a b) = go a ++ " " ++ go b
go (RAlt a b) = go a ++ " | " ++ go b
go (RTer a) = "'" ++ show a ++ "'"
go (REps) = "ε"
go (REof) = "<<EOF>>"
instance (Show t, Show a) => Show (Rule t a) where
show = showRule
---
class IsRule a r | a -> r where
toRule :: a -> r
instance IsRule (Rule t a) (Rule t a) where
toRule = id
---
infixr 6 *>
infixl 4 <|>
eof = REof
eps = REps
rule = RTag
a *> b = RSeq (toRule a) (toRule b)
a <|> b = RAlt (toRule a) (toRule b)
---
data Grammar t a = Grammar { start :: Rule t a }
---
traversal :: (Ord t) => (s -> Rule t a -> s) -> s -> Rule t a -> s
traversal f s rule = runST $ do
skipsR <- newSTRef Set.empty
queueR <- newSTRef (Seq.singleton rule)
sR <- newSTRef s
let observe r = do
modifySTRef sR (flip f r)
let putQ r = do
modifySTRef queueR (Seq.|> r)
let addSkip t = do
modifySTRef skipsR (Set.insert t)
let hasSkip t = do
Set.member t <$> readSTRef skipsR
let putSkip r@(RTag t a) ifNew = do
whenM (not <$> hasSkip t) $ do
addSkip t
putQ a
ifNew
let popQ = do
top <- flip Seq.index 0 <$> readSTRef queueR
modifySTRef queueR (Seq.drop 1)
return top
let isEmptyQ = do
Seq.null <$> readSTRef queueR
let withPopQ f = do
whenM (not <$> isEmptyQ) $ do
popQ >>= f
let go = do
withPopQ $ \r -> do
case r of
RSeq a b -> observe r >> putQ a >> putQ b
RAlt a b -> observe r >> putQ a >> putQ b
RTag t a -> putSkip r (observe r)
r -> observe r
go
go >> readSTRef sR
nonterms :: (Ord t, Eq a) => Rule t a -> [Rule t a]
nonterms = nub . traversal f []
where
f ts r@RTag{} = r : ts
f ts _ = ts
terminals :: (Ord t, Eq a) => Rule t a -> [Rule t a]
terminals = nub . traversal f []
where
f ts r@RTer{} = r : ts
f ts _ = ts
tagAlts :: Rule t a -> [Rule t a]
tagAlts (RTag t a) = go a
where
go (RAlt a b) = go a ++ go b
go r = [r]
isEps REps = True
isEps _ = False
hasEps = or . map isEps
isTag RTag{} = True
isTag _ = False
tag (RTag t _) = t
first :: (Ord t, Eq a) => Rule t a -> [Rule t a]
first = go Set.empty
where
go ks r@REps{} = [r]
go ks r@RTer{} = [r]
go ks r@(RTag t _) =
if Set.member t ks then
[]
else
concatMap (go (Set.insert t ks)) (tagAlts r)
go ks (RSeq a b) =
let y = go ks a
y' = y \\ [eps] in
if hasEps y then
y' ++ go ks b
else
y'
follow :: (Ord t, Eq a) => Grammar t a -> Rule t a -> [Rule t a]
follow gram = go (nonterms $ start gram)
where
go nts x@RTag{} = nub $ execWriter $ do
mapM_ f nts
when (x == start gram) $
tell [eof]
where
f nt = mapM_ g (tagAlts nt)
where
g (RSeq a b) = do
g b
when (a == x) $ do
let y = first b
let y' = y \\ [eps]
tell y'
when (hasEps y) $
tell $ go (nts \\ [x]) nt
g r =
when (r == x) $
tell $ go (nts \\ [x]) nt
---
printParseTable :: (Ord t, Ord a, Show t, Show a) => Grammar t a -> IO ()
printParseTable gram = do
let ts = [eof] ++ terminals (start gram)
let nts = sortOn tag $ nonterms (start gram)
forM_ nts $ \nt -> do
let alts = tagAlts nt
row <- newIORef Map.empty
forM_ alts $ \alt -> do
let fts = first alt
forM_ fts $ \ft -> do
whenM (Map.member ft <$> readIORef row) $
error ("not LL1: " ++ show (nt, ft))
modifyIORef row (Map.insert ft alt)
when (hasEps fts) $ do
let fws = follow gram nt
forM_ fws $ \fw -> do
whenM (Map.member fw <$> readIORef row) $
error ("not LL1: " ++ show (nt, fw))
modifyIORef row (Map.insert fw alt)
putStrLn (show nt)
forM_ ts $ \t -> do
mrule <- Map.lookup t <$> readIORef row
case mrule of
Just rule -> putStr ("\t" ++ show (RPretty t) ++ "\t: " ++ show (RPretty rule) ++ "\n")
otherwise -> return ()
putStr "\n"
| Garciat/LL1 | LL1.hs | mit | 5,727 | 0 | 27 | 2,087 | 2,769 | 1,350 | 1,419 | -1 | -1 |
module Main where
import Data.Text
import MlgscTypes
import NewickDumper (treeToNewick)
import API (rawTree)
main :: IO ()
main = interact $ unpack . treeToNewick . rawTree Taxonomy
| tjunier/mlgsc | src/taxo2nw.hs | mit | 185 | 0 | 7 | 30 | 58 | 33 | 25 | 7 | 1 |
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
{-# OPTIONS_GHC -fconstraint-solver-iterations=20 #-}
module AI.Funn.CL.Layers.Upscale (doubleDiff) where
import Control.Monad
import Control.Monad.IO.Class
import Data.Foldable
import Data.List
import Data.Monoid
import Data.Proxy
import Data.Traversable
import GHC.TypeLits
import qualified AI.Funn.CL.DSL.AST as AST
import AI.Funn.CL.DSL.Array
import AI.Funn.CL.DSL.Code as C
import AI.Funn.CL.DSL.Tensor
import AI.Funn.CL.Function
import AI.Funn.CL.MonadCL
import AI.Funn.CL.Network
import AI.Funn.CL.Tensor (Tensor, MTensor)
import qualified AI.Funn.CL.Tensor as Tensor
import AI.Funn.Diff.Diff (Derivable(..), Diff(..))
import AI.Funn.Space
import AI.Funn.TypeLits
{-# NOINLINE doubleForward #-}
doubleForward :: KernelProgram '[TensorCL [w, h, c],
MTensorCL [2*w, 2*h, c]]
doubleForward = compile $ \input output -> do
~[ox, oy, c] <- traverse get_global_id [0, 1, 2]
output![ox, oy, c] .= input![ox `div'` 2, oy `div'` 2, c]
{-# NOINLINE doubleBackward #-}
doubleBackward :: KernelProgram '[MTensorCL [w, h, c],
TensorCL [2*w, 2*h, c]]
doubleBackward = compile $ \d_input d_output -> do
~[ix, iy, c] <- traverse get_global_id [0, 1, 2]
ox <- eval (2 * ix)
oy <- eval (2 * iy)
d_input![ix, iy, c] .= sum [d_output![x,y,c] | (x,y) <- [
(ox, oy),
(ox+1, oy),
(ox, oy+1),
(ox+1, oy+1)]]
doubleDiff :: forall w h c m.
(MonadIO m, KnownDimsF [w, h, c])
=> Diff m (Tensor [w, h, c]) (Tensor [2*w, 2*h, c])
doubleDiff = Diff run
where
run input = do
output <- Tensor.new
liftIO (clfun doubleForward (dimVal output) input output :: IO ())
return (Tensor.unsafeFreeze output, backward)
backward d_output = do
d_input <- Tensor.new
liftIO (clfun doubleBackward (dimVal d_input) d_input d_output :: IO ())
return (Tensor.unsafeFreeze d_input)
doubleNet :: (MonadIO m, KnownDimsF [w, h, c])
=> Network m 0 (Tensor [w, h, c]) (Tensor [2*w, 2*h, c])
doubleNet = liftDiff doubleDiff
| nshepperd/funn | AI/Funn/CL/Layers/Upscale.hs | mit | 2,961 | 0 | 16 | 813 | 881 | 513 | 368 | 72 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Orville.PostgreSQL.PgCatalog.PgClass
( PgClass (..),
RelationName,
relationNameToString,
RelationKind (..),
pgClassTable,
relationNameField,
namespaceOidField,
relationKindField,
)
where
import qualified Data.String as String
import qualified Data.Text as T
import qualified Database.PostgreSQL.LibPQ as LibPQ
import qualified Orville.PostgreSQL as Orville
import Orville.PostgreSQL.PgCatalog.OidField (oidField, oidTypeField)
{- |
The Haskell representation of data read from the @pg_catalog.pg_class@
table. Rows in this table correspond to tables, indexes, sequences, views,
materialized views, composite types and TOAST tables.
-}
data PgClass = PgClass
{ -- | The PostgreSQL @oid@ for the relation
pgClassOid :: LibPQ.Oid
, -- | The PostgreSQL @oid@ of the namespace that the relation belongs to.
-- References @pg_namespace.oid@.
pgClassNamespaceOid :: LibPQ.Oid
, -- | The name of relation
pgClassRelationName :: RelationName
, -- | The kind of relation (table, view, etc)
pgClassRelationKind :: RelationKind
}
{- |
A Haskell type for the name of the relation represented by a 'PgClass'
-}
newtype RelationName
= RelationName T.Text
deriving (Show, Eq, Ord, String.IsString)
{- |
Convert a 'RelationName' to a plain 'String'
-}
relationNameToString :: RelationName -> String
relationNameToString (RelationName text) =
T.unpack text
{- |
The kind of relation represented by a 'PgClass', as described at
https://www.postgresql.org/docs/13/catalog-pg-class.html.
-}
data RelationKind
= OrdinaryTable
| Index
| Sequence
| ToastTable
| View
| MaterializedView
| CompositeType
| ForeignTable
| PartitionedTable
| PartitionedIndex
deriving (Show, Eq)
{- |
An Orville 'Orville.TableDefinition' for querying the
@pg_catalog.pg_class@ table
-}
pgClassTable :: Orville.TableDefinition (Orville.HasKey LibPQ.Oid) PgClass PgClass
pgClassTable =
Orville.setTableSchema "pg_catalog" $
Orville.mkTableDefinition
"pg_class"
(Orville.primaryKey oidField)
pgClassMarshaller
pgClassMarshaller :: Orville.SqlMarshaller PgClass PgClass
pgClassMarshaller =
PgClass
<$> Orville.marshallField pgClassOid oidField
<*> Orville.marshallField pgClassNamespaceOid namespaceOidField
<*> Orville.marshallField pgClassRelationName relationNameField
<*> Orville.marshallField pgClassRelationKind relationKindField
{- |
The @relnamespace@ column of the @pg_catalog.pg_class@ table
-}
namespaceOidField :: Orville.FieldDefinition Orville.NotNull LibPQ.Oid
namespaceOidField =
oidTypeField "relnamespace"
{- |
The @relname@ column of the @pg_catalog.pg_class@ table
-}
relationNameField :: Orville.FieldDefinition Orville.NotNull RelationName
relationNameField =
Orville.coerceField $
Orville.unboundedTextField "relname"
{- |
The @relkind@ column of the @pg_catalog.pg_class@ table
-}
relationKindField :: Orville.FieldDefinition Orville.NotNull RelationKind
relationKindField =
Orville.convertField
(Orville.tryConvertSqlType relationKindToPgText pgTextToRelationKind)
(Orville.unboundedTextField "relkind")
{- |
Converts a 'RelationKind' to the corresponding single character text
representation used by PostgreSQL.
See also 'pgTextToRelationKind'
-}
relationKindToPgText :: RelationKind -> T.Text
relationKindToPgText kind =
T.pack $
case kind of
OrdinaryTable -> "r"
Index -> "i"
Sequence -> "S"
ToastTable -> "t"
View -> "v"
MaterializedView -> "m"
CompositeType -> "c"
ForeignTable -> "f"
PartitionedTable -> "p"
PartitionedIndex -> "I"
{- |
Attempts to parse a PostgreSQL single character textual value as a
'RelationKind'
See also 'relationKindToPgText'
-}
pgTextToRelationKind :: T.Text -> Either String RelationKind
pgTextToRelationKind text =
case T.unpack text of
"r" -> Right OrdinaryTable
"i" -> Right Index
"S" -> Right Sequence
"t" -> Right ToastTable
"v" -> Right View
"m" -> Right MaterializedView
"c" -> Right CompositeType
"f" -> Right ForeignTable
"p" -> Right PartitionedTable
"I" -> Right PartitionedIndex
kind -> Left ("Unrecognized PostgreSQL relation kind: " <> kind)
| flipstone/orville | orville-postgresql-libpq/src/Orville/PostgreSQL/PgCatalog/PgClass.hs | mit | 4,330 | 0 | 10 | 793 | 690 | 377 | 313 | 92 | 11 |
import Data.Maybe
import Data.List
import System.Environment
-- main = do
-- let Movements _ movements = executeProgramTrackMoves (interpolate 9 "Fa") (-1) (Movements (defaultPos) [])
-- filteredMovements = fmap (\l -> abs ((trd3 (l !! 0)) - ((trd3 (l !! 1))))) $ nub $ filter (\l -> (length l) > 1) $ fmap (\(x1, y1, _) -> filter (\(x2, y2, _) -> (x1, y1) == (x2, y2)) movements) movements
-- in print filteredMovements
-- main = do
-- args <- getArgs
-- let interpolateCount = read (args !! 0)
-- moveCount = (-1)
-- in print $ executeProgramTrackMoveDirection (interpolate interpolateCount "Fa") moveCount 0 defaultPos
-- main = do
-- print $ executeProgramWithInitialDirection "Fa" (-1) North
-- print $ executeProgram (interpolate 0 "Fa") (-1)
-- putStrLn "--"
-- print $ executeProgramWithInitialDirection "Rb FR" (-1) North
-- print $ executeProgram (interpolate 1 "Fa") (-1)
-- putStrLn "--"
-- print $ executeProgramWithInitialDirection "RLF aLb FR" (-1) South
-- print $ executeProgram (interpolate 2 "Fa") (-1)
-- putStrLn "--"
-- print $ executeProgramWithInitialDirection "RLF aRb FRLLF aLb FR" (-1) South
-- print $ executeProgram (interpolate 3 "Fa") (-1)
-- putStrLn "--"
-- print $ executeProgramWithInitialDirection "RLF aRb FRRLF aLb FRLLF aRb FRLLF aLb FR" (-1) South
-- print $ executeProgram (interpolate 4 "Fa") (-1)
-- putStrLn "--"
-- print $ executeProgramWithInitialDirection "RLF aRb FRRLF aLb FRRLF aRb FRLLF aLb FRLLF aRb FRRLF aLb FRLLF aRb FRLLF aLb FR" (-1) South
-- print $ executeProgram (interpolate 5 "Fa") (-1)
-- main = do
-- print $ executeProgram (interpolate 0 i) (-1)
-- print $ executeProgram (interpolate 1 i) (-1)
-- print $ executeProgram (interpolate 2 i) (-1)
-- print $ executeProgram (interpolate 3 i) (-1)
-- print $ executeProgram (interpolate 4 i) (-1)
-- print $ executeProgram (interpolate 5 i) (-1)
-- print $ executeProgram (interpolate 6 i) (-1)
-- print $ executeProgram (interpolate 7 i) (-1)
-- print $ executeProgram (interpolate 8 i) (-1)
-- print $ executeProgram (interpolate 9 i) (-1)
-- print $ executeProgram (interpolate 10 i) (-1)
-- print $ executeProgram (interpolate 11 i) (-1)
i = "Fa"
printNTimes n = printN 0 n where
printN index n = do
print $ executeProgram (interpolate index i) (-1)
if index < n then printN (index + 1) n else return ()
main = do
args <- getArgs
printNTimes $ read (args !! 0)
data Position = Position Int Int Direction deriving (Show)
data Direction = North | South | East | West deriving (Show)
data Movements = Movements Position [(Int, Int, Int)] deriving (Show)
defaultPos :: Position
defaultPos = Position 0 0 North
getX :: Position -> Int
getX (Position x _ _) = x
getY :: Position -> Int
getY (Position _ y _) = y
direction :: Position -> Direction
direction (Position _ _ d) = d
getMovements :: Movements -> [(Int, Int, Int)]
getMovements (Movements _ m) = m
moveX :: Position -> Int -> Position
moveX p m = Position ((getX p) + m) (getY p) (direction p)
moveY :: Position -> Int -> Position
moveY p m = Position (getX p) ((getY p) + m) (direction p)
updateDir :: Position -> Direction -> Position
updateDir p d = Position (getX p) (getY p) d
advance :: Position -> Position
advance p = case (direction p) of
North -> moveY p 1
South -> moveY p (-1)
East -> moveX p 1
West -> moveX p (-1)
rotL :: Position -> Position
rotL p = updateDir p $ case (direction p) of
North -> West
South -> East
East -> North
West -> South
rotR :: Position -> Position
rotR p = updateDir p $ case (direction p) of
North -> East
South -> West
East -> South
West -> North
fst3 :: (a, a, a) -> a
fst3 (f, _, _) = f
snd3 :: (a, a, a) -> a
snd3 (_, s, _) = s
trd3 :: (a, a, a) -> a
trd3 (_, _, t) = t
executeProgramTrackMoves :: String -> Int -> Movements -> Movements
executeProgramTrackMoves prog stepLimit movements = execute prog stepLimit 0 movements where
execute prog stepLimit stepCount (Movements pos locations) = do
if (length prog) > 0 && (stepLimit < 0 || stepLimit > stepCount) then case (head prog) of
'F' -> let newPos = advance pos
in execute (tail prog) stepLimit (stepCount + 1) (Movements newPos ((getX pos, getY pos, stepCount):locations))
'L' -> execute (tail prog) stepLimit stepCount (Movements (rotL pos) locations)
'R' -> execute (tail prog) stepLimit stepCount (Movements (rotR pos) locations)
_ -> execute (tail prog) stepLimit stepCount (Movements pos locations)
else Movements pos locations
executeProgram :: String -> Int -> Position
executeProgram prog stepLimit = execute prog stepLimit 0 (defaultPos)
executeProgramTrackMoveDirection :: String -> Int -> Int -> Position -> [Direction]
executeProgramTrackMoveDirection prog stepLimit stepCount pos = do
if (length prog) > 0 && (stepLimit < 0 || stepLimit > stepCount) then case (head prog) of
'F' -> (direction pos):(executeProgramTrackMoveDirection (tail prog) stepLimit (stepCount + 1) (advance pos))
'L' -> executeProgramTrackMoveDirection (tail prog) stepLimit (stepCount + 1) (rotL pos)
'R' -> executeProgramTrackMoveDirection (tail prog) stepLimit (stepCount + 1) (rotR pos)
_ -> executeProgramTrackMoveDirection (tail prog) stepLimit (stepCount + 1) pos
else []
execute :: String -> Int -> Int -> Position -> Position
execute prog stepLimit stepCount pos = do
if (length prog) > 0 && (stepLimit < 0 || stepLimit > stepCount) then case (head prog) of
'F' -> execute (tail prog) stepLimit (stepCount + 1) (advance pos)
'L' -> execute (tail prog) stepLimit stepCount (rotL pos)
'R' -> execute (tail prog) stepLimit stepCount (rotR pos)
_ -> execute (tail prog) stepLimit stepCount pos
else pos
executeProgramWithInitialDirection :: String -> Int -> Direction -> Position
executeProgramWithInitialDirection prog stepLimit dir = execute prog stepLimit 0 (Position 0 0 dir)
interpolate :: Int -> [Char] -> String
interpolate count strToInterpolate = do
if count > 0 then
interpolate (count - 1) $ concat $ fmap (\c -> case c of
'a' -> "aRbFR"
'b' -> "LFaLb"
_ -> [c]) strToInterpolate
else strToInterpolate
| dcjohnson/Project-Euler | 220/interpolate_execute.hs | mit | 6,349 | 0 | 21 | 1,381 | 1,729 | 911 | 818 | 92 | 5 |
module GHCJS.DOM.SVGPathSegArcRel (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/SVGPathSegArcRel.hs | mit | 46 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
import Test.HUnit
import Test.QuickCheck
import Pictures (Picture)
import Chapter5Exercises (onSeparateLines)
-------------------------------------------------------------------------------
-- Exercise 6.1
-------------------------------------------------------------------------------
-- snd :: (a,y) -> y
-- snd (x,y) = y
-- sing :: x -> [x]
-- sing x = [x]
-------------------------------------------------------------------------------
-- Exercise 6.2
-------------------------------------------------------------------------------
-- There are types for id which are not intances of [[a]]->[[a]]
-------------------------------------------------------------------------------
-- Exercise 6.3
-------------------------------------------------------------------------------
-- shift :: ((x,y),z) -> (x,(y,z))
-------------------------------------------------------------------------------
-- Exercise 6.4
-------------------------------------------------------------------------------
superimposeChar :: Char -> Char -> Char
superimposeChar '.' '.' = '.'
superimposeChar _ _ = '#'
superimposeCharTest = TestList
[ TestCase (assertEqual "" '.' (superimposeChar '.' '.'))
, TestCase (assertEqual "" '#' (superimposeChar '.' '#'))
, TestCase (assertEqual "" '#' (superimposeChar '#' '.'))
, TestCase (assertEqual "" '#' (superimposeChar '#' '#'))
]
-------------------------------------------------------------------------------
-- Exercise 6.5
-------------------------------------------------------------------------------
superimposeLine :: [Char] -> [Char] -> [Char]
superimposeLine a b = [ superimposeChar a b | (a,b) <- zip a b ]
superimposeLineTest
= TestCase (assertEqual "" ".###" (superimposeLine ".##." ".#.#"))
-------------------------------------------------------------------------------
-- Exercise 6.6
-------------------------------------------------------------------------------
superimpose :: Picture -> Picture -> Picture
superimpose a b = [ superimposeLine a b | (a,b) <- zip a b ]
superimposeTest =
TestCase (assertEqual "" expected (superimpose a b) )
where a = [ ".##.",
".##.",
".##." ]
b = [ ".#.#",
".#.#",
".#.#" ]
expected = [ ".###",
".###",
".###" ]
-------------------------------------------------------------------------------
-- Exercise 6.7
-------------------------------------------------------------------------------
printPicture :: Picture -> IO ()
printPicture picture = putStr (onSeparateLines picture)
-------------------------------------------------------------------------------
-- Exercise 6.8
-------------------------------------------------------------------------------
rotate90 :: Picture -> Picture
rotate90 p = [ line n p | n <- [0..((length p)-1)] ]
where line n p = reverse [ l!!n | l <- p]
testRotate90 = TestCase (assertEqual "" expected (rotate90 input))
where input = [ ".##.",
".#.#",
".###",
"####" ]
expected = [ "#...",
"####",
"##.#",
"###." ]
| c089/haskell-craft3e | Chapter6Exercises.hs | mit | 3,347 | 0 | 12 | 730 | 571 | 319 | 252 | 43 | 1 |
-- xmobar config used by Vic Fryzel
-- Author: Vic Fryzel
-- http://github.com/vicfryzel/xmonad-config
-- This is setup for dual 1920x1080 monitors, with the center monitor as primary
Config {
font = "xft:Fixed-8",
bgColor = "#000000",
fgColor = "#ffffff",
position = Static { xpos = 1920, ypos = 1064, width = 1919, height = 16 },
lowerOnStart = True,
commands = [
--Run Weather "KORTUALA3" ["-t","<tempF>F <skyCondition>","-L","64","-H","77","-n","#CEFFAC","-h","#FFB6B0","-l","#96CBFE"] 36000,
Run MultiCpu ["-t","Cpu: <total0> <total1> <total2> <total3>","-L","30","-H","60","-h","#FFB6B0","-l","#CEFFAC","-n","#FFFFCC","-w","3"] 10,
Run Memory ["-t","Mem: <usedratio>%","-H","8192","-L","4096","-h","#FFB6B0","-l","#CEFFAC","-n","#FFFFCC"] 10,
Run Swap ["-t","Swap: <usedratio>%","-H","1024","-L","512","-h","#FFB6B0","-l","#CEFFAC","-n","#FFFFCC"] 10,
Run Network "eth0" ["-t","Net: <rx>, <tx>","-H","200","-L","10","-h","#FFB6B0","-l","#CEFFAC","-n","#FFFFCC"] 10,
Run Com "volume" [] "vol" 10,
Run Date "%a %b %_d %l:%M" "date" 10,
Run StdinReader
],
sepChar = "%",
alignSep = "}{",
template = "%StdinReader% }{ %multicpu% %memory% %swap% %eth0% Vol: <fc=#CEFFAC>%vol%</fc> <fc=#FFFFCC>%date%</fc>"
}
| justinhoward/dotfiles | modules/xmonad/installed-config/xmobar.hs | mit | 1,324 | 0 | 9 | 242 | 317 | 198 | 119 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module JCDecaux.Vls.Types
( Position(..)
, StationStatus(..)
, Station(..)
, Contract(..)
)
where
import Data.Aeson
import Data.Text (Text)
import Control.Applicative
import Control.Monad
-- WGS 84 position
data Position = Position {
positionLatitude :: Double
, positionLongitude :: Double
} deriving (Show, Eq)
instance FromJSON Position where
parseJSON (Object v) = Position <$> v .: "lat" <*> v .: "lng"
parseJSON _ = mzero
instance ToJSON Position where
toJSON (Position lat lng) = object ["lat" .= toJSON lat, "lng" .= toJSON lng]
type City = Text
data Contract = Contract {
contractName :: Text
, contractCommercialName :: Text
, contractCities :: [City]
, contractCountryCode :: Text
} deriving (Show, Eq)
instance FromJSON Contract where
parseJSON (Object v) = Contract
<$> v .: "name"
<*> v .: "commercial_name"
<*> v .: "cities"
<*> v .: "country_code"
parseJSON _ = mzero
instance ToJSON Contract where
toJSON c = object ["name" .= contractName c
,"commercial_name" .= contractCommercialName c
,"cities" .= contractCities c
,"country_code" .= contractCountryCode c
]
data StationStatus = Open | Closed deriving (Show, Eq)
instance FromJSON StationStatus where
parseJSON (String "OPEN") = pure Open
parseJSON (String "CLOSED") = pure Closed
parseJSON _ = mzero
instance ToJSON StationStatus where
toJSON Open = toJSON ("OPEN" :: Text)
toJSON Closed = toJSON ("CLOSED" :: Text)
data Station = Station {
stationNumber :: Int
, stationName :: Text
, stationAddress :: Text
, stationPosition :: Position
, stationBanking :: Bool
, stationBonus :: Bool
, stationStatus :: StationStatus
, stationBikeStands :: Int
, stationAvailableBikeStands :: Int
, stationAvailableBikes :: Int
, stationLastUpdate :: Integer
} deriving (Show, Eq)
instance FromJSON Station where
parseJSON (Object v) = Station
<$> v .: "number"
<*> v .: "name"
<*> v .: "address"
<*> v .: "position"
<*> v .: "banking"
<*> v .: "bonus"
<*> v .: "status"
<*> v .: "bike_stands"
<*> v .: "available_bike_stands"
<*> v .: "available_bikes"
<*> v .: "last_update"
parseJSON _ = mzero
instance ToJSON Station where
toJSON s = object ["number" .= stationNumber s
,"name" .= stationName s
,"address" .= stationAddress s
,"position" .= stationPosition s
,"banking" .= stationBanking s
,"bonus" .= stationBonus s
,"status" .= stationStatus s
,"bike_stands" .= stationBikeStands s
,"available_bike_stands" .= stationAvailableBikeStands s
,"available_bikes" .= stationAvailableBikes s
,"last_update" .= stationLastUpdate s
]
| Herzult/hs-jcdecaux-vls | JCDecaux/Vls/Types.hs | mit | 3,657 | 0 | 27 | 1,508 | 809 | 437 | 372 | 85 | 0 |
module Args (Args(..), getArgs) where
import Prelude hiding (words,lines)
import Options.Applicative
data Args = Args { bytes :: Bool
, chars :: Bool
, lines :: Bool
, words :: Bool
, longest :: Bool
, files :: Maybe [String]
, files0from :: Maybe FilePath
} deriving Show
bytesFlag :: Parser Bool
bytesFlag = switch ( long "bytes"
<> short 'c'
<> help "print the byte counts"
)
charsFlag :: Parser Bool
charsFlag = switch ( long "chars"
<> short 'm'
<> help "print the character counts"
)
linesFlag :: Parser Bool
linesFlag = switch ( long "lines"
<> short 'l'
<> help "print the newline counts"
)
wordsFlag :: Parser Bool
wordsFlag = switch ( long "words"
<> short 'w'
<> help "print the word counts"
)
longestFlag :: Parser Bool
longestFlag = switch ( long "max-line-length"
<> short 'L'
<> help "print the length of the longest line"
)
fileArgs :: Parser (Maybe [String])
fileArgs = optional $ some $ argument str (metavar "FILES...")
files0fromArg :: Parser (Maybe FilePath)
files0fromArg = optional $ strOption ( long "files0-from"
<> help "read input from the files specified by NUL-terminated names in file F; If F is - then read names from standard input"
)
options :: Parser Args
options =
Args
<$> bytesFlag
<*> charsFlag
<*> linesFlag
<*> wordsFlag
<*> longestFlag
<*> fileArgs
<*> files0fromArg
getArgs :: IO Args
getArgs = do
a <- execParser $ info (helper <*> options) ( fullDesc <> header "")
if bytes a || words a || lines a || chars a || longest a
then return a
else return a { bytes = True, words = True, lines = True }
| mrak/coreutils.hs | src/wc/Args.hs | mit | 2,088 | 0 | 12 | 826 | 511 | 264 | 247 | 52 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html
module Stratosphere.ResourceProperties.AutoScalingScalingPolicyCustomizedMetricSpecification where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.AutoScalingScalingPolicyMetricDimension
-- | Full data type definition for
-- AutoScalingScalingPolicyCustomizedMetricSpecification. See
-- 'autoScalingScalingPolicyCustomizedMetricSpecification' for a more
-- convenient constructor.
data AutoScalingScalingPolicyCustomizedMetricSpecification =
AutoScalingScalingPolicyCustomizedMetricSpecification
{ _autoScalingScalingPolicyCustomizedMetricSpecificationDimensions :: Maybe [AutoScalingScalingPolicyMetricDimension]
, _autoScalingScalingPolicyCustomizedMetricSpecificationMetricName :: Val Text
, _autoScalingScalingPolicyCustomizedMetricSpecificationNamespace :: Val Text
, _autoScalingScalingPolicyCustomizedMetricSpecificationStatistic :: Val Text
, _autoScalingScalingPolicyCustomizedMetricSpecificationUnit :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON AutoScalingScalingPolicyCustomizedMetricSpecification where
toJSON AutoScalingScalingPolicyCustomizedMetricSpecification{..} =
object $
catMaybes
[ fmap (("Dimensions",) . toJSON) _autoScalingScalingPolicyCustomizedMetricSpecificationDimensions
, (Just . ("MetricName",) . toJSON) _autoScalingScalingPolicyCustomizedMetricSpecificationMetricName
, (Just . ("Namespace",) . toJSON) _autoScalingScalingPolicyCustomizedMetricSpecificationNamespace
, (Just . ("Statistic",) . toJSON) _autoScalingScalingPolicyCustomizedMetricSpecificationStatistic
, fmap (("Unit",) . toJSON) _autoScalingScalingPolicyCustomizedMetricSpecificationUnit
]
-- | Constructor for 'AutoScalingScalingPolicyCustomizedMetricSpecification'
-- containing required fields as arguments.
autoScalingScalingPolicyCustomizedMetricSpecification
:: Val Text -- ^ 'asspcmsMetricName'
-> Val Text -- ^ 'asspcmsNamespace'
-> Val Text -- ^ 'asspcmsStatistic'
-> AutoScalingScalingPolicyCustomizedMetricSpecification
autoScalingScalingPolicyCustomizedMetricSpecification metricNamearg namespacearg statisticarg =
AutoScalingScalingPolicyCustomizedMetricSpecification
{ _autoScalingScalingPolicyCustomizedMetricSpecificationDimensions = Nothing
, _autoScalingScalingPolicyCustomizedMetricSpecificationMetricName = metricNamearg
, _autoScalingScalingPolicyCustomizedMetricSpecificationNamespace = namespacearg
, _autoScalingScalingPolicyCustomizedMetricSpecificationStatistic = statisticarg
, _autoScalingScalingPolicyCustomizedMetricSpecificationUnit = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-dimensions
asspcmsDimensions :: Lens' AutoScalingScalingPolicyCustomizedMetricSpecification (Maybe [AutoScalingScalingPolicyMetricDimension])
asspcmsDimensions = lens _autoScalingScalingPolicyCustomizedMetricSpecificationDimensions (\s a -> s { _autoScalingScalingPolicyCustomizedMetricSpecificationDimensions = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-metricname
asspcmsMetricName :: Lens' AutoScalingScalingPolicyCustomizedMetricSpecification (Val Text)
asspcmsMetricName = lens _autoScalingScalingPolicyCustomizedMetricSpecificationMetricName (\s a -> s { _autoScalingScalingPolicyCustomizedMetricSpecificationMetricName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-namespace
asspcmsNamespace :: Lens' AutoScalingScalingPolicyCustomizedMetricSpecification (Val Text)
asspcmsNamespace = lens _autoScalingScalingPolicyCustomizedMetricSpecificationNamespace (\s a -> s { _autoScalingScalingPolicyCustomizedMetricSpecificationNamespace = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-statistic
asspcmsStatistic :: Lens' AutoScalingScalingPolicyCustomizedMetricSpecification (Val Text)
asspcmsStatistic = lens _autoScalingScalingPolicyCustomizedMetricSpecificationStatistic (\s a -> s { _autoScalingScalingPolicyCustomizedMetricSpecificationStatistic = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-unit
asspcmsUnit :: Lens' AutoScalingScalingPolicyCustomizedMetricSpecification (Maybe (Val Text))
asspcmsUnit = lens _autoScalingScalingPolicyCustomizedMetricSpecificationUnit (\s a -> s { _autoScalingScalingPolicyCustomizedMetricSpecificationUnit = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/AutoScalingScalingPolicyCustomizedMetricSpecification.hs | mit | 5,277 | 0 | 13 | 373 | 540 | 308 | 232 | 46 | 1 |
module ExtractRules (
extractRules
) where
import DataModel
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Map(Map)
extractRules :: Confidence -> [ItemSet] -> [ItemSet] -> [Rule]
extractRules threshold table patterns = filter (\x -> threshold <= confidence table x) rules where
rules = Map.foldrWithKey (\k v old -> ruleFromSubset v k : old) [] subsets
subsets = foldr (\x -> insertMultiple (filteredPowerset x) x) Map.empty patterns
filteredPowerset (ItemSet set) = map (ItemSet . Set.fromList) $
filter (\val -> val /= Set.toList set && val /= []) $ powerset $ Set.toList set
ruleFromSubset :: ItemSet -> ItemSet -> Rule
ruleFromSubset set subset = Rule subset (difference set subset)
insertMultiple :: Ord k => [k] -> a -> Map k a -> Map k a
insertMultiple keys value m = foldr (\x old -> Map.insert x value old) m keys
powerset :: [a] -> [[a]]
powerset [] = [[]]
powerset (x:xs) = xss /\/ map (x:) xss where
xss = powerset xs
(/\/) :: [a] -> [a] -> [a]
[] /\/ ys = ys
(x:xs) /\/ ys = x : (ys /\/ xs)
| Xawirses/GitMining | ExtractRules.hs | gpl-2.0 | 1,077 | 0 | 17 | 226 | 491 | 261 | 230 | 23 | 1 |
-- by Partick Yoon yeyoon and Mark Smyda msmyda
{-# OPTIONS -Wall -fwarn-tabs -fno-warn-type-defaults -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, ScopedTypeVariables, NamedFieldPuns,
TupleSections, FlexibleContexts #-}
module Helper (char2bin,
swap,
twoTupleM,
threeTupleM,
repeatWhile,
toBinRep,
map2,
isOrdered
) where
import Data.List (unfoldr)
import Control.Monad
-- | Helper function for checking if a list is ordered
isOrdered :: Ord b => (a -> b) -> [a] -> Bool
isOrdered f (x1:x2:xs) = f x1 <= f x2 && isOrdered f (x2:xs)
isOrdered _ _ = True
-- | repeat until a condition is met. Used for
-- repeatedly evolving the population.
repeatWhile :: Monad m => (a -> Bool) -> (a -> m a) -> a -> m a
repeatWhile stop f = go
where go x | stop x = return x
| otherwise = f x >>= go
-- | Helper function : make a two-tuple by replicating a monad instance twice
twoTupleM :: Monad m => m a -> m (a, a)
twoTupleM = liftM toTwoTuple . replicateM 2
where toTwoTuple :: [a] -> (a, a)
toTwoTuple [x,y] = (x,y)
toTwoTuple _ = error "Impossible case"
-- | Helper function : make a three-tuple by replicating a monad instance
-- three times
threeTupleM :: Monad m => m a -> m (a, a, a)
threeTupleM = liftM toThreeTuple . replicateM 3
where toThreeTuple :: [a] -> (a, a, a)
toThreeTuple [x, y, z] = (x, y, z)
toThreeTuple _ = error "Impossible case."
-- | helper swap function for mutateChSwap.
-- Swaps element of a list at two indices.
swap :: Int -> Int -> [a] -> [a]
swap i j xs
| i == j = xs
| otherwise = take l xs ++ [xs !! u] ++
(take (u-l-1) $ drop (l+1) xs) ++ [xs !! l] ++ drop (u+1) xs
where l = if i < j then i else j
u = if i > j then i else j
-- | Converts a character into its binary represenation
-- reference : PLEAC-Haskell
char2bin :: Char -> [Char]
char2bin = map i2c . reverse . unfoldr decomp . fromEnum
where decomp :: Int -> Maybe (Int, Int)
decomp n = if n == 0 then Nothing else Just(n `mod` 2, n `div` 2)
i2c :: Int -> Char
i2c i = if i == 0 then '0' else '1'
-- | Convert to binary representation of the String
toBinRep :: String -> String
toBinRep = concat . map char2bin
-- | map over two lists
-- reference : hw1 solution
map2 :: (a -> b -> c) -> [a] -> [b] -> [c]
map2 f (x:xs) (y:ys) = f x y : map2 f xs ys
map2 _ [] _ = []
map2 _ _ [] = [] | patyoon/haskell-genetic-algorithm | Helper.hs | gpl-2.0 | 2,610 | 0 | 14 | 797 | 867 | 467 | 400 | -1 | -1 |
import Parser
import Obj
import Data.List
import Data.Set (fromList)
import Test.QuickCheck
instance Arbitrary Exp where
arbitrary = oneof $ map return
[Vertex 1 2 3
,Vertex 2 3 4
,Vertex 4 5 6
,Face 1 2 3]
prop_permutation xs = processObj xs `check` processObj (reverse xs)
check (vs, fs, os) (vs', fs', os') = all check' [(vs, vs'), (fs, fs'), (os, os')]
check' (as, as') = fromList as == fromList as'
| mvcisback/typesafe_teapot | src/Test.hs | gpl-2.0 | 477 | 0 | 9 | 144 | 199 | 109 | 90 | 14 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Vdv.Filter where
import ClassyPrelude
import Control.Lens(makeLenses)
import qualified Data.Attoparsec.Text as AP
import Vdv.FilterOperator
import Vdv.ElementPath
import Vdv.Attoparsec
import Options.Applicative(ReadM,eitherReader)
data Filter = Filter {
_filterTagPath :: ElementPath
, _filterOperator :: FilterOperator
, _filterTagValue :: Text
} deriving(Show,Eq)
$(makeLenses ''Filter)
operatorChars = "|<>=~"
parseElementPath :: AP.Parser ElementPath
parseElementPath = pathFromParts <$> (manyNotChars ("/," <> operatorChars) `AP.sepBy` (AP.char '/'))
parseOperatorString :: AP.Parser Text
parseOperatorString = pack <$> (AP.many1 (AP.satisfy (AP.inClass operatorChars)))
filterParser :: AP.Parser [Filter]
filterParser = singleFilter `AP.sepBy` (AP.char ',')
where parseOperator "=" = FilterOperatorEq
parseOperator "~" = FilterOperatorLike
parseOperator "<" = FilterOperatorLe
parseOperator ">" = FilterOperatorGe
parseOperator "|<" = FilterOperatorDateLe
parseOperator "|>" = FilterOperatorDateGe
parseOperator "|=" = FilterOperatorDateEq
parseOperator o = error $ "Invalid operator " <> show o
singleFilter = Filter <$> parseElementPath <*> (parseOperator <$> parseOperatorString) <*> (pack <$> (AP.many1 (AP.notChar ',')))
parseFilters :: Text -> Either String [Filter]
parseFilters t = AP.parseOnly filterParser t
filtersOpt :: ReadM [Filter]
filtersOpt = eitherReader (parseFilters . pack)
| pmiddend/vdvanalyze | src/Vdv/Filter.hs | gpl-3.0 | 1,528 | 0 | 14 | 248 | 419 | 228 | 191 | 35 | 8 |
{-# LANGUAGE OverloadedStrings #-}
module Estuary.Help.LanguageHelp where
import Reflex
import Reflex.Dom
import Data.Text (Text)
import qualified Data.Text as Td
import Data.Map
import Control.Monad
import GHCJS.DOM.EventM -- just used for our test, maybe delete-able later
import Estuary.Help.NoHelpFile
import Estuary.Help.MiniTidal
import Estuary.Help.CQenze
import Estuary.Help.LaCalle
import Estuary.Help.Sucixxx
import Estuary.Help.Togo
import Estuary.Help.PunctualAudio
import Estuary.Help.Hydra
import Estuary.Help.CineCer0.CineCer0
import Estuary.Help.CineCer0.CineCer0Reference
import Estuary.Types.TidalParser
import Estuary.Languages.TidalParsers
import Estuary.Types.TextNotation
parserToHelp :: (MonadWidget t m) => TextNotation -> m ()
parserToHelp (TidalTextNotation CQenze) = cqenzeHelpFile
parserToHelp (TidalTextNotation Sucixxx) = sucixxxHelpFile
parserToHelp (TidalTextNotation MiniTidal) = miniTidalHelpFile
parserToHelp (TidalTextNotation LaCalle) = laCalleHelpFile
parserToHelp (TidalTextNotation Togo) = togoHelpFile
parserToHelp Punctual = punctualAudioHelpFile
parserToHelp _ = noHelpFile
| d0kt0r0/estuary | client/src/Estuary/Help/LanguageHelp.hs | gpl-3.0 | 1,121 | 0 | 8 | 107 | 242 | 144 | 98 | 30 | 1 |
{-# Language DataKinds, OverloadedStrings #-}
-- Shows how to connect to a broker, subscribe to a bunch of topics and inspect
-- to which of those a message was published to.
-- Doesn't publish any messages itself, use mosquitto_pub or something else for
-- that.
module Subscribe where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad (unless, forever)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import qualified Network.MQTT as MQTT
t1, t2 :: MQTT.Topic
t1 = "topic1"
t2 = "topic2/#"
handleMsg :: MQTT.Message MQTT.PUBLISH -> IO ()
handleMsg msg =
-- sometimes it's useful to ignore retained messages
unless (MQTT.retain $ MQTT.header msg) $ do
let t = MQTT.topic $ MQTT.body msg
p = MQTT.payload $ MQTT.body msg
case MQTT.getLevels t of
["topic1"] -> putStr "topic1: " >> print p
["topic2", "foo"] -> putStr "foo: " >> print p
"topic2" : bar -> print bar
_unexpected -> putStrLn $ "unexpected message on '" ++ show t ++ "': " ++ show p
main :: IO ()
main = do
cmds <- MQTT.mkCommands
pubChan <- newTChanIO
let conf = (MQTT.defaultConfig cmds pubChan)
{ MQTT.cUsername = Just "mqtt-hs"
, MQTT.cPassword = Just "secret"
}
_ <- forkIO $ do
qosGranted <- MQTT.subscribe conf [(t1, MQTT.Handshake), (t2, MQTT.Handshake)]
case qosGranted of
[MQTT.Handshake, MQTT.Handshake] -> forever $ atomically (readTChan pubChan) >>= handleMsg
_ -> do
hPutStrLn stderr $ "Wanted QoS Handshake, got " ++ show qosGranted
exitFailure
-- this will throw IOExceptions
terminated <- MQTT.run conf
print terminated
| k00mi/mqtt-hs | examples/subscribe.hs | gpl-3.0 | 1,714 | 0 | 18 | 408 | 470 | 242 | 228 | 37 | 4 |
module Aura.Flags
( Program(..), opts
, PacmanOp( Sync ), SyncOp( SyncUpgrade ), SyncSwitch(..), MiscOp
, AuraOp(..), AurSwitch(..), _AurSync, _AurIgnore, _AurIgnoreGroup
, AurOp(..), BackupOp(..), CacheOp(..), LogOp(..), OrphanOp(..), AnalysisOp(..)
) where
import Aura.Cache (defaultPackageCache)
import Aura.Pacman (defaultLogFile, pacmanConfFile)
import Aura.Settings
import Aura.Types
import Lens.Micro (Traversal')
import Options.Applicative
import RIO hiding (exp, log)
import RIO.FilePath
import RIO.List.Partial (foldr1)
import qualified RIO.NonEmpty as NEL
import qualified RIO.NonEmpty.Partial as NELP
import qualified RIO.Set as S
import qualified RIO.Text as T
---
-- | A description of a run of Aura to attempt.
data Program = Program {
_operation :: Either (PacmanOp, Set MiscOp) AuraOp
-- ^ Whether Aura handles everything, or the ops and input are just passed down to Pacman.
, _commons :: CommonConfig
-- ^ Settings common to both Aura and Pacman.
, _buildConf :: BuildConfig
-- ^ Settings specific to building packages.
, _language :: Maybe Language
-- ^ The human language of text output.
, _logLevel :: LogLevel
-- ^ The default RIO logging level.
} deriving (Show)
-- | Inherited operations that are fed down to Pacman.
data PacmanOp
= Database (Either DatabaseOp (NonEmpty PkgName))
| Files (Set FilesOp)
| Query (Either QueryOp (Set QueryFilter, Set PkgName))
| Remove (Set RemoveOp) (NonEmpty PkgName)
| Sync (Either (NonEmpty SyncOp) (Set PkgName)) (Set SyncSwitch)
| TestDeps (NonEmpty Text)
| Upgrade (Set UpgradeSwitch) (NonEmpty PkgName)
deriving (Show)
instance Flagable PacmanOp where
asFlag (Database (Left o)) = "-D" : asFlag o
asFlag (Database (Right fs)) = "-D" : asFlag fs
asFlag (Files os) = "-F" : asFlag os
asFlag (Query (Left o)) = "-Q" : asFlag o
asFlag (Query (Right (fs, ps))) = "-Q" : asFlag ps ++ asFlag fs
asFlag (Remove os ps) = "-R" : asFlag os ++ asFlag ps
asFlag (Sync (Left o) ss) = "-S" : asFlag ss ++ asFlag o
asFlag (Sync (Right ps) ss) = "-S" : asFlag ss ++ asFlag ps
asFlag (TestDeps ps) = "-T" : asFlag ps
asFlag (Upgrade s ps) = "-U" : asFlag s ++ asFlag ps
data DatabaseOp
= DBCheck
| DBAsDeps (NonEmpty Text)
| DBAsExplicit (NonEmpty Text)
deriving (Show)
instance Flagable DatabaseOp where
asFlag DBCheck = ["--check"]
asFlag (DBAsDeps ps) = "--asdeps" : asFlag ps
asFlag (DBAsExplicit ps) = "--asexplicit" : asFlag ps
data FilesOp
= FilesList (NonEmpty Text)
| FilesOwns Text
| FilesSearch Text
| FilesRegex
| FilesRefresh
| FilesMachineReadable
deriving (Eq, Ord, Show)
instance Flagable FilesOp where
asFlag (FilesList fs) = "--list" : asFlag fs
asFlag (FilesOwns f) = ["--owns", f]
asFlag (FilesSearch f) = ["--search", f]
asFlag FilesRegex = ["--regex"]
asFlag FilesRefresh = ["--refresh"]
asFlag FilesMachineReadable = ["--machinereadable"]
data QueryOp
= QueryChangelog (NonEmpty Text)
| QueryGroups (NonEmpty Text)
| QueryInfo (NonEmpty Text)
| QueryCheck (NonEmpty Text)
| QueryList (NonEmpty Text)
| QueryOwns (NonEmpty Text)
| QueryFile (NonEmpty Text)
| QuerySearch Text
deriving (Show)
instance Flagable QueryOp where
asFlag (QueryChangelog ps) = "--changelog" : asFlag ps
asFlag (QueryGroups ps) = "--groups" : asFlag ps
asFlag (QueryInfo ps) = "--info" : asFlag ps
asFlag (QueryCheck ps) = "--check" : asFlag ps
asFlag (QueryList ps) = "--list" : asFlag ps
asFlag (QueryOwns ps) = "--owns" : asFlag ps
asFlag (QueryFile ps) = "--file" : asFlag ps
asFlag (QuerySearch t) = ["--search", t]
data QueryFilter
= QueryDeps
| QueryExplicit
| QueryForeign
| QueryNative
| QueryUnrequired
| QueryUpgrades
deriving (Eq, Ord, Show)
instance Flagable QueryFilter where
asFlag QueryDeps = ["--deps"]
asFlag QueryExplicit = ["--explicit"]
asFlag QueryForeign = ["--foreign"]
asFlag QueryNative = ["--native"]
asFlag QueryUnrequired = ["--unrequired"]
asFlag QueryUpgrades = ["--upgrades"]
data RemoveOp
= RemoveCascade
| RemoveNoSave
| RemoveRecursive
| RemoveUnneeded
deriving (Eq, Ord, Show)
instance Flagable RemoveOp where
asFlag RemoveCascade = ["--cascade"]
asFlag RemoveNoSave = ["--nosave"]
asFlag RemoveRecursive = ["--recursive"]
asFlag RemoveUnneeded = ["--unneeded"]
data SyncOp
= SyncClean
| SyncGroups (NonEmpty Text)
| SyncInfo (NonEmpty Text)
| SyncList Text
| SyncSearch (NonEmpty Text)
| SyncUpgrade (Set Text)
| SyncDownload (NonEmpty Text)
deriving (Eq, Ord, Show)
instance Flagable SyncOp where
asFlag SyncClean = ["--clean"]
asFlag (SyncGroups gs) = "--groups" : asFlag gs
asFlag (SyncInfo ps) = "--info" : asFlag ps
asFlag (SyncList r) = ["--list", r]
asFlag (SyncSearch s) = "--search" : asFlag s
asFlag (SyncUpgrade ps) = "--sysupgrade" : asFlag ps
asFlag (SyncDownload ps) = "--downloadonly" : asFlag ps
data SyncSwitch
= SyncRefresh
| SyncIgnore (Set PkgName)
| SyncIgnoreGroup (Set PkgGroup)
| SyncOverwrite Text
deriving (Eq, Ord, Show)
instance Flagable SyncSwitch where
asFlag SyncRefresh = ["--refresh"]
asFlag (SyncIgnore ps) = ["--ignore", T.intercalate "," $ asFlag ps ]
asFlag (SyncIgnoreGroup gs) = ["--ignoregroup" , T.intercalate "," $ asFlag gs ]
asFlag (SyncOverwrite glob) = "--overwrite" : asFlag glob
data UpgradeSwitch
= UpgradeAsDeps
| UpgradeAsExplicit
| UpgradeIgnore (Set PkgName)
| UpgradeIgnoreGroup (Set PkgGroup)
| UpgradeOverwrite Text
deriving (Eq, Ord, Show)
instance Flagable UpgradeSwitch where
asFlag UpgradeAsDeps = ["--asdeps"]
asFlag UpgradeAsExplicit = ["--asexplicit"]
asFlag (UpgradeIgnore ps) = ["--ignore", T.intercalate "," $ asFlag ps ]
asFlag (UpgradeIgnoreGroup gs) = ["--ignoregroup", T.intercalate "," $ asFlag gs ]
asFlag (UpgradeOverwrite glob) = "--overwrite" : asFlag glob
-- | Flags common to several Pacman operations.
data MiscOp
= MiscArch FilePath
| MiscAssumeInstalled Text
| MiscColor Text
| MiscConfirm
| MiscDBOnly
| MiscDBPath FilePath
| MiscGpgDir FilePath
| MiscHookDir FilePath
| MiscNoDeps
| MiscNoProgress
| MiscNoScriptlet
| MiscPrint
| MiscPrintFormat Text
| MiscRoot FilePath
| MiscVerbose
deriving (Eq, Ord, Show)
instance Flagable MiscOp where
asFlag (MiscArch p) = ["--arch", T.pack p]
asFlag (MiscAssumeInstalled p) = ["--assume-installed", p]
asFlag (MiscColor c) = ["--color", c]
asFlag (MiscDBPath p) = ["--dbpath", T.pack p]
asFlag (MiscGpgDir p) = ["--gpgdir", T.pack p]
asFlag (MiscHookDir p) = ["--hookdir", T.pack p]
asFlag (MiscPrintFormat s) = ["--print-format", s]
asFlag (MiscRoot p) = ["--root", T.pack p]
asFlag MiscConfirm = ["--confirm"]
asFlag MiscDBOnly = ["--dbonly"]
asFlag MiscNoDeps = ["--nodeps"]
asFlag MiscNoProgress = ["--noprogressbar"]
asFlag MiscNoScriptlet = ["--noscriptlet"]
asFlag MiscPrint = ["--print"]
asFlag MiscVerbose = ["--verbose"]
-- | Operations unique to Aura.
data AuraOp
= AurSync (Either AurOp (NonEmpty PkgName)) (Set AurSwitch)
| Backup (Maybe BackupOp)
| Cache (Either CacheOp (NonEmpty PkgName))
| Log (Maybe LogOp)
| Orphans (Maybe OrphanOp)
| Analysis (Maybe AnalysisOp)
| Version
| Languages
| ViewConf
deriving (Show)
_AurSync :: Traversal' AuraOp (Set AurSwitch)
_AurSync f (AurSync o s) = AurSync o <$> f s
_AurSync _ x = pure x
data AurOp
= AurDeps (NonEmpty PkgName)
| AurInfo (NonEmpty PkgName)
| AurPkgbuild (NonEmpty PkgName)
| AurSearch Text
| AurUpgrade (Set PkgName)
| AurJson (NonEmpty PkgName)
| AurTarball (NonEmpty PkgName)
deriving (Show)
data AurSwitch
= AurIgnore (Set PkgName)
| AurIgnoreGroup (Set PkgGroup)
| AurRepoSync
deriving (Eq, Ord, Show)
_AurIgnore :: Traversal' AurSwitch (Set PkgName)
_AurIgnore f (AurIgnore s) = AurIgnore <$> f s
_AurIgnore _ x = pure x
_AurIgnoreGroup :: Traversal' AurSwitch (Set PkgGroup)
_AurIgnoreGroup f (AurIgnoreGroup s) = AurIgnoreGroup <$> f s
_AurIgnoreGroup _ x = pure x
data BackupOp
= BackupClean Word
| BackupRestore
| BackupList deriving (Show)
data CacheOp
= CacheBackup FilePath
| CacheClean Word
| CacheCleanNotSaved
| CacheSearch Text
deriving (Show)
data LogOp
= LogInfo (NonEmpty PkgName)
| LogSearch Text
deriving (Show)
data OrphanOp
= OrphanAbandon
| OrphanAdopt (NonEmpty PkgName)
deriving (Show)
data AnalysisOp
= AnalysisFile FilePath
| AnalysisDir FilePath
| AnalysisAudit
deriving (Show)
opts :: ParserInfo Program
opts = info (program <**> helper)
(fullDesc <> header "Aura - Package manager for Arch Linux and the AUR.")
program :: Parser Program
program = Program
<$> (fmap Right aurOps <|> (curry Left <$> pacOps <*> misc))
<*> commonConfig
<*> buildConfig
<*> optional language
<*> logLevel
where
aurOps = aursync <|> backups <|> cache <|> log <|> orphans <|> analysis <|> version' <|> languages <|> viewconf
pacOps = database <|> files <|> queries <|> remove <|> sync <|> testdeps <|> upgrades
aursync :: Parser AuraOp
aursync = bigA *>
(AurSync
<$> (fmap (Right . NEL.map (PkgName . T.toLower)) someArgs <|> fmap Left mods)
<*> (S.fromList <$> many switches)
)
where bigA = flag' () (long "aursync" <> short 'A' <> help "Install packages from the AUR.")
mods = ds <|> ainfo <|> pkgb <|> search <|> upgrade <|> aur <|> tarball
ds = AurDeps <$> (flag' () (long "deps" <> short 'd' <> hidden <> help "View dependencies of an AUR package.") *> somePkgs')
ainfo = AurInfo <$> (flag' () (long "info" <> short 'i' <> hidden <> help "View AUR package information.") *> somePkgs')
pkgb = AurPkgbuild <$> (flag' () (long "pkgbuild" <> short 'p' <> hidden <> help "View an AUR package's PKGBUILD file.") *> somePkgs')
search = AurSearch <$> strOption (long "search" <> short 's' <> metavar "STRING" <> hidden <> help "Search the AUR via a search string.")
upgrade = AurUpgrade <$> (flag' () (long "sysupgrade" <> short 'u' <> hidden <> help "Upgrade all installed AUR packages.") *> fmap (S.map PkgName) manyArgs')
aur = AurJson <$> (flag' () (long "json" <> hidden <> help "Retrieve package JSON straight from the AUR.") *> somePkgs')
tarball = AurTarball <$> (flag' () (long "downloadonly" <> short 'w' <> hidden <> help "Download a package tarball.") *> somePkgs')
switches = ign <|> igg <|> y
ign = AurIgnore . S.fromList . map PkgName . T.split (== ',')
<$> strOption (long "ignore" <> metavar "PKG(,PKG,...)" <> hidden <> help "Ignore given packages.")
igg = AurIgnoreGroup . S.fromList . map PkgGroup . T.split (== ',')
<$> strOption (long "ignoregroup" <> metavar "PKG(,PKG,...)" <> hidden <> help "Ignore packages from the given groups.")
y = flag' AurRepoSync (short 'y' <> hidden <> help "Do an -Sy before continuing.")
backups :: Parser AuraOp
backups = bigB *> (Backup <$> optional mods)
where bigB = flag' () (long "save" <> short 'B' <> help "Save a package state.")
mods = clean <|> restore <|> lst
clean = BackupClean <$> option auto (long "clean" <> short 'c' <> metavar "N" <> hidden <> help "Keep the most recent N states, delete the rest.")
restore = flag' BackupRestore (long "restore" <> short 'r' <> hidden <> help "Restore a previous package state.")
lst = flag' BackupList (long "list" <> short 'l' <> hidden <> help "Show all saved package state filenames.")
cache :: Parser AuraOp
cache = bigC *> (Cache <$> (fmap Left mods <|> fmap Right somePkgs))
where bigC = flag' () (long "downgrade" <> short 'C' <> help "Interact with the package cache.")
mods = backup <|> clean <|> clean' <|> search
backup = CacheBackup <$> option (eitherReader absFilePath) (long "backup" <> short 'b' <> metavar "PATH" <> help "Backup the package cache to a given directory." <> hidden)
clean = CacheClean <$> option auto (long "clean" <> short 'c' <> metavar "N" <> help "Save the most recent N versions of a package in the cache, deleting the rest." <> hidden)
clean' = flag' CacheCleanNotSaved (long "notsaved" <> help "Clean out any cached package files which doesn't appear in any saved state." <> hidden)
search = CacheSearch <$> strOption (long "search" <> short 's' <> metavar "STRING" <> help "Search the package cache via a search string." <> hidden)
log :: Parser AuraOp
log = bigL *> (Log <$> optional mods)
where bigL = flag' () (long "viewlog" <> short 'L' <> help "View the Pacman log.")
mods = inf <|> sch
inf = LogInfo <$> (flag' () (long "info" <> short 'i' <> help "Display the installation history for given packages." <> hidden) *> somePkgs')
sch = LogSearch <$> strOption (long "search" <> short 's' <> metavar "STRING" <> help "Search the Pacman log via a search string." <> hidden)
orphans :: Parser AuraOp
orphans = bigO *> (Orphans <$> optional mods)
where bigO = flag' () (long "orphans" <> short 'O' <> help "Display all orphan packages.")
mods = abandon <|> adopt
abandon = flag' OrphanAbandon (long "abandon" <> short 'j' <> hidden <> help "Uninstall all orphan packages.")
adopt = OrphanAdopt <$> (flag' () (long "adopt" <> short 'a' <> hidden <> help "Mark some packages' install reason as 'Explicit'.") *> somePkgs')
analysis :: Parser AuraOp
analysis = bigP *> (Analysis <$> optional mods)
where
bigP = flag' () (long "analysis" <> short 'P' <> help "Analyse PKGBUILDs for malicious bash code.")
mods = file <|> dir <|> audit
file = AnalysisFile <$> strOption (long "file" <> short 'f' <> metavar "PATH" <> hidden <> help "Path to a PKGBUILD file.")
dir = AnalysisDir <$> strOption (long "dir" <> short 'd' <> metavar "PATH" <> hidden <> help "Path to a directory containing a PKGBUILD file.")
audit = flag' AnalysisAudit (long "audit" <> short 'a' <> hidden <> help "Analyse PKGBUILDs of installed AUR packages.")
version' :: Parser AuraOp
version' = flag' Version (long "version" <> short 'V' <> help "Display Aura's version.")
languages :: Parser AuraOp
languages = flag' Languages (long "languages" <> help "Show all human languages available for output.")
viewconf :: Parser AuraOp
viewconf = flag' ViewConf (long "viewconf" <> help "View the Pacman config file.")
buildConfig :: Parser BuildConfig
buildConfig = BuildConfig <$> makepkg <*> bp <*> bu <*> asp <*> vp <*> trunc <*> buildSwitches
where makepkg = S.fromList <$> many (ia <|> as <|> si)
ia = flag' IgnoreArch (long "ignorearch" <> hidden <> help "Exposed makepkg flag.")
as = flag' AllSource (long "allsource" <> hidden <> help "Exposed makepkg flag.")
si = flag' SkipInteg (long "skipinteg" <> hidden <> help "Skip all makepkg integrity checks.")
bp = optional $ option (eitherReader absFilePath) (long "build" <> metavar "PATH" <> hidden <> help "Directory in which to build packages.")
bu = optional $ User <$> strOption (long "builduser" <> metavar "USER" <> hidden <> help "User account to build as.")
asp = optional $ option (eitherReader absFilePath) (long "allsourcepath" <> metavar "PATH" <> hidden <> help "Directory in which to store the output of --allsource.")
vp = optional $ option (eitherReader absFilePath) (long "vcspath" <> metavar "PATH" <> hidden <> help "Directory in which to build and store VCS packages.")
trunc = fmap Head (option auto (long "head" <> metavar "N" <> hidden <> help "Only show top N search results."))
<|> fmap Tail (option auto (long "tail" <> metavar "N" <> hidden <> help "Only show last N search results."))
<|> pure None
buildSwitches :: Parser (Set BuildSwitch)
buildSwitches = S.fromList <$> many (lv <|> dmd <|> dsm <|> dpb <|> rbd <|> he <|> dr <|> sa <|> fo <|> npc <|> asd)
where dmd = flag' DeleteMakeDeps (long "delmakedeps" <> short 'a' <> hidden <> help "Uninstall makedeps after building.")
dsm = flag' DontSuppressMakepkg (long "unsuppress" <> short 'x' <> hidden <> help "Unsuppress makepkg output.")
dpb = flag' DiffPkgbuilds (long "diff" <> short 'k' <> hidden <> help "Show PKGBUILD diffs.")
rbd = flag' RebuildDevel (long "devel" <> hidden <> help "Rebuild all git/hg/svn/darcs-based packages.")
he = flag' HotEdit (long "hotedit" <> hidden <> help "Edit a PKGBUILD before building.")
dr = flag' DryRun (long "dryrun" <> hidden <> help "Run dependency checks and PKGBUILD diffs, but don't build.")
sa = flag' SortAlphabetically (long "abc" <> hidden <> help "Sort search results alphabetically.")
lv = flag' LowVerbosity (long "quiet" <> short 'q' <> hidden <> help "Display less information.")
fo = flag' ForceBuilding (long "force" <> hidden <> help "Always (re)build specified packages.")
npc = flag' NoPkgbuildCheck (long "noanalysis" <> hidden <> help "Do not analyse PKGBUILDs for security flaws.")
asd = flag' AsDeps (long "asdeps" <> hidden <> help "All installed packages will be marked as dependencies.")
commonConfig :: Parser CommonConfig
commonConfig = CommonConfig <$> cap <*> cop <*> lfp <*> commonSwitches
where cap = fmap Right
(option (eitherReader absFilePath) (long "cachedir" <> hidden <> help "Use an alternate package cache location."))
<|> pure (Left defaultPackageCache)
cop = fmap Right
(option (eitherReader absFilePath) (long "config" <> hidden <> help "Use an alternate Pacman config file."))
<|> pure (Left pacmanConfFile)
lfp = fmap Right
(option (eitherReader absFilePath) (long "logfile" <> hidden <> help "Use an alternate Pacman log."))
<|> pure (Left defaultLogFile)
commonSwitches :: Parser (Set CommonSwitch)
commonSwitches = S.fromList <$> many (nc <|> no <|> dbg <|> clr <|> ovr)
where nc = flag' NoConfirm (long "noconfirm" <> hidden <> help "Never ask for Aura or Pacman confirmation.")
no = flag' NeededOnly (long "needed" <> hidden <> help "Don't rebuild/reinstall up-to-date packages.")
dbg = flag' Debug (long "debug" <> hidden <> help "Print useful debugging info.")
ovr = Overwrite <$> strOption (long "overwrite" <> hidden <> help "Bypass file conflict checks." <> metavar "GLOB")
clr = Colour . f <$> strOption (long "color" <> metavar "WHEN" <> hidden <> help "Colourize the output.")
f :: String -> ColourMode
f "never" = Never
f "always" = Always
f _ = Auto
database :: Parser PacmanOp
database = bigD *> (Database <$> (fmap Right somePkgs <|> fmap Left mods))
where bigD = flag' () (long "database" <> short 'D' <> help "Interact with the package database.")
mods = check <|> asdeps <|> asexp
check = flag' DBCheck (long "check" <> short 'k' <> hidden <> help "Test local database validity.")
asdeps = DBAsDeps <$> (flag' () (long "asdeps" <> hidden <> help "Mark packages as being dependencies.") *> someArgs')
asexp = DBAsExplicit <$> (flag' () (long "asexplicit" <> hidden <> help "Mark packages as being explicitely installed.") *> someArgs')
files :: Parser PacmanOp
files = bigF *> (Files <$> fmap S.fromList (many mods))
where bigF = flag' () (long "files" <> short 'F' <> help "Interact with the file database.")
mods = lst <|> own <|> sch <|> rgx <|> rfr <|> mch
lst = FilesList <$> (flag' () (long "list" <> short 'l' <> hidden <> help "List the files owned by given packages.") *> someArgs')
own = FilesOwns <$> strOption (long "owns" <> short 'o' <> metavar "FILE" <> hidden <> help "Query the package that owns FILE.")
sch = FilesSearch <$> strOption (long "search" <> short 's' <> metavar "FILE" <> hidden <> help "Find package files that match the given FILEname.")
rgx = flag' FilesRegex (long "regex" <> short 'x' <> hidden <> help "Interpret the input of -Fs as a regex.")
rfr = flag' FilesRefresh (long "refresh" <> short 'y' <> hidden <> help "Download fresh package databases.")
mch = flag' FilesMachineReadable (long "machinereadable" <> hidden <> help "Produce machine-readable output.")
queries :: Parser PacmanOp
queries = bigQ *> (Query <$> (fmap Right query <|> fmap Left mods))
where bigQ = flag' () (long "query" <> short 'Q' <> help "Interact with the local package database.")
query = curry (second (S.map PkgName)) <$> queryFilters <*> manyArgs
mods = chl <|> gps <|> inf <|> lst <|> own <|> fls <|> sch <|> chk
chl = QueryChangelog <$> (flag' () (long "changelog" <> short 'c' <> hidden <> help "View a package's changelog.") *> someArgs')
gps = QueryGroups <$> (flag' () (long "groups" <> short 'g' <> hidden <> help "View all members of a package group.") *> someArgs')
inf = QueryInfo <$> (flag' () (long "info" <> short 'i' <> hidden <> help "View package information.") *> someArgs')
lst = QueryList <$> (flag' () (long "list" <> short 'l' <> hidden <> help "List files owned by a package.") *> someArgs')
chk = QueryCheck <$> (flag' () (long "check" <> short 'k' <> hidden <> help "Check that package files exist.") *> someArgs')
own = QueryOwns <$> (flag' () (long "owns" <> short 'o' <> hidden <> help "Find the package some file belongs to.") *> someArgs')
fls = QueryFile <$> (flag' () (long "file" <> short 'p' <> hidden <> help "Query a package file.") *> someArgs')
sch = QuerySearch <$> strOption (long "search" <> short 's' <> metavar "REGEX" <> hidden <> help "Search the local database.")
queryFilters :: Parser (Set QueryFilter)
queryFilters = S.fromList <$> many (dps <|> exp <|> frg <|> ntv <|> urq <|> upg)
where dps = flag' QueryDeps (long "deps" <> short 'd' <> hidden <> help "[filter] Only list packages installed as deps.")
exp = flag' QueryExplicit (long "explicit" <> short 'e' <> hidden <> help "[filter] Only list explicitly installed packages.")
frg = flag' QueryForeign (long "foreign" <> short 'm' <> hidden <> help "[filter] Only list AUR packages.")
ntv = flag' QueryNative (long "native" <> short 'n' <> hidden <> help "[filter] Only list official packages.")
urq = flag' QueryUnrequired (long "unrequired" <> short 't' <> hidden <> help "[filter] Only list packages not required as a dependency to any other.")
upg = flag' QueryUpgrades (long "upgrades" <> short 'u' <> hidden <> help "[filter] Only list outdated packages.")
remove :: Parser PacmanOp
remove = bigR *> (Remove <$> mods <*> somePkgs)
where bigR = flag' () (long "remove" <> short 'R' <> help "Uninstall packages.")
mods = S.fromList <$> many (cascade <|> nosave <|> recurse <|> unneeded)
cascade = flag' RemoveCascade (long "cascade" <> short 'c' <> hidden <> help "Remove packages and all others that depend on them.")
nosave = flag' RemoveNoSave (long "nosave" <> short 'n' <> hidden <> help "Remove configuration files as well.")
recurse = flag' RemoveRecursive (long "recursive" <> short 's' <> hidden <> help "Remove unneeded dependencies.")
unneeded = flag' RemoveUnneeded (long "unneeded" <> short 'u' <> hidden <> help "Remove unneeded packages.")
sync :: Parser PacmanOp
sync = bigS *> (Sync <$> (fmap (Right . S.map PkgName) manyArgs <|> fmap Left mods) <*> (S.fromList <$> many (ref <|> ign <|> igg)))
where bigS = flag' () (long "sync" <> short 'S' <> help "Install official packages.")
ref = flag' SyncRefresh (long "refresh" <> short 'y' <> hidden <> help "Update the package database.")
mods = NELP.fromList <$> some (cln <|> gps <|> inf <|> lst <|> sch <|> upg <|> dnl)
cln = flag' SyncClean (long "clean" <> short 'c' <> hidden <> help "Remove old packages from the cache.")
gps = SyncGroups <$> (flag' () (long "groups" <> short 'g' <> hidden <> help "View members of a package group.") *> someArgs')
inf = SyncInfo <$> (flag' () (long "info" <> short 'i' <> hidden <> help "View package information.") *> someArgs')
lst = SyncList <$> strOption (long "list" <> short 'l' <> metavar "REPO" <> hidden <> help "List the packages in a REPO.")
sch = SyncSearch <$> (flag' () (long "search" <> short 's' <> hidden <> help "Search the official package repos.") *> someArgs')
upg = SyncUpgrade <$> (flag' () (long "sysupgrade" <> short 'u' <> hidden <> help "Upgrade installed packages.") *> manyArgs')
dnl = SyncDownload <$> (flag' () (long "downloadonly" <> short 'w' <> hidden <> help "Download package tarballs.") *> someArgs')
ign = SyncIgnore . S.fromList . map PkgName . T.split (== ',') <$>
strOption (long "ignore" <> metavar "PKG(,PKG,...)" <> hidden <> help "Ignore given packages.")
igg = SyncIgnoreGroup . S.fromList . map PkgGroup . T.split (== ',') <$>
strOption (long "ignoregroup" <> metavar "PKG(,PKG,...)" <> hidden <> help "Ignore packages from the given groups.")
misc :: Parser (Set MiscOp)
misc = S.fromList <$> many (ar <|> dbp <|> roo <|> ver <|> gpg <|> hd <|> con <|> dbo <|> nop <|> nos <|> pf <|> nod <|> prt <|> asi)
where ar = MiscArch
<$> option (eitherReader absFilePath) (long "arch" <> metavar "ARCH" <> hidden <> help "Use an alternate architecture.")
dbp = MiscDBPath
<$> option (eitherReader absFilePath) (long "dbpath" <> short 'b' <> metavar "PATH" <> hidden <> help "Use an alternate database location.")
roo = MiscRoot
<$> option (eitherReader absFilePath) (long "root" <> short 'r' <> metavar "PATH" <> hidden <> help "Use an alternate installation root.")
ver = flag' MiscVerbose (long "verbose" <> short 'v' <> hidden <> help "Be more verbose.")
gpg = MiscGpgDir
<$> option (eitherReader absFilePath) (long "gpgdir" <> metavar "PATH" <> hidden <> help "Use an alternate GnuGPG directory.")
hd = MiscHookDir
<$> option (eitherReader absFilePath) (long "hookdir" <> metavar "PATH" <> hidden <> help "Use an alternate hook directory.")
con = flag' MiscConfirm (long "confirm" <> hidden <> help "Always ask for confirmation.")
dbo = flag' MiscDBOnly (long "dbonly" <> hidden <> help "Only modify database entries, not package files.")
nop = flag' MiscNoProgress (long "noprogressbar" <> hidden <> help "Don't show a progress bar when downloading.")
nos = flag' MiscNoScriptlet (long "noscriptlet" <> hidden <> help "Don't run available install scriptlets.")
pf = MiscPrintFormat <$> strOption (long "print-format" <> metavar "STRING" <> hidden <> help "Specify how targets should be printed.")
nod = flag' MiscNoDeps (long "nodeps" <> short 'd' <> hidden <> help "Skip dependency version checks.")
prt = flag' MiscPrint (long "print" <> short 'p' <> hidden <> help "Print the targets instead of performing the operation.")
asi = MiscAssumeInstalled <$> strOption (long "assume-installed" <> metavar "<package=version>" <> hidden <> help "Add a virtual package to satisfy dependencies.")
testdeps :: Parser PacmanOp
testdeps = bigT *> (TestDeps <$> someArgs)
where bigT = flag' () (long "deptest" <> short 'T' <> help "Test dependencies - useful for scripts.")
upgrades :: Parser PacmanOp
upgrades = bigU *> (Upgrade <$> (S.fromList <$> many mods) <*> somePkgs)
where bigU = flag' () (long "upgrade" <> short 'U' <> help "Install given package files.")
mods = asd <|> ase <|> ign <|> igg
asd = flag' UpgradeAsDeps (long "asdeps" <> hidden)
ase = flag' UpgradeAsExplicit (long "asexplicit" <> hidden)
ign = UpgradeIgnore . S.fromList . map PkgName . T.split (== ',') <$>
strOption (long "ignore" <> metavar "PKG(,PKG,...)" <> hidden <> help "Ignore given packages.")
igg = UpgradeIgnoreGroup . S.fromList . map PkgGroup . T.split (== ',') <$>
strOption (long "ignoregroup" <> metavar "PKG(,PKG,...)" <> hidden <> help "Ignore packages from the given groups.")
somePkgs :: Parser (NonEmpty PkgName)
somePkgs = NELP.fromList . map PkgName <$> some (argument str (metavar "PACKAGES"))
-- | Same as `someArgs`, but the help message "brief display" won't show PACKAGES.
somePkgs' :: Parser (NonEmpty PkgName)
somePkgs' = NELP.fromList . map PkgName <$> some (argument str (metavar "PACKAGES" <> hidden))
-- | One or more arguments.
someArgs :: Parser (NonEmpty Text)
someArgs = NEL.nub . NELP.fromList <$> some (argument str (metavar "PACKAGES"))
-- | Same as `someArgs`, but the help message "brief display" won't show PACKAGES.
someArgs' :: Parser (NonEmpty Text)
someArgs' = NEL.nub . NELP.fromList <$> some (argument str (metavar "PACKAGES" <> hidden))
-- | Zero or more arguments.
manyArgs :: Parser (Set Text)
manyArgs = S.fromList <$> many (argument str (metavar "PACKAGES"))
-- | Zero or more arguments.
manyArgs' :: Parser (Set Text)
manyArgs' = S.fromList <$> many (argument str (metavar "PACKAGES" <> hidden))
language :: Parser Language
language = foldr1 (<|>) $ map (\(f, v) -> flag' v (long f <> hidden)) langs
where langs = [ ( "japanese", Japanese ), ( "日本語", Japanese )
, ( "polish", Polish ), ( "polski", Polish )
, ( "croatian", Croatian ), ( "hrvatski", Croatian )
, ( "swedish", Swedish ), ( "svenska", Swedish )
, ( "german", German ), ( "deutsch", German )
, ( "spanish", Spanish ), ( "español", Spanish )
, ( "portuguese", Portuguese ), ( "português", Portuguese )
, ( "french", French), ( "français", French )
, ( "russian", Russian ), ( "русский", Russian )
, ( "italian", Italian ), ( "italiano", Italian )
, ( "serbian", Serbian ), ( "српски", Serbian )
, ( "norwegian", Norwegian ), ( "norsk", Norwegian )
, ( "indonesian", Indonesia )
, ( "chinese", Chinese ), ( "中文", Chinese )
, ( "esperanto", Esperanto )
, ( "dutch", Dutch ), ( "nederlands", Dutch ) ]
logLevel :: Parser LogLevel
logLevel = option (eitherReader l)
(long "log-level" <> metavar "debug|info|warn|error" <> value LevelInfo
<> help "The minimum level of log messages to display (default: info)")
where
l :: String -> Either String LogLevel
l "debug" = Right LevelDebug
l "info" = Right LevelInfo
l "warn" = Right LevelWarn
l "error" = Right LevelError
l _ = Left "Must be one of debug|info|warn|error"
absFilePath :: String -> Either String FilePath
absFilePath fp = bool (Left $ "Not absolute: " <> fp) (Right fp) $ isAbsolute fp
| bb010g/aura | aura/exec/Aura/Flags.hs | gpl-3.0 | 31,681 | 0 | 20 | 7,538 | 9,822 | 4,982 | 4,840 | 507 | 5 |
module Main where
import System.Random
import GHC.Float (double2Float)
import Codec.Picture( PixelRGBA8( .. ), writePng )
import Codec.Picture.Types (Image(..))
import Graphics.Text.TrueType( loadFontFile, Font(..) )
import Graphics.Rasterific
import Graphics.Rasterific.Texture
import MC.Pi (approximatePi)
import MC.Internal.Circle as MCI
numSamples :: Int
numSamples = 1000000
imageRadius :: Num a => a
imageRadius = 1024
imageDiameter :: Num a => a
imageDiameter = 2 * imageRadius
samples :: StdGen -> [MCI.Point]
samples = take numSamples . randoms
transformPoint :: MCI.Point -> [Primitive]
transformPoint (MCI.Point x y) = circle (V2 (double2Float $ toImageScale x)
(double2Float $ toImageScale y)) 1
where toImageScale num = (num + 1) * imageRadius
inPoints :: [MCI.Point] -> [[Primitive]]
inPoints points = fmap transformPoint inPts
where inPts = filter (not . MCI.isInUnitCircle) points
outPoints :: [MCI.Point] -> [[Primitive]]
outPoints points = fmap transformPoint outPts
where outPts = filter MCI.isInUnitCircle points
main :: IO ()
main = do
gen <- getStdGen
fontResult <- loadFontFile "/usr/share/fonts/noto/NotoMono-Regular.ttf"
case fontResult of
Left err -> print err
Right font -> writePng "/tmp/pi.png" $ createPNG gen font
createPNG :: StdGen -> Font -> Image PixelRGBA8
createPNG gen font = renderDrawing imageDiameter imageDiameter white $ do
withColor blue $ mapM_ fill $ inPoints points
withColor red $ mapM_ fill $ outPoints points
withColor black $ mapM_ (stroke 4 JoinRound (CapRound, CapRound)) [circle (V2 imageRadius imageRadius) imageRadius,
line (V2 0 imageRadius) (V2 imageDiameter imageRadius),
line (V2 imageRadius 0) (V2 imageRadius imageDiameter)]
withColor black $ printTextAt font (PointSize 72) (V2 (imageRadius + 64) (imageRadius - 64)) $ show pi
where white = PixelRGBA8 255 255 255 255
black = PixelRGBA8 0 0 0 255
blue = PixelRGBA8 255 0 0 255
red = PixelRGBA8 0 0 255 255
points = samples gen
pi = approximatePi points
withColor = withTexture . uniformTexture
| matt-keibler/monte-carlo-pi | monte-carlo-pi-hs/app/Main.hs | gpl-3.0 | 2,285 | 0 | 14 | 567 | 738 | 382 | 356 | 50 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Pirandello.Kruger ( Address (..), Manager, Host, Port
, newManager, krugerLookup, krugerPublish )
where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Control.Monad.Morph (hoist)
import Control.Monad.Trans.Except (ExceptT (ExceptT))
import Control.Monad.Trans.State.Strict (evalStateT)
import Data.Aeson (FromJSON (parseJSON), Value (Object), (.=), (.:), encode, object)
import Data.Text.Encoding (encodeUtf8)
import Pipes.Aeson (decode)
import qualified Pipes.HTTP as H
import Pirandello.Config (Host, Port)
import Pirandello.Events (RemoteId)
import UnexceptionalIO (UIO, fromIO')
import Web.Cookie (def)
data Address = Address Host Port deriving (Show)
data Manager = Manager { http ∷ H.Manager
, req ∷ H.Request }
instance FromJSON Address where
parseJSON (Object v) = Address <$> v .: "host" <*> v .: "port"
parseJSON _ = mzero
mkReq ∷ Host → H.Request
mkReq host = def { H.secure = True
, H.host = encodeUtf8 host
, H.path = "/"
, H.port = 443
, H.method = "POST" }
-- NB http-client package promises to only throw HttpException
-- https://www.stackage.org/haddock/nightly-2015-03-27/http-client-0.4.9/Network-HTTP-Client.html
newManager ∷ Host → ExceptT H.HttpException UIO Manager
newManager host = ExceptT $ fromIO' $ do
m ← H.newManager H.tlsManagerSettings
return Manager { http = m, req = mkReq host }
krugerLookup ∷ Manager → RemoteId → ExceptT H.HttpException UIO (Maybe Address)
krugerLookup man remoteId =
ExceptT $ fromIO' $ H.withHTTP req' (http man) $ \httpResp → do
resp ← evalStateT decode (H.responseBody httpResp)
case resp of
(Just (Right addr)) → return $ Just addr
_ → return Nothing
where
req' = (req man) { H.requestBody = H.RequestBodyLBS $ encode body }
body = object [ "op" .= ("get" ∷ String), "name" .= remoteId ]
krugerPublish ∷ Manager → RemoteId → Address → ExceptT () (ExceptT H.HttpException UIO) ()
krugerPublish man remoteId (Address host port) =
hoist (ExceptT . fromIO') . ExceptT $ H.withHTTP req' (http man) $ \httpResp → do
resp ← evalStateT decode (H.responseBody httpResp)
case resp of
(Just (Right (Object _))) → return $ Right ()
_ → return $ Left ()
where
req' = (req man) { H.requestBody = H.RequestBodyLBS $ encode body }
body = object [ "op" .= ("publish" ∷ String)
, "name" .= remoteId
, "host" .= host
, "port" .= port ]
| rimmington/pirandello | src/Pirandello/Kruger.hs | gpl-3.0 | 2,812 | 0 | 17 | 769 | 873 | 482 | 391 | -1 | -1 |
module Data.Graph.Inductive.Query.BCC(
bcc
) where
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Query.DFS
import Data.Graph.Inductive.Query.ArtPoint
------------------------------------------------------------------------------
-- Given a graph g, this function computes the subgraphs which are
-- g's connected components.
------------------------------------------------------------------------------
gComponents :: DynGraph gr => gr a b -> [gr a b]
gComponents g = map (\(x,y)-> mkGraph x y) (zip ln le)
where ln = map (\x->[(u,l)|(u,l)<-vs,elem u x]) cc
le = map (\x->[(u,v,l)|(u,v,l)<-es,elem u x]) cc
(vs,es,cc) = (labNodes g,labEdges g,components g)
embedContexts :: DynGraph gr => Context a b -> [gr a b] -> [gr a b]
embedContexts (_,v,l,s) gs = map (\(x,y)-> x & y) (zip lc gs)
where lc = map (\e->(e,v,l,e)) lc'
lc'= map (\g->[ e | e <- s, gelem (snd e) g]) gs
------------------------------------------------------------------------------
-- Given a node v and a list of graphs, this functions returns the graph which
-- v belongs to.
------------------------------------------------------------------------------
findGraph :: DynGraph gr => Node -> [gr a b] -> Decomp gr a b
findGraph _ [] = error "findGraph: empty graph list"
findGraph v (g:gs) = case match v g of
(Nothing, _) -> findGraph v gs
(Just c, g') -> (Just c, g')
------------------------------------------------------------------------------
-- Given a graph g and its articulation points, this function disconnects g
-- for each articulation point and returns the connected components of the
-- resulting disconnected graph.
------------------------------------------------------------------------------
splitGraphs :: DynGraph gr => [gr a b] -> [Node] -> [gr a b]
splitGraphs gs [] = gs
splitGraphs [] _ = error "splitGraphs: empty graph list"
splitGraphs (g:gs) (v:vs) = splitGraphs (gs''++gs) vs
where gs'' = embedContexts c gs'
gs' = gComponents g'
(Just c,g') = findGraph v (g:gs)
{-|
Finds the bi-connected components of an undirected connected graph.
It first finds the articulation points of the graph. Then it disconnects the
graph on each articulation point and computes the connected components.
-}
bcc :: DynGraph gr => gr a b -> [gr a b]
bcc g = splitGraphs [g] (ap g)
| ckaestne/CIDE | CIDE_Language_Haskell/test/FGL-layout/Graph/Inductive/Query/BCC.hs | gpl-3.0 | 2,716 | 4 | 14 | 763 | 752 | 409 | 343 | 28 | 2 |
-- TabCode - A parser for the Tabcode lute tablature language
--
-- Copyright (C) 2015-2017 Richard Lewis
-- Author: Richard Lewis <richard@rjlewis.me.uk>
-- This file is part of TabCode
-- TabCode is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- TabCode is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with TabCode. If not, see <http://www.gnu.org/licenses/>.
module Main where
import Data.ByteString.Char8 (pack, putStrLn)
import Options.Applicative
import Prelude hiding (putStrLn)
import TabCode.Serialiser.MEIXML.Converter
import TabCode.Serialiser.MEIXML.Serialiser (meiDoc)
import TabCode.Options
import TabCode.Parser (parseTabcodeStdIn)
import Text.XML.Generator
opts :: ParserInfo TCOptions
opts = info ( helper <*> config )
( fullDesc
<> progDesc "Reads TabCode text from stdin and writes MEI XML to stdout."
<> header "tc2mei - TabCode MEI XML converter" )
main :: IO ()
main = execParser opts >>= runSerialiser
where
runSerialiser o = do
tc <- parseTabcodeStdIn o
m <- case mei (structure o) defaultDoc "stdin" tc of
Right m -> return m
Left err -> do { putStrLn $ pack $ "Could not construct MEI tree: " ++ (show err); return $ MEIMusic [] [] }
putStrLn $ xrender $ doc defaultDocInfo $ meiDoc m (xmlIds o)
| TransformingMusicology/tabcode-haskell | prog/TC2MEI.hs | gpl-3.0 | 1,747 | 0 | 17 | 343 | 287 | 157 | 130 | 22 | 2 |
module BionetSimulator where
import qualified Data.List as List
import qualified Data.Map.Strict as Map
-- Types and Data
-----------------
type Node = String
type EdgeType = String
-- Some typeclass decisions for (edge) polarity:
-- not Ord (b/c I don't think it makes sense to compare polarities w/ gt/lt)
-- not Bounded (same reasoning, no sense in thinking one is smaller than the other)
-- not Enum (Don't think it makes sense to think of one polarity as having the other as a predecessor)
data Polarity = Activating | Inhibiting deriving (Eq, Show, Read)
-- Probably makes sense to couple polarity in the interaction type
type InteractionType = (EdgeType, Maybe Polarity)
-- A net is a map of node to a list of interaction type - parent pairs
type Net = Map.Map Node [(InteractionType, Node)]
-- Map of node to expression level
type Value = Double
type Values = Map.Map Node Value
type InteractionSpec = InteractionType -> Value -> Value
-- Local computation = child -> [parent, parent value, interaction] -> child value
type LocalComputation = Node -> [(Node, Value, InteractionType)] -> Value
-- Network building
-------------------
-- Empty net
empty :: Net
empty = Map.empty
-- Add an edge
(+-) :: Net -> (Node, InteractionType, Node) -> Net
original +- (src,it,dest) = Map.insert dest ((it,src):net Map.! dest) net where
net = original +. src +. dest
-- Add a node
(+.) :: Net -> Node -> Net
original +. node = if node `Map.member` original
then original
else Map.insert node [] original
-- Network inspection
---------------------
-- List Nodes
nodes :: Net -> [Node]
nodes = Map.keys
-- Get incoming arcs for node
getArcs :: Net -> Node -> [(InteractionType, Node)]
getArcs = (Map.!)
-- List all interaction types
edgeTypes :: Net -> [EdgeType]
edgeTypes net = foldl List.union [] $ map cleanup $ Map.assocs net where
cleanup (_, list) = map (fst.fst) list
-- General computation framework
--------------------------------
-- Running a computation really consists of querying a values map from a network and an interaction spec.
compute :: Net -> LocalComputation -> Values
compute net computation = values where
values = Map.mapWithKey comp net
comp node arcs = computation node (map addValue arcs)
addValue (interaction, parent) = (parent, values Map.! parent, interaction)
-- Explicit manipulation
force :: LocalComputation -> Node -> Value -> LocalComputation
force computation node value node _ = value
force computation _ _ = computation
| sverchkov/bionet-simulator-haskell | src/BionetSimulator.hs | apache-2.0 | 2,507 | 0 | 9 | 449 | 585 | 340 | 245 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Tweeter.Db (
findById
, insert
, insert'
, newTweetId
, list
, TweetDb
, init
) where
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import qualified Data.List as DL
import qualified Data.Map as M
import Data.UUID
import Data.UUID.V4
import P
import System.IO
import Tweeter.Data
-- MVar backed hashmap of tweet id's to tweets
type TweetDb = MVar (M.Map TweetId Tweet)
init :: IO TweetDb
init = do
s <- newMVar M.empty
pure s
findById :: TweetDb -> TweetId -> IO (Maybe Tweet)
findById t id' = modifyMVar t $ \m ->
pure (m, M.lookup id' m)
insert :: TweetDb -> Tweet -> IO TweetId
insert t t' = do
uuid <- newTweetId
insert' t uuid t'
insert' :: TweetDb -> TweetId -> Tweet -> IO TweetId
insert' db id' t' = do
modifyMVar_ db $ \m ->
pure $ M.insert id' t' m
pure id'
list :: TweetDb -> IO [KeyedTweet]
list t = modifyMVar t $ \m ->
pure (m, DL.sort . fmap (\(x,y) -> KeyedTweet x y) $ (M.assocs m))
newTweetId :: IO TweetId
newTweetId = liftIO nextRandom >>= return . TweetId . toText
| ambiata/airship-tutorial | src/Tweeter/Db.hs | apache-2.0 | 1,193 | 0 | 14 | 308 | 416 | 221 | 195 | 41 | 1 |
-- Copyright 2020 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Runfiles where
import qualified Bazel.Runfiles as Runfiles
test :: FilePath -> IO ()
test output = do
rfiles <- Runfiles.create
mapM_ (readAndWrite rfiles) allData
where
allData = [ "hrepl/hrepl/tests/source-data.txt"
, "hrepl/hrepl/tests/generated-data.txt"
]
readAndWrite rfiles f =
readFile (Runfiles.rlocation rfiles f)>>= appendFile output
| google/hrepl | hrepl/tests/Runfiles.hs | apache-2.0 | 997 | 0 | 11 | 200 | 113 | 65 | 48 | 10 | 1 |
-- Copyright (C) 2010-2012 John Millikin <john@john-millikin.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module DBusTests.ObjectPath (test_ObjectPath) where
import Data.List (intercalate)
import Test.QuickCheck
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import DBus
test_ObjectPath :: TestTree
test_ObjectPath = testGroup "ObjectPath"
[ test_Parse
, test_ParseInvalid
]
test_Parse :: TestTree
test_Parse = testProperty "parse" prop where
prop = forAll gen_ObjectPath check
check x = case parseObjectPath x of
Nothing -> False
Just parsed -> formatObjectPath parsed == x
test_ParseInvalid :: TestTree
test_ParseInvalid = testCase "parse-invalid" $ do
-- empty
Nothing @=? parseObjectPath ""
-- bad char
Nothing @=? parseObjectPath "/f!oo"
-- ends with a slash
Nothing @=? parseObjectPath "/foo/"
-- empty element
Nothing @=? parseObjectPath "/foo//bar"
-- trailing chars
Nothing @=? parseObjectPath "/foo!"
gen_ObjectPath :: Gen String
gen_ObjectPath = gen where
chars = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "_"
gen = do
xs <- listOf (listOf1 (elements chars))
return ("/" ++ intercalate "/" xs)
instance Arbitrary ObjectPath where
arbitrary = fmap objectPath_ gen_ObjectPath
| rblaze/haskell-dbus | tests/DBusTests/ObjectPath.hs | apache-2.0 | 1,844 | 0 | 14 | 364 | 326 | 175 | 151 | 32 | 2 |
module Calc.Calc
where
type Number = Integer
data Expr
= Lit Number
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
deriving Show
instance Num Expr where
e1 + e2 = Add e1 e2
e1 - e2 = Sub e1 e2
e1 * e2 = Mul e1 e2
abs e = e
signum e = e
fromInteger = Lit
| jeannekamikaze/calc | Calc/Calc.hs | bsd-3-clause | 343 | 0 | 6 | 150 | 122 | 63 | 59 | 15 | 0 |
-- Copyright: 2007-2012 Dino Morelli
-- License: BSD3 (see LICENSE)
-- Author: Dino Morelli <dino@ui3.info>
module Photoname.DateFormat
( buildDatePath
)
where
import System.FilePath
import Text.Printf
import Photoname.Common
import Photoname.Date
import Photoname.Exif
import Photoname.Opts ( Options (..) )
{- Given a path to a file with EXIF data, construct a new path based on the
date and some serial number info we can parse out of the filename.
-}
buildDatePath :: FilePath -> Ph FilePath
buildDatePath oldPath = do
dateString <- getDate oldPath
let date = readDate dateString
suffix <- asks optSuffix
let fileName = printf "%s%s.jpg" (formatDateTime date) suffix
parentDir <- asks optParentDir
noDirs <- asks optNoDirs
return $ if (noDirs)
then parentDir </> fileName
else parentDir </> (formatYearMonth date) </> fileName
| tkawachi/photoname | src/Photoname/DateFormat.hs | bsd-3-clause | 883 | 0 | 12 | 174 | 184 | 95 | 89 | 19 | 2 |
#!/usr/bin/runghc
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Mt2 where
import Control.Concurrent ;import Control.Monad (forever)
import System.Console.ANSI ;import System.IO
import Turtle hiding (stdout) ;import Control.Exception
type E = IO (Either AsyncException ())
run func value = do
let tmpf = putStrF (" n is: " ++ show value)
hideCursor >> setCursorColumn 40 >> clearLine >> (putStrF . show) (func value) >> tmpf >> delay 1
where putStrF s = putStr s >> hFlush stdout
delay d = threadDelay (d *500000)
adjvar dl = initbuffer >> getChar >>= \case 'w' -> takeMVar dl >>= (putMVar dl . (\x -> x + 1))
's' -> takeMVar dl >>= (putMVar dl . (\x -> x - 1))
_ -> pure ()
where initbuffer = hSetBuffering stdiin NoBuffering >>
hSetEcho stdiin False
where stdiin = System.IO.stdin
interactive argdescr hlp function = do
n <- options argdescr parser
dl <- newMVar n
putStrLn hlp
forkIO $ forever ( readMVar dl >>= run function)
catchexceptions ( forever (adjvar dl) )
where
catchexceptions p = (try p :: E) >>= \case Left _ -> showCursor >> putStrLn " \nBye!" ; Right a -> return a
parser = optInt "maxnumber" 'n' "Generates numbers from 0 to n" :: Parser Int -- this line is not general
helptext1 = "Math trainer n2 : squares"
helptext2 = "Stop me with Ctr-C.\n w next,s previous."
main = interactive helptext1 helptext2 (\n -> n*n)
| alexander31415926535/Liftconsole | math-tutor2.hs | bsd-3-clause | 1,706 | 0 | 14 | 582 | 502 | 254 | 248 | 29 | 3 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE PolyKinds #-}
module Untyped2 (TmVar(..), TmLam(..), TmApp(..)) where
import Lib
import Text.Parsec hiding (runP)
import Text.PrettyPrint hiding (char, space)
import GHC.TypeLits
import Data.Proxy
import Arith1
-- Var
type VarId = String
data TmVar (e :: Nat -> *) l where
TmVar :: VarId -> TmVar e 0
instance HFunctor TmVar where
hfmap _ (TmVar s) = TmVar s
instance MyShow TmVar where
showMe (TmVar s) = s
parseTmVar :: NewParser TmVar fs 0
parseTmVar e _ = (In e . TmVar) <$> parseWord
instance Syntax TmVar 0 where
parseF _ = parseTmVar
-- Lam
data TmLam e l where
TmLam :: VarId -> e 0 -> TmLam e 0
instance HFunctor TmLam where
hfmap f (TmLam s e) = TmLam s (f e)
instance MyShow TmLam where
showMe (TmLam s (In _ e)) = "[\\" ++ s ++ ". (" ++ showMe e ++ ")]"
parseTmLam :: NewParser TmLam fs 0
parseTmLam e p = do
keyword "\\"
x <- parseWord
keyword "."
body <- p !!! (Proxy :: Proxy 0)
return $ In e (TmLam x body)
instance Syntax TmLam 0 where
parseF _ = parseTmLam
-- App
data TmApp e l where
TmApp :: e 0 -> e 0 -> TmApp e 0
instance HFunctor TmApp where
hfmap f (TmApp e1 e2) = TmApp (f e1) (f e2)
instance MyShow TmApp where
showMe (TmApp (In _ e1) (In _ e2)) = "(" ++ showMe e1 ++ " " ++ showMe e2 ++ ")"
parseTmApp :: NewParser TmApp fs 0
parseTmApp e p = chainlR (spaces >> (p !!! (Proxy :: Proxy 0))) TmApp e (p !!! (Proxy :: Proxy 0))
instance Syntax TmApp 0 where
parseF _ = parseTmApp
-- s :: [Int] -> Syntactic '[TmBool, TmNat, TmArith, TmVar, TmLam, TmApp] '[0, 0, 0, 0, 0, 0]
-- s (x1 : x2 : x3 : x4 : x5 : x6 : xs) = CCons 1 $ CCons 2 $ CCons 3 $ CCons x1 $ CCons x2 $ CCons x3 $ CVoid
-- r = testRun s 6 (Proxy :: Proxy 0)
-- r' = test (s [4,2,5,1,6,3]) (Proxy :: Proxy 0)
-- [("x", "x"),
-- ("\\x.x", "\\x. (x)"),
-- ("(\\x.x) (\\x.x x)", "(\\x. (x) \\x. ((x x)))")]
-- s :: [Int] -> Syntactic '[TmBool, TmNat, TmArith, TmVar, TmLam, TmApp] '[0, 0, 0, 0, 0, 0]
-- s (x1 : x2 : x3 : x4 : x5 : x6 : xs) = CCons x1 $ CCons x2 $ CCons x3 $ CCons x4 $ CCons x5 $ CCons x6 $ CVoid
-- r1 = "if iszero (\\x.x y) then true else pred (succ 0)"
-- r2 = "\\y.if (if (\\x.y) then y else ((succ z) (\\x.succ 0))) then true else (succ 0)"
-- r3 = "succ (pred (succ (iszero ((\\x.x) (\\x.x x)))))"
-- r = testRun (s [4,6,8,2,10,12]) (Proxy :: Proxy 0)
-- input = ["x",
-- "y'",
-- "\\x.x",
-- "(\\x.x) \\x.x",
-- "\\x.(x)",
-- "\\x.(x x)",
-- "\\x.x \\x.x"]
| hy-zhang/parser | experimental/Untyped2.hs | bsd-3-clause | 3,011 | 0 | 11 | 812 | 679 | 370 | 309 | 55 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
{-| Makes @Expr@ an instance of @Translatable@ (see "CodeGen.Typeclasses") -}
module CodeGen.Expr () where
import CodeGen.Typeclasses
import CodeGen.CCodeNames
import qualified CodeGen.CCodeNames as C
import CodeGen.Type
import qualified CodeGen.Context as Ctx
import CodeGen.DTrace
import CCode.Main
import CCode.PrettyCCode
import qualified AST.AST as A
import qualified AST.Util as Util
import qualified AST.Meta as Meta
import qualified AST.PrettyPrinter as PP
import qualified Identifiers as ID
import qualified Types as Ty
import Control.Monad.State hiding (void)
import Data.List
import Data.List.Utils(split)
import qualified Data.Set as Set
import Data.Maybe
import Debug.Trace
instance Translatable ID.BinaryOp (CCode Name) where
translate op = Nam $ case op of
ID.AND -> "&&"
ID.OR -> "||"
ID.LT -> "<"
ID.GT -> ">"
ID.LTE -> "<="
ID.GTE -> ">="
ID.EQ -> "=="
ID.NEQ -> "!="
ID.PLUS -> "+"
ID.MINUS -> "-"
ID.TIMES -> "*"
ID.DIV -> "/"
ID.MOD -> "%"
instance Translatable ID.UnaryOp (CCode Name) where
translate op = Nam $
case op of
ID.NOT -> "!"
ID.NEG -> "-"
typeToPrintfFstr :: Ty.Type -> String
typeToPrintfFstr ty
| Ty.isIntType ty = "%lli"
| Ty.isUIntType ty = "%llu"
| Ty.isRealType ty = "%f"
| Ty.isStringObjectType ty = "%s"
| Ty.isStringType ty = "%s"
| Ty.isCharType ty = "%c"
| Ty.isBoolType ty = "%s"
| Ty.isRefAtomType ty = show ty ++ "@%p"
| Ty.isCapabilityType ty = "(" ++ show ty ++ ")@%p"
| Ty.isUnionType ty = "(" ++ show ty ++ ")@%p"
| Ty.isFutureType ty = "Fut@%p"
| Ty.isStreamType ty = "Stream@%p"
| Ty.isParType ty = "Par@%p"
| Ty.isArrowType ty = "(" ++ show ty ++ ")@%p"
| Ty.isArrayType ty = show ty ++ "@%p"
| Ty.isRangeType ty = "[%d..%d by %d]"
| Ty.isTupleType ty =
let argFormats = map typeToPrintfFstr (Ty.getArgTypes ty) :: [String]
formatString = intercalate ", " argFormats
in "(" ++ formatString ++ ")"
| Ty.isMaybeType ty = "%s" -- A generated string
| Ty.isUnitType ty = "%s" -- Always "()"
| otherwise = case translate ty of
Ptr _ -> "%p"
_ -> error $ "Expr.hs: typeToPrintfFstr not defined for " ++ show ty
-- | If the type is not void, create a variable to store it in. If it is void, return the lval UNIT
namedTmpVar :: String -> Ty.Type -> CCode Expr -> State Ctx.Context (CCode Lval, CCode Stat)
namedTmpVar name ty cex
| Ty.isUnitType ty = return $ (unit, Seq [cex])
| otherwise = do na <- Ctx.genNamedSym name
return $ (Var na, Assign (Decl (translate ty, Var na)) cex)
tmpArr :: CCode Ty -> [CCode Expr] -> State Ctx.Context (CCode Lval, CCode Stat)
tmpArr cty arr = do
na <- Ctx.genSym
return $ (Var na, Assign (Decl (cty, Var $ na ++ "[]")) (Record arr))
substituteVar :: ID.Name -> CCode Lval -> State Ctx.Context ()
substituteVar na impl = do
c <- get
put $ Ctx.substAdd c na impl
return ()
unsubstituteVar :: ID.Name -> State Ctx.Context ()
unsubstituteVar na = do
c <- get
put $ Ctx.substRem c na
return ()
getRuntimeType :: A.Expr -> CCode Expr
getRuntimeType = runtimeType . Ty.getResultType . A.getType
newParty :: A.Expr -> CCode Name
newParty (A.PartyPar {}) = partyNewParP
newParty _ = error "Expr.hs: node is not 'PartyPar'"
translateDecl (vars, expr) = do
(ne, te) <- translate expr
let exprType = A.getType expr
tmp <- Var <$> Ctx.genSym
theAssigns <- mapM (assignDecl ne exprType) vars
return (tmp,
[Comm $ intercalate ", " (map (show . A.varName) vars) ++
" = " ++ show (PP.ppSugared expr)
,te
] ++ theAssigns)
where
assignDecl rhs rhsType var = do
let x = A.varName var
tmp <- Var <$> Ctx.genNamedSym (show x)
substituteVar x tmp
let (lhsType, theRhs) =
case var of
A.VarType{A.varType} ->
(translate varType, Cast (translate varType) rhs)
A.VarNoType{} ->
(translate rhsType, AsExpr rhs)
return $ Assign (Decl (lhsType, tmp)) theRhs
instance Translatable A.Expr (State Ctx.Context (CCode Lval, CCode Stat)) where
-- | Translate an expression into the corresponding C code
translate skip@(A.Skip {}) = namedTmpVar "skip" (A.getType skip) (AsExpr unit)
translate A.Break{} = return (unit, Break{})
translate A.Continue{} = return (unit, Continue{})
translate null@(A.Null {}) = namedTmpVar "literal" (A.getType null) Null
translate true@(A.BTrue {}) = namedTmpVar "literal" (A.getType true) (Embed "1/*True*/"::CCode Expr)
translate false@(A.BFalse {}) = namedTmpVar "literal" (A.getType false) (Embed "0/*False*/"::CCode Expr)
translate lit@(A.IntLiteral {A.intLit = i}) = namedTmpVar "literal" (A.getType lit) (Int i)
translate lit@(A.UIntLiteral {A.intLit = i}) = namedTmpVar "literal" (A.getType lit) (Int i)
translate lit@(A.RealLiteral {A.realLit = r}) = namedTmpVar "literal" (A.getType lit) (Double r)
translate lit@(A.StringLiteral {A.stringLit = s}) = namedTmpVar "literal" (A.getType lit) (String s)
translate lit@(A.CharLiteral {A.charLit = c}) = namedTmpVar "literal" (A.getType lit) (Char c)
translate A.TypedExpr {A.body, A.ty} = do
(nbody, tbody) <- translate body
tmp <- Ctx.genNamedSym "cast"
let ty' = translate ty
theCast = Assign (Decl (ty', Var tmp))
(Cast ty' nbody)
return $ (Var tmp,
Seq [tbody, theCast])
translate unary@(A.Unary {A.uop, A.operand}) = do
(noperand, toperand) <- translate operand
tmp <- Ctx.genNamedSym "unary"
return $ (Var tmp,
Seq [toperand,
Statement (Assign
(Decl (translate $ A.getType unary, Var tmp))
(CUnary (translate uop) noperand))])
translate bin@(A.Binop {A.binop, A.loper, A.roper}) = do
(nlo, tlo) <- translate loper
(nro, tro) <- translate roper
tmp <- Ctx.genNamedSym "binop"
let ltype = A.getType loper
le = wrap ltype nlo tlo
re' = wrap ltype nro tro
re = if Ty.isRefType ltype
then Cast (translate ltype) re'
else re'
theAssign = Assign (Decl (translate $ A.getType bin, Var tmp))
(BinOp (translate binop) le re)
return (Var tmp, Statement theAssign)
where
wrap ty n t =
StatAsExpr (if Ty.isTypeVar ty
then fromEncoreArgT (Ptr void) (AsExpr n)
else n) t
translate p@(A.PartyPar {A.parl, A.parr}) = do
(nleft, tleft) <- translate parl
(nright, tright) <- translate parr
let runtimeT = (runtimeType . A.getType) p
(npar, tpar) <- namedTmpVar "par" (A.getType p) $
Call (newParty p) [AsExpr encoreCtxVar, AsExpr nleft, AsExpr nright, runtimeT]
return (npar, Seq [tleft, tright, tpar])
translate ps@(A.PartySeq {A.par, A.seqfunc}) = do
(npar, tpar) <- translate par
(nseqfunc, tseqfunc) <- translate seqfunc
let runtimeT = (runtimeType . Ty.getResultType . A.getType) ps
(nResultPar, tResultPar) <- namedTmpVar "par" (A.getType ps) $
Call partySequence [AsExpr encoreCtxVar,
AsExpr npar,
AsExpr nseqfunc,
runtimeT]
return (nResultPar, Seq [tpar, tseqfunc, tResultPar])
translate ps@(A.PartyReduce {A.seqfun, A.pinit, A.par, A.runassoc}) = do
(nseqfunc, tseqfunc) <- translate seqfun
(npinit, tpinit) <- translate pinit
(npar, tpar) <- translate par
let npinit' = asEncoreArgT (translate $ A.getType pinit) npinit
runtimeT = (runtimeType . Ty.getResultType . A.getType) ps
reduceFn = partyReduce runassoc
(nResultPar, tResultPar) <- namedTmpVar "par" (A.getType ps) $
Call reduceFn [AsExpr encoreCtxVar
,AsExpr npar
,npinit'
,AsExpr nseqfunc
,runtimeT]
return (nResultPar, Seq [tseqfunc, tpinit, tpar, tResultPar])
translate (A.Print {A.args, A.file}) = do
let string = head args
rest = tail args
unless (Ty.isStringType $ A.getType string) $
error $ "Expr.hs: Print expects first argument to be a string literal"
targs <- mapM translate rest
let argNames = map (AsExpr . fst) targs
argDecls = map snd targs
argTys = map A.getType rest
fstring = formatString (A.stringLit string) argTys
expandedArgs = concat $ zipWith expandPrintfArg argTys argNames
outputOn = case file of
A.Stdout -> C.stdout
A.Stderr -> C.stderr
return (unit,
Seq $ argDecls ++
[Statement
(Call (Nam "fprintf")
(AsExpr outputOn : String fstring : expandedArgs))])
where
formatString s [] = s
formatString "" (ty:tys) =
error "Expr.hs: Wrong number of arguments to printf"
formatString ('{':'}':s) (ty:tys) =
typeToPrintfFstr ty ++ formatString s tys
formatString (c:s) tys =
c : formatString s tys
expandPrintfArg :: Ty.Type -> CCode Expr -> [CCode Expr]
expandPrintfArg ty argName
| Ty.isStringObjectType ty =
let castArg = Cast (translate Ty.stringObjectType) argName
in [AsExpr $ castArg `Arrow` fieldName (ID.Name "cstring")]
| Ty.isBoolType ty =
[Ternary argName (String "true") (String "false")]
| Ty.isRangeType ty =
map (`Call` [argName]) [rangeStart, rangeStop, rangeStep]
| Ty.isTupleType ty =
let argTypes = Ty.getArgTypes ty
args = zipWith (get argName) argTypes [0..]
in
concat $ zipWith expandPrintfArg argTypes args
| Ty.isMaybeType ty =
[Ternary (isNothing argName)
(String "Nothing") $
showJust argName (Ty.getResultType ty)]
| Ty.isUnitType ty =
[String "()"]
| Ty.isNullType ty =
[String "null"]
| otherwise =
[argName]
where
get tup ty i =
AsExpr $ Call tupleGet [tup, Int i] `Dot`
encoreArgTTag (translate ty)
isNothing arg =
BinOp (Nam "==")
(Cast option arg `Arrow` Nam "tag")
(Var "NOTHING")
showJust just resType =
let result = AsExpr $ Cast option just `Arrow`
encoreArgTTag (translate resType)
len = BinOp (Nam "+") (Int 10)
(approximateLength result resType)
resArgs = expandPrintfArg resType result
format = typeToPrintfFstr resType
in StatAsExpr (Var "tmp") $ Seq
[Assign (Decl (int, Var "len")) len,
Assign (Decl (Ptr char, Var "tmp")) $
Call encoreAllocName [Deref encoreCtxVar, Var "len"],
Statement . Call (Nam "sprintf") $
[AsExpr $ Var "tmp",
String $ "Just " ++ if Ty.isMaybeType resType
then "(" ++ format ++ ")"
else format] ++
resArgs]
where
approximateLength result ty
| Ty.isTupleType ty =
foldr1 (BinOp (Nam "+")) $
zipWith approximateLength
(zipWith (get result)
(Ty.getArgTypes ty) [0..])
(Ty.getArgTypes ty)
| Ty.isStringObjectType ty =
AsExpr $
Cast (translate Ty.stringObjectType) result
`Arrow` fieldName (ID.Name "length")
| otherwise =
Int $ length (show ty) + 30
translate exit@(A.Exit {A.args = [arg]}) = do
(narg, targ) <- translate arg
let exitCall = Call (Nam "exit") [narg]
return (unit, Seq [Statement targ, Statement exitCall])
translate abort@(A.Abort {A.args = []}) = do
let abortCall = Call (Nam "abort") ([]::[CCode Lval])
return (unit, Statement abortCall)
translate seq@(A.Seq {A.eseq}) = do
ntes <- mapM translate eseq
let (nes, tes) = unzip ntes
return (last nes, Seq $ map commentAndTe (zip eseq tes))
where
commentFor = (Comm . show . PP.ppSugared)
commentAndTe (ast, te) = Seq [commentFor ast, te]
translate (A.Assign {A.lhs = lhs@(A.ArrayAccess {A.target, A.index}), A.rhs}) = do
(nrhs, trhs) <- translate rhs
(ntarg, ttarg) <- translate target
(nindex, tindex) <- translate index
let ty = translate $ A.getType lhs
theSet =
Statement $
Call arraySet [AsExpr ntarg, AsExpr nindex, asEncoreArgT ty $ AsExpr nrhs]
return (unit, Seq [trhs, ttarg, tindex, theSet])
translate (A.Assign {A.lhs, A.rhs}) = do
(nrhs, trhs) <- translate rhs
castRhs <- case lhs of
A.FieldAccess {A.name, A.target} ->
do fld <- gets $ Ctx.lookupField (A.getType target) name
if Ty.isTypeVar (A.ftype fld) then
return $ asEncoreArgT (translate . A.getType $ rhs) $ AsExpr nrhs
else
return $ upCast nrhs
_ -> return $ upCast nrhs
lval <- mkLval lhs
let theAssign = Assign lval castRhs
return (unit, Seq [trhs, theAssign])
where
upCast e = if needUpCast then cast e else AsExpr e
where
lhsType = A.getType lhs
rhsType = A.getType rhs
needUpCast = rhsType /= lhsType
cast = Cast (translate lhsType)
mkLval (A.VarAccess {A.qname}) =
do ctx <- get
case Ctx.substLkp ctx qname of
Just substName -> return substName
Nothing -> error $ "Expr.hs: LVal is not assignable: " ++
show qname
mkLval (A.FieldAccess {A.target, A.name}) =
do (ntarg, ttarg) <- translate target
let ttargTrace = Seq [ttarg
,dtraceFieldWrite ntarg name
]
return (Deref (StatAsExpr ntarg ttargTrace) `Dot` fieldName name)
mkLval e = error $ "Cannot translate '" ++ show e ++ "' to a valid lval"
translate mayb@(A.MaybeValue _ (A.JustData e)) = do
(nE, tE) <- translate e
let runtimeT = (runtimeType . A.getType) e
let bodyDecl = asEncoreArgT (translate $ A.getType e) nE
optionLval = Call optionMkFn [AsExpr encoreCtxVar, AsExpr just,
bodyDecl, runtimeT]
(nalloc, talloc) <- namedTmpVar "option" (A.getType mayb) optionLval
return (nalloc, Seq [tE, talloc])
translate maybe@(A.MaybeValue _ (A.NothingData {})) = do
let createOption = Amp (Nam "DEFAULT_NOTHING")
(nalloc, talloc) <- namedTmpVar "option" (A.getType maybe) createOption
return (nalloc, talloc)
translate tuple@(A.Tuple {A.args}) = do
tupleName <- Ctx.genNamedSym "tuple"
transArgs <- mapM translate args
let elemTypes = map A.getType args
realTypes = map runtimeType elemTypes
tupLen = Int $ length args
tupType = A.getType tuple
eAlloc = Call tupleMkFn [AsExpr encoreCtxVar, tupLen]
theTupleDecl = Assign (Decl (translate tupType, Var tupleName)) eAlloc
tSetTupleType = Seq $ zipWith (tupleSetType tupleName) [0..] realTypes
(theTupleVars, theTupleContent) = unzip transArgs
theTupleInfo = zip theTupleVars elemTypes
theTupleSets = zipWith (tupleSet tupleName) [0..] theTupleInfo
return (Var tupleName, Seq $ theTupleDecl : tSetTupleType :
theTupleContent ++ theTupleSets)
where
tupleSetType name index ty =
Statement $ Call C.tupleSetType
[AsExpr $ Var name, Int index, ty]
tupleSet tupleName index (narg, ty) =
Statement $ Call C.tupleSet
[AsExpr $ Var tupleName,
Int index,
asEncoreArgT (translate ty) $ AsExpr narg]
translate (A.VarAccess {A.qname}) = do
c <- get
case Ctx.substLkp c qname of
Just substName ->
return (substName , Skip)
Nothing -> do
(_, header) <- gets $ Ctx.lookupFunction qname
let name = resolveFunctionSource header
return (Var . show $ globalClosureName name, Skip)
where
resolveFunctionSource header =
case ID.qnsource qname of
Just source ->
ID.setSourceFile source $
ID.qLocal $ A.hname header
Nothing ->
ID.qLocal $ A.hname header
translate fun@(A.FunctionAsValue {A.typeArgs}) = do
tmp <- Var <$> Ctx.genSym
let funName = functionAsValueWrapperNameOf fun
(rtArray, rtArrayInit) <- runtimeTypeArguments typeArgs
return (tmp,
Seq $
rtArrayInit:
[Assign (Decl (closure, tmp))
(Call closureMkFn [encoreCtxVar, AsLval funName,
nullVar, nullVar, rtArray])])
translate (A.Consume {A.target = arrAcc@A.ArrayAccess{A.target, A.index}}) = do
(ntarg, ttarg) <- translate target
(nindex, tindex) <- translate index
accessName <- Ctx.genNamedSym "access"
let ty = translate $ A.getType arrAcc
theAccess =
Assign (Decl (ty, Var accessName))
(Call (Nam "array_get") [ntarg, nindex]
`Dot` encoreArgTTag ty)
theSet =
Statement $
Call (Nam "array_set")
[AsExpr ntarg, AsExpr nindex, asEncoreArgT ty Null]
return (Var accessName, Seq [ttarg, tindex, theAccess, theSet])
translate (A.Consume {A.target}) = do
(ntarg, ttarg) <- translate target
lval <- mkLval target
accessName <- Ctx.genNamedSym "consume"
let ty = translate $ A.getType target
theRead = Assign (Decl (ty, Var accessName)) ntarg
theConsume = if Ty.isMaybeType $ A.getType target
then Assign lval $ Amp (Nam "DEFAULT_NOTHING")
else Assign lval Null
return (Var accessName, Seq [ttarg, theRead, theConsume])
where
mkLval (A.VarAccess {A.qname}) =
do ctx <- get
case Ctx.substLkp ctx qname of
Just substName -> return substName
Nothing -> error $ "Expr.hs: Unbound variable: " ++ show qname
mkLval (A.FieldAccess {A.target, A.name}) =
do (ntarg, ttarg) <- translate target
return (Deref (StatAsExpr ntarg ttarg) `Dot` fieldName name)
mkLval e = error $ "Cannot translate '" ++ show e ++ "' to a valid lval"
translate acc@(A.FieldAccess {A.target, A.name}) = do
(ntarg,ttarg) <- translate target
tmp <- Ctx.genNamedSym "fieldacc"
fld <- gets $ Ctx.lookupField (A.getType target) name
let theAccess = if Ty.isTypeVar (A.ftype fld) then
fromEncoreArgT (translate . A.getType $ acc) $
AsExpr (Deref ntarg `Dot` fieldName name)
else
Deref ntarg `Dot` fieldName name
theAssign = Assign (Decl (translate (A.getType acc), Var tmp)) theAccess
return (Var tmp, Seq [ttarg
,dtraceFieldAccess ntarg name
,theAssign
])
translate acc@(A.TupleAccess {A.target, A.compartment}) = do
(ntarg,ttarg) <- translate target
tmp <- Ctx.genNamedSym "tupleacc"
let ty = translate $ (A.getType acc)
theValue = fromEncoreArgT ty $ (Call tupleGet [AsExpr ntarg, Int compartment])
theDecl = Decl (ty, Var tmp)
theAssign = Assign theDecl theValue
return (Var tmp, Seq [ttarg
-- ,dtraceFieldAccess ntarg $ Int compartment
,theAssign
])
translate (A.Let {A.decls, A.body}) = do
tmpsTdecls <- mapM translateDecl decls
let (tmps, tdecls) = unzip tmpsTdecls
(nbody, tbody) <- translate body
mapM_ (mapM_ (unsubstituteVar . A.varName) . fst) decls
return (nbody, Seq $ concat tdecls ++ [tbody])
translate new@(A.NewWithInit {A.ty, A.args})
| Ty.isActiveSingleType ty = delegateUse callTheMethodOneway
| Ty.isSharedSingleType ty = delegateUse callTheMethodOneway
| otherwise = delegateUse callTheMethodSync
where
delegateUse methodCall =
let
fName = constructorImplName ty
callCtor = Call fName [encoreCtxName, nullName]
typeParams = Ty.getTypeParameters ty
callTypeParamsInit args = Call (runtimeTypeInitFnName ty) args
in
do
let typeArgs = map runtimeType typeParams
(nnew, constructorCall) <- namedTmpVar "new" ty callCtor
(initArgs, result) <-
methodCall nnew ty ID.constructorName args [] ty
return (nnew,
Seq $
[constructorCall] ++
initArgs ++
[ Statement $ callTypeParamsInit $ AsExpr nnew:typeArgs
, Statement result]
)
translate arrNew@(A.ArrayNew {A.ty, A.size}) = do
arrName <- Ctx.genNamedSym "array"
(nsize, tsize) <- translate size
let ty' = runtimeType ty
theArrayDecl =
Assign (Decl (array, Var arrName))
(Call arrayMkFn [AsExpr encoreCtxVar, AsExpr nsize, ty'])
return (Var arrName, Seq [tsize, theArrayDecl])
translate rangeLit@(A.RangeLiteral {A.start = start, A.stop = stop, A.step = step}) = do
(nstart, tstart) <- translate start
(nstop, tstop) <- translate stop
(nstep, tstep) <- translate step
rangeLiteral <- Ctx.genNamedSym "range_literal"
let ty = translate $ A.getType rangeLit
return (Var rangeLiteral, Seq [tstart, tstop, tstep,
Assign (Decl (ty, Var rangeLiteral))
(Call rangeMkFn [encoreCtxVar, nstart, nstop, nstep])])
translate arrAcc@(A.ArrayAccess {A.target, A.index}) =
do (ntarg, ttarg) <- translate target
(nindex, tindex) <- translate index
accessName <- Ctx.genNamedSym "access"
let ty = translate $ A.getType arrAcc
theAccess =
Assign (Decl (ty, Var accessName))
(fromEncoreArgT ty (Call arrayGet [ntarg, nindex]))
return (Var accessName, Seq [ttarg, tindex, theAccess])
translate arrLit@(A.ArrayLiteral {A.args}) =
do arrName <- Ctx.genNamedSym "array"
targs <- mapM translate args
let len = length args
ty = Ty.getResultType $ A.getType arrLit
let runtimeT = runtimeType ty
theArrayDecl =
Assign (Decl (array, Var arrName))
(Call arrayMkFn [AsExpr encoreCtxVar, Int len, runtimeT])
theArrayContent = Seq $ map (\(_, targ) -> targ) targs
theArraySets = snd $ mapAccumL (arraySet arrName ty) 0 targs
return (Var arrName, Seq $ theArrayDecl : theArrayContent : theArraySets)
where
arraySet arrName ty index (narg, _) =
(index + 1,
Statement $ Call C.arraySet
[AsExpr $ Var arrName,
Int index,
asEncoreArgT (translate ty) $ AsExpr narg])
translate arrSize@(A.ArraySize {A.target}) =
do (ntarg, ttarg) <- translate target
tmp <- Ctx.genNamedSym "size"
let theSize = Assign (Decl (int, Var tmp))
(Call arraySize [ntarg])
return (Var tmp, Seq [ttarg, theSize])
translate call@(A.MethodCall { A.emeta, A.target, A.name, A.typeArguments, A.args})
| (Ty.isTraitType . A.getType) target ||
(Ty.isUnionType . A.getType) target ||
(Ty.isTypeVar . A.getType) target = do
(ntarget, ttarget) <- translate target
let ntarget' = if Ty.isTypeVar $ A.getType target
then Cast capability (ntarget `Dot` Nam "p")
else AsExpr ntarget
(nCall, tCall) <- traitMethod msgId ntarget' (A.getType target) name
typeArguments args (translate (A.getType call))
let recvNullCheck = targetNullCheck ntarget' target name emeta "."
return (nCall, Seq [ttarget
,recvNullCheck
,tCall
])
| syncAccess = delegateUse callTheMethodSync "sync_method_call"
| sharedAccess = delegateUse callTheMethodFuture "shared_method_call"
| otherwise = error $ "Expr.hs: Don't know how to call target of type " ++
Ty.showWithKind targetTy ++
" at " ++ Meta.showPos (A.getMeta call)
where
targetTy = A.getType target
retTy = A.getType call
delegateUse methodCall sym = do
result <- Ctx.genNamedSym sym
(ntarget, ttarget) <- translate target
(initArgs, resultExpr) <-
methodCall ntarget targetTy name args typeArguments retTy
return (Var result,
Seq $
ttarget :
targetNullCheck (AsExpr ntarget) target name emeta "." :
initArgs ++
[Assign (Decl (translate retTy, Var result)) resultExpr]
)
syncAccess = A.isThisAccess target ||
(Ty.isPassiveRefType . A.getType) target
sharedAccess = Ty.isSharedSingleType $ A.getType target
translate call@A.MessageSend{A.emeta, A.target, A.name, A.args, A.typeArguments}
| (Ty.isTraitType . A.getType) target ||
(Ty.isUnionType . A.getType) target = do
(ntarget, ttarget) <- translate target
let idFun = if Util.isStatement call
then oneWayMsgId
else futMsgId
(nCall, tCall) <- traitMethod idFun ntarget (A.getType target) name
typeArguments args (translate (A.getType call))
let recvNullCheck = targetNullCheck (AsExpr ntarget) target name emeta "."
return (nCall, Seq [ttarget
,recvNullCheck
,tCall
])
| Util.isStatement call = delegateUseM callTheMethodOneway Nothing
| isActive && isStream = delegateUseM callTheMethodStream (Just "stream")
| otherwise = delegateUseM callTheMethodFuture (Just "fut")
where
targetTy = A.getType target
isActive = Ty.isActiveSingleType targetTy
isStream = Ty.isStreamType $ A.getType call
delegateUseM msgSend sym = do
(ntarget, ttarget) <- translate target
(initArgs, resultExpr) <-
msgSend ntarget targetTy name args typeArguments retTy
(resultVar, handleResult) <- returnValue
return (resultVar,
Seq $ ttarget : targetNullCheck (AsExpr ntarget) target name emeta " ! " :
initArgs ++ [handleResult resultExpr])
where
retTy | isNothing sym = Ty.unitType
| otherwise = A.getType call
returnValue | isNothing sym = return (unit, Statement)
| otherwise = do
result <- Ctx.genNamedSym (fromJust sym)
return (Var result, Assign (Decl (translate retTy, Var result)))
translate w@(A.DoWhile {A.cond, A.body}) = do
(ncond,tcond) <- translate cond
(_,tbody) <- translate body
return (unit, DoWhile (StatAsExpr ncond tcond) (Statement tbody))
translate w@(A.While {A.cond, A.body}) = do
(ncond,tcond) <- translate cond
(_,tbody) <- translate body
return (unit, While (StatAsExpr ncond tcond) (Statement tbody))
translate for@(A.For {A.name, A.step, A.src, A.body}) = do
indexVar <- Var <$> Ctx.genNamedSym "index"
eltVar <- Var <$> Ctx.genNamedSym (show name)
startVar <- Var <$> Ctx.genNamedSym "start"
stopVar <- Var <$> Ctx.genNamedSym "stop"
stepVar <- Var <$> Ctx.genNamedSym "step"
srcStepVar <- Var <$> Ctx.genNamedSym "src_step"
(srcN, srcT) <- if A.isRangeLiteral src
then return (undefined, Comm "Range not generated")
else translate src
let srcType = A.getType src
eltType = if Ty.isRangeType srcType
then int
else translate $ Ty.getResultType (A.getType src)
srcStart = if Ty.isRangeType srcType
then Call rangeStart [srcN]
else Int 0 -- Arrays start at 0
srcStop = if Ty.isRangeType srcType
then Call rangeStop [srcN]
else BinOp (translate ID.MINUS)
(Call arraySize [srcN])
(Int 1)
srcStep = if Ty.isRangeType srcType
then Call rangeStep [srcN]
else Int 1
(srcStartN, srcStartT) <- translateSrc src A.start startVar srcStart
(srcStopN, srcStopT) <- translateSrc src A.stop stopVar srcStop
(srcStepN, srcStepT) <- translateSrc src A.step srcStepVar srcStep
(stepN, stepT) <- translate step
substituteVar name eltVar
(bodyN, bodyT) <- translate body
unsubstituteVar name
let stepDecl = Assign (Decl (int, stepVar))
(BinOp (translate ID.TIMES) stepN srcStepN)
stepAssert = Statement $ Call rangeAssertStep [stepVar]
indexDecl = Seq [AsExpr $ Decl (int, indexVar)
,If (BinOp (translate ID.GT)
(AsExpr stepVar) (Int 0))
(Assign indexVar srcStartN)
(Assign indexVar srcStopN)]
cond = BinOp (translate ID.AND)
(BinOp (translate ID.GTE) indexVar srcStartN)
(BinOp (translate ID.LTE) indexVar srcStopN)
eltDecl =
Assign (Decl (eltType, eltVar))
(if Ty.isRangeType srcType
then AsExpr indexVar
else AsExpr $ fromEncoreArgT eltType (Call arrayGet [srcN, indexVar]))
inc = Assign indexVar (BinOp (translate ID.PLUS) indexVar stepVar)
theBody = Seq [eltDecl, Statement bodyT, inc]
theLoop = While cond theBody
return (unit, Seq [srcT
,srcStartT
,srcStopT
,srcStepT
,stepT
,stepDecl
,stepAssert
,indexDecl
,theLoop])
where
translateSrc src selector var rhs
| A.isRangeLiteral src = translate (selector src)
| otherwise = return (var, Assign (Decl (int, var)) rhs)
translate ite@(A.IfThenElse { A.cond, A.thn, A.els }) =
do tmp <- Ctx.genNamedSym "ite"
(ncond, tcond) <- translate cond
(nthn, tthn) <- translate thn
(nels, tels) <- translate els
let resultType = A.getType ite
exportThn = Seq $ tthn :
[Assign (Var tmp) (Cast (translate resultType) nthn)]
exportEls = Seq $ tels :
[Assign (Var tmp) (Cast (translate resultType) nels)]
return (Var tmp,
Seq [AsExpr $ Decl (translate (A.getType ite), Var tmp),
If (StatAsExpr ncond tcond) (Statement exportThn) (Statement exportEls)])
translate m@(A.Match {A.arg, A.clauses}) =
do retTmp <- Ctx.genNamedSym "match"
(narg, targ) <- translate arg
let argty = A.getType arg
mType = translate (A.getType m)
tIfChain <- ifChain clauses narg argty retTmp mType (A.getPos m)
let lRetDecl = Decl (mType, Var retTmp)
eZeroInit = Cast mType (Int 0)
tRetDecl = Assign lRetDecl eZeroInit
return (Var retTmp, Seq [targ, Statement lRetDecl, tIfChain])
where
withPatDecls assocs expr = do
mapM_ (\name -> substituteVar name $ lookupVar name) varNames
(nexpr, texpr) <- translate expr
mapM_ unsubstituteVar varNames
return (nexpr, texpr)
where
varNames = map (ID.Name . fst) assocs
lookupVar name = fromJust $ lookup (show name) assocs
translateMaybePattern e derefedArg argty assocs = do
optionVar <- Ctx.genNamedSym "optionVal"
nCheck <- Ctx.genNamedSym "optionCheck"
let eMaybeVal = AsExpr $ Dot derefedArg (Nam "val")
valType = Ty.getResultType argty
eMaybeField = fromEncoreArgT (translate valType) eMaybeVal
tVal = Assign (Decl (translate valType, Var optionVar)) eMaybeField
(nRest, tRest) <- translatePattern e (Var optionVar) valType assocs
let expectedTag = AsExpr $ AsLval $ Nam "JUST"
actualTag = AsExpr $ Dot derefedArg $ Nam "tag"
eTagsCheck = BinOp (translate ID.EQ) expectedTag actualTag
intTy = translate Ty.intType
tDecl = Statement $ Decl (intTy, nRest)
tRestWithDecl = Seq [tDecl, tVal, tRest]
eRest = StatAsExpr nRest tRestWithDecl
eCheck = BinOp (translate ID.AND) eTagsCheck eRest
tCheck = Assign (Var nCheck) eCheck
return (Var nCheck, tCheck)
translateComparison e1 e2 ty
| Ty.isStringType ty = do
let strcmpCall = Call (Nam "strcmp") [e1, e2]
return $ BinOp (translate ID.EQ) strcmpCall (Int 0)
| Ty.isStringObjectType ty =
-- TODO: this code generation should be autogenerated
return $ Call (methodImplName Ty.stringObjectType (ID.Name "eq"))
[AsExpr encoreCtxVar, e1, AsExpr nullVar, e2]
| otherwise =
return (BinOp (translate ID.EQ) e1 e2)
translatePattern e@A.AdtExtractorPattern{A.name
,A.arg = A.Tuple{A.args}
,A.adtClassDecl =
c@A.Class{A.cname
,A.cfields}}
argName argty assocs = do
let eSelfArg = AsExpr argName
tag = Ty.getAdtTag cname
typeName = Ptr $ AsType (classTypeName cname)
castArgName = Cast typeName argName
fieldVar <- Var <$> Ctx.genNamedSym "adtFieldCheck"
tmp <- Var <$> Ctx.genNamedSym "adtPatternResult"
tFields <-
zipWithM (translateAdtField castArgName assocs fieldVar)
args (map (\f -> (A.fname f, A.ftype f)) (drop 1 cfields))
let nullCheck = BinOp (translate ID.NEQ) eSelfArg Null
actualTag = Cast typeName eSelfArg `Arrow` Nam "_enc__field__ADT_tag"
tagCheck = BinOp (translate ID.EQ) (AsExpr actualTag) (Int tag)
eCheck = BinOp (translate ID.AND) nullCheck tagCheck
fwdDecl = Assign (Decl (translate Ty.intType, fieldVar)) (Int 1)
result = BinOp (translate ID.AND)
eCheck (StatAsExpr fieldVar (Seq tFields))
theAssign = Assign tmp result
return (tmp, Seq [fwdDecl, theAssign])
where
translateAdtField argName assocs retVar field (formalName, formalType) = do
let fieldType = A.getType field
fieldCType = translate fieldType
fieldAccess = argName `Arrow` fieldName formalName
fieldLookup =
if Ty.isTypeVar formalType
then fromEncoreArgT fieldCType (AsExpr fieldAccess)
else fieldAccess
(nField, tField) <-
translatePattern field fieldLookup fieldType assocs
let theAnd =
BinOp (translate ID.AND) (AsExpr retVar) (AsExpr nField)
theRetAssign = Assign retVar theAnd
theHelpDecl = Statement $ Decl (translate Ty.intType, nField)
return $ Seq [theHelpDecl, tField, theRetAssign]
translatePattern (A.ExtractorPattern {A.name, A.arg}) narg argty assocs = do
let eSelfArg = AsExpr narg
eNullCheck = BinOp (translate ID.NEQ) eSelfArg Null
innerTy = A.getType arg
tmpTy = Ty.maybeType innerTy
noArgs = [] :: [A.Expr]
(nCall, tCall) <-
if Ty.isCapabilityType argty ||
Ty.isUnionType argty
then do
calledType <- gets $ Ctx.lookupCalledType argty name
-- TODO: should we pass the typeArguments? I don't think so because
-- pattern matching a function header works only on methods with
-- no arguments, and there is no meaning in allowing this at
-- the time being
traitMethod msgId narg calledType name [] noArgs (translate tmpTy)
else do
tmp <- Ctx.genNamedSym "extractedOption"
(argDecls, theCall) <-
passiveMethodCall narg argty name noArgs tmpTy
let theAssign = Assign (Decl (translate tmpTy, Var tmp)) theCall
return (Var tmp, Seq $ argDecls ++ [theAssign])
let derefedCall = Deref nCall
(nRest, tRest) <-
translateMaybePattern arg derefedCall tmpTy assocs
nCheck <- Ctx.genNamedSym "extractoCheck"
let tDecl = Statement $ Decl (translate Ty.intType, nRest)
tRestWithDecl = Seq [tDecl, tCall, tRest]
eCheck = BinOp (translate ID.AND) eNullCheck $ StatAsExpr nRest tRestWithDecl
tAssign = Assign (Var nCheck) eCheck
return (Var nCheck, tAssign)
translatePattern (tuple@A.Tuple {A.args}) larg argty assocs = do
tmp <- Ctx.genNamedSym "tupleCheck"
let elemTypes = Ty.getArgTypes $ A.getType tuple
elemInfo = zip elemTypes args
theInit = Assign (Var tmp) (Int 1)
tChecks <- checkElems elemInfo (Var tmp) larg assocs 0
return (Var tmp, Seq $ theInit:tChecks)
where
checkElems [] _ _ _ _ = return []
checkElems ((ty, arg):rest) retVar larg assocs index = do
accessName <- Ctx.genNamedSym "tupleAccess"
let elemTy = translate ty
theDecl = Decl (elemTy, Var accessName)
theCall = fromEncoreArgT elemTy (Call tupleGet [AsExpr larg, Int index])
theCast = Cast elemTy theCall
theAssign = Assign theDecl theCall
(ncheck, tcheck) <- translatePattern arg (Var accessName) ty assocs
tRest <- checkElems rest retVar larg assocs (index + 1)
let theAnd = BinOp (translate ID.AND) (AsExpr retVar) (AsExpr ncheck)
theRetAssign = Assign retVar theAnd
theHelpDecl = Statement $ Decl (translate Ty.intType, ncheck)
return (theAssign : theHelpDecl : tcheck : theRetAssign : tRest)
translatePattern (A.MaybeValue {A.mdt=A.JustData{A.e}}) larg argty assocs = do
let derefedArg = Deref larg
translateMaybePattern e derefedArg argty assocs
translatePattern (A.VarAccess{A.qname}) larg argty assocs = do
tmp <- Ctx.genNamedSym "varBinding"
let name = ID.qnlocal qname
lVar = fromJust $ lookup (show name) assocs
eArg = AsExpr larg
tBindVar = Assign lVar eArg
tBindRet = Assign (Var tmp) (Int 1)
tBindAll = Seq [tBindVar, tBindRet]
return (Var tmp, tBindAll)
translatePattern value larg argty _ = do
tmp <- Ctx.genNamedSym "valueCheck"
(nvalue, tvalue) <- translate value
let eValue = StatAsExpr nvalue tvalue
eArg = AsExpr larg
eComp <- translateComparison eValue eArg argty
let tAssign = Assign (Var tmp) eComp
return (Var tmp, tAssign)
translateIfCond (A.MatchClause {A.mcpattern, A.mcguard})
narg argty assocs = do
(nPattern, tPatternNoDecl) <- translatePattern mcpattern narg argty assocs
-- The binding expression should evaluate to true,
-- regardless of the values that are bound.
let ty = translate Ty.intType
eDeclPattern = AsExpr $ Decl (ty, nPattern)
tPattern = Seq [Statement eDeclPattern, tPatternNoDecl]
ePattern = StatAsExpr nPattern tPattern
(nguard, tguard) <- withPatDecls assocs mcguard
let eGuard = StatAsExpr nguard tguard
eCond = BinOp (translate ID.AND) ePattern eGuard
return eCond
translateHandler clause handlerReturnVar assocs retTy = do
(nexpr, texpr) <- withPatDecls assocs (A.mchandler clause)
let eExpr = StatAsExpr nexpr texpr
eCast = Cast retTy eExpr
tAssign = Assign (Var handlerReturnVar) eCast
return tAssign
ifChain [] _ _ _ _ pos = do
let errorCode = Int 1
exitCall = Statement $ Call (Nam "exit") [errorCode]
errorMsg = String $ "*** Runtime error: No matching clause was found at " ++ show pos ++ " ***\n"
errorPrint = Statement $ Call (Nam "fprintf") [AsExpr C.stderr, errorMsg]
return $ Seq [errorPrint, exitCall]
ifChain (clause:rest) narg argty retTmp retTy pos = do
let freeVars = Util.foldrExp (\e a -> getExprVars e ++ a) [] (A.mcpattern clause)
assocs <- mapM createAssoc freeVars
thenExpr <- translateHandler clause retTmp assocs retTy
elseExpr <- ifChain rest narg argty retTmp retTy pos
eCond <- translateIfCond clause narg argty assocs
let tIf = Statement $ If eCond thenExpr elseExpr
tDecls = Seq $ map (fwdDecl assocs) freeVars
return $ Seq [tDecls, tIf]
where
createAssoc (name, _) = do
let varName = show name
tmp <- Ctx.genNamedSym varName
return (varName, Var tmp)
fwdDecl assocs (name, ty) =
let tname = fromJust $ lookup (show name) assocs
in Statement $ Decl (translate ty, tname)
getExprVars var@(A.VarAccess {A.qname}) =
[(ID.qnlocal qname, A.getType var)]
getExprVars _ =
[]
translate e@(A.Embed {A.embedded}) = do
translated <- liftM concat $ mapM translatePair embedded
if Ty.isUnitType (A.getType e) then
return (unit, Embed $ "({" ++ translated ++ "});")
else
namedTmpVar "embed" (A.getType e) (Embed $ "({" ++ translated ++ "})")
where
translatePair (code, e) = do
interpolated <- translateInterpolated e
return $ code ++ pp interpolated
translateInterpolated A.Skip{} =
return (Embed "")
translateInterpolated A.VarAccess{A.qname} = do
result <- gets (`Ctx.substLkp` qname)
let var = fromMaybe (AsLval $ globalClosureName qname) result
return $ AsExpr var
translateInterpolated A.FieldAccess{A.name, A.target} = do
targ <- translateInterpolated target
return $ AsExpr $ targ `Arrow` fieldName name
translateInterpolated e = do
(ne, te) <- translate e
return $ StatAsExpr ne te
translate get@(A.Get{A.val})
| Ty.isFutureType $ A.getType val =
do (nval, tval) <- translate val
let resultType = translate (Ty.getResultType $ A.getType val)
theGet = fromEncoreArgT resultType (Call futureGetActor [encoreCtxVar, nval])
tmp <- Ctx.genSym
return (Var tmp, Seq [tval, Assign (Decl (resultType, Var tmp)) theGet])
| Ty.isStreamType $ A.getType val =
do (nval, tval) <- translate val
let resultType = translate (Ty.getResultType $ A.getType val)
theGet = fromEncoreArgT resultType (Call streamGet [encoreCtxVar, nval])
tmp <- Ctx.genSym
return (Var tmp, Seq [tval, Assign (Decl (resultType, Var tmp)) theGet])
| otherwise = error $ "Cannot translate get of " ++ show val
translate A.Forward{A.forwardExpr = expr@A.MessageSend{A.emeta
,A.target
,A.name
,A.typeArguments
,A.args}} = do
isAsyncForward <- gets Ctx.isAsyncForward
eCtx <- gets Ctx.getExecCtx
let dtraceExit = getDtraceExit eCtx
if isAsyncForward
then do
(ntarget, ttarget) <- translate target
let targetType = A.getType target
(initArgs, forwardingCall) <-
callTheMethodForward [futVar]
ntarget targetType name args typeArguments Ty.unitType
(initArgs1, oneWayMsg) <-
callTheMethodOneway
ntarget targetType name args typeArguments Ty.unitType
let nullCheck = targetNullCheck (AsExpr ntarget) target name emeta "."
result =
case eCtx of
Ctx.ClosureContext clos -> []
_ -> [dtraceExit, Return Skip]
return (unit, Seq $
ttarget : nullCheck :
[Statement $
If futVar
(Seq $ initArgs ++ [Statement forwardingCall])
(Seq $ initArgs1 ++ [Statement oneWayMsg])] ++
result
)
else do
(sendn, sendt) <- translate A.MessageSend{A.emeta
,A.target
,A.name
,A.typeArguments
,A.args}
tmp <- Ctx.genSym
let resultType = translate (Ty.getResultType $ A.getType expr)
theGet = fromEncoreArgT resultType (Call futureGetActor [encoreCtxVar, sendn])
result =
case eCtx of
Ctx.MethodContext mdecl ->
(unit, Seq [sendt, dtraceExit, Return theGet])
Ctx.ClosureContext clos ->
let ty = (Ty.getResultType $ A.getType clos)
in (Var tmp, Seq [sendt, Assign (Decl (resultType, Var tmp)) theGet])
_ -> error "Expr.hs: No context to forward"
return result
translate A.Forward{A.emeta, A.forwardExpr = fchain@A.FutureChain{A.future, A.chain}} = do
(nfuture,tfuture) <- translate future
(nchain, tchain) <- translate chain
eCtx <- gets $ Ctx.getExecCtx
isAsyncForward <- gets Ctx.isAsyncForward
let ty = getRuntimeType chain
dtraceExit = getDtraceExit eCtx
result = case eCtx of
Ctx.ClosureContext clos -> []
_ -> [dtraceExit, Return Skip]
futureChain =
if Util.isForwardInExpr chain
then Call futureChainActor
[AsExpr encoreCtxVar, AsExpr nfuture, ty, AsExpr nchain]
else Call futureChainWithFut
[AsExpr encoreCtxVar, AsExpr nfuture, ty, AsExpr nchain
,AsExpr futVar, AsExpr $ AsLval $ Nam "false"]
when (A.isVarAccess chain) $
unless (A.isIdClosure chain) $
error $ "Expr.hs: The closure that contains forward must be defined in chain."
if isAsyncForward
then do
return (unit, Seq $
[tfuture,
tchain,
Statement futureChain] ++
result)
else do
tmp <- Ctx.genSym
result <- Ctx.genSym
let nfchain = Var result
resultType = translate (Ty.getResultType $ A.getType fchain)
theGet = fromEncoreArgT resultType (Call futureGetActor [encoreCtxVar, nfchain])
return $ (Var tmp, Seq $
[tfuture,
tchain,
(Assign (Decl (C.future, Var result))
(Call futureChainActor
[AsExpr encoreCtxVar, AsExpr nfuture, ty, AsExpr nchain]
)),
Assign (Decl (resultType, Var tmp)) theGet])
translate yield@(A.Yield{A.val}) =
do (nval, tval) <- translate val
tmp <- Ctx.genSym
let yieldArg = asEncoreArgT (translate (A.getType val)) nval
tmpStream = Assign (Decl (stream, Var tmp)) streamHandle
updateStream = Assign (streamHandle)
(Call streamPut [AsExpr encoreCtxVar, AsExpr streamHandle,
yieldArg, runtimeType $ A.getType val])
return (unit, Seq [tval, tmpStream, updateStream])
translate eos@(A.Eos{}) =
let eosCall = Call streamClose [encoreCtxVar, streamHandle]
in return (unit, Seq [Statement eosCall, Return Skip])
translate ret@(A.Return{A.val}) =
do (nval, tval) <- translate val
eCtx <- gets Ctx.getExecCtx
isAsyncForward <- gets Ctx.isAsyncForward
let theReturn =
if isAsyncForward then
case eCtx of
Ctx.FunctionContext fun ->
let ty = A.getType fun
in [dtraceFunctionExit (A.functionName fun)
,Statement $ Call futureFulfil [AsExpr encoreCtxVar, AsExpr futVar
,asEncoreArgT (translate ty) nval]
,Return Skip]
Ctx.MethodContext mdecl ->
let ty = A.getType mdecl
in [dtraceMethodExit thisVar (A.methodName mdecl)
,Statement $ Call futureFulfil [AsExpr encoreCtxVar, AsExpr futVar
,asEncoreArgT (translate ty) nval]
,Return Skip]
Ctx.ClosureContext clos ->
let ty = (Ty.getResultType $ A.getType clos)
in [dtraceClosureExit
,Statement $ Call futureFulfil [AsExpr encoreCtxVar, AsExpr futVar
,asEncoreArgT (translate ty) nval]
,Return Skip]
_ -> error "Expr.hs: No context to return from"
else
case eCtx of
Ctx.FunctionContext fun ->
[dtraceFunctionExit (A.functionName fun), Return nval]
Ctx.MethodContext mdecl ->
[dtraceMethodExit thisVar (A.methodName mdecl), Return nval]
Ctx.ClosureContext clos ->
let ty = (Ty.getResultType $ A.getType clos)
in [dtraceClosureExit,
Return $ asEncoreArgT (translate ty) nval]
_ -> error "Expr.hs: No context to return from"
return (unit, Seq $ tval:theReturn)
translate iseos@(A.IsEos{A.target}) =
do (ntarg, ttarg) <- translate target
tmp <- Ctx.genSym
let theCall = Assign (Decl (bool, Var tmp)) (Call streamEos [encoreCtxVar, ntarg])
return (Var tmp, Seq [ttarg, theCall])
translate next@(A.StreamNext{A.target}) =
do (ntarg, ttarg) <- translate target
tmp <- Ctx.genSym
let theCall = Assign (Decl (stream, Var tmp)) (Call streamGetNext [encoreCtxVar, ntarg])
return (Var tmp, Seq [ttarg, theCall])
translate await@(A.Await{A.val}) =
do (nval, tval) <- translate val
return (unit, Seq [tval, Statement $ Call futureAwait [encoreCtxVar, nval]])
translate suspend@(A.Suspend{}) =
return (unit, Seq [Call actorSuspend [encoreCtxVar]])
translate futureChain@(A.FutureChain{A.future, A.chain}) = do
(nfuture,tfuture) <- translate future
(nchain, tchain) <- translate chain
result <- Ctx.genSym
isAsyncForward <- gets Ctx.isAsyncForward
let ty = getRuntimeType chain
return $ (Var result,
Seq $ [tfuture,
tchain,
if (Util.isForwardInExpr chain && isAsyncForward)
then Statement $
(Call futureChainWithFut
[AsExpr encoreCtxVar, AsExpr nfuture, ty, AsExpr nchain,
AsExpr ((Deref envName) `Dot` futNam), AsExpr $ AsLval $ Nam "true"])
else Assign (Decl (C.future, Var result))
(Call futureChainActor [AsExpr encoreCtxVar, AsExpr nfuture, ty, AsExpr nchain])
] ++
if (Util.isForwardInExpr chain && isAsyncForward)
then [assignVar futNam (Decl (C.future, Var result))]
else [])
where
metaId = Meta.getMetaId . A.getMeta $ chain
envName = closureEnvName metaId
assignVar lhs rhs = Assign rhs ((Deref envName) `Dot` lhs)
translate clos@(A.Closure{A.eparams, A.body}) = do
tmp <- Ctx.genSym
futClos <- Ctx.genNamedSym "fut_closure"
globalFunctionNames <- gets Ctx.getGlobalFunctionNames
isAsyncForward <- gets Ctx.isAsyncForward
let bound = map (ID.qLocal . A.pname) eparams
freeVars = filter (ID.isLocalQName . fst) $
Util.freeVariables bound body
ty = runtimeType . A.getType $ body
fillEnv <- insertAllVars freeVars fTypeVars
return
(Var tmp,
Seq $
mkEnv envName : fillEnv ++
if isAsyncForward then
if forwardInBody
then [Assign (Decl (future, Var futClos))
(Call futureMkFn [AsExpr encoreCtxVar, ty])
,assignVar futNam (Var futClos)
,Assign (Decl (closure, Var tmp))
(Call closureMkFn [encoreCtxName, funNameAsync, envName, traceNameAsync, nullName])]
else [Assign (Decl (closure, Var tmp))
(Call closureMkFn [encoreCtxName, funName, envName, traceName, nullName])]
else
[Assign (Decl (closure, Var tmp))
(Call closureMkFn [encoreCtxName, funName, envName, traceName, nullName])])
where
forwardInBody = Util.isForwardInExpr body
metaIdAsync = metaId ++ "_async"
idClos = A.isIdClosure body
funNameAsync = if idClos || not forwardInBody then funName
else closureFunName metaIdAsync
traceNameAsync = if idClos || not forwardInBody then traceName
else closureTraceName metaIdAsync
metaId = Meta.getMetaId . A.getMeta $ clos
funName = closureFunName metaId
envName = closureEnvName metaId
traceName = closureTraceName metaId
fTypeVars = Util.freeTypeVars body
mkEnv name =
Assign (Decl (Ptr $ Struct name, AsLval name))
(Call encoreAllocName [AsExpr (Deref encoreCtxVar), Sizeof $ Struct name])
insertAllVars vars typeVars =
liftM2 (++)
(mapM insertVar vars)
(filterM localTypeVar typeVars >>= mapM insertTypeVar)
insertVar (name, _) = do
c <- get
let tname = fromMaybe (AsLval $ globalClosureName name)
(Ctx.substLkp c name)
return $ assignVar (fieldName (ID.qnlocal name)) tname
insertTypeVar ty = do
c <- get
let
Just tname = Ctx.substLkp c name
fName = typeVarRefName ty
return $ assignVar fName tname
where
name = ID.qName $ Ty.getId ty
assignVar :: (UsableAs e Expr) => CCode Name -> CCode e -> CCode Stat
assignVar lhs rhs = Assign ((Deref envName) `Dot` lhs) rhs
localTypeVar ty = do
c <- get
return $ isJust $ Ctx.substLkp c name
where
name = ID.qName $ Ty.getId ty
translate fcall@(A.FunctionCall{A.qname, A.args}) = do
ctx <- get
case Ctx.substLkp ctx qname of
Just clos -> closureCall clos fcall
Nothing -> functionCall fcall
translate other = error $ "Expr.hs: can't translate: '" ++ show other ++ "'"
getDtraceExit eCtx =
case eCtx of
Ctx.FunctionContext fun ->
dtraceFunctionExit (A.functionName fun)
Ctx.MethodContext mdecl ->
dtraceMethodExit thisVar (A.methodName mdecl)
Ctx.ClosureContext clos ->
dtraceClosureExit
_ -> error "Expr.hs: No context to forward from"
closureCall :: CCode Lval -> A.Expr ->
State Ctx.Context (CCode Lval, CCode Stat)
closureCall clos fcall@A.FunctionCall{A.qname, A.args} = do
targs <- mapM translateArgument args
(tmpArgs, tmpArgDecl) <- tmpArr (Typ "value_t") targs
(calln, theCall) <- namedTmpVar "clos" typ $
AsExpr $
fromEncoreArgT (translate typ) $
Call closureCallName [encoreCtxVar, clos, tmpArgs]
return (if Ty.isUnitType typ then unit else calln
,Seq [tmpArgDecl
,dtraceClosureCall qname (extractArgs tmpArgs (length args))
,theCall
])
where
typ = A.getType fcall
translateArgument arg = do
(ntother, tother) <- translate arg
return $ asEncoreArgT (translate $ A.getType arg)
(StatAsExpr ntother tother)
extractArgs arr n = map (\i -> ArrAcc i arr) [0..n-1]
functionCall :: A.Expr -> State Ctx.Context (CCode Lval, CCode Stat)
functionCall fcall@A.FunctionCall{A.typeArguments = typeArguments
,A.qname
,A.args} = do
(argNames, initArgs) <- unzip <$> mapM translate args
(callVar, call) <- buildFunctionCallExpr args argNames
let ret = if Ty.isUnitType typ then unit else callVar
return (ret, Seq $ initArgs ++ [dtraceFunctionCall qname argNames
,call
])
where
typ = A.getType fcall
buildFunctionCallExpr args cArgs = do
let functionType = A.getArrowType fcall
expectedTypes = Ty.getArgTypes functionType
actualTypes = map A.getType args
castedArguments = zipWith3 castArguments expectedTypes cArgs actualTypes
let runtimeTypes = map runtimeType typeArguments
(tmpType, tmpTypeDecl) <- tmpArr (Ptr ponyTypeT) runtimeTypes
(cname, header) <- gets (Ctx.lookupFunction qname)
let runtimeTypeVar = if null runtimeTypes then nullVar else tmpType
prototype = Call cname
(map AsExpr [encoreCtxVar, runtimeTypeVar] ++ castedArguments)
rPrototype <- unwrapReturnType prototype
(callVar, call) <- namedTmpVar "fun_call" typ rPrototype
return (callVar, Seq [tmpTypeDecl, call])
unwrapReturnType functionCall = do
-- this function checks if the formal parameter return type is a type variable
-- and, if so, unwraps it (adds the .i, .p or .d)
(_, header) <- gets (Ctx.lookupFunction qname)
let formalReturnType = A.htype header
return (if Ty.isTypeVar formalReturnType then
AsExpr (fromEncoreArgT (translate typ) functionCall)
else functionCall)
indexArgument msgName i = Arrow msgName (Nam $ "f" ++ show i)
callTheMethodFuture = callTheMethodForName callMethodFutureName
callTheMethodForward extras =
callTheMethodForNameWithExtraArguments extras methodImplForwardName
callTheMethodOneway = callTheMethodForName methodImplOneWayName
callTheMethodStream = callTheMethodForName methodImplStreamName
callTheMethodSync targetName targetType methodName args typeargs resultType = do
(initArgs, expr) <- callTheMethodForName methodImplName
targetName targetType methodName args typeargs resultType
header <- gets $ Ctx.lookupMethod targetType methodName
return (initArgs
,convertBack (A.htype header) expr)
where
convertBack retType
| Ty.isTypeVar retType && (not . Ty.isTypeVar) resultType =
AsExpr . fromEncoreArgT (translate resultType)
| otherwise = id
callTheMethodForName ::
(Ty.Type -> ID.Name -> CCode Name) ->
CCode Lval -> Ty.Type -> ID.Name -> [A.Expr] -> [Ty.Type] -> Ty.Type
-> State Ctx.Context ([CCode Stat], CCode CCode.Main.Expr)
callTheMethodForName = callTheMethodForName' []
callTheMethodForNameWithExtraArguments ::
[CCode Lval] ->
(Ty.Type -> ID.Name -> CCode Name) ->
CCode Lval -> Ty.Type -> ID.Name -> [A.Expr] -> [Ty.Type] -> Ty.Type
-> State Ctx.Context ([CCode Stat], CCode CCode.Main.Expr)
callTheMethodForNameWithExtraArguments = callTheMethodForName'
callTheMethodForName' ::
[CCode Lval] ->
(Ty.Type -> ID.Name -> CCode Name) ->
CCode Lval -> Ty.Type -> ID.Name -> [A.Expr] -> [Ty.Type] -> Ty.Type
-> State Ctx.Context ([CCode Stat], CCode CCode.Main.Expr)
callTheMethodForName'
extraArguments
genCMethodName targetName targetType methodName args typeargs resulttype = do
(args', initArgs) <- unzip <$> mapM translate args
header <- gets $ Ctx.lookupMethod targetType methodName
-- translate actual method type variables
let runtimeTypes = map runtimeType typeargs
(tmpType, tmpTypeDecl) <- tmpArr (Ptr ponyTypeT) runtimeTypes
let runtimeTypeVar = if null runtimeTypes then nullVar else tmpType
return (initArgs ++ [tmpTypeDecl],
Call cMethodName $
map AsExpr [encoreCtxVar, targetName, runtimeTypeVar] ++
doCast (map A.ptype (A.hparams header)) args' ++
map AsExpr extraArguments
)
where
cMethodName = genCMethodName targetType methodName
actualArgTypes = map A.getType args
doCast expectedArgTypes args =
zipWith3 castArguments expectedArgTypes args actualArgTypes
arrMethodTypeVars formaltys actualtys =
let arrName = "methodTypeVars"
arr = map (AsExpr . AsLval . typeVarRefName) actualtys
in (Var arrName, Assign
(Decl (Ptr ponyTypeT, Var $ arrName ++ "[]"))
(Record arr))
passiveMethodCall :: CCode Lval -> Ty.Type -> ID.Name -> [A.Expr] -> Ty.Type
-> State Ctx.Context ([CCode Stat], CCode CCode.Main.Expr)
passiveMethodCall targetName targetType name args resultType = do
targs <- mapM translate args
header <- gets $ Ctx.lookupMethod targetType name
let targsTypes = map A.getType args
expectedTypes = map A.ptype (A.hparams header)
(argNames, argDecls) = unzip targs
castedArguments = zipWith3 castArguments expectedTypes argNames targsTypes
theCall =
if Ty.isTypeVar (A.htype header) then
AsExpr $ fromEncoreArgT (translate resultType)
(Call (methodImplName targetType name)
(AsExpr encoreCtxVar :
AsExpr targetName :
AsExpr nullVar : castedArguments))
else
Call (methodImplName targetType name)
(AsExpr encoreCtxVar :
AsExpr targetName : AsExpr nullVar : castedArguments)
return (argDecls, theCall)
castArguments :: Ty.Type -> CCode Lval -> Ty.Type -> CCode Expr
castArguments expected targ targType
| Ty.isTypeVar expected = asEncoreArgT (translate targType) $ AsExpr targ
| targType /= expected = Cast (translate expected) targ
| otherwise = AsExpr targ
traitMethod idFun this targetType name typeargs args resultType =
let
id = idFun targetType name
tyStr = Ty.getId targetType
nameStr = show name
in
do
f <- Ctx.genNamedSym $ concat [tyStr, "_", nameStr]
vtable <- Ctx.genNamedSym $ concat [tyStr, "_", "vtable"]
tmp <- Ctx.genNamedSym "trait_method_call"
(args, initArgs) <- unzip <$> mapM translate args
let runtimeTypes = map runtimeType typeargs
(tmpType, tmpTypeDecl) <- tmpArr (Ptr ponyTypeT) runtimeTypes
let tmpType' = if null runtimeTypes then nullVar else tmpType
return (Var tmp,
Seq $
initArgs ++
[declF f
,declVtable vtable
,initVtable this vtable
,initF f vtable id
,tmpTypeDecl
,ret tmp $ callF f this args tmpType'
]
)
where
argTypes = map (translate . A.getType) args
declF f = FunPtrDecl resultType (Nam f) $
Ptr (Ptr encoreCtxT):capability: Ptr (Ptr ponyTypeT): argTypes
declVtable vtable = FunPtrDecl (Ptr void) (Nam vtable) [Typ "int"]
vtable this = this `Arrow` selfTypeField `Arrow` Nam "vtable"
initVtable this v = Assign (Var v) $ Cast (Ptr void) $ vtable this
initF f vtable id = Assign (Var f) $ Call (Nam vtable) [id]
callF f this args typeArgs = Call (Nam f) $ AsExpr encoreCtxVar : Cast capability this :
AsExpr typeArgs : map AsExpr args
ret tmp fcall = Assign (Decl (resultType, Var tmp)) fcall
targetNullCheck ntarget target name meta op =
Statement $
Call (Nam "check_receiver")
[ntarget,
String op,
String (show (PP.ppExpr target)),
String (show name),
String (Meta.showPos meta)]
runtimeTypeArguments [] = return (nullVar, Skip)
runtimeTypeArguments typeArgs = do
tmpArray <- Var <$> Ctx.genNamedSym "rt_array"
let runtimeTypes = map runtimeType typeArgs
rtArraySize = BinOp (translate ID.TIMES)
(Int $ length typeArgs) (Sizeof $ Ptr ponyTypeT)
rtArrayDecl = Decl (Ptr . Ptr $ ponyTypeT, tmpArray)
rtArrayAlloc = Call encoreAllocName [AsExpr $ Deref encoreCtxVar
,rtArraySize]
rtArrayAssign = Assign rtArrayDecl rtArrayAlloc
rtArrayInit = Seq $ zipWith (\i t -> Assign (ArrAcc i tmpArray) t)
[0..] runtimeTypes
return (tmpArray, Seq [rtArrayAssign, rtArrayInit])
| parapluu/encore | src/back/CodeGen/Expr.hs | bsd-3-clause | 67,689 | 0 | 26 | 23,333 | 21,340 | 10,627 | 10,713 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module CNC.InterpreterTests where
import CNC.FanucMacro
import CNC.HCode
import CNC.FInterpreter
import CNC.GInterpreter
import CNC.GTypes
import CNC.AwePrelude
--import Prelude(Num(..), Fractional(..), Floating(..), Int, ($), id, putStrLn, (++), Just)
prog1 = do
frame [g 0, x 0, y 0, z 0]
x 10000
f 10000
frame [g 1, y 10000]
frame [g 1, z 10000]
interpreter_tests = do
Just (_, fcode) <- fanucGen prog1
putStrLn $ "***** fcode:"
putHCode prog1
gcode <- fcodeToGCode fcode
putStrLn "*** iso code:"
print gcode
gtrace <- gcodeToMoves gcode
mapM_ print gtrace
print $ gcode_stats gtrace
| akamaus/gcodec | test/CNC/InterpreterTests.hs | bsd-3-clause | 654 | 0 | 9 | 123 | 208 | 97 | 111 | 24 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Smallpt.Storable where
import qualified Data.Vector as V
import qualified Data.Vector.Storable.Mutable as VM
import Data.List (find, minimumBy, foldl')
import Data.IORef
import Text.Printf
import Foreign
import Foreign.C.Types
import System.IO (stderr, withFile, IOMode(..))
-- position, also color (r,g,b)
data Vec = Vec {-# UNPACK #-} !CDouble {-# UNPACK #-} !CDouble {-# UNPACK #-} !CDouble
zerov = Vec 0 0 0
addv (Vec a b c) (Vec x y z) = Vec (a+x) (b+y) (c+z)
subv (Vec a b c) (Vec x y z) = Vec (a-x) (b-y) (c-z)
mulvs (Vec a b c) x = Vec (a*x) (b*x) (c*x)
mulv (Vec a b c) (Vec x y z) = Vec (a*x) (b*y) (c*z)
len (Vec a b c) = sqrt $ a*a+b*b+c*c
norm v = v `mulvs` (1/len v)
dot (Vec a b c) (Vec x y z) = a*x+b*y+c*z
cross (Vec a b c) (Vec x y z) = Vec (b*z-c*y) (c*x-a*z) (a*y-b*x)
maxv (Vec a b c) = maximum [a,b,c]
data Ray = Ray Vec Vec -- origin, direction
data Refl = DIFF | SPEC | REFR -- material types, used in radiance
-- radius, position, emission, color, reflection
data Sphere = Sphere CDouble Vec Vec Vec Refl
intersect (Ray o d) (Sphere r p e c refl) =
if det<0 then Nothing else f (b-sdet) (b+sdet)
where op = p `subv` o
eps = 1e-4
b = op `dot` d
det = b*b - (op `dot` op) + r*r
sdet = sqrt det
f a b = if a>eps then Just a else if b>eps then Just b else Nothing
spheres = let s = Sphere ; z = zerov ; (*) = mulvs ; v = Vec in
[ s 1e5 (v (1e5+1) 40.8 81.6) z (v 0.75 0.25 0.25) DIFF --Left
, s 1e5 (v (-1e5+99) 40.8 81.6) z (v 0.25 0.25 0.75) DIFF --Rght
, s 1e5 (v 50 40.8 1e5) z (v 0.75 0.75 0.75) DIFF --Back
, s 1e5 (v 50 40.8 (-1e5+170)) z z DIFF --Frnt
, s 1e5 (v 50 1e5 81.6) z (v 0.75 0.75 0.75) DIFF --Botm
, s 1e5 (v 50 (-1e5+81.6) 81.6) z (v 0.75 0.75 0.75) DIFF --Top
, s 16.5(v 27 16.5 47) z ((v 1 1 1)* 0.999) SPEC --Mirr
, s 16.5(v 73 16.5 78) z ((v 1 1 1)* 0.999) REFR --Glas
, s 600 (v 50 (681.6-0.27) 81.6) (v 12 12 12) z DIFF]--Lite
clamp x = if x<0 then 0 else if x>1 then 1 else x
toInt :: CDouble -> Int
toInt x = floor $ clamp x ** (1/2.2) * 255 + 0.5
intersects ray = (k, s)
where (k,s) = foldl' f (Nothing,undefined) spheres
f (k,sp) s = case (k,intersect ray s) of
(Nothing,Just x) -> (Just x,s)
(Just y,Just x) | x < y -> (Just x,s)
_ -> (k,sp)
radiance :: Ray -> CInt -> Ptr CUShort -> IO Vec
radiance ray@(Ray o d) depth xi = case intersects ray of
(Nothing,_) -> return zerov
(Just t,Sphere r p e c refl) -> do
let x = o `addv` (d `mulvs` t)
n = norm $ x `subv` p
nl = if n `dot` d < 0 then n else n `mulvs` (-1)
pr = maxv c
depth' = depth + 1
continue f = case refl of
DIFF -> do
r1 <- ((2*pi)*) `fmap` erand48 xi
r2 <- erand48 xi
let r2s = sqrt r2
w@(Vec wx _ _) = nl
u = norm $ (if abs wx > 0.1 then (Vec 0 1 0) else (Vec 1 0 0)) `cross` w
v = w `cross` u
d' = norm $ (u`mulvs`(cos r1*r2s)) `addv` (v`mulvs`(sin r1*r2s)) `addv` (w`mulvs`sqrt (1-r2))
rad <- radiance (Ray x d') depth' xi
return $ e `addv` (f `mulv` rad)
SPEC -> do
let d' = d `subv` (n `mulvs` (2 * (n`dot`d)))
rad <- radiance (Ray x d') depth' xi
return $ e `addv` (f `mulv` rad)
REFR -> do
let reflRay = Ray x (d `subv` (n `mulvs` (2* n`dot`d))) -- Ideal dielectric REFRACTION
into = n`dot`nl > 0 -- Ray from outside going in?
nc = 1
nt = 1.5
nnt = if into then nc/nt else nt/nc
ddn= d`dot`nl
cos2t = 1-nnt*nnt*(1-ddn*ddn)
if cos2t<0 -- Total internal reflection
then do
rad <- radiance reflRay depth' xi
return $ e `addv` (f `mulv` rad)
else do
let tdir = norm $ (d`mulvs`nnt `subv` (n`mulvs`((if into then 1 else -1)*(ddn*nnt+sqrt cos2t))))
a=nt-nc
b=nt+nc
r0=a*a/(b*b)
c = 1-(if into then -ddn else tdir`dot`n)
re=r0+(1-r0)*c*c*c*c*c
tr=1-re
pp=0.25+0.5*re
rp=re/pp
tp=tr/(1-pp)
rad <-
if depth>2
then do er <- erand48 xi
if er<pp -- Russian roulette
then (`mulvs` rp) `fmap` radiance reflRay depth' xi
else (`mulvs` tp) `fmap` radiance (Ray x tdir) depth' xi
else do rad0 <- (`mulvs` re) `fmap` radiance reflRay depth' xi
rad1 <- (`mulvs` tr) `fmap` radiance(Ray x tdir) depth' xi
return $ rad0 `addv` rad1
return $ e `addv` (f `mulv` rad)
if depth'>5
then do
er <- erand48 xi
if er < pr then continue $ c `mulvs` (1/pr)
else return e
else continue c
smallpt :: Int -> Int -> Int -> IO ()
smallpt w h nsamps = do
let samps = nsamps `div` 4
org = Vec 50 52 295.6
dir = norm $ Vec 0 (-0.042612) (-1)
cx = Vec (fromIntegral w * 0.5135 / fromIntegral h) 0 0
cy = norm (cx `cross` dir) `mulvs` 0.5135
c <- VM.newWith (w * h) zerov
allocaArray 3 $ \xi ->
flip mapM_ [0..h-1] $ \y -> do
--hPrintf stderr "\rRendering (%d spp) %5.2f%%" (samps*4::Int) (100.0*fromIntegral y/(fromIntegral h-1)::Double)
writeXi xi y
flip mapM_ [0..w-1] $ \x -> do
let i = (h-y-1) * w + x
flip mapM_ [0..1] $ \sy -> do
flip mapM_ [0..1] $ \sx -> do
r <- newIORef zerov
flip mapM_ [0..samps-1] $ \s -> do
r1 <- (2*) `fmap` erand48 xi
let dx = if r1<1 then sqrt r1-1 else 1-sqrt(2-r1)
r2 <- (2*) `fmap` erand48 xi
let dy = if r2<1 then sqrt r2-1 else 1-sqrt(2-r2)
d = (cx `mulvs` (((sx + 0.5 + dx)/2 + fromIntegral x)/fromIntegral w - 0.5)) `addv`
(cy `mulvs` (((sy + 0.5 + dy)/2 + fromIntegral y)/fromIntegral h - 0.5)) `addv` dir
rad <- radiance (Ray (org`addv`(d`mulvs`140)) (norm d)) 0 xi
-- Camera rays are pushed forward ^^^^^ to start in interior
modifyIORef r (`addv` (rad `mulvs` (1 / fromIntegral samps)))
ci <- VM.unsafeRead c i
Vec rr rg rb <- readIORef r
VM.unsafeWrite c i $ ci `addv` (Vec (clamp rr) (clamp rg) (clamp rb) `mulvs` 0.25)
withFile "image-storable.ppm" WriteMode $ \hdl -> do
hPrintf hdl "P3\n%d %d\n%d\n" w h (255::Int)
flip mapM_ [0..w*h-1] $ \i -> do
Vec r g b <- VM.unsafeRead c i
hPrintf hdl "%d %d %d " (toInt r) (toInt g) (toInt b)
writeXi :: Ptr CUShort -> Int -> IO ()
writeXi xi y = do
let y' = fromIntegral y
pokeElemOff xi 0 0
pokeElemOff xi 1 0
pokeElemOff xi 2 (y' * y' * y')
foreign import ccall unsafe "erand48"
erand48 :: Ptr CUShort -> IO CDouble
instance Storable Vec where
sizeOf _ = sizeOf (undefined :: CDouble) * 3
alignment _ = alignment (undefined :: CDouble)
{-# INLINE peek #-}
peek p = do
a <- peekElemOff q 0
b <- peekElemOff q 1
c <- peekElemOff q 2
return (Vec a b c)
where
q = castPtr p
{-# INLINE poke #-}
poke p (Vec a b c) = do
pokeElemOff q 0 a
pokeElemOff q 1 b
pokeElemOff q 2 c
where
q = castPtr p
| noteed/smallpt-hs | Smallpt/Storable.hs | bsd-3-clause | 7,750 | 2 | 44 | 2,808 | 3,748 | 1,994 | 1,754 | 171 | 14 |
-- #hide
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.GLboolean
-- Copyright : (c) Sven Panne 2003
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : sven_panne@yahoo.com
-- Stability : provisional
-- Portability : portable
--
-- This is a purely internal module for (un-)marshaling GLboolean.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.GLboolean (
GLboolean, marshalGLboolean, unmarshalGLboolean
) where
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLboolean )
--------------------------------------------------------------------------------
marshalGLboolean :: Bool -> GLboolean
marshalGLboolean False = 0
marshalGLboolean True = 1
unmarshalGLboolean :: GLboolean -> Bool
unmarshalGLboolean = (/= 0)
| OS2World/DEV-UTIL-HUGS | libraries/Graphics/Rendering/OpenGL/GL/GLboolean.hs | bsd-3-clause | 926 | 0 | 5 | 116 | 91 | 62 | 29 | 8 | 1 |
module Parse.Expression (def,term,typeAnnotation,expr) where
import Control.Applicative ((<$>), (<*>))
import qualified Data.List as List
import Text.Parsec hiding (newline, spaces)
import Text.Parsec.Indent (block, withPos)
import qualified Parse.Binop as Binop
import Parse.Helpers
import qualified Parse.Helpers as Help
import qualified Parse.Literal as Literal
import qualified Parse.Pattern as Pattern
import qualified Parse.Type as Type
import qualified AST.Annotation as Annotation
import qualified AST.Expression.General as E
import qualified AST.Expression.Source as Source
import qualified AST.Literal as L
import qualified AST.Pattern as P
import qualified AST.Variable as Var
-------- Basic Terms --------
varTerm :: IParser Source.Expr'
varTerm = toVar <$> var <?> "variable"
toVar :: String -> Source.Expr'
toVar v =
case v of
"True" -> E.Literal (L.Boolean True)
"False" -> E.Literal (L.Boolean False)
_ -> E.rawVar v
accessor :: IParser Source.Expr'
accessor = do
(start, lbl, end) <- located (try (string "." >> rLabel))
let loc e = Annotation.at start end e
return (E.Lambda (P.Var "_") (loc $ E.Access (loc $ E.rawVar "_") lbl))
negative :: IParser Source.Expr'
negative = do
(start, nTerm, end) <-
located (try (char '-' >> notFollowedBy (char '.' <|> char '-')) >> term)
let loc e = Annotation.at start end e
return (E.Binop (Var.Raw "-") (loc $ E.Literal (L.IntNum 0)) nTerm)
-------- Complex Terms --------
listTerm :: IParser Source.Expr'
listTerm = shader' <|> braces (try range <|> E.ExplicitList <$> commaSep expr)
where
range = do
lo <- expr
padded (string "..")
E.Range lo <$> expr
shader' = do
pos <- getPosition
let uid = show (sourceLine pos) ++ ":" ++ show (sourceColumn pos)
(rawSrc, tipe) <- Help.shader
return $ E.GLShader uid (filter (/='\r') rawSrc) tipe
parensTerm :: IParser Source.Expr
parensTerm = try (parens opFn) <|> parens (tupleFn <|> parened)
where
opFn = do
(start, op, end) <- located anyOp
let loc = Annotation.at start end
return . loc . E.Lambda (P.Var "x") . loc . E.Lambda (P.Var "y") . loc $
E.Binop (Var.Raw op) (loc (E.rawVar "x")) (loc (E.rawVar "y"))
tupleFn = do
let comma = char ',' <?> "comma ','"
(start, commas, end) <- located (comma >> many (whitespace >> comma))
let vars = map (('v':) . show) [ 0 .. length commas + 1 ]
loc = Annotation.at start end
return $ foldr (\x e -> loc $ E.Lambda x e)
(loc . E.tuple $ map (loc . E.rawVar) vars) (map P.Var vars)
parened = do
(start, es, end) <- located (commaSep expr)
return $ case es of
[e] -> e
_ -> Annotation.at start end (E.tuple es)
recordTerm :: IParser Source.Expr
recordTerm = brackets $ choice [ misc, addLocation record ]
where
field = do
label <- rLabel
patterns <- spacePrefix Pattern.term
padded equals
body <- expr
return (label, makeFunction patterns body)
record = E.Record <$> commaSep field
change = do
lbl <- rLabel
padded (string "<-")
(,) lbl <$> expr
remove r = addLocation (string "-" >> whitespace >> E.Remove r <$> rLabel)
insert r = addLocation $ do
string "|" >> whitespace
E.Insert r <$> rLabel <*> (padded equals >> expr)
modify r =
addLocation (string "|" >> whitespace >> E.Modify r <$> commaSep1 change)
misc = try $ do
record <- addLocation (E.rawVar <$> rLabel)
opt <- padded (optionMaybe (remove record))
case opt of
Just e -> try (insert e) <|> return e
Nothing -> try (insert record) <|> try (modify record)
term :: IParser Source.Expr
term = addLocation (choice [ E.Literal <$> Literal.literal, listTerm, accessor, negative ])
<|> accessible (addLocation varTerm <|> parensTerm <|> recordTerm)
<?> "basic term (4, x, 'c', etc.)"
-------- Applications --------
appExpr :: IParser Source.Expr
appExpr = do
t <- term
ts <- constrainedSpacePrefix term $ \str ->
if null str then notFollowedBy (char '-') else return ()
return $ case ts of
[] -> t
_ -> List.foldl' (\f x -> Annotation.merge f x $ E.App f x) t ts
-------- Normal Expressions --------
binaryExpr :: IParser Source.Expr
binaryExpr = Binop.binops appExpr lastExpr anyOp
where lastExpr = addLocation (choice [ ifExpr, letExpr, caseExpr ])
<|> lambdaExpr
ifExpr :: IParser Source.Expr'
ifExpr = reserved "if" >> whitespace >> (normal <|> multiIf)
where
normal = do
bool <- expr
padded (reserved "then")
thenBranch <- expr
whitespace <?> "an 'else' branch" ; reserved "else" <?> "an 'else' branch" ; whitespace
elseBranch <- expr
return $ E.MultiIf
[ (bool, thenBranch)
, (Annotation.sameAs elseBranch (E.Literal . L.Boolean $ True), elseBranch)
]
multiIf = E.MultiIf <$> spaceSep1 iff
where iff = do string "|" ; whitespace
b <- expr ; padded arrow
(,) b <$> expr
lambdaExpr :: IParser Source.Expr
lambdaExpr = do char '\\' <|> char '\x03BB' <?> "anonymous function"
whitespace
args <- spaceSep1 Pattern.term
padded arrow
body <- expr
return (makeFunction args body)
defSet :: IParser [Source.Def]
defSet = block (do d <- def ; whitespace ; return d)
letExpr :: IParser Source.Expr'
letExpr = do
reserved "let" ; whitespace
defs <- defSet
padded (reserved "in")
E.Let defs <$> expr
caseExpr :: IParser Source.Expr'
caseExpr = do
reserved "case"; e <- padded expr; reserved "of"; whitespace
E.Case e <$> (with <|> without)
where case_ = do p <- Pattern.expr
padded arrow
(,) p <$> expr
with = brackets (semiSep1 (case_ <?> "cases { x -> ... }"))
without = block (do c <- case_ ; whitespace ; return c)
expr :: IParser Source.Expr
expr = addLocation (choice [ ifExpr, letExpr, caseExpr ])
<|> lambdaExpr
<|> binaryExpr
<?> "an expression"
defStart :: IParser [P.RawPattern]
defStart =
choice [ do p1 <- try Pattern.term
infics p1 <|> func p1
, func =<< (P.Var <$> parens symOp)
, (:[]) <$> Pattern.expr
] <?> "the definition of a variable (x = ...)"
where
func pattern =
case pattern of
P.Var _ -> (pattern:) <$> spacePrefix Pattern.term
_ -> do try (lookAhead (whitespace >> string "="))
return [pattern]
infics p1 = do
o:p <- try (whitespace >> anyOp)
p2 <- (whitespace >> Pattern.term)
return $ if o == '`' then [ P.Var $ takeWhile (/='`') p, p1, p2 ]
else [ P.Var (o:p), p1, p2 ]
makeFunction :: [P.RawPattern] -> Source.Expr -> Source.Expr
makeFunction args body@(Annotation.A ann _) =
foldr (\arg body' -> Annotation.A ann $ E.Lambda arg body') body args
definition :: IParser Source.Def
definition = withPos $ do
(name:args) <- defStart
padded equals
body <- expr
return . Source.Definition name $ makeFunction args body
typeAnnotation :: IParser Source.Def
typeAnnotation = Source.TypeAnnotation <$> try start <*> Type.expr
where
start = do
v <- lowVar <|> parens symOp
padded hasType
return v
def :: IParser Source.Def
def = typeAnnotation <|> definition
| JoeyEremondi/haskelm | src/Parse/Expression.hs | bsd-3-clause | 7,757 | 0 | 17 | 2,258 | 2,808 | 1,409 | 1,399 | 185 | 3 |
module Teem
(mask
,fa
,gzip
,makeMask
,isNrrd
,center
,getB0Indices
,extractB0
,diceCoefficient
)
where
-- Script Deps
-- center.py
import qualified Data.Map as M
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import System.Process (callProcess, readProcess)
import Teem.Parser (Result (..), Value (..),
readNrrdHeader)
gzip :: FilePath -> IO ()
gzip out = callProcess "unu" ["save","-e","gzip","-f","nrrd","-i",out,"-o",out]
mask :: FilePath -> FilePath -> FilePath -> IO ()
mask mask vol out = do
callProcess "unu" ["3op", "ifelse", mask, vol
, "0", "-o", out]
gzip out
fa :: FilePath -> FilePath -> Action ()
fa dwi out = do
withTempFile $ \tensor -> do
command_ [] "tend" ["estim","-est","lls","-B","kvp","-knownB0","true","-i",dwi,"-o",tensor]
command_ [] "tend" ["anvol","-t","-1","-a","fa","-i",tensor,"-o",out]
liftIO $ gzip out
makeMask :: FilePath -> FilePath -> Action()
makeMask invol outvol = do
command_ [] "unu" ["3op","ifelse",invol,"1","0","-o",outvol]
liftIO $ gzip outvol
isNrrd :: FilePath -> Bool
isNrrd file = ext == "nrrd)" || ext == "nhdr"
where
ext = takeExtension file
toNifti :: FilePath -> FilePath -> Action ()
toNifti nrrd out = unit $ cmd "ConvertBetweenFileFormats" nrrd out
center :: FilePath -> IO ()
center nrrd = callProcess "center.py"
["-i", nrrd
,"-o", nrrd]
getB0Indices :: FilePath -> IO [Int]
getB0Indices nrrd = do
maybeKvps <- Teem.Parser.readNrrdHeader nrrd
case maybeKvps of
(Success kvps) -> return
$ map (read . drop 15 . fst)
. filter ((== VGradientDirection (0,0,0)) . snd)
. M.toList
$ kvps
failure -> do
print failure
error $ "Teem.getB0Indices: Failed to parse nrrd header: " ++ nrrd
extractB0 :: FilePath -> FilePath -> IO ()
extractB0 dwi out = do
b0index <- head <$> getB0Indices dwi
callProcess "unu" ["slice"
,"-a", "3"
,"-p", show b0index
,"-i", dwi
,"-o", out]
gzip out
diceCoefficient :: FilePath -> FilePath -> Action Float
diceCoefficient mask1 mask2 =
let getVol :: FilePath -> Action Int
getVol nrrd = do
Stdout vol <- cmd Shell "unu histo -b 1 -min 1 -max 1 -i" nrrd "| unu save -f text"
return $ read vol
intersectVol :: FilePath -> FilePath -> Action Int
intersectVol nrrd1 nrrd2 = do
Stdout vol <- cmd Shell "unu 2op x" nrrd1 nrrd2 "| unu histo -b 1 -min 1 -max 1 | unu save -f text"
return $ read vol
in do
vol1 <- fromIntegral <$> getVol mask1
vol2 <- fromIntegral <$> getVol mask2
volIntersect <- fromIntegral <$> intersectVol mask1 mask2
return $ (2 * volIntersect / (vol1 + vol2)) | pnlbwh/test-tensormasking | pipeline-lib/Teem.hs | bsd-3-clause | 2,936 | 0 | 18 | 826 | 974 | 511 | 463 | 79 | 2 |
module Toys.Mat.Field
where
import Data.Ratio
class Eq g => MatGroup g where
dim :: g -> Int
gzero :: Int -> g
gadd, gsub :: g -> g -> g
gneg :: g -> g
gsub a b = gadd a (gneg b)
class MatGroup f => MatField f where
fone :: Int -> f
fmul, fdiv :: f -> f -> f
finv :: f -> f
fdiv a b = fmul a (finv b)
instance MatGroup Int where
dim _ = 1
gzero _ = 0
gadd = (+)
gsub = (-)
gneg = negate
instance MatGroup Integer where
dim _ = 1
gzero _ = 0
gadd = (+)
gsub = (-)
gneg = negate
instance MatGroup Float where
dim _ = 1
gzero _ = 0
gadd = (+)
gsub = (-)
gneg = negate
instance MatField Float where
fone _ = 1
fmul = (*)
fdiv = (/)
finv = recip
instance MatGroup Double where
dim _ = 1
gzero _ = 0
gadd = (+)
gsub = (-)
gneg = negate
instance MatField Double where
fone _ = 1
fmul = (*)
fdiv = (/)
finv = recip
instance (Eq a, Integral a) => MatGroup (Ratio a) where
dim _ = 1
gzero _ = 0 % 1
gadd = (+)
gsub = (-)
gneg = negate
instance (Eq a, Integral a) => MatField (Ratio a) where
fone _ = 1 % 1
fmul = (*)
fdiv = (/)
finv = recip
| dagezi/ToysMat | src/Toys/Mat/Field.hs | bsd-3-clause | 1,138 | 0 | 9 | 355 | 531 | 299 | 232 | 58 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Pudding (
conduitPuddingParser,
conduitPuddingEvaluator,
) where
import Control.Monad.Error (runErrorT)
import Control.Monad.State (StateT, runStateT)
import Control.Monad.Writer (execWriterT)
import Data.ByteString.Char8 as BC (ByteString, pack, append)
import Data.Conduit as C (Conduit, (=$=))
import qualified Data.Conduit.List as CL (map, concatMapAccumM)
import Data.Map as Map (fromList)
import Data.Tuple (swap)
import Data.Vector as V (fromList)
import Prelude hiding (div)
import Pudding.Core
import Pudding.Words
-- $setup
-- >>> import Data.Conduit
-- >>> import Data.Conduit.List
-- >>> :set -XOverloadedStrings
initEnv :: Monad m => Environment m
initEnv = Environment { stack = []
, wordMap = Map.fromList [(".", nativeProcedure "." showTop)
,(".s", nativeProcedure ".s" showStack)
,(".cs", nativeProcedure ".cs" showCallStack)
,("drop", nativeProcedure "drop" pdrop)
,("dup", nativeProcedure "dup" dup)
,("nip", nativeProcedure "nip" nip)
,("over", nativeProcedure "over" over)
,("tuck", nativeProcedure "tuck" tuck)
,("2dup", nativeProcedure "2dup" dup2)
,("+", nativeProcedure "+" $ numericOp2 PVNumber "+" (+))
,("-", nativeProcedure "-" $ numericOp2 PVNumber "-" (-))
,("*", nativeProcedure "*" $ numericOp2 PVNumber "*" (*))
,("/", nativeProcedure "/" $ numericOp2 PVNumber "/" (/))
,("==", nativeProcedure "==" $ numericOp2 PVBool "==" (==))
,("!=", nativeProcedure "!=" $ numericOp2 PVBool "!=" (/=))
,("<", nativeProcedure "<" $ numericOp2 PVBool "<" (<))
,("<=", nativeProcedure "<=" $ numericOp2 PVBool "<=" (<=))
,(">", nativeProcedure ">" $ numericOp2 PVBool ">" (>))
,(">=", nativeProcedure ">=" $ numericOp2 PVBool ">=" (>=))
,("&&", nativeProcedure "&&" $ booleanOp2 PVBool "&&" (&&))
,("||", nativeProcedure "||" $ booleanOp2 PVBool "||" (||))
,("!", nativeProcedure "!" $ booleanOp1 PVBool "!" not)
,("mod", nativeProcedure "mod" . numericOp2 PVNumber "mod" $ \a b -> fromIntegral (mod (floor a) (floor b) :: Integer))
,("nop", nativeProcedure "nop" nop)
,("swap", nativeProcedure "swap" pswap)
,(":", nativeProcedure ":" startCompile)
,(";", ImmediateWord ";" endCompile)
,("jump", CompileOnlyWord "jump" jump cpush)
,("fjump", CompileOnlyWord "fjump" fjump cpush)
,("if", CompileOnlyWord "if" nop cpush)
,("else", CompileOnlyWord "else" nop cpush)
,("then", CompileOnlyWord "then" nop cthen)
,("_test", UserDefinedWord "_test" $ V.fromList [PWord ".cs", PNumber 3, PNumber 3, PWord "*", PWord "."])
,("_testJump1", UserDefinedWord "_testJump1" $ V.fromList [PWord ".cs", PBool True, PNumber 3, PWord "jump", PString "a", PString "b", PString "c", PString "d"])
,("_testJump2", UserDefinedWord "_testJump2" $ V.fromList [PWord ".cs", PBool False, PNumber 3, PWord "jump", PString "a", PString "b", PString "c", PString "d"])
]
, state = Run
, pc = 0
, callStack = []
}
-- |
-- >>> runResourceT $ sourceList [PNumber 1.0,PNumber 2.0,PNumber 3.0, PWord $ pack ".s", PWord $ pack "+", PWord $ pack "+", PWord $ pack "."] $= conduitPuddingEvaluator $$ consume
-- ["> [3.0, 2.0, 1.0]\n","> 6.0\n"]
conduitPuddingEvaluator :: Monad m => Conduit PToken m ByteString
conduitPuddingEvaluator = CL.concatMapAccumM step initEnv =$= CL.map (`append` "\n")
where
step :: Monad m => PToken -> Environment m -> m (Environment m, [ByteString])
step t e = return . swap =<< runStateT s e
where
s :: Monad m => StateT (Environment m) m [ByteString]
s = execWriterT $ do
Right result <- runErrorT . runEnvT $ eval t `catchError` (ng . pack)
return result
| masaedw/PuddingX | src/Pudding.hs | bsd-3-clause | 5,375 | 0 | 16 | 2,300 | 1,245 | 696 | 549 | 65 | 1 |
-- Chapter1Exercise3.hs
module Chapter1Exercise3 where
import System.Environment
-- Exercise 3:
-- getLine is an IO action that reads a line from the console and returns it as
-- a string. Change the program so it prompts for a name, reads the name, and
-- prints that instead of the command line value
main :: IO ()
main = do
putStr "Hi, what's your name? "
name <- getLine
putStrLn $ "Hi, " ++ name ++ "! Nice to meet you!"
| EFulmer/haskell-scheme-wikibook | src/Exercises/Ch1/Ex3.hs | bsd-3-clause | 434 | 0 | 9 | 88 | 57 | 31 | 26 | 7 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Knowledge where
import Data.Aeson
import Database.Persist.TH
import GHC.Generics
import Web.HttpApiData (FromHttpApiData, parseUrlPiece)
import Prelude
data Knowledge
= None
| Poor
| Medium
| Good
| Excelent
deriving (Generic, Show, Read, Eq)
derivePersistField "Knowledge"
instance FromHttpApiData Knowledge where
parseUrlPiece knowledge
| knowledge == "None" = Right None
| knowledge == "Poor" = Right Poor
| knowledge == "Medium" = Right Medium
| knowledge == "Good" = Right Good
| knowledge == "Excelent" = Right Excelent
| otherwise = Left "Error parsing the knowledge string"
instance FromJSON Knowledge
instance ToJSON Knowledge
| leohahn/learning-with-texts-clone | src/Knowledge.hs | bsd-3-clause | 832 | 0 | 9 | 192 | 202 | 102 | 100 | 27 | 0 |
{-
Image.hs (adapted from image.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2005 <sven.panne@aedion.de>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program demonstrates drawing pixels and shows the effect of
drawPixels, copyPixels, and pixelZoom.
Interaction: moving the mouse while pressing the mouse button will copy
the image in the lower-left corner of the window to the mouse position,
using the current pixel zoom factors. There is no attempt to prevent you
from drawing over the original image. If you press the 'r' key, the
original image and zoom factors are reset. If you press the 'z' or 'Z'
keys, you change the zoom factors.
-}
import Data.Bits ( (.&.) )
import Data.IORef ( IORef, newIORef )
import Foreign ( newArray )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
data State = State { zoomFactor :: IORef GLfloat }
makeState :: IO State
makeState = do
z <- newIORef 1
return $ State { zoomFactor = z }
-- Create checkerboard image
checkImageSize :: Size
checkImageSize = Size 64 64
type Image = PixelData (Color3 GLubyte)
makeCheckImage :: Size -> GLsizei -> (GLubyte -> (Color3 GLubyte)) -> IO Image
makeCheckImage (Size w h) n f =
fmap (PixelData RGB UnsignedByte) $
newArray [ f c |
i <- [ 0 .. w - 1 ],
j <- [ 0 .. h - 1 ],
let c | (i .&. n) == (j .&. n) = 0
| otherwise = 255 ]
myInit :: IO Image
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
rowAlignment Unpack $= 1
makeCheckImage checkImageSize 0x8 (\c -> Color3 c c c)
display :: Image -> DisplayCallback
display pixelData = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let rasterPos2i = rasterPos :: Vertex2 GLint -> IO ()
rasterPos2i (Vertex2 0 0)
drawPixels checkImageSize pixelData
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 (fromIntegral w) 0 (fromIntegral h)
matrixMode $= Modelview 0
loadIdentity
motion :: State -> MotionCallback
motion state (Position x y) = do
Size _ height <- get windowSize
let screenY = height - y
-- resolve overloading, not needed in "real" programs
let rasterPos2i = rasterPos :: Vertex2 GLint -> IO ()
rasterPos2i (Vertex2 x screenY)
z <- get (zoomFactor state)
pixelZoom $= (z, z)
copyPixels (Position 0 0) checkImageSize CopyColor
pixelZoom $= (1, 1)
flush
resetZoomFactor :: State -> IO ()
resetZoomFactor state = do
zoomFactor state $= 1.0
postRedisplay Nothing
putStrLn "zoomFactor reset to 1.0"
incZoomFactor :: State -> GLfloat -> IO ()
incZoomFactor state inc = do
zoomFactor state $~! (max 0.5 . min 3.0 . (+ inc))
get (zoomFactor state) >>= putStrLn . ("zoomFactor is now " ++) . show
keyboard :: State -> KeyboardMouseCallback
keyboard state (Char 'r') Down _ _ = resetZoomFactor state
keyboard state (Char 'R') Down _ _ = resetZoomFactor state
keyboard state (Char 'z') Down _ _ = incZoomFactor state 0.5
keyboard state (Char 'Z') Down _ _ = incZoomFactor state (-0.5)
keyboard _ (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 250 250
initialWindowPosition $= Position 100 100
createWindow progName
state <- makeState
checkImage <- myInit
displayCallback $= display checkImage
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just (keyboard state)
motionCallback $= Just (motion state)
mainLoop
| FranklinChen/hugs98-plus-Sep2006 | packages/GLUT/examples/RedBook/Image.hs | bsd-3-clause | 3,901 | 0 | 17 | 931 | 1,129 | 551 | 578 | 83 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Inspection.Data.Task where
import Prelude ()
import MyLittlePrelude
import Data.Aeson.Extra (ToJSON (..), genericToJSON, FromJSON(..), genericParseJSON)
import Data.Aeson.Types (Options (..), defaultOptions)
import Data.SafeCopy (base, deriveSafeCopy)
import Inspection.Data.BuildConfig
import Inspection.Data.Target
newtype TaskId = TaskId Int deriving (Show, Eq, Ord, Generic, Typeable, Data)
data Task = Task { taskBuildConfig :: BuildConfig
, taskTarget :: Target
}
deriving (Show, Eq, Ord, Generic, Typeable, Data)
instance ToJSON Task where
toJSON = genericToJSON defaultOptions { fieldLabelModifier = modifier }
where
modifier "taskBuildConfig" = "buildConfig"
modifier "taskTarget" = "target"
modifier a = a
instance FromJSON Task where
parseJSON = genericParseJSON defaultOptions { fieldLabelModifier = modifier }
where
modifier "taskBuildConfig" = "buildConfig"
modifier "taskTarget" = "target"
modifier a = a
deriveSafeCopy 0 'base ''Task
| zudov/purescript-inspection | src/Inspection/Data/Task.hs | bsd-3-clause | 1,098 | 0 | 8 | 228 | 284 | 163 | 121 | 24 | 0 |
{-# LANGUAGE QuasiQuotes, OverloadedStrings, OverloadedLists #-}
module Test.Network.AuthorizeNet.Response (responseTests) where
import Network.AuthorizeNet.Response
import Network.AuthorizeNet.Types
import Network.AuthorizeNet.Util
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Data.Monoid
import Text.RawString.QQ
import Test.Tasty
import Test.Tasty.HUnit
import Test.Network.AuthorizeNet.Util
testMessages :: Messages
testMessages = Messages Message_Ok $ ArrayOf [ Message "I00001" "Successful." ]
test_authenticateTestResponse :: Assertion
test_authenticateTestResponse =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?>
<authenticateTestResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
</authenticateTestResponse>
|]
actual = mkAuthenticateTestResponse testMessages
in assertEncodes expected actual
test_createCustomerProfileResponse :: Assertion
test_createCustomerProfileResponse =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?>
<createCustomerProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<customerProfileId>10000</customerProfileId>
<customerPaymentProfileIdList>
<numericString>20000</numericString>
<numericString>20001</numericString>
</customerPaymentProfileIdList>
<customerShippingAddressIdList>
<numericString>30000</numericString>
<numericString>30001</numericString>
</customerShippingAddressIdList>
<validationDirectResponseList>
<string>1,1,1,This transaction has been approved.,000000,Y,2000000000,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,custId123,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,000-000-0000,,mark@example.com,,,,,,,,,0.00,0.00,0.00,,none,D18EB6B211FE0BBF556B271FDA6F92EE,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,</string>
</validationDirectResponseList>
</createCustomerProfileResponse>
|]
actual = CreateCustomerProfileResponse {
createCustomerProfileResponse_refId = Nothing,
createCustomerProfileResponse_messages = testMessages,
createCustomerProfileResponse_sessionToken = Nothing,
createCustomerProfileResponse_customerProfileId = Just 10000,
createCustomerProfileResponse_customerPaymentProfileIdList = [20000,20001],
createCustomerProfileResponse_customerShippingAddressIdList = [30000,30001],
createCustomerProfileResponse_validationDirectResponseList = ArrayOfString ["1,1,1,This transaction has been approved.,000000,Y,2000000000,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,custId123,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,000-000-0000,,mark@example.com,,,,,,,,,0.00,0.00,0.00,,none,D18EB6B211FE0BBF556B271FDA6F92EE,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"]
}
in assertEncodes expected actual
test_getCustomerProfileResponse :: Assertion
test_getCustomerProfileResponse =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?>
<getCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<profile>
<merchantCustomerId>CUST001</merchantCustomerId>
<description>Profile created by Subscription: 3078153</description>
<email>joe@mail.com</email>
<customerProfileId>39598611</customerProfileId>
<paymentProfiles>
<customerType>individual</customerType>
<billTo>
<firstName>John</firstName>
<lastName>Smith</lastName>
</billTo>
<customerPaymentProfileId>35936989</customerPaymentProfileId>
<payment>
<creditCard>
<cardNumber>XXXX1111</cardNumber>
<expirationDate>XXXX</expirationDate>
</creditCard>
</payment>
</paymentProfiles>
</profile>
<subscriptionIds>
<subscriptionId>3078153</subscriptionId>
<subscriptionId>3078154</subscriptionId>
</subscriptionIds>
</getCustomerProfileResponse>
|]
profile = CustomerProfileMasked {
customerProfileMasked_merchantCustomerId = Just "CUST001",
customerProfileMasked_description = Just "Profile created by Subscription: 3078153",
customerProfileMasked_email = Just "joe@mail.com",
customerProfileMasked_customerProfileId = Just 39598611,
customerProfileMasked_paymentProfiles = [
(mkCustomerPaymentProfileMasked 35936989) {
customerPaymentProfileMasked_customerType = Just CustomerType_individual,
customerPaymentProfileMasked_billTo = Just $ mkCustomerAddress {
customerAddress_firstName = Just "John",
customerAddress_lastName = Just "Smith"
},
customerPaymentProfileMasked_payment = Just $ PaymentMasked_creditCard $ mkCreditCardMasked "XXXX1111" "XXXX"
}
],
customerProfileMasked_shipToList = []
}
subscriptionIds = Just $ SubscriptionIdList $ ArrayOf [ 3078153, 3078154 ]
actual = GetCustomerProfileResponse Nothing testMessages Nothing profile subscriptionIds
in assertEncodes expected actual
test_getCustomerProfileResponse2 :: Assertion
test_getCustomerProfileResponse2 =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?><getCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><profile><merchantCustomerId>1</merchantCustomerId><description>MichaelBurge</description><email>michaelburge@pobox.com</email><customerProfileId>40243901</customerProfileId></profile></getCustomerProfileResponse>
|]
profile = CustomerProfileMasked {
customerProfileMasked_merchantCustomerId = Just "1",
customerProfileMasked_description = Just "MichaelBurge",
customerProfileMasked_email = Just "michaelburge@pobox.com",
customerProfileMasked_customerProfileId = Just 40243901,
customerProfileMasked_paymentProfiles = [],
customerProfileMasked_shipToList = []
}
actual = GetCustomerProfileResponse Nothing testMessages Nothing profile Nothing
in assertEncodes expected actual
test_getCustomerProfile_MultiplePaymentMethods :: Assertion
test_getCustomerProfile_MultiplePaymentMethods =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<getCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<profile>
<merchantCustomerId>1</merchantCustomerId>
<description>MichaelBurge</description>
<email>michaelburge@example.com</email>
<customerProfileId>40243901</customerProfileId>
<paymentProfiles>
<billTo>
<firstName>Michael</firstName>
<lastName>Burge</lastName>
<address>Example Address</address>
<city>Fairview</city>
<state>OR</state>
<zip>97024</zip>
<country>United States</country>
<phoneNumber>123-456-7890</phoneNumber>
</billTo>
<customerPaymentProfileId>36910106</customerPaymentProfileId>
<payment>
<bankAccount>
<accountType>checking</accountType>
<routingNumber>XXXX0220</routingNumber>
<accountNumber>XXXX7890</accountNumber>
<nameOnAccount>Michael Burge</nameOnAccount>
<bankName>US Bank</bankName>
</bankAccount>
</payment>
</paymentProfiles>
<paymentProfiles>
<billTo>
<firstName>Michael</firstName>
<lastName>Burge</lastName>
<address>Example Address</address>
<city>Fairview</city>
<state>OR</state>
<zip>97024</zip>
<country>United States</country>
<phoneNumber>123-456-7890</phoneNumber>
</billTo>
<customerPaymentProfileId>36910046</customerPaymentProfileId>
<payment>
<creditCard>
<cardNumber>XXXX0027</cardNumber>
<expirationDate>XXXX</expirationDate>
</creditCard>
</payment>
</paymentProfiles>
</profile>
</getCustomerProfileResponse>
|]
address = mkCustomerAddress {
customerAddress_firstName = Just "Michael",
customerAddress_lastName = Just "Burge",
customerAddress_address = Just "Example Address",
customerAddress_city = Just "Fairview",
customerAddress_state = Just "OR",
customerAddress_zip = Just "97024",
customerAddress_country = Just "United States",
customerAddress_phoneNumber = Just "123-456-7890"
}
profile = CustomerProfileMasked {
customerProfileMasked_merchantCustomerId = Just "1",
customerProfileMasked_description = Just "MichaelBurge",
customerProfileMasked_email = Just "michaelburge@example.com",
customerProfileMasked_customerProfileId = Just 40243901,
customerProfileMasked_shipToList = [],
customerProfileMasked_paymentProfiles = [
(mkCustomerPaymentProfileMasked 36910106) {
customerPaymentProfileMasked_customerType = Nothing,
customerPaymentProfileMasked_billTo = Just address,
customerPaymentProfileMasked_payment = Just $ PaymentMasked_bankAccount $ BankAccountMasked {
bankAccountMasked_accountType = Just BankAccountType_checking,
bankAccountMasked_routingNumber = "XXXX0220",
bankAccountMasked_accountNumber = "XXXX7890",
bankAccountMasked_nameOnAccount = "Michael Burge",
bankAccountMasked_bankName = Just "US Bank",
bankAccountMasked_echeckType = Nothing
}
},
(mkCustomerPaymentProfileMasked 36910046) {
customerPaymentProfileMasked_customerType = Nothing,
customerPaymentProfileMasked_billTo = Just address,
customerPaymentProfileMasked_customerPaymentProfileId = 36910046,
customerPaymentProfileMasked_payment = Just $ PaymentMasked_creditCard $ mkCreditCardMasked "XXXX0027" "XXXX"
}
]
}
response = GetCustomerProfileResponse Nothing testMessages Nothing profile Nothing
in assertEncodes text response
test_getCustomerProfileIdsResponse :: Assertion
test_getCustomerProfileIdsResponse =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?>
<getCustomerProfileIdsResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<ids>
<numericString>10000</numericString>
<numericString>10001</numericString>
<numericString>10002</numericString>
</ids>
</getCustomerProfileIdsResponse>
|]
actual = GetCustomerProfileIdsResponse Nothing testMessages Nothing $ [10000, 10001, 10002]
in assertEncodes expected actual
test_updateCustomerProfileResponse :: Assertion
test_updateCustomerProfileResponse =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?>
<updateCustomerProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
</updateCustomerProfileResponse>
|]
actual = UpdateCustomerProfileResponse Nothing testMessages Nothing
in assertEncodes expected actual
test_deleteCustomerProfileResponse :: Assertion
test_deleteCustomerProfileResponse =
let expected = [r|
<?xml version="1.0" encoding="utf-8"?>
<deleteCustomerProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
</deleteCustomerProfileResponse>
|]
actual = DeleteCustomerProfileResponse Nothing testMessages Nothing
in assertEncodes expected actual
test_createCustomerPaymentProfileResponse :: Assertion
test_createCustomerPaymentProfileResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<createCustomerPaymentProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<customerPaymentProfileId>20000</customerPaymentProfileId>
<validationDirectResponse>1,1,1,This transaction has been approved.,000000,Y,2000000000,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,custId123,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,000-000-0000,,mark@example.com,,,,,,,,,0.00,0.00,0.00,,none,D18EB6B211FE0BBF556B271FDA6F92EE,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,</validationDirectResponse>
</createCustomerPaymentProfileResponse>
|]
response = CreateCustomerPaymentProfileResponse Nothing testMessages Nothing (Just 20000) $ Just "1,1,1,This transaction has been approved.,000000,Y,2000000000,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,custId123,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,000-000-0000,,mark@example.com,,,,,,,,,0.00,0.00,0.00,,none,D18EB6B211FE0BBF556B271FDA6F92EE,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"
in assertEncodes text response
test_getCustomerPaymentProfileResponse :: Assertion
test_getCustomerPaymentProfileResponse =
let text = [r|
<?xmlversion='1.0'encoding='utf-8'?>
<getCustomerPaymentProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<paymentProfile>
<customerType>individual</customerType>
<billTo>
<firstName>John</firstName>
<lastName>Smith</lastName>
</billTo>
<customerProfileId>39598611</customerProfileId>
<customerPaymentProfileId>35936989</customerPaymentProfileId>
<payment>
<creditCard>
<cardNumber>XXXX1111</cardNumber>
<expirationDate>XXXX</expirationDate>
</creditCard>
</payment>
<subscriptionIds>
<subscriptionId>3078153</subscriptionId>
<subscriptionId>3078154</subscriptionId>
</subscriptionIds>
</paymentProfile>
</getCustomerPaymentProfileResponse>
|]
response = GetCustomerPaymentProfileResponse Nothing testMessages Nothing $ Just $ (mkCustomerPaymentProfileMasked 39598611) {
customerPaymentProfileMasked_customerType = Just CustomerType_individual,
customerPaymentProfileMasked_billTo = Just $ mkCustomerAddress {
customerAddress_firstName = Just "John",
customerAddress_lastName = Just "Smith"
},
customerPaymentProfileMasked_customerProfileId = Just 39598611,
customerPaymentProfileMasked_customerPaymentProfileId = 35936989,
customerPaymentProfileMasked_payment = Just $ PaymentMasked_creditCard CreditCardMasked {
creditCardMasked_cardNumber = "XXXX1111",
creditCardMasked_expirationDate = "XXXX",
creditCardMasked_cardType = Nothing,
creditCardMasked_cardArt = Nothing
},
customerPaymentProfileMasked_subscriptionIds = Just [ 3078153, 3078154 ]
}
in assertEncodes text response
test_getCustomerPaymentProfileListResponse :: Assertion
test_getCustomerPaymentProfileListResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<getCustomerPaymentProfileListResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<totalNumInResultSet>
1
</totalNumInResultSet>
<paymentProfiles>
<paymentProfile>
<customerPaymentProfileId>1051079</customerPaymentProfileId>
<customerProfileId>918787</customerProfileId>
<billTo>
<firstName>John</firstName>
<lastName>Smith</lastName>
</billTo>
<payment>
<creditCard>
<cardNumber>XXXX1111</cardNumber>
<expirationDate>XXXX</expirationDate>
</creditCard>
</payment>
</paymentProfile>
</paymentProfiles>
</getCustomerPaymentProfileListResponse>
|]
response = GetCustomerPaymentProfileListResponse Nothing testMessages Nothing 1 $
Just $ ArrayOfCustomerPaymentProfileListItem $ ArrayOf $ pure $
CustomerPaymentProfileListItem {
customerPaymentProfileListItem_customerPaymentProfileId = 1051079,
customerPaymentProfileListItem_customerProfileId = 918787,
customerPaymentProfileListItem_billTo = mkCustomerAddress {
customerAddress_firstName = Just "John",
customerAddress_lastName = Just "Smith"
},
customerPaymentProfileListItem_payment = PaymentMasked_creditCard $ mkCreditCardMasked "XXXX1111" "XXXX"
}
in assertEncodes text response
test_validateCustomerPaymentProfileResponse :: Assertion
test_validateCustomerPaymentProfileResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<validateCustomerPaymentProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<directResponse>1,1,1,This transaction has been approved.,000000,Y,2000000003,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,custId123,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,000-000-0000,,mark@example.com,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,0.00,0.00,0.00,,none,D18EB6B211FE0BBF556B271FDA6F92EE,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,</directResponse>
</validateCustomerPaymentProfileResponse>
|]
response = ValidateCustomerPaymentProfileResponse Nothing testMessages Nothing $ Just "1,1,1,This transaction has been approved.,000000,Y,2000000003,none,Test transaction for ValidateCustomerPaymentProfile.,0.01,CC,auth_only,custId123,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,000-000-0000,,mark@example.com,John,Doe,,123 Main St.,Bellevue,WA,98004,USA,0.00,0.00,0.00,,none,D18EB6B211FE0BBF556B271FDA6F92EE,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"
in assertEncodes text response
test_updateCustomerPaymentProfileResponse :: Assertion
test_updateCustomerPaymentProfileResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<updateCustomerPaymentProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
</updateCustomerPaymentProfileResponse>
|]
response = UpdateCustomerPaymentProfileResponse Nothing testMessages Nothing Nothing
in assertEncodes text response
test_deleteCustomerPaymentProfileResponse :: Assertion
test_deleteCustomerPaymentProfileResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<deleteCustomerPaymentProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
</deleteCustomerPaymentProfileResponse>
|]
response = DeleteCustomerPaymentProfileResponse Nothing testMessages Nothing
in assertEncodes text response
test_createCustomerProfileFromTransactionResponse :: Assertion
test_createCustomerProfileFromTransactionResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<createCustomerProfileResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<customerProfileId>1234</customerProfileId>
<customerPaymentProfileIdList>
<numericString>5678</numericString>
</customerPaymentProfileIdList>
<customerShippingAddressIdList>
<numericString>1212</numericString>
</customerShippingAddressIdList>
<validationDirectResponseList />
</createCustomerProfileResponse>
|]
response = CreateCustomerProfileResponse Nothing testMessages Nothing (Just 1234) [ 5678 ] [ 1212 ] (ArrayOfString [])
in assertEncodes text response
test_chargeCustomerProfile :: Assertion
test_chargeCustomerProfile =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<refId>123456</refId>
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<authCode>UGELQC</authCode>
<avsResultCode>E</avsResultCode>
<transId>2148061808</transId>
<transHash>0B428D8A928AAC61121AF2F6EAC5FF3F</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX0015</accountNumber>
<accountType>MasterCard</accountType>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
<userFields>
<userField>
<name>MerchantDefinedFieldName1</name>
<value>MerchantDefinedFieldValue1</value>
</userField>
<userField>
<name>favorite_color</name>
<value>lavender</value>
</userField>
</userFields>
</transactionResponse>
</createTransactionResponse>
|]
transactionResponse = mkTransactionResponse {
transactionResponse_responseCode = Just "1",
transactionResponse_authCode = Just "UGELQC",
transactionResponse_avsResultCode = Just "E",
transactionResponse_transId = Just "2148061808",
transactionResponse_transHash = Just "0B428D8A928AAC61121AF2F6EAC5FF3F",
transactionResponse_testRequest = Just "0",
transactionResponse_accountNumber = Just "XXXX0015",
transactionResponse_accountType = Just "MasterCard",
transactionResponse_message = Just $ TransactionResponse_message (Just "1") (Just "This transaction has been approved."),
transactionResponse_userFields = Just $ [
UserField "MerchantDefinedFieldName1" "MerchantDefinedFieldValue1",
UserField "favorite_color" "lavender"
]
}
response = CreateTransactionResponse (Just "123456") testMessages Nothing transactionResponse Nothing
in assertEncodes text response
test_chargeCustomerProfile_BankAccount :: Assertion
test_chargeCustomerProfile_BankAccount =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<createTransactionResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<transactionResponse>
<responseCode>1</responseCode>
<avsResultCode>P</avsResultCode>
<transId>20000482972</transId>
<transHash>EDD6E8D1F838AAEED90D717A7422594D</transHash>
<testRequest>0</testRequest>
<accountNumber>XXXX7890</accountNumber>
<entryMode>Keyed</entryMode>
<accountType>eCheck</accountType>
<messages>
<message>
<code>1</code>
<description>This transaction has been approved.</description>
</message>
</messages>
</transactionResponse>
</createTransactionResponse>
|]
transactionResponse = mkTransactionResponse {
transactionResponse_responseCode = Just "1",
transactionResponse_avsResultCode = Just "P",
transactionResponse_transId = Just "20000482972",
transactionResponse_transHash = Just "EDD6E8D1F838AAEED90D717A7422594D",
transactionResponse_testRequest = Just "0",
transactionResponse_accountNumber = Just "XXXX7890",
transactionResponse_entryMode = Just "Keyed",
transactionResponse_accountType = Just "eCheck",
transactionResponse_messages = Just $ ArrayOfTransactionResponseMessage $ ArrayOf $ pure $ TransactionResponse_message (Just "1") (Just "This transaction has been approved.")
}
response = CreateTransactionResponse Nothing testMessages Nothing transactionResponse Nothing
in do
assertEncodes text response
test_getHostedProfilePageResponse :: Assertion
test_getHostedProfilePageResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<getHostedProfilePageResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Ok</resultCode>
<message>
<code>I00001</code>
<text>Successful.</text>
</message>
</messages>
<token>+ZeWDaUOPoQPRGTHcKd7DYbMfcAFDrhO8GPOFNt+ACzJnvkz+aWO0SYSAA9x602jAIKKfUHUt2ybwQRaG8LzHluuR5dRgsuh+kjarKvD0hpieGjLHmnz0LHmFv1Xe9P3zpmawqBCSB/d4jcSg9dAxecNBUzMwIuYzY+vGUGLUXgr9QPaRh93HqWZrV4Mbwop</token>
</getHostedProfilePageResponse>
|]
response = GetHostedProfilePageResponse Nothing testMessages Nothing $ Just "+ZeWDaUOPoQPRGTHcKd7DYbMfcAFDrhO8GPOFNt+ACzJnvkz+aWO0SYSAA9x602jAIKKfUHUt2ybwQRaG8LzHluuR5dRgsuh+kjarKvD0hpieGjLHmnz0LHmFv1Xe9P3zpmawqBCSB/d4jcSg9dAxecNBUzMwIuYzY+vGUGLUXgr9QPaRh93HqWZrV4Mbwop"
in assertEncodes text response
test_aNetApiResponse :: Assertion
test_aNetApiResponse =
let text = [r|
<?xml version="1.0" encoding="utf-8"?>
<getCustomerProfileResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<messages>
<resultCode>Error</resultCode>
<message>
<code>E00040</code>
<text>The record cannot be found.</text>
</message>
</messages>
</getCustomerProfileResponse>
|]
messages = Messages Message_Error $ ArrayOf [ Message "E00040" "The record cannot be found." ]
actual = ANetApiResponse Nothing messages Nothing
in assertEncodesWithOptions (XmlParseOptions $ Just "getCustomerProfileResponse") text actual
responseTests :: TestTree
responseTests = testGroup "API Responses Encode and Decode to JSON correctly" [
testCase "authenticateTestResponse" test_authenticateTestResponse,
testCase "createCustomerProfileResponse" test_createCustomerProfileResponse,
testCase "getCustomerProfileResponse" test_getCustomerProfileResponse,
testCase "getCustomerProfileResponse2" test_getCustomerProfileResponse2,
testCase "getCustomerProfile_MultiplePaymentMethods" test_getCustomerProfile_MultiplePaymentMethods,
testCase "getCustomerProfileIdsResponse" test_getCustomerProfileIdsResponse,
testCase "updateCustomerProfileResponse" test_updateCustomerProfileResponse,
testCase "deleteCustomerProfileResponse" test_deleteCustomerProfileResponse,
testCase "createCustomerPaymentProfileResponse" test_createCustomerPaymentProfileResponse,
testCase "getCustomerPaymentProfileResponse" test_getCustomerPaymentProfileResponse,
testCase "getCustomerPaymentProfileListResponse" test_getCustomerPaymentProfileListResponse,
testCase "validateCustomerPaymentProfileResponse" test_validateCustomerPaymentProfileResponse,
testCase "updateCustomerPaymentProfileResponse" test_updateCustomerPaymentProfileResponse,
testCase "deleteCustomerPaymentProfileResponse" test_deleteCustomerPaymentProfileResponse,
testCase "createCustomerProfileFromTransactionResponse" test_createCustomerProfileFromTransactionResponse,
testCase "getHostedProfilePageResponse" test_getHostedProfilePageResponse,
testCase "chargeCustomerProfile" test_chargeCustomerProfile,
testCase "chargeCustomerProfile_BankAccount" test_chargeCustomerProfile_BankAccount,
testCase "aNetApiResponse" test_aNetApiResponse
]
| MichaelBurge/haskell-authorize-net | test/Test/Network/AuthorizeNet/Response.hs | bsd-3-clause | 28,963 | 0 | 17 | 4,869 | 2,201 | 1,226 | 975 | 235 | 1 |
import Data.List (zip4)
import Data.Ratio
thomas :: Fractional a => [a] -> [a] -> [a] -> [a] -> [a]
thomas a b c = init . scanr back 0 . tail . scanl forward (0, 0) . zip4 a b c
where
forward (c', d') (a, b, c, d) =
let denominator = b - a * c'
in (c / denominator, (d - a * d') / denominator)
back (c, d) x = d - c * x
main :: IO ()
main = do
let a = [0, 2, 3] :: [Ratio Int]
b = [1, 3, 6]
c = [4, 5, 0]
d = [7, 5, 3]
print $ thomas a b c d
| Gathros/algorithm-archive | contents/thomas_algorithm/code/haskell/thomas.hs | mit | 489 | 0 | 13 | 164 | 308 | 169 | 139 | 15 | 1 |
module Orlin.Frontend.Parser (
program
) where
import Text.Parsec
import Text.Parsec.String (Parser)
import Orlin.Frontend.Ast
program :: Parser Prog
program = Prog <$> many1 statement <* spaces
statement :: Parser Stmt
statement = try definition <|> declaration
definition :: Parser Stmt
definition = namedParens "var" $ do
name <- varName <$> variable
value <- expression
return $ Def name value
declaration :: Parser Stmt
declaration = namedParens ":" $ do
name <- varName <$> variable
ty <- type_
return $ Decl name ty
expression :: Parser Expr
expression = try number
<|> try unit
<|> try variable
<|> try fn
<|> try let_
<|> call
number :: Parser Expr
number = spaces *> (Int . read <$> many1 digit)
variable :: Parser Expr
variable = do
spaces
first <- letter <|> oneOf "+-*/!?_"
rest <- many (alphaNum <|> oneOf "+-*/!?_'")
return $ Var (first:rest) TUnit 0
unit :: Parser Expr
unit = wsString ":unit" *> pure Unit
fn :: Parser Expr
fn = namedParens "fn" $
Fn <$> parens (many1 param)
<*> many1 expression
where param = do
name <- varName <$> variable
ty <- type_
return (name, ty)
let_ :: Parser Expr
let_ = namedParens "let" $ do
binds <- parens (many1 binding)
body <- many1 expression
return $ foldr (\b e -> Let b [e])
(Let (last binds) body)
(init binds)
where binding = do
name <- varName <$> variable
value <- expression
return (name, value)
call :: Parser Expr
call = parens $
Call <$> callee
<*> many1 expression
<*> pure TUnit
where callee = do
e <- expression
if isVar e && (varName e `elem` ["let", "fn"])
then unexpected (varName e ++ ": Bad syntax.")
else return e
type_ :: Parser Type
type_ = try (wsString "int" *> return TInt)
<|> try (wsString "unit" *> return TUnit)
<|> arrow
where arrow = namedParens "->" $ do
first <- type_
rest <- many1 type_
return $ TFn (first : init rest) (last rest)
parens :: Parser a -> Parser a
parens p = lparen *> p <* rparen
namedParens :: String -> Parser a -> Parser a
namedParens name p = lparen *> wsString name *> p <* rparen
lparen :: Parser Char
lparen = spaces *> oneOf "(["
rparen :: Parser Char
rparen = spaces *> oneOf ")]"
wsString :: String -> Parser String
wsString s = spaces *> string s
| nicball/orlin-lang | src/Orlin/Frontend/Parser.hs | mit | 2,467 | 0 | 14 | 697 | 918 | 446 | 472 | 83 | 2 |
{- |
Module : IOEnv
Description : The main monad used in the type checker.
Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt)
License : BSD3
Maintainer : Zhiyuan Shi <zhiyuan.shi@gmail.com>
Stability : experimental
Portability : portable
-}
module IOEnv
( IOEnv(..)
, runIOEnv, evalIOEnv, execIOEnv
, getEnv, setEnv, localEnv
) where
import Control.Monad.State
newtype IOEnv env a = IOEnv { unIOEnv :: StateT env IO a }
-- Recall:
-- newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }
instance Monad (IOEnv m) where
return = returnM
(>>=) = thenM
returnM :: a -> IOEnv env a
returnM a = IOEnv (StateT (\ env -> return (a, env)))
thenM :: IOEnv env a -> (a -> IOEnv env b) -> IOEnv env b
thenM (IOEnv m) f = IOEnv (StateT (\ env ->
do (r, env') <- runStateT m env
runStateT (unIOEnv (f r)) env'))
instance MonadIO (IOEnv m) where
liftIO = liftIOM
liftIOM :: IO a -> IOEnv m a
liftIOM = IOEnv . liftIO
runIOEnv :: env -> IOEnv env a -> IO (a, env)
runIOEnv env (IOEnv m) = runStateT m env
evalIOEnv :: env -> IOEnv env a -> IO a
evalIOEnv env = liftM fst . runIOEnv env
execIOEnv :: env -> IOEnv env a -> IO env
execIOEnv env = liftM snd . runIOEnv env
getEnv :: IOEnv env env
getEnv = IOEnv get
setEnv :: env -> IOEnv env ()
setEnv env = IOEnv $ put env
localEnv :: (env -> env) -> IOEnv env a -> IOEnv env a
localEnv f do_this
= do env <- getEnv
setEnv (f env)
r <- do_this
setEnv env
return r
| xnning/fcore | lib/IOEnv.hs | bsd-2-clause | 1,595 | 0 | 16 | 450 | 540 | 276 | 264 | 36 | 1 |
-- | Maintainer: 2016 Evan Cofsky <evan@theunixman.com>
--
-- FreeBSD Properties
--
-- This module is designed to be imported unqualified.
module Propellor.Property.FreeBSD (
module Propellor.Property.FreeBSD.Pkg,
module Propellor.Property.FreeBSD.Poudriere
) where
import Propellor.Property.FreeBSD.Pkg
import Propellor.Property.FreeBSD.Poudriere
| ArchiveTeam/glowing-computing-machine | src/Propellor/Property/FreeBSD.hs | bsd-2-clause | 353 | 4 | 5 | 39 | 48 | 35 | 13 | 5 | 0 |
module Type.Inference where
import Control.Arrow (first, second)
import Control.Monad.Except (Except, forM, liftIO, runExceptT, throwError)
import qualified Data.Map as Map
import qualified Data.Traversable as Traverse
import AST.Module as Module
import qualified AST.Module.Name as ModuleName
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Type as Error
import qualified Type.Constrain.Expression as TcExpr
import qualified Type.Environment as Env
import qualified Type.Solve as Solve
import qualified Type.State as TS
import qualified Type.Type as T
import System.IO.Unsafe
-- Maybe possible to switch over to ST instead of IO.
-- I don't think that'd be worthwhile though.
infer
:: Module.Interfaces
-> Module.CanonicalModule
-> Except [A.Located Error.Error] (Map.Map String Type.Canonical)
infer interfaces modul =
either throwError return $ unsafePerformIO $ runExceptT $
do (header, constraint) <-
liftIO (genConstraints interfaces modul)
state <- Solve.solve constraint
let header' = Map.delete "::" header
let types = Map.map A.drop (Map.difference (TS.sSavedEnv state) header')
liftIO (Traverse.traverse T.toSrcType types)
genConstraints
:: Module.Interfaces
-> Module.CanonicalModule
-> IO (Map.Map String T.Type, T.TypeConstraint)
genConstraints interfaces modul =
do env <- Env.initialize (canonicalizeAdts interfaces modul)
ctors <-
forM (Env.ctorNames env) $ \name ->
do (_, vars, args, result) <- Env.freshDataScheme env name
return (name, (vars, foldr (T.==>) result args))
importedVars <-
mapM (canonicalizeValues env) (Map.toList interfaces)
let allTypes = concat (ctors : importedVars)
let vars = concatMap (fst . snd) allTypes
let header = Map.map snd (Map.fromList allTypes)
let environ = T.CLet [ T.Scheme vars [] T.CTrue (Map.map (A.A undefined) header) ]
fvar <- T.mkVar Nothing
constraint <-
TcExpr.constrain env (program (body modul)) (T.VarN fvar)
return (header, environ constraint)
canonicalizeValues
:: Env.Environment
-> (ModuleName.Canonical, Interface)
-> IO [(String, ([T.Variable], T.Type))]
canonicalizeValues env (moduleName, iface) =
forM (Map.toList (iTypes iface)) $ \(name,tipe) ->
do tipe' <- Env.instantiateType env tipe Map.empty
return
( ModuleName.canonicalToString moduleName ++ "." ++ name
, tipe'
)
canonicalizeAdts :: Module.Interfaces -> Module.CanonicalModule -> [CanonicalAdt]
canonicalizeAdts interfaces modul =
localAdts ++ importedAdts
where
localAdts :: [CanonicalAdt]
localAdts =
format (Module.name modul, datatypes (body modul))
importedAdts :: [CanonicalAdt]
importedAdts =
concatMap (format . second iAdts) (Map.toList interfaces)
format :: (ModuleName.Canonical, Module.ADTs) -> [CanonicalAdt]
format (home, adts) =
map canonical (Map.toList adts)
where
canonical :: (String, AdtInfo String) -> CanonicalAdt
canonical (name, (tvars, ctors)) =
( toVar name
, (tvars, map (first toVar) ctors)
)
toVar :: String -> Var.Canonical
toVar name =
Var.fromModule home name
| 5outh/Elm | src/Type/Inference.hs | bsd-3-clause | 3,418 | 0 | 17 | 777 | 1,073 | 576 | 497 | 78 | 1 |
-- |
-- Module : Data.ASN1.Stream
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
module Data.ASN1.Stream
( ASN1Repr
, getConstructedEnd
, getConstructedEndRepr
) where
import Data.ASN1.Types
import Data.ASN1.Types.Lowlevel
{- associate a list of asn1 event with an ASN1 type.
- it's sometimes required to know the exact byte sequence leading to an ASN1 type:
- eg: cryptographic signature -}
type ASN1Repr = (ASN1, [ASN1Event])
getConstructedEnd :: Int -> [ASN1] -> ([ASN1],[ASN1])
getConstructedEnd _ xs@[] = (xs, [])
getConstructedEnd i ((x@(Start _)):xs) = let (yz, zs) = getConstructedEnd (i+1) xs in (x:yz,zs)
getConstructedEnd i ((x@(End _)):xs)
| i == 0 = ([], xs)
| otherwise = let (ys, zs) = getConstructedEnd (i-1) xs in (x:ys,zs)
getConstructedEnd i (x:xs) = let (ys, zs) = getConstructedEnd i xs in (x:ys,zs)
getConstructedEndRepr :: [ASN1Repr] -> ([ASN1Repr],[ASN1Repr])
getConstructedEndRepr = g
where g [] = ([], [])
g (x@(Start _,_):xs) = let (ys, zs) = getEnd 1 xs in (x:ys, zs)
g (x:xs) = ([x],xs)
getEnd :: Int -> [ASN1Repr] -> ([ASN1Repr],[ASN1Repr])
getEnd _ [] = ([], [])
getEnd 0 xs = ([], xs)
getEnd i ((x@(Start _, _)):xs) = let (ys, zs) = getEnd (i+1) xs in (x:ys,zs)
getEnd i ((x@(End _, _)):xs) = let (ys, zs) = getEnd (i-1) xs in (x:ys,zs)
getEnd i (x:xs) = let (ys, zs) = getEnd i xs in (x:ys,zs)
| mboes/hs-asn1 | encoding/Data/ASN1/Stream.hs | bsd-3-clause | 1,655 | 0 | 13 | 476 | 717 | 401 | 316 | 25 | 7 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TupleSections #-}
-- | Names for flags.
module Stack.Types.FlagName
(FlagName
,FlagNameParseFail(..)
,flagNameParser
,parseFlagName
,parseFlagNameFromString
,flagNameString
,flagNameText
,fromCabalFlagName
,toCabalFlagName
,mkFlagName)
where
import Control.Applicative
import Control.DeepSeq (NFData)
import Control.Monad.Catch
import Data.Aeson.Extended
import Data.Attoparsec.Combinators
import Data.Attoparsec.Text
import Data.Char (isLetter, isDigit, toLower)
import Data.Data
import Data.Hashable
import Data.Store (Store)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Binary ()
import qualified Distribution.PackageDescription as Cabal
import GHC.Generics
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
-- | A parse fail.
data FlagNameParseFail
= FlagNameParseFail Text
deriving (Typeable)
instance Exception FlagNameParseFail
instance Show FlagNameParseFail where
show (FlagNameParseFail bs) = "Invalid flag name: " ++ show bs
-- | A flag name.
newtype FlagName =
FlagName Text
deriving (Typeable,Data,Generic,Hashable,Store,NFData,ToJSONKey)
instance Eq FlagName where
x == y = compare x y == EQ
instance Ord FlagName where
compare (FlagName x) (FlagName y) =
compare (T.map toLower x) (T.map toLower y)
instance Lift FlagName where
lift (FlagName n) =
appE (conE 'FlagName)
(stringE (T.unpack n))
instance Show FlagName where
show (FlagName n) = T.unpack n
instance FromJSON FlagName where
parseJSON j =
do s <- parseJSON j
case parseFlagNameFromString s of
Nothing ->
fail ("Couldn't parse flag name: " ++ s)
Just ver -> return ver
instance FromJSONKey FlagName where
fromJSONKey = FromJSONKeyTextParser $ \k ->
either (fail . show) return $ parseFlagName k
-- | Attoparsec parser for a flag name
flagNameParser :: Parser FlagName
flagNameParser =
fmap (FlagName . T.pack)
(appending (many1 (satisfy isLetter))
(concating (many (alternating
(pured (satisfy isAlphaNum))
(appending (pured (satisfy separator))
(pured (satisfy isAlphaNum)))))))
where separator c = c == '-' || c == '_'
isAlphaNum c = isLetter c || isDigit c
-- | Make a flag name.
mkFlagName :: String -> Q Exp
mkFlagName s =
case parseFlagNameFromString s of
Nothing -> error ("Invalid flag name: " ++ show s)
Just pn -> [|pn|]
-- | Convenient way to parse a flag name from a 'Text'.
parseFlagName :: MonadThrow m => Text -> m FlagName
parseFlagName x = go x
where go =
either (const (throwM (FlagNameParseFail x))) return .
parseOnly (flagNameParser <* endOfInput)
-- | Convenience function for parsing from a 'String'
parseFlagNameFromString :: MonadThrow m => String -> m FlagName
parseFlagNameFromString =
parseFlagName . T.pack
-- | Produce a string representation of a flag name.
flagNameString :: FlagName -> String
flagNameString (FlagName n) = T.unpack n
-- | Produce a string representation of a flag name.
flagNameText :: FlagName -> Text
flagNameText (FlagName n) = n
-- | Convert from a Cabal flag name.
fromCabalFlagName :: Cabal.FlagName -> FlagName
fromCabalFlagName (Cabal.FlagName name) =
let !x = T.pack name
in FlagName x
-- | Convert to a Cabal flag name.
toCabalFlagName :: FlagName -> Cabal.FlagName
toCabalFlagName (FlagName name) =
let !x = T.unpack name
in Cabal.FlagName x
| AndreasPK/stack | src/Stack/Types/FlagName.hs | bsd-3-clause | 3,925 | 0 | 19 | 965 | 1,003 | 529 | 474 | 100 | 2 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Socket where
import Control.Monad.Trans (MonadIO(liftIO))
import Control.Concurrent (threadDelay, forkIO, killThread, ThreadId)
import qualified Control.Exception as E
import qualified Data.ByteString.Char8 as BSC
import qualified Network.WebSockets as WS
import qualified System.FSNotify.Devel as NDevel
import qualified System.FSNotify as Notify
import qualified Compile
fileChangeApp :: FilePath -> WS.ServerApp
fileChangeApp watchedFile pendingConnection =
do connection <- WS.acceptRequest pendingConnection
Notify.withManager $ \notifyManager ->
do _ <- NDevel.treeExtExists notifyManager "." "elm" (sendHotSwap watchedFile connection)
keepAlive connection
sendHotSwap :: FilePath -> WS.Connection -> FilePath -> IO ()
sendHotSwap watchedFile connection _ =
do result <- liftIO (Compile.toJson watchedFile)
WS.sendTextData connection (BSC.pack result)
keepAlive :: WS.Connection -> IO ()
keepAlive connection =
loop
where
loop :: IO ()
loop =
do pingThread <- forkIO ping
listen pingThread
ping :: IO ()
ping =
do threadDelay (10 * 1000000) -- 10 seconds
WS.sendPing connection ("ping" :: BSC.ByteString) `E.catch` connectionClosed
connectionClosed :: E.SomeException -> IO ()
connectionClosed _ = return ()
listen :: ThreadId -> IO ()
listen pingThread =
do pong <- WS.receive connection
case pong of
WS.DataMessage _ -> listen pingThread
WS.ControlMessage controlMessage ->
case controlMessage of
WS.Ping _ -> listen pingThread
WS.Pong _ -> loop
WS.Close _ _ ->
killThread pingThread >> return ()
| johnpmayer/elm-reactor | backend/Socket.hs | bsd-3-clause | 1,828 | 0 | 17 | 460 | 498 | 257 | 241 | 45 | 4 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section[CoreMonad]{The core pipeline monad}
-}
{-# LANGUAGE CPP #-}
module CoreMonad (
-- * Configuration of the core-to-core passes
CoreToDo(..), runWhen, runMaybe,
SimplifierMode(..),
FloatOutSwitches(..),
pprPassDetails,
-- * Plugins
PluginPass, bindsOnlyPass,
-- * Counting
SimplCount, doSimplTick, doFreeSimplTick, simplCountN,
pprSimplCount, plusSimplCount, zeroSimplCount,
isZeroSimplCount, hasDetailedCounts, Tick(..),
-- * The monad
CoreM, runCoreM,
-- ** Reading from the monad
getHscEnv, getRuleBase, getModule,
getDynFlags, getOrigNameCache, getPackageFamInstEnv,
getVisibleOrphanMods,
getPrintUnqualified, getSrcSpanM,
-- ** Writing to the monad
addSimplCount,
-- ** Lifting into the monad
liftIO, liftIOWithCount,
liftIO1, liftIO2, liftIO3, liftIO4,
-- ** Global initialization
reinitializeGlobals,
-- ** Dealing with annotations
getAnnotations, getFirstAnnotations,
-- ** Screen output
putMsg, putMsgS, errorMsg, errorMsgS, warnMsg,
fatalErrorMsg, fatalErrorMsgS,
debugTraceMsg, debugTraceMsgS,
dumpIfSet_dyn,
-- * Getting 'Name's
thNameToGhcName
) where
import Name( Name )
import TcRnMonad ( initTcForLookup )
import CoreSyn
import HscTypes
import Module
import DynFlags
import StaticFlags
import BasicTypes ( CompilerPhase(..) )
import Annotations
import IOEnv hiding ( liftIO, failM, failWithM )
import qualified IOEnv ( liftIO )
import TcEnv ( lookupGlobal )
import Var
import Outputable
import FastString
import qualified ErrUtils as Err
import ErrUtils( Severity(..) )
import Maybes
import UniqSupply
import UniqFM ( UniqFM, mapUFM, filterUFM )
import MonadUtils
import NameCache
import SrcLoc
import ListSetOps ( runs )
import Data.List
import Data.Ord
import Data.Dynamic
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Word
import Control.Monad
import Control.Applicative ( Alternative(..) )
import Prelude hiding ( read )
import {-# SOURCE #-} TcSplice ( lookupThName_maybe )
import qualified Language.Haskell.TH as TH
{-
************************************************************************
* *
The CoreToDo type and related types
Abstraction of core-to-core passes to run.
* *
************************************************************************
-}
data CoreToDo -- These are diff core-to-core passes,
-- which may be invoked in any order,
-- as many times as you like.
= CoreDoSimplify -- The core-to-core simplifier.
Int -- Max iterations
SimplifierMode
| CoreDoPluginPass String PluginPass
| CoreDoFloatInwards
| CoreDoFloatOutwards FloatOutSwitches
| CoreLiberateCase
| CoreDoPrintCore
| CoreDoStaticArgs
| CoreDoCallArity
| CoreDoStrictness
| CoreDoWorkerWrapper
| CoreDoSpecialising
| CoreDoSpecConstr
| CoreCSE
| CoreDoRuleCheck CompilerPhase String -- Check for non-application of rules
-- matching this string
| CoreDoVectorisation
| CoreDoNothing -- Useful when building up
| CoreDoPasses [CoreToDo] -- lists of these things
| CoreDesugar -- Right after desugaring, no simple optimisation yet!
| CoreDesugarOpt -- CoreDesugarXXX: Not strictly a core-to-core pass, but produces
-- Core output, and hence useful to pass to endPass
| CoreTidy
| CorePrep
instance Outputable CoreToDo where
ppr (CoreDoSimplify _ _) = text "Simplifier"
ppr (CoreDoPluginPass s _) = text "Core plugin: " <+> text s
ppr CoreDoFloatInwards = text "Float inwards"
ppr (CoreDoFloatOutwards f) = text "Float out" <> parens (ppr f)
ppr CoreLiberateCase = text "Liberate case"
ppr CoreDoStaticArgs = text "Static argument"
ppr CoreDoCallArity = text "Called arity analysis"
ppr CoreDoStrictness = text "Demand analysis"
ppr CoreDoWorkerWrapper = text "Worker Wrapper binds"
ppr CoreDoSpecialising = text "Specialise"
ppr CoreDoSpecConstr = text "SpecConstr"
ppr CoreCSE = text "Common sub-expression"
ppr CoreDoVectorisation = text "Vectorisation"
ppr CoreDesugar = text "Desugar (before optimization)"
ppr CoreDesugarOpt = text "Desugar (after optimization)"
ppr CoreTidy = text "Tidy Core"
ppr CorePrep = text "CorePrep"
ppr CoreDoPrintCore = text "Print core"
ppr (CoreDoRuleCheck {}) = text "Rule check"
ppr CoreDoNothing = text "CoreDoNothing"
ppr (CoreDoPasses passes) = text "CoreDoPasses" <+> ppr passes
pprPassDetails :: CoreToDo -> SDoc
pprPassDetails (CoreDoSimplify n md) = vcat [ text "Max iterations =" <+> int n
, ppr md ]
pprPassDetails _ = Outputable.empty
data SimplifierMode -- See comments in SimplMonad
= SimplMode
{ sm_names :: [String] -- Name(s) of the phase
, sm_phase :: CompilerPhase
, sm_rules :: Bool -- Whether RULES are enabled
, sm_inline :: Bool -- Whether inlining is enabled
, sm_case_case :: Bool -- Whether case-of-case is enabled
, sm_eta_expand :: Bool -- Whether eta-expansion is enabled
}
instance Outputable SimplifierMode where
ppr (SimplMode { sm_phase = p, sm_names = ss
, sm_rules = r, sm_inline = i
, sm_eta_expand = eta, sm_case_case = cc })
= text "SimplMode" <+> braces (
sep [ text "Phase =" <+> ppr p <+>
brackets (text (concat $ intersperse "," ss)) <> comma
, pp_flag i (sLit "inline") <> comma
, pp_flag r (sLit "rules") <> comma
, pp_flag eta (sLit "eta-expand") <> comma
, pp_flag cc (sLit "case-of-case") ])
where
pp_flag f s = ppUnless f (text "no") <+> ptext s
data FloatOutSwitches = FloatOutSwitches {
floatOutLambdas :: Maybe Int, -- ^ Just n <=> float lambdas to top level, if
-- doing so will abstract over n or fewer
-- value variables
-- Nothing <=> float all lambdas to top level,
-- regardless of how many free variables
-- Just 0 is the vanilla case: float a lambda
-- iff it has no free vars
floatOutConstants :: Bool, -- ^ True <=> float constants to top level,
-- even if they do not escape a lambda
floatOutOverSatApps :: Bool,
-- ^ True <=> float out over-saturated applications
-- based on arity information.
-- See Note [Floating over-saturated applications]
-- in SetLevels
floatToTopLevelOnly :: Bool -- ^ Allow floating to the top level only.
}
instance Outputable FloatOutSwitches where
ppr = pprFloatOutSwitches
pprFloatOutSwitches :: FloatOutSwitches -> SDoc
pprFloatOutSwitches sw
= text "FOS" <+> (braces $
sep $ punctuate comma $
[ text "Lam =" <+> ppr (floatOutLambdas sw)
, text "Consts =" <+> ppr (floatOutConstants sw)
, text "OverSatApps =" <+> ppr (floatOutOverSatApps sw) ])
-- The core-to-core pass ordering is derived from the DynFlags:
runWhen :: Bool -> CoreToDo -> CoreToDo
runWhen True do_this = do_this
runWhen False _ = CoreDoNothing
runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
runMaybe (Just x) f = f x
runMaybe Nothing _ = CoreDoNothing
{-
************************************************************************
* *
Types for Plugins
* *
************************************************************************
-}
-- | A description of the plugin pass itself
type PluginPass = ModGuts -> CoreM ModGuts
bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
bindsOnlyPass pass guts
= do { binds' <- pass (mg_binds guts)
; return (guts { mg_binds = binds' }) }
{-
************************************************************************
* *
Counting and logging
* *
************************************************************************
-}
verboseSimplStats :: Bool
verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
zeroSimplCount :: DynFlags -> SimplCount
isZeroSimplCount :: SimplCount -> Bool
hasDetailedCounts :: SimplCount -> Bool
pprSimplCount :: SimplCount -> SDoc
doSimplTick :: DynFlags -> Tick -> SimplCount -> SimplCount
doFreeSimplTick :: Tick -> SimplCount -> SimplCount
plusSimplCount :: SimplCount -> SimplCount -> SimplCount
data SimplCount
= VerySimplCount !Int -- Used when don't want detailed stats
| SimplCount {
ticks :: !Int, -- Total ticks
details :: !TickCounts, -- How many of each type
n_log :: !Int, -- N
log1 :: [Tick], -- Last N events; <= opt_HistorySize,
-- most recent first
log2 :: [Tick] -- Last opt_HistorySize events before that
-- Having log1, log2 lets us accumulate the
-- recent history reasonably efficiently
}
type TickCounts = Map Tick Int
simplCountN :: SimplCount -> Int
simplCountN (VerySimplCount n) = n
simplCountN (SimplCount { ticks = n }) = n
zeroSimplCount dflags
-- This is where we decide whether to do
-- the VerySimpl version or the full-stats version
| dopt Opt_D_dump_simpl_stats dflags
= SimplCount {ticks = 0, details = Map.empty,
n_log = 0, log1 = [], log2 = []}
| otherwise
= VerySimplCount 0
isZeroSimplCount (VerySimplCount n) = n==0
isZeroSimplCount (SimplCount { ticks = n }) = n==0
hasDetailedCounts (VerySimplCount {}) = False
hasDetailedCounts (SimplCount {}) = True
doFreeSimplTick tick sc@SimplCount { details = dts }
= sc { details = dts `addTick` tick }
doFreeSimplTick _ sc = sc
doSimplTick dflags tick
sc@(SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1 })
| nl >= historySize dflags = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
| otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
where
sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
doSimplTick _ _ (VerySimplCount n) = VerySimplCount (n+1)
-- Don't use Map.unionWith because that's lazy, and we want to
-- be pretty strict here!
addTick :: TickCounts -> Tick -> TickCounts
addTick fm tick = case Map.lookup tick fm of
Nothing -> Map.insert tick 1 fm
Just n -> n1 `seq` Map.insert tick n1 fm
where
n1 = n+1
plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
sc2@(SimplCount { ticks = tks2, details = dts2 })
= log_base { ticks = tks1 + tks2, details = Map.unionWith (+) dts1 dts2 }
where
-- A hackish way of getting recent log info
log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
| null (log2 sc2) = sc2 { log2 = log1 sc1 }
| otherwise = sc2
plusSimplCount (VerySimplCount n) (VerySimplCount m) = VerySimplCount (n+m)
plusSimplCount _ _ = panic "plusSimplCount"
-- We use one or the other consistently
pprSimplCount (VerySimplCount n) = text "Total ticks:" <+> int n
pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
= vcat [text "Total ticks: " <+> int tks,
blankLine,
pprTickCounts dts,
if verboseSimplStats then
vcat [blankLine,
text "Log (most recent first)",
nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
else Outputable.empty
]
pprTickCounts :: Map Tick Int -> SDoc
pprTickCounts counts
= vcat (map pprTickGroup groups)
where
groups :: [[(Tick,Int)]] -- Each group shares a comon tag
-- toList returns common tags adjacent
groups = runs same_tag (Map.toList counts)
same_tag (tick1,_) (tick2,_) = tickToTag tick1 == tickToTag tick2
pprTickGroup :: [(Tick, Int)] -> SDoc
pprTickGroup group@((tick1,_):_)
= hang (int (sum [n | (_,n) <- group]) <+> text (tickString tick1))
2 (vcat [ int n <+> pprTickCts tick
-- flip as we want largest first
| (tick,n) <- sortBy (flip (comparing snd)) group])
pprTickGroup [] = panic "pprTickGroup"
data Tick
= PreInlineUnconditionally Id
| PostInlineUnconditionally Id
| UnfoldingDone Id
| RuleFired FastString -- Rule name
| LetFloatFromLet
| EtaExpansion Id -- LHS binder
| EtaReduction Id -- Binder on outer lambda
| BetaReduction Id -- Lambda binder
| CaseOfCase Id -- Bndr on *inner* case
| KnownBranch Id -- Case binder
| CaseMerge Id -- Binder on outer case
| AltMerge Id -- Case binder
| CaseElim Id -- Case binder
| CaseIdentity Id -- Case binder
| FillInCaseDefault Id -- Case binder
| BottomFound
| SimplifierDone -- Ticked at each iteration of the simplifier
instance Outputable Tick where
ppr tick = text (tickString tick) <+> pprTickCts tick
instance Eq Tick where
a == b = case a `cmpTick` b of
EQ -> True
_ -> False
instance Ord Tick where
compare = cmpTick
tickToTag :: Tick -> Int
tickToTag (PreInlineUnconditionally _) = 0
tickToTag (PostInlineUnconditionally _) = 1
tickToTag (UnfoldingDone _) = 2
tickToTag (RuleFired _) = 3
tickToTag LetFloatFromLet = 4
tickToTag (EtaExpansion _) = 5
tickToTag (EtaReduction _) = 6
tickToTag (BetaReduction _) = 7
tickToTag (CaseOfCase _) = 8
tickToTag (KnownBranch _) = 9
tickToTag (CaseMerge _) = 10
tickToTag (CaseElim _) = 11
tickToTag (CaseIdentity _) = 12
tickToTag (FillInCaseDefault _) = 13
tickToTag BottomFound = 14
tickToTag SimplifierDone = 16
tickToTag (AltMerge _) = 17
tickString :: Tick -> String
tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
tickString (UnfoldingDone _) = "UnfoldingDone"
tickString (RuleFired _) = "RuleFired"
tickString LetFloatFromLet = "LetFloatFromLet"
tickString (EtaExpansion _) = "EtaExpansion"
tickString (EtaReduction _) = "EtaReduction"
tickString (BetaReduction _) = "BetaReduction"
tickString (CaseOfCase _) = "CaseOfCase"
tickString (KnownBranch _) = "KnownBranch"
tickString (CaseMerge _) = "CaseMerge"
tickString (AltMerge _) = "AltMerge"
tickString (CaseElim _) = "CaseElim"
tickString (CaseIdentity _) = "CaseIdentity"
tickString (FillInCaseDefault _) = "FillInCaseDefault"
tickString BottomFound = "BottomFound"
tickString SimplifierDone = "SimplifierDone"
pprTickCts :: Tick -> SDoc
pprTickCts (PreInlineUnconditionally v) = ppr v
pprTickCts (PostInlineUnconditionally v)= ppr v
pprTickCts (UnfoldingDone v) = ppr v
pprTickCts (RuleFired v) = ppr v
pprTickCts LetFloatFromLet = Outputable.empty
pprTickCts (EtaExpansion v) = ppr v
pprTickCts (EtaReduction v) = ppr v
pprTickCts (BetaReduction v) = ppr v
pprTickCts (CaseOfCase v) = ppr v
pprTickCts (KnownBranch v) = ppr v
pprTickCts (CaseMerge v) = ppr v
pprTickCts (AltMerge v) = ppr v
pprTickCts (CaseElim v) = ppr v
pprTickCts (CaseIdentity v) = ppr v
pprTickCts (FillInCaseDefault v) = ppr v
pprTickCts _ = Outputable.empty
cmpTick :: Tick -> Tick -> Ordering
cmpTick a b = case (tickToTag a `compare` tickToTag b) of
GT -> GT
EQ -> cmpEqTick a b
LT -> LT
cmpEqTick :: Tick -> Tick -> Ordering
cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
cmpEqTick _ _ = EQ
{-
************************************************************************
* *
Monad and carried data structure definitions
* *
************************************************************************
-}
newtype CoreState = CoreState {
cs_uniq_supply :: UniqSupply
}
data CoreReader = CoreReader {
cr_hsc_env :: HscEnv,
cr_rule_base :: RuleBase,
cr_module :: Module,
cr_print_unqual :: PrintUnqualified,
cr_loc :: SrcSpan, -- Use this for log/error messages so they
-- are at least tagged with the right source file
cr_visible_orphan_mods :: !ModuleSet
}
-- Note: CoreWriter used to be defined with data, rather than newtype. If it
-- is defined that way again, the cw_simpl_count field, at least, must be
-- strict to avoid a space leak (Trac #7702).
newtype CoreWriter = CoreWriter {
cw_simpl_count :: SimplCount
}
emptyWriter :: DynFlags -> CoreWriter
emptyWriter dflags = CoreWriter {
cw_simpl_count = zeroSimplCount dflags
}
plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
plusWriter w1 w2 = CoreWriter {
cw_simpl_count = (cw_simpl_count w1) `plusSimplCount` (cw_simpl_count w2)
}
type CoreIOEnv = IOEnv CoreReader
-- | The monad used by Core-to-Core passes to access common state, register simplification
-- statistics and so on
newtype CoreM a = CoreM { unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }
instance Functor CoreM where
fmap = liftM
instance Monad CoreM where
mx >>= f = CoreM $ \s -> do
(x, s', w1) <- unCoreM mx s
(y, s'', w2) <- unCoreM (f x) s'
let w = w1 `plusWriter` w2
return $ seq w (y, s'', w)
-- forcing w before building the tuple avoids a space leak
-- (Trac #7702)
instance Applicative CoreM where
pure x = CoreM $ \s -> nop s x
(<*>) = ap
m *> k = m >>= \_ -> k
instance Alternative CoreM where
empty = CoreM (const Control.Applicative.empty)
m <|> n = CoreM (\rs -> unCoreM m rs <|> unCoreM n rs)
instance MonadPlus CoreM
instance MonadUnique CoreM where
getUniqueSupplyM = do
us <- getS cs_uniq_supply
let (us1, us2) = splitUniqSupply us
modifyS (\s -> s { cs_uniq_supply = us2 })
return us1
getUniqueM = do
us <- getS cs_uniq_supply
let (u,us') = takeUniqFromSupply us
modifyS (\s -> s { cs_uniq_supply = us' })
return u
runCoreM :: HscEnv
-> RuleBase
-> UniqSupply
-> Module
-> ModuleSet
-> PrintUnqualified
-> SrcSpan
-> CoreM a
-> IO (a, SimplCount)
runCoreM hsc_env rule_base us mod orph_imps print_unqual loc m
= liftM extract $ runIOEnv reader $ unCoreM m state
where
reader = CoreReader {
cr_hsc_env = hsc_env,
cr_rule_base = rule_base,
cr_module = mod,
cr_visible_orphan_mods = orph_imps,
cr_print_unqual = print_unqual,
cr_loc = loc
}
state = CoreState {
cs_uniq_supply = us
}
extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
extract (value, _, writer) = (value, cw_simpl_count writer)
{-
************************************************************************
* *
Core combinators, not exported
* *
************************************************************************
-}
nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop s x = do
r <- getEnv
return (x, s, emptyWriter $ (hsc_dflags . cr_hsc_env) r)
read :: (CoreReader -> a) -> CoreM a
read f = CoreM (\s -> getEnv >>= (\r -> nop s (f r)))
getS :: (CoreState -> a) -> CoreM a
getS f = CoreM (\s -> nop s (f s))
modifyS :: (CoreState -> CoreState) -> CoreM ()
modifyS f = CoreM (\s -> nop (f s) ())
write :: CoreWriter -> CoreM ()
write w = CoreM (\s -> return ((), s, w))
-- \subsection{Lifting IO into the monad}
-- | Lift an 'IOEnv' operation into 'CoreM'
liftIOEnv :: CoreIOEnv a -> CoreM a
liftIOEnv mx = CoreM (\s -> mx >>= (\x -> nop s x))
instance MonadIO CoreM where
liftIO = liftIOEnv . IOEnv.liftIO
-- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
liftIOWithCount :: IO (SimplCount, a) -> CoreM a
liftIOWithCount what = liftIO what >>= (\(count, x) -> addSimplCount count >> return x)
{-
************************************************************************
* *
Reader, writer and state accessors
* *
************************************************************************
-}
getHscEnv :: CoreM HscEnv
getHscEnv = read cr_hsc_env
getRuleBase :: CoreM RuleBase
getRuleBase = read cr_rule_base
getVisibleOrphanMods :: CoreM ModuleSet
getVisibleOrphanMods = read cr_visible_orphan_mods
getPrintUnqualified :: CoreM PrintUnqualified
getPrintUnqualified = read cr_print_unqual
getSrcSpanM :: CoreM SrcSpan
getSrcSpanM = read cr_loc
addSimplCount :: SimplCount -> CoreM ()
addSimplCount count = write (CoreWriter { cw_simpl_count = count })
-- Convenience accessors for useful fields of HscEnv
instance HasDynFlags CoreM where
getDynFlags = fmap hsc_dflags getHscEnv
instance HasModule CoreM where
getModule = read cr_module
-- | The original name cache is the current mapping from 'Module' and
-- 'OccName' to a compiler-wide unique 'Name'
getOrigNameCache :: CoreM OrigNameCache
getOrigNameCache = do
nameCacheRef <- fmap hsc_NC getHscEnv
liftIO $ fmap nsNames $ readIORef nameCacheRef
getPackageFamInstEnv :: CoreM PackageFamInstEnv
getPackageFamInstEnv = do
hsc_env <- getHscEnv
eps <- liftIO $ hscEPS hsc_env
return $ eps_fam_inst_env eps
{-# DEPRECATED reinitializeGlobals "It is not necessary to call reinitializeGlobals. Since GHC 8.2, this function is a no-op and will be removed in GHC 8.4" #-}
reinitializeGlobals :: CoreM ()
reinitializeGlobals = return ()
{-
************************************************************************
* *
Dealing with annotations
* *
************************************************************************
-}
-- | Get all annotations of a given type. This happens lazily, that is
-- no deserialization will take place until the [a] is actually demanded and
-- the [a] can also be empty (the UniqFM is not filtered).
--
-- This should be done once at the start of a Core-to-Core pass that uses
-- annotations.
--
-- See Note [Annotations]
getAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
getAnnotations deserialize guts = do
hsc_env <- getHscEnv
ann_env <- liftIO $ prepareAnnotations hsc_env (Just guts)
return (deserializeAnns deserialize ann_env)
-- | Get at most one annotation of a given type per Unique.
getFirstAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
getFirstAnnotations deserialize guts
= liftM (mapUFM head . filterUFM (not . null))
$ getAnnotations deserialize guts
{-
Note [Annotations]
~~~~~~~~~~~~~~~~~~
A Core-to-Core pass that wants to make use of annotations calls
getAnnotations or getFirstAnnotations at the beginning to obtain a UniqFM with
annotations of a specific type. This produces all annotations from interface
files read so far. However, annotations from interface files read during the
pass will not be visible until getAnnotations is called again. This is similar
to how rules work and probably isn't too bad.
The current implementation could be optimised a bit: when looking up
annotations for a thing from the HomePackageTable, we could search directly in
the module where the thing is defined rather than building one UniqFM which
contains all annotations we know of. This would work because annotations can
only be given to things defined in the same module. However, since we would
only want to deserialise every annotation once, we would have to build a cache
for every module in the HTP. In the end, it's probably not worth it as long as
we aren't using annotations heavily.
************************************************************************
* *
Direct screen output
* *
************************************************************************
-}
msg :: Severity -> SDoc -> CoreM ()
msg sev doc
= do { dflags <- getDynFlags
; loc <- getSrcSpanM
; unqual <- getPrintUnqualified
; let sty = case sev of
SevError -> err_sty
SevWarning -> err_sty
SevDump -> dump_sty
_ -> user_sty
err_sty = mkErrStyle dflags unqual
user_sty = mkUserStyle unqual AllTheWay
dump_sty = mkDumpStyle unqual
; liftIO $
(log_action dflags) dflags NoReason sev loc sty doc }
-- | Output a String message to the screen
putMsgS :: String -> CoreM ()
putMsgS = putMsg . text
-- | Output a message to the screen
putMsg :: SDoc -> CoreM ()
putMsg = msg SevInfo
-- | Output an error to the screen. Does not cause the compiler to die.
errorMsgS :: String -> CoreM ()
errorMsgS = errorMsg . text
-- | Output an error to the screen. Does not cause the compiler to die.
errorMsg :: SDoc -> CoreM ()
errorMsg = msg SevError
warnMsg :: SDoc -> CoreM ()
warnMsg = msg SevWarning
-- | Output a fatal error to the screen. Does not cause the compiler to die.
fatalErrorMsgS :: String -> CoreM ()
fatalErrorMsgS = fatalErrorMsg . text
-- | Output a fatal error to the screen. Does not cause the compiler to die.
fatalErrorMsg :: SDoc -> CoreM ()
fatalErrorMsg = msg SevFatal
-- | Output a string debugging message at verbosity level of @-v@ or higher
debugTraceMsgS :: String -> CoreM ()
debugTraceMsgS = debugTraceMsg . text
-- | Outputs a debugging message at verbosity level of @-v@ or higher
debugTraceMsg :: SDoc -> CoreM ()
debugTraceMsg = msg SevDump
-- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
dumpIfSet_dyn :: DumpFlag -> String -> SDoc -> CoreM ()
dumpIfSet_dyn flag str doc
= do { dflags <- getDynFlags
; unqual <- getPrintUnqualified
; when (dopt flag dflags) $ liftIO $
Err.dumpSDoc dflags unqual flag str doc }
{-
************************************************************************
* *
Finding TyThings
* *
************************************************************************
-}
instance MonadThings CoreM where
lookupThing name = do { hsc_env <- getHscEnv
; liftIO $ lookupGlobal hsc_env name }
{-
************************************************************************
* *
Template Haskell interoperability
* *
************************************************************************
-}
-- | Attempt to convert a Template Haskell name to one that GHC can
-- understand. Original TH names such as those you get when you use
-- the @'foo@ syntax will be translated to their equivalent GHC name
-- exactly. Qualified or unqualifed TH names will be dynamically bound
-- to names in the module being compiled, if possible. Exact TH names
-- will be bound to the name they represent, exactly.
thNameToGhcName :: TH.Name -> CoreM (Maybe Name)
thNameToGhcName th_name = do
hsc_env <- getHscEnv
liftIO $ initTcForLookup hsc_env (lookupThName_maybe th_name)
| olsner/ghc | compiler/simplCore/CoreMonad.hs | bsd-3-clause | 31,188 | 0 | 18 | 9,925 | 6,297 | 3,392 | 2,905 | 510 | 4 |
module Settings.StaticFiles where
import Prelude (IO, otherwise)
import Yesod.Static
import qualified Yesod.Static as Static
import Settings (staticDir, development)
-- | use this to create your static file serving site
staticSite :: IO Static.Static
staticSite
| development = Static.staticDevel staticDir
| otherwise = Static.static staticDir
-- | This generates easy references to files in the static directory at compile time,
-- giving you compile-time verification that referenced files exist.
-- Warning: any files added to your static directory during run-time can't be
-- accessed this way. You'll have to use their FilePath or URL to access them.
$(staticFiles Settings.staticDir)
| wolftune/yesodweb.com | Settings/StaticFiles.hs | bsd-2-clause | 710 | 0 | 8 | 117 | 98 | 55 | 43 | -1 | -1 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section[SimplUtils]{The simplifier utilities}
-}
{-# LANGUAGE CPP #-}
module ETA.SimplCore.SimplUtils (
-- Rebuilding
mkLam, mkCase, prepareAlts, tryEtaExpandRhs,
-- Inlining,
preInlineUnconditionally, postInlineUnconditionally,
activeUnfolding, activeRule,
getUnfoldingInRuleMatch,
simplEnvForGHCi, updModeForStableUnfoldings, updModeForRules,
-- The continuation type
SimplCont(..), DupFlag(..),
isSimplified,
contIsDupable, contResultType, contHoleType,
contIsTrivial, contArgs,
countValArgs, countArgs,
mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg,
interestingCallContext,
-- ArgInfo
ArgInfo(..), ArgSpec(..), mkArgInfo,
addValArgTo, addCastTo, addTyArgTo,
argInfoExpr, argInfoAppArgs, pushSimplifiedArgs,
abstractFloats
) where
#include "HsVersions.h"
import ETA.SimplCore.SimplEnv
import ETA.SimplCore.CoreMonad ( SimplifierMode(..), Tick(..) )
import ETA.Core.MkCore ( sortQuantVars )
import ETA.Main.DynFlags
import ETA.Core.CoreSyn
import qualified ETA.Core.CoreSubst as CoreSubst
import ETA.Core.PprCore
import ETA.Core.CoreFVs
import ETA.Core.CoreUtils
import ETA.Core.CoreArity
import ETA.Core.CoreUnfold
import ETA.BasicTypes.Name
import ETA.BasicTypes.Id
import ETA.BasicTypes.Var
import ETA.BasicTypes.Demand
import ETA.SimplCore.SimplMonad
import ETA.Types.Type hiding( substTy )
import ETA.Types.Coercion hiding( substCo, substTy )
import ETA.BasicTypes.DataCon ( dataConWorkId )
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.BasicTypes
import ETA.Utils.Util
import ETA.Utils.MonadUtils
import ETA.Utils.Outputable
import ETA.Utils.FastString
import ETA.Utils.Pair
import ETA.Utils.ListSetOps ( minusList )
import Control.Monad ( when )
import Data.List ( partition )
{-
************************************************************************
* *
The SimplCont and DupFlag types
* *
************************************************************************
A SimplCont allows the simplifier to traverse the expression in a
zipper-like fashion. The SimplCont represents the rest of the expression,
"above" the point of interest.
You can also think of a SimplCont as an "evaluation context", using
that term in the way it is used for operational semantics. This is the
way I usually think of it, For example you'll often see a syntax for
evaluation context looking like
C ::= [] | C e | case C of alts | C `cast` co
That's the kind of thing we are doing here, and I use that syntax in
the comments.
Key points:
* A SimplCont describes a *strict* context (just like
evaluation contexts do). E.g. Just [] is not a SimplCont
* A SimplCont describes a context that *does not* bind
any variables. E.g. \x. [] is not a SimplCont
-}
data SimplCont
= Stop -- An empty context, or <hole>
OutType -- Type of the <hole>
CallCtxt -- Tells if there is something interesting about
-- the context, and hence the inliner
-- should be a bit keener (see interestingCallContext)
-- Specifically:
-- This is an argument of a function that has RULES
-- Inlining the call might allow the rule to fire
-- Never ValAppCxt (use ApplyToVal instead)
-- or CaseCtxt (use Select instead)
| CastIt -- <hole> `cast` co
OutCoercion -- The coercion simplified
-- Invariant: never an identity coercion
SimplCont
| ApplyToVal { -- <hole> arg
sc_dup :: DupFlag, -- See Note [DupFlag invariants]
sc_arg :: InExpr, -- The argument,
sc_env :: StaticEnv, -- and its static env
sc_cont :: SimplCont }
| ApplyToTy { -- <hole> ty
sc_arg_ty :: OutType, -- Argument type
sc_hole_ty :: OutType, -- Type of the function, presumably (forall a. blah)
-- See Note [The hole type in ApplyToTy]
sc_cont :: SimplCont }
| Select -- case <hole> of alts
DupFlag -- See Note [DupFlag invariants]
InId [InAlt] StaticEnv -- The case binder, alts type, alts, and subst-env
SimplCont
-- The two strict forms have no DupFlag, because we never duplicate them
| StrictBind -- (\x* \xs. e) <hole>
InId [InBndr] -- let x* = <hole> in e
InExpr StaticEnv -- is a special case
SimplCont
| StrictArg -- f e1 ..en <hole>
ArgInfo -- Specifies f, e1..en, Whether f has rules, etc
-- plus strictness flags for *further* args
CallCtxt -- Whether *this* argument position is interesting
SimplCont
| TickIt
(Tickish Id) -- Tick tickish <hole>
SimplCont
data DupFlag = NoDup -- Unsimplified, might be big
| Simplified -- Simplified
| OkToDup -- Simplified and small
isSimplified :: DupFlag -> Bool
isSimplified NoDup = False
isSimplified _ = True -- Invariant: the subst-env is empty
perhapsSubstTy :: DupFlag -> StaticEnv -> Type -> Type
perhapsSubstTy dup env ty
| isSimplified dup = ty
| otherwise = substTy env ty
{-
Note [DupFlag invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~
In both (ApplyToVal dup _ env k)
and (Select dup _ _ env k)
the following invariants hold
(a) if dup = OkToDup, then continuation k is also ok-to-dup
(b) if dup = OkToDup or Simplified, the subst-env is empty
(and and hence no need to re-simplify)
-}
instance Outputable DupFlag where
ppr OkToDup = ptext (sLit "ok")
ppr NoDup = ptext (sLit "nodup")
ppr Simplified = ptext (sLit "simpl")
instance Outputable SimplCont where
ppr (Stop ty interesting) = ptext (sLit "Stop") <> brackets (ppr interesting) <+> ppr ty
ppr (ApplyToTy { sc_arg_ty = ty
, sc_cont = cont }) = (ptext (sLit "ApplyToTy") <+> pprParendType ty) $$ ppr cont
ppr (ApplyToVal { sc_arg = arg
, sc_dup = dup
, sc_cont = cont }) = (ptext (sLit "ApplyToVal") <+> ppr dup <+> pprParendExpr arg)
$$ ppr cont
ppr (StrictBind b _ _ _ cont) = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
ppr (StrictArg ai _ cont) = (ptext (sLit "StrictArg") <+> ppr (ai_fun ai)) $$ ppr cont
ppr (Select dup bndr alts se cont) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$
ifPprDebug (nest 2 $ vcat [ppr (seTvSubst se), ppr alts]) $$ ppr cont
ppr (CastIt co cont ) = (ptext (sLit "CastIt") <+> ppr co) $$ ppr cont
ppr (TickIt t cont) = (ptext (sLit "TickIt") <+> ppr t) $$ ppr cont
{- Note [The hole type in ApplyToTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The sc_hole_ty field of ApplyToTy records the type of the "hole" in the
continuation. It is absolutely necessary to compute contHoleType, but it is
not used for anything else (and hence may not be evaluated).
Why is it necessary for contHoleType? Consider the continuation
ApplyToType Int (Stop Int)
corresponding to
(<hole> @Int) :: Int
What is the type of <hole>? It could be (forall a. Int) or (forall a. a),
and there is no way to know which, so we must record it.
In a chain of applications (f @t1 @t2 @t3) we'll lazily compute exprType
for (f @t1) and (f @t1 @t2), which is potentially non-linear; but it probably
doesn't matter because we'll never compute them all.
************************************************************************
* *
ArgInfo and ArgSpec
* *
************************************************************************
-}
data ArgInfo
= ArgInfo {
ai_fun :: OutId, -- The function
ai_args :: [ArgSpec], -- ...applied to these args (which are in *reverse* order)
ai_type :: OutType, -- Type of (f a1 ... an)
ai_rules :: [CoreRule], -- Rules for this function
ai_encl :: Bool, -- Flag saying whether this function
-- or an enclosing one has rules (recursively)
-- True => be keener to inline in all args
ai_strs :: [Bool], -- Strictness of remaining arguments
-- Usually infinite, but if it is finite it guarantees
-- that the function diverges after being given
-- that number of args
ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline
-- Always infinite
}
data ArgSpec
= ValArg OutExpr -- Apply to this (coercion or value); c.f. ApplyToVal
| TyArg { as_arg_ty :: OutType -- Apply to this type; c.f. ApplyToTy
, as_hole_ty :: OutType } -- Type of the function (presumably forall a. blah)
| CastBy OutCoercion -- Cast by this; c.f. CastIt
instance Outputable ArgSpec where
ppr (ValArg e) = ptext (sLit "ValArg") <+> ppr e
ppr (TyArg { as_arg_ty = ty }) = ptext (sLit "TyArg") <+> ppr ty
ppr (CastBy c) = ptext (sLit "CastBy") <+> ppr c
addValArgTo :: ArgInfo -> OutExpr -> ArgInfo
addValArgTo ai arg = ai { ai_args = ValArg arg : ai_args ai
, ai_type = funResultTy (ai_type ai) }
addTyArgTo :: ArgInfo -> OutType -> ArgInfo
addTyArgTo ai arg_ty = ai { ai_args = arg_spec : ai_args ai
, ai_type = applyTy poly_fun_ty arg_ty }
where
poly_fun_ty = ai_type ai
arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = poly_fun_ty }
addCastTo :: ArgInfo -> OutCoercion -> ArgInfo
addCastTo ai co = ai { ai_args = CastBy co : ai_args ai
, ai_type = pSnd (coercionKind co) }
argInfoAppArgs :: [ArgSpec] -> [OutExpr]
argInfoAppArgs [] = []
argInfoAppArgs (CastBy {} : _) = [] -- Stop at a cast
argInfoAppArgs (ValArg e : as) = e : argInfoAppArgs as
argInfoAppArgs (TyArg { as_arg_ty = ty } : as) = Type ty : argInfoAppArgs as
pushSimplifiedArgs :: SimplEnv -> [ArgSpec] -> SimplCont -> SimplCont
pushSimplifiedArgs _env [] k = k
pushSimplifiedArgs env (arg : args) k
= case arg of
TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }
-> ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = rest }
ValArg e -> ApplyToVal { sc_arg = e, sc_env = env, sc_dup = Simplified, sc_cont = rest }
CastBy c -> CastIt c rest
where
rest = pushSimplifiedArgs env args k
-- The env has an empty SubstEnv
argInfoExpr :: OutId -> [ArgSpec] -> OutExpr
-- NB: the [ArgSpec] is reversed so that the first arg
-- in the list is the last one in the application
argInfoExpr fun rev_args
= go rev_args
where
go [] = Var fun
go (ValArg a : as) = go as `App` a
go (TyArg { as_arg_ty = ty } : as) = go as `App` Type ty
go (CastBy co : as) = mkCast (go as) co
{-
************************************************************************
* *
Functions on SimplCont
* *
************************************************************************
-}
mkBoringStop :: OutType -> SimplCont
mkBoringStop ty = Stop ty BoringCtxt
mkRhsStop :: OutType -> SimplCont -- See Note [RHS of lets] in CoreUnfold
mkRhsStop ty = Stop ty RhsCtxt
mkLazyArgStop :: OutType -> CallCtxt -> SimplCont
mkLazyArgStop ty cci = Stop ty cci
-------------------
contIsRhsOrArg :: SimplCont -> Bool
contIsRhsOrArg (Stop {}) = True
contIsRhsOrArg (StrictBind {}) = True
contIsRhsOrArg (StrictArg {}) = True
contIsRhsOrArg _ = False
contIsRhs :: SimplCont -> Bool
contIsRhs (Stop _ RhsCtxt) = True
contIsRhs _ = False
-------------------
contIsDupable :: SimplCont -> Bool
contIsDupable (Stop {}) = True
contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k
contIsDupable (ApplyToVal { sc_dup = OkToDup }) = True -- See Note [DupFlag invariants]
contIsDupable (Select OkToDup _ _ _ _) = True -- ...ditto...
contIsDupable (CastIt _ k) = contIsDupable k
contIsDupable _ = False
-------------------
contIsTrivial :: SimplCont -> Bool
contIsTrivial (Stop {}) = True
contIsTrivial (ApplyToTy { sc_cont = k }) = contIsTrivial k
contIsTrivial (ApplyToVal { sc_arg = Coercion _, sc_cont = k }) = contIsTrivial k
contIsTrivial (CastIt _ k) = contIsTrivial k
contIsTrivial _ = False
-------------------
contResultType :: SimplCont -> OutType
contResultType (Stop ty _) = ty
contResultType (CastIt _ k) = contResultType k
contResultType (StrictBind _ _ _ _ k) = contResultType k
contResultType (StrictArg _ _ k) = contResultType k
contResultType (Select _ _ _ _ k) = contResultType k
contResultType (ApplyToTy { sc_cont = k }) = contResultType k
contResultType (ApplyToVal { sc_cont = k }) = contResultType k
contResultType (TickIt _ k) = contResultType k
contHoleType :: SimplCont -> OutType
contHoleType (Stop ty _) = ty
contHoleType (TickIt _ k) = contHoleType k
contHoleType (CastIt co _) = pFst (coercionKind co)
contHoleType (Select d b _ se _) = perhapsSubstTy d se (idType b)
contHoleType (StrictBind b _ _ se _) = substTy se (idType b)
contHoleType (StrictArg ai _ _) = funArgTy (ai_type ai)
contHoleType (ApplyToTy { sc_hole_ty = ty }) = ty -- See Note [The hole type in ApplyToTy]
contHoleType (ApplyToVal { sc_arg = e, sc_env = se, sc_dup = dup, sc_cont = k })
= mkFunTy (perhapsSubstTy dup se (exprType e))
(contHoleType k)
-------------------
countValArgs :: SimplCont -> Int
-- Count value arguments excluding coercions
countValArgs (ApplyToVal { sc_arg = arg, sc_cont = cont })
| Coercion {} <- arg = countValArgs cont
| otherwise = 1 + countValArgs cont
countValArgs _ = 0
countArgs :: SimplCont -> Int
-- Count all arguments, including types, coercions, and other values
countArgs (ApplyToTy { sc_cont = cont }) = 1 + countArgs cont
countArgs (ApplyToVal { sc_cont = cont }) = 1 + countArgs cont
countArgs _ = 0
contArgs :: SimplCont -> (Bool, [ArgSummary], SimplCont)
-- Summarises value args, discards type args and coercions
-- The returned continuation of the call is only used to
-- answer questions like "are you interesting?"
contArgs cont
| lone cont = (True, [], cont)
| otherwise = go [] cont
where
lone (ApplyToTy {}) = False -- See Note [Lone variables] in CoreUnfold
lone (ApplyToVal {}) = False
lone (CastIt {}) = False
lone _ = True
go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k })
= go (is_interesting arg se : args) k
go args (ApplyToTy { sc_cont = k }) = go args k
go args (CastIt _ k) = go args k
go args k = (False, reverse args, k)
is_interesting arg se = interestingArg se arg
-- Do *not* use short-cutting substitution here
-- because we want to get as much IdInfo as possible
-------------------
mkArgInfo :: Id
-> [CoreRule] -- Rules for function
-> Int -- Number of value args
-> SimplCont -- Context of the call
-> ArgInfo
mkArgInfo fun rules n_val_args call_cont
| n_val_args < idArity fun -- Note [Unsaturated functions]
= ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty
, ai_rules = rules, ai_encl = False
, ai_strs = vanilla_stricts
, ai_discs = vanilla_discounts }
| otherwise
= ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty
, ai_rules = rules
, ai_encl = interestingArgContext rules call_cont
, ai_strs = add_type_str fun_ty arg_stricts
, ai_discs = arg_discounts }
where
fun_ty = idType fun
vanilla_discounts, arg_discounts :: [Int]
vanilla_discounts = repeat 0
arg_discounts = case idUnfolding fun of
CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}}
-> discounts ++ vanilla_discounts
_ -> vanilla_discounts
vanilla_stricts, arg_stricts :: [Bool]
vanilla_stricts = repeat False
arg_stricts
= case splitStrictSig (idStrictness fun) of
(demands, result_info)
| not (demands `lengthExceeds` n_val_args)
-> -- Enough args, use the strictness given.
-- For bottoming functions we used to pretend that the arg
-- is lazy, so that we don't treat the arg as an
-- interesting context. This avoids substituting
-- top-level bindings for (say) strings into
-- calls to error. But now we are more careful about
-- inlining lone variables, so its ok (see SimplUtils.analyseCont)
if isBotRes result_info then
map isStrictDmd demands -- Finite => result is bottom
else
map isStrictDmd demands ++ vanilla_stricts
| otherwise
-> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun)
<+> ppr n_val_args <+> ppr demands )
vanilla_stricts -- Not enough args, or no strictness
add_type_str :: Type -> [Bool] -> [Bool]
-- If the function arg types are strict, record that in the 'strictness bits'
-- No need to instantiate because unboxed types (which dominate the strict
-- types) can't instantiate type variables.
-- add_type_str is done repeatedly (for each call); might be better
-- once-for-all in the function
-- But beware primops/datacons with no strictness
add_type_str _ [] = []
add_type_str fun_ty strs -- Look through foralls
| Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions
= add_type_str fun_ty' strs
add_type_str fun_ty (str:strs) -- Add strict-type info
| Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
= (str || isStrictType arg_ty) : add_type_str fun_ty' strs
add_type_str _ strs
= strs
{- Note [Unsaturated functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (test eyeball/inline4)
x = a:as
y = f x
where f has arity 2. Then we do not want to inline 'x', because
it'll just be floated out again. Even if f has lots of discounts
on its first argument -- it must be saturated for these to kick in
-}
{-
************************************************************************
* *
Interesting arguments
* *
************************************************************************
Note [Interesting call context]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to avoid inlining an expression where there can't possibly be
any gain, such as in an argument position. Hence, if the continuation
is interesting (eg. a case scrutinee, application etc.) then we
inline, otherwise we don't.
Previously some_benefit used to return True only if the variable was
applied to some value arguments. This didn't work:
let x = _coerce_ (T Int) Int (I# 3) in
case _coerce_ Int (T Int) x of
I# y -> ....
we want to inline x, but can't see that it's a constructor in a case
scrutinee position, and some_benefit is False.
Another example:
dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
.... case dMonadST _@_ x0 of (a,b,c) -> ....
we'd really like to inline dMonadST here, but we *don't* want to
inline if the case expression is just
case x of y { DEFAULT -> ... }
since we can just eliminate this case instead (x is in WHNF). Similar
applies when x is bound to a lambda expression. Hence
contIsInteresting looks for case expressions with just a single
default case.
-}
interestingCallContext :: SimplCont -> CallCtxt
-- See Note [Interesting call context]
interestingCallContext cont
= interesting cont
where
interesting (Select _ _bndr _ _ _) = CaseCtxt
interesting (ApplyToVal {}) = ValAppCtxt
-- Can happen if we have (f Int |> co) y
-- If f has an INLINE prag we need to give it some
-- motivation to inline. See Note [Cast then apply]
-- in CoreUnfold
interesting (StrictArg _ cci _) = cci
interesting (StrictBind {}) = BoringCtxt
interesting (Stop _ cci) = cci
interesting (TickIt _ k) = interesting k
interesting (ApplyToTy { sc_cont = k }) = interesting k
interesting (CastIt _ k) = interesting k
-- If this call is the arg of a strict function, the context
-- is a bit interesting. If we inline here, we may get useful
-- evaluation information to avoid repeated evals: e.g.
-- x + (y * z)
-- Here the contIsInteresting makes the '*' keener to inline,
-- which in turn exposes a constructor which makes the '+' inline.
-- Assuming that +,* aren't small enough to inline regardless.
--
-- It's also very important to inline in a strict context for things
-- like
-- foldr k z (f x)
-- Here, the context of (f x) is strict, and if f's unfolding is
-- a build it's *great* to inline it here. So we must ensure that
-- the context for (f x) is not totally uninteresting.
interestingArgContext :: [CoreRule] -> SimplCont -> Bool
-- If the argument has form (f x y), where x,y are boring,
-- and f is marked INLINE, then we don't want to inline f.
-- But if the context of the argument is
-- g (f x y)
-- where g has rules, then we *do* want to inline f, in case it
-- exposes a rule that might fire. Similarly, if the context is
-- h (g (f x x))
-- where h has rules, then we do want to inline f; hence the
-- call_cont argument to interestingArgContext
--
-- The ai-rules flag makes this happen; if it's
-- set, the inliner gets just enough keener to inline f
-- regardless of how boring f's arguments are, if it's marked INLINE
--
-- The alternative would be to *always* inline an INLINE function,
-- regardless of how boring its context is; but that seems overkill
-- For example, it'd mean that wrapper functions were always inlined
--
-- The call_cont passed to interestingArgContext is the context of
-- the call itself, e.g. g <hole> in the example above
interestingArgContext rules call_cont
= notNull rules || enclosing_fn_has_rules
where
enclosing_fn_has_rules = go call_cont
go (Select {}) = False
go (ApplyToVal {}) = False -- Shouldn't really happen
go (ApplyToTy {}) = False -- Ditto
go (StrictArg _ cci _) = interesting cci
go (StrictBind {}) = False -- ??
go (CastIt _ c) = go c
go (Stop _ cci) = interesting cci
go (TickIt _ c) = go c
interesting RuleArgCtxt = True
interesting _ = False
{- Note [Interesting arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An argument is interesting if it deserves a discount for unfoldings
with a discount in that argument position. The idea is to avoid
unfolding a function that is applied only to variables that have no
unfolding (i.e. they are probably lambda bound): f x y z There is
little point in inlining f here.
Generally, *values* (like (C a b) and (\x.e)) deserve discounts. But
we must look through lets, eg (let x = e in C a b), because the let will
float, exposing the value, if we inline. That makes it different to
exprIsHNF.
Before 2009 we said it was interesting if the argument had *any* structure
at all; i.e. (hasSomeUnfolding v). But does too much inlining; see Trac #3016.
But we don't regard (f x y) as interesting, unless f is unsaturated.
If it's saturated and f hasn't inlined, then it's probably not going
to now!
Note [Conlike is interesting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f d = ...((*) d x y)...
... f (df d')...
where df is con-like. Then we'd really like to inline 'f' so that the
rule for (*) (df d) can fire. To do this
a) we give a discount for being an argument of a class-op (eg (*) d)
b) we say that a con-like argument (eg (df d)) is interesting
-}
interestingArg :: SimplEnv -> CoreExpr -> ArgSummary
-- See Note [Interesting arguments]
interestingArg env e = go env 0 e
where
-- n is # value args to which the expression is applied
go env n (Var v)
| SimplEnv { seIdSubst = ids, seInScope = in_scope } <- env
= case lookupVarEnv ids v of
Nothing -> go_var n (refineFromInScope in_scope v)
Just (DoneId v') -> go_var n (refineFromInScope in_scope v')
Just (DoneEx e) -> go (zapSubstEnv env) n e
Just (ContEx tvs cvs ids e) -> go (setSubstEnv env tvs cvs ids) n e
go _ _ (Lit {}) = ValueArg
go _ _ (Type _) = TrivArg
go _ _ (Coercion _) = TrivArg
go env n (App fn (Type _)) = go env n fn
go env n (App fn (Coercion _)) = go env n fn
go env n (App fn _) = go env (n+1) fn
go env n (Tick _ a) = go env n a
go env n (Cast e _) = go env n e
go env n (Lam v e)
| isTyVar v = go env n e
| n>0 = go env (n-1) e
| otherwise = ValueArg
go env n (Let _ e) = case go env n e of { ValueArg -> ValueArg; _ -> NonTrivArg }
go _ _ (Case {}) = NonTrivArg
go_var n v
| isConLikeId v = ValueArg -- Experimenting with 'conlike' rather that
-- data constructors here
| idArity v > n = ValueArg -- Catches (eg) primops with arity but no unfolding
| n > 0 = NonTrivArg -- Saturated or unknown call
| conlike_unfolding = ValueArg -- n==0; look for an interesting unfolding
-- See Note [Conlike is interesting]
| otherwise = TrivArg -- n==0, no useful unfolding
where
conlike_unfolding = isConLikeUnfolding (idUnfolding v)
{-
************************************************************************
* *
SimplifierMode
* *
************************************************************************
The SimplifierMode controls several switches; see its definition in
CoreMonad
sm_rules :: Bool -- Whether RULES are enabled
sm_inline :: Bool -- Whether inlining is enabled
sm_case_case :: Bool -- Whether case-of-case is enabled
sm_eta_expand :: Bool -- Whether eta-expansion is enabled
-}
simplEnvForGHCi :: DynFlags -> SimplEnv
simplEnvForGHCi dflags
= mkSimplEnv $ SimplMode { sm_names = ["GHCi"]
, sm_phase = InitialPhase
, sm_rules = rules_on
, sm_inline = False
, sm_eta_expand = eta_expand_on
, sm_case_case = True }
where
rules_on = gopt Opt_EnableRewriteRules dflags
eta_expand_on = gopt Opt_DoLambdaEtaExpansion dflags
-- Do not do any inlining, in case we expose some unboxed
-- tuple stuff that confuses the bytecode interpreter
updModeForStableUnfoldings :: Activation -> SimplifierMode -> SimplifierMode
-- See Note [Simplifying inside stable unfoldings]
updModeForStableUnfoldings inline_rule_act current_mode
= current_mode { sm_phase = phaseFromActivation inline_rule_act
, sm_inline = True
, sm_eta_expand = False }
-- For sm_rules, just inherit; sm_rules might be "off"
-- because of -fno-enable-rewrite-rules
where
phaseFromActivation (ActiveAfter n) = Phase n
phaseFromActivation _ = InitialPhase
updModeForRules :: SimplifierMode -> SimplifierMode
-- See Note [Simplifying rules]
updModeForRules current_mode
= current_mode { sm_phase = InitialPhase
, sm_inline = False
, sm_rules = False
, sm_eta_expand = False }
{- Note [Simplifying rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When simplifying a rule, refrain from any inlining or applying of other RULES.
Doing anything to the LHS is plain confusing, because it means that what the
rule matches is not what the user wrote. c.f. Trac #10595, and #10528.
Moreover, inlining (or applying rules) on rule LHSs risks introducing
Ticks into the LHS, which makes matching trickier. Trac #10665, #10745.
Doing this to either side confounds tools like HERMIT, which seek to reason
about and apply the RULES as originally written. See Trac #10829.
Note [Inlining in gentle mode]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Something is inlined if
(i) the sm_inline flag is on, AND
(ii) the thing has an INLINE pragma, AND
(iii) the thing is inlinable in the earliest phase.
Example of why (iii) is important:
{-# INLINE [~1] g #-}
g = ...
{-# INLINE f #-}
f x = g (g x)
If we were to inline g into f's inlining, then an importing module would
never be able to do
f e --> g (g e) ---> RULE fires
because the stable unfolding for f has had g inlined into it.
On the other hand, it is bad not to do ANY inlining into an
stable unfolding, because then recursive knots in instance declarations
don't get unravelled.
However, *sometimes* SimplGently must do no call-site inlining at all
(hence sm_inline = False). Before full laziness we must be careful
not to inline wrappers, because doing so inhibits floating
e.g. ...(case f x of ...)...
==> ...(case (case x of I# x# -> fw x#) of ...)...
==> ...(case x of I# x# -> case fw x# of ...)...
and now the redex (f x) isn't floatable any more.
The no-inlining thing is also important for Template Haskell. You might be
compiling in one-shot mode with -O2; but when TH compiles a splice before
running it, we don't want to use -O2. Indeed, we don't want to inline
anything, because the byte-code interpreter might get confused about
unboxed tuples and suchlike.
Note [Simplifying inside stable unfoldings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must take care with simplification inside stable unfoldings (which come from
INLINE pragmas).
First, consider the following example
let f = \pq -> BIG
in
let g = \y -> f y y
{-# INLINE g #-}
in ...g...g...g...g...g...
Now, if that's the ONLY occurrence of f, it might be inlined inside g,
and thence copied multiple times when g is inlined. HENCE we treat
any occurrence in a stable unfolding as a multiple occurrence, not a single
one; see OccurAnal.addRuleUsage.
Second, we do want *do* to some modest rules/inlining stuff in stable
unfoldings, partly to eliminate senseless crap, and partly to break
the recursive knots generated by instance declarations.
However, suppose we have
{-# INLINE <act> f #-}
f = <rhs>
meaning "inline f in phases p where activation <act>(p) holds".
Then what inlinings/rules can we apply to the copy of <rhs> captured in
f's stable unfolding? Our model is that literally <rhs> is substituted for
f when it is inlined. So our conservative plan (implemented by
updModeForStableUnfoldings) is this:
-------------------------------------------------------------
When simplifying the RHS of an stable unfolding, set the phase
to the phase in which the stable unfolding first becomes active
-------------------------------------------------------------
That ensures that
a) Rules/inlinings that *cease* being active before p will
not apply to the stable unfolding, consistent with it being
inlined in its *original* form in phase p.
b) Rules/inlinings that only become active *after* p will
not apply to the stable unfolding, again to be consistent with
inlining the *original* rhs in phase p.
For example,
{-# INLINE f #-}
f x = ...g...
{-# NOINLINE [1] g #-}
g y = ...
{-# RULE h g = ... #-}
Here we must not inline g into f's RHS, even when we get to phase 0,
because when f is later inlined into some other module we want the
rule for h to fire.
Similarly, consider
{-# INLINE f #-}
f x = ...g...
g y = ...
and suppose that there are auto-generated specialisations and a strictness
wrapper for g. The specialisations get activation AlwaysActive, and the
strictness wrapper get activation (ActiveAfter 0). So the strictness
wrepper fails the test and won't be inlined into f's stable unfolding. That
means f can inline, expose the specialised call to g, so the specialisation
rules can fire.
A note about wrappers
~~~~~~~~~~~~~~~~~~~~~
It's also important not to inline a worker back into a wrapper.
A wrapper looks like
wraper = inline_me (\x -> ...worker... )
Normally, the inline_me prevents the worker getting inlined into
the wrapper (initially, the worker's only call site!). But,
if the wrapper is sure to be called, the strictness analyser will
mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
continuation.
-}
activeUnfolding :: SimplEnv -> Id -> Bool
activeUnfolding env
| not (sm_inline mode) = active_unfolding_minimal
| otherwise = case sm_phase mode of
InitialPhase -> active_unfolding_gentle
Phase n -> active_unfolding n
where
mode = getMode env
getUnfoldingInRuleMatch :: SimplEnv -> InScopeEnv
-- When matching in RULE, we want to "look through" an unfolding
-- (to see a constructor) if *rules* are on, even if *inlinings*
-- are not. A notable example is DFuns, which really we want to
-- match in rules like (op dfun) in gentle mode. Another example
-- is 'otherwise' which we want exprIsConApp_maybe to be able to
-- see very early on
getUnfoldingInRuleMatch env
= (in_scope, id_unf)
where
in_scope = seInScope env
mode = getMode env
id_unf id | unf_is_active id = idUnfolding id
| otherwise = NoUnfolding
unf_is_active id
| not (sm_rules mode) = active_unfolding_minimal id
| otherwise = isActive (sm_phase mode) (idInlineActivation id)
active_unfolding_minimal :: Id -> Bool
-- Compuslory unfoldings only
-- Ignore SimplGently, because we want to inline regardless;
-- the Id has no top-level binding at all
--
-- NB: we used to have a second exception, for data con wrappers.
-- On the grounds that we use gentle mode for rule LHSs, and
-- they match better when data con wrappers are inlined.
-- But that only really applies to the trivial wrappers (like (:)),
-- and they are now constructed as Compulsory unfoldings (in MkId)
-- so they'll happen anyway.
active_unfolding_minimal id = isCompulsoryUnfolding (realIdUnfolding id)
active_unfolding :: PhaseNum -> Id -> Bool
active_unfolding n id = isActiveIn n (idInlineActivation id)
active_unfolding_gentle :: Id -> Bool
-- Anything that is early-active
-- See Note [Gentle mode]
active_unfolding_gentle id
= isInlinePragma prag
&& isEarlyActive (inlinePragmaActivation prag)
-- NB: wrappers are not early-active
where
prag = idInlinePragma id
----------------------
activeRule :: SimplEnv -> Activation -> Bool
-- Nothing => No rules at all
activeRule env
| not (sm_rules mode) = \_ -> False -- Rewriting is off
| otherwise = isActive (sm_phase mode)
where
mode = getMode env
{-
************************************************************************
* *
preInlineUnconditionally
* *
************************************************************************
preInlineUnconditionally
~~~~~~~~~~~~~~~~~~~~~~~~
@preInlineUnconditionally@ examines a bndr to see if it is used just
once in a completely safe way, so that it is safe to discard the
binding inline its RHS at the (unique) usage site, REGARDLESS of how
big the RHS might be. If this is the case we don't simplify the RHS
first, but just inline it un-simplified.
This is much better than first simplifying a perhaps-huge RHS and then
inlining and re-simplifying it. Indeed, it can be at least quadratically
better. Consider
x1 = e1
x2 = e2[x1]
x3 = e3[x2]
...etc...
xN = eN[xN-1]
We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
This can happen with cascades of functions too:
f1 = \x1.e1
f2 = \xs.e2[f1]
f3 = \xs.e3[f3]
...etc...
THE MAIN INVARIANT is this:
---- preInlineUnconditionally invariant -----
IF preInlineUnconditionally chooses to inline x = <rhs>
THEN doing the inlining should not change the occurrence
info for the free vars of <rhs>
----------------------------------------------
For example, it's tempting to look at trivial binding like
x = y
and inline it unconditionally. But suppose x is used many times,
but this is the unique occurrence of y. Then inlining x would change
y's occurrence info, which breaks the invariant. It matters: y
might have a BIG rhs, which will now be dup'd at every occurrenc of x.
Even RHSs labelled InlineMe aren't caught here, because there might be
no benefit from inlining at the call site.
[Sept 01] Don't unconditionally inline a top-level thing, because that
can simply make a static thing into something built dynamically. E.g.
x = (a,b)
main = \s -> h x
[Remember that we treat \s as a one-shot lambda.] No point in
inlining x unless there is something interesting about the call site.
But watch out: if you aren't careful, some useful foldr/build fusion
can be lost (most notably in spectral/hartel/parstof) because the
foldr didn't see the build. Doing the dynamic allocation isn't a big
deal, in fact, but losing the fusion can be. But the right thing here
seems to be to do a callSiteInline based on the fact that there is
something interesting about the call site (it's strict). Hmm. That
seems a bit fragile.
Conclusion: inline top level things gaily until Phase 0 (the last
phase), at which point don't.
Note [pre/postInlineUnconditionally in gentle mode]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Even in gentle mode we want to do preInlineUnconditionally. The
reason is that too little clean-up happens if you don't inline
use-once things. Also a bit of inlining is *good* for full laziness;
it can expose constant sub-expressions. Example in
spectral/mandel/Mandel.hs, where the mandelset function gets a useful
let-float if you inline windowToViewport
However, as usual for Gentle mode, do not inline things that are
inactive in the intial stages. See Note [Gentle mode].
Note [Stable unfoldings and preInlineUnconditionally]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Surprisingly, do not pre-inline-unconditionally Ids with INLINE pragmas!
Example
{-# INLINE f #-}
f :: Eq a => a -> a
f x = ...
fInt :: Int -> Int
fInt = f Int dEqInt
...fInt...fInt...fInt...
Here f occurs just once, in the RHS of f1. But if we inline it there
we'll lose the opportunity to inline at each of fInt's call sites.
The INLINE pragma will only inline when the application is saturated
for exactly this reason; and we don't want PreInlineUnconditionally
to second-guess it. A live example is Trac #3736.
c.f. Note [Stable unfoldings and postInlineUnconditionally]
Note [Top-level botomming Ids]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don't inline top-level Ids that are bottoming, even if they are used just
once, because FloatOut has gone to some trouble to extract them out.
Inlining them won't make the program run faster!
Note [Do not inline CoVars unconditionally]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Coercion variables appear inside coercions, and the RHS of a let-binding
is a term (not a coercion) so we can't necessarily inline the latter in
the former.
-}
preInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
-- Precondition: rhs satisfies the let/app invariant
-- See Note [CoreSyn let/app invariant] in CoreSyn
-- Reason: we don't want to inline single uses, or discard dead bindings,
-- for unlifted, side-effect-full bindings
preInlineUnconditionally dflags env top_lvl bndr rhs
| not active = False
| isStableUnfolding (idUnfolding bndr) = False -- Note [Stable unfoldings and preInlineUnconditionally]
| isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids]
| not (gopt Opt_SimplPreInlining dflags) = False
| isCoVar bndr = False -- Note [Do not inline CoVars unconditionally]
| otherwise = case idOccInfo bndr of
IAmDead -> True -- Happens in ((\x.1) v)
OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
_ -> False
where
mode = getMode env
active = isActive (sm_phase mode) act
-- See Note [pre/postInlineUnconditionally in gentle mode]
act = idInlineActivation bndr
try_once in_lam int_cxt -- There's one textual occurrence
| not in_lam = isNotTopLevel top_lvl || early_phase
| otherwise = int_cxt && canInlineInLam rhs
-- Be very careful before inlining inside a lambda, because (a) we must not
-- invalidate occurrence information, and (b) we want to avoid pushing a
-- single allocation (here) into multiple allocations (inside lambda).
-- Inlining a *function* with a single *saturated* call would be ok, mind you.
-- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
-- where
-- is_cheap = exprIsCheap rhs
-- ok = is_cheap && int_cxt
-- int_cxt The context isn't totally boring
-- E.g. let f = \ab.BIG in \y. map f xs
-- Don't want to substitute for f, because then we allocate
-- its closure every time the \y is called
-- But: let f = \ab.BIG in \y. map (f y) xs
-- Now we do want to substitute for f, even though it's not
-- saturated, because we're going to allocate a closure for
-- (f y) every time round the loop anyhow.
-- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
-- so substituting rhs inside a lambda doesn't change the occ info.
-- Sadly, not quite the same as exprIsHNF.
canInlineInLam (Lit _) = True
canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e
canInlineInLam _ = False
-- not ticks. Counting ticks cannot be duplicated, and non-counting
-- ticks around a Lam will disappear anyway.
early_phase = case sm_phase mode of
Phase 0 -> False
_ -> True
-- If we don't have this early_phase test, consider
-- x = length [1,2,3]
-- The full laziness pass carefully floats all the cons cells to
-- top level, and preInlineUnconditionally floats them all back in.
-- Result is (a) static allocation replaced by dynamic allocation
-- (b) many simplifier iterations because this tickles
-- a related problem; only one inlining per pass
--
-- On the other hand, I have seen cases where top-level fusion is
-- lost if we don't inline top level thing (e.g. string constants)
-- Hence the test for phase zero (which is the phase for all the final
-- simplifications). Until phase zero we take no special notice of
-- top level things, but then we become more leery about inlining
-- them.
{-
************************************************************************
* *
postInlineUnconditionally
* *
************************************************************************
postInlineUnconditionally
~~~~~~~~~~~~~~~~~~~~~~~~~
@postInlineUnconditionally@ decides whether to unconditionally inline
a thing based on the form of its RHS; in particular if it has a
trivial RHS. If so, we can inline and discard the binding altogether.
NB: a loop breaker has must_keep_binding = True and non-loop-breakers
only have *forward* references. Hence, it's safe to discard the binding
NOTE: This isn't our last opportunity to inline. We're at the binding
site right now, and we'll get another opportunity when we get to the
ocurrence(s)
Note that we do this unconditional inlining only for trival RHSs.
Don't inline even WHNFs inside lambdas; doing so may simply increase
allocation when the function is called. This isn't the last chance; see
NOTE above.
NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
Because we don't even want to inline them into the RHS of constructor
arguments. See NOTE above
NB: At one time even NOINLINE was ignored here: if the rhs is trivial
it's best to inline it anyway. We often get a=E; b=a from desugaring,
with both a and b marked NOINLINE. But that seems incompatible with
our new view that inlining is like a RULE, so I'm sticking to the 'active'
story for now.
-}
postInlineUnconditionally
:: DynFlags -> SimplEnv -> TopLevelFlag
-> OutId -- The binder (an InId would be fine too)
-- (*not* a CoVar)
-> OccInfo -- From the InId
-> OutExpr
-> Unfolding
-> Bool
-- Precondition: rhs satisfies the let/app invariant
-- See Note [CoreSyn let/app invariant] in CoreSyn
-- Reason: we don't want to inline single uses, or discard dead bindings,
-- for unlifted, side-effect-full bindings
postInlineUnconditionally dflags env top_lvl bndr occ_info rhs unfolding
| not active = False
| isWeakLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline
-- because it might be referred to "earlier"
| isExportedId bndr = False
| isStableUnfolding unfolding = False -- Note [Stable unfoldings and postInlineUnconditionally]
| isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally]
| exprIsTrivial rhs = True
| otherwise
= case occ_info of
-- The point of examining occ_info here is that for *non-values*
-- that occur outside a lambda, the call-site inliner won't have
-- a chance (because it doesn't know that the thing
-- only occurs once). The pre-inliner won't have gotten
-- it either, if the thing occurs in more than one branch
-- So the main target is things like
-- let x = f y in
-- case v of
-- True -> case x of ...
-- False -> case x of ...
-- This is very important in practice; e.g. wheel-seive1 doubles
-- in allocation if you miss this out
OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue
-> smallEnoughToInline dflags unfolding -- Small enough to dup
-- ToDo: consider discount on smallEnoughToInline if int_cxt is true
--
-- NB: Do NOT inline arbitrarily big things, even if one_br is True
-- Reason: doing so risks exponential behaviour. We simplify a big
-- expression, inline it, and simplify it again. But if the
-- very same thing happens in the big expression, we get
-- exponential cost!
-- PRINCIPLE: when we've already simplified an expression once,
-- make sure that we only inline it if it's reasonably small.
&& (not in_lam ||
-- Outside a lambda, we want to be reasonably aggressive
-- about inlining into multiple branches of case
-- e.g. let x = <non-value>
-- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
-- Inlining can be a big win if C3 is the hot-spot, even if
-- the uses in C1, C2 are not 'interesting'
-- An example that gets worse if you add int_cxt here is 'clausify'
(isCheapUnfolding unfolding && int_cxt))
-- isCheap => acceptable work duplication; in_lam may be true
-- int_cxt to prevent us inlining inside a lambda without some
-- good reason. See the notes on int_cxt in preInlineUnconditionally
IAmDead -> True -- This happens; for example, the case_bndr during case of
-- known constructor: case (a,b) of x { (p,q) -> ... }
-- Here x isn't mentioned in the RHS, so we don't want to
-- create the (dead) let-binding let x = (a,b) in ...
_ -> False
-- Here's an example that we don't handle well:
-- let f = if b then Left (\x.BIG) else Right (\y.BIG)
-- in \y. ....case f of {...} ....
-- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
-- But
-- - We can't preInlineUnconditionally because that woud invalidate
-- the occ info for b.
-- - We can't postInlineUnconditionally because the RHS is big, and
-- that risks exponential behaviour
-- - We can't call-site inline, because the rhs is big
-- Alas!
where
active = isActive (sm_phase (getMode env)) (idInlineActivation bndr)
-- See Note [pre/postInlineUnconditionally in gentle mode]
{-
Note [Top level and postInlineUnconditionally]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't do postInlineUnconditionally for top-level things (even for
ones that are trivial):
* Doing so will inline top-level error expressions that have been
carefully floated out by FloatOut. More generally, it might
replace static allocation with dynamic.
* Even for trivial expressions there's a problem. Consider
{-# RULE "foo" forall (xs::[T]). reverse xs = ruggle xs #-}
blah xs = reverse xs
ruggle = sort
In one simplifier pass we might fire the rule, getting
blah xs = ruggle xs
but in *that* simplifier pass we must not do postInlineUnconditionally
on 'ruggle' because then we'll have an unbound occurrence of 'ruggle'
If the rhs is trivial it'll be inlined by callSiteInline, and then
the binding will be dead and discarded by the next use of OccurAnal
* There is less point, because the main goal is to get rid of local
bindings used in multiple case branches.
* The inliner should inline trivial things at call sites anyway.
Note [Stable unfoldings and postInlineUnconditionally]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do not do postInlineUnconditionally if the Id has an stable unfolding,
otherwise we lose the unfolding. Example
-- f has stable unfolding with rhs (e |> co)
-- where 'e' is big
f = e |> co
Then there's a danger we'll optimise to
f' = e
f = f' |> co
and now postInlineUnconditionally, losing the stable unfolding on f. Now f'
won't inline because 'e' is too big.
c.f. Note [Stable unfoldings and preInlineUnconditionally]
************************************************************************
* *
Rebuilding a lambda
* *
************************************************************************
-}
mkLam :: [OutBndr] -> OutExpr -> SimplCont -> SimplM OutExpr
-- mkLam tries three things
-- a) eta reduction, if that gives a trivial expression
-- b) eta expansion [only if there are some value lambdas]
mkLam [] body _cont
= return body
mkLam bndrs body cont
= do { dflags <- getDynFlags
; mkLam' dflags bndrs body }
where
mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
mkLam' dflags bndrs (Cast body co)
| not (any bad bndrs)
-- Note [Casts and lambdas]
= do { lam <- mkLam' dflags bndrs body
; return (mkCast lam (mkPiCos Representational bndrs co)) }
where
co_vars = tyCoVarsOfCo co
bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars
mkLam' dflags bndrs body@(Lam {})
= mkLam' dflags (bndrs ++ bndrs1) body1
where
(bndrs1, body1) = collectBinders body
mkLam' dflags bndrs (Tick t expr)
| tickishFloatable t
= mkTick t <$> mkLam' dflags bndrs expr
mkLam' dflags bndrs body
| gopt Opt_DoEtaReduction dflags
, Just etad_lam <- tryEtaReduce bndrs body
= do { tick (EtaReduction (head bndrs))
; return etad_lam }
| not (contIsRhs cont) -- See Note [Eta-expanding lambdas]
, gopt Opt_DoLambdaEtaExpansion dflags
, any isRuntimeVar bndrs
, let body_arity = exprEtaExpandArity dflags body
, body_arity > 0
= do { tick (EtaExpansion (head bndrs))
; return (mkLams bndrs (etaExpand body_arity body)) }
| otherwise
= return (mkLams bndrs body)
{-
Note [Eta expanding lambdas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In general we *do* want to eta-expand lambdas. Consider
f (\x -> case x of (a,b) -> \s -> blah)
where 's' is a state token, and hence can be eta expanded. This
showed up in the code for GHc.IO.Handle.Text.hPutChar, a rather
important function!
The eta-expansion will never happen unless we do it now. (Well, it's
possible that CorePrep will do it, but CorePrep only has a half-baked
eta-expander that can't deal with casts. So it's much better to do it
here.)
However, when the lambda is let-bound, as the RHS of a let, we have a
better eta-expander (in the form of tryEtaExpandRhs), so we don't
bother to try expansion in mkLam in that case; hence the contIsRhs
guard.
Note [Casts and lambdas]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider
(\x. (\y. e) `cast` g1) `cast` g2
There is a danger here that the two lambdas look separated, and the
full laziness pass might float an expression to between the two.
So this equation in mkLam' floats the g1 out, thus:
(\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
where x:tx.
In general, this floats casts outside lambdas, where (I hope) they
might meet and cancel with some other cast:
\x. e `cast` co ===> (\x. e) `cast` (tx -> co)
/\a. e `cast` co ===> (/\a. e) `cast` (/\a. co)
/\g. e `cast` co ===> (/\g. e) `cast` (/\g. co)
(if not (g `in` co))
Notice that it works regardless of 'e'. Originally it worked only
if 'e' was itself a lambda, but in some cases that resulted in
fruitless iteration in the simplifier. A good example was when
compiling Text.ParserCombinators.ReadPrec, where we had a definition
like (\x. Get `cast` g)
where Get is a constructor with nonzero arity. Then mkLam eta-expanded
the Get, and the next iteration eta-reduced it, and then eta-expanded
it again.
Note also the side condition for the case of coercion binders.
It does not make sense to transform
/\g. e `cast` g ==> (/\g.e) `cast` (/\g.g)
because the latter is not well-kinded.
************************************************************************
* *
Eta expansion
* *
************************************************************************
-}
tryEtaExpandRhs :: SimplEnv -> OutId -> OutExpr -> SimplM (Arity, OutExpr)
-- See Note [Eta-expanding at let bindings]
tryEtaExpandRhs env bndr rhs
= do { dflags <- getDynFlags
; (new_arity, new_rhs) <- try_expand dflags
; WARN( new_arity < old_id_arity,
(ptext (sLit "Arity decrease:") <+> (ppr bndr <+> ppr old_id_arity
<+> ppr old_arity <+> ppr new_arity) $$ ppr new_rhs) )
-- Note [Arity decrease] in Simplify
return (new_arity, new_rhs) }
where
try_expand dflags
| exprIsTrivial rhs
= return (exprArity rhs, rhs)
| sm_eta_expand (getMode env) -- Provided eta-expansion is on
, let new_arity1 = findRhsArity dflags bndr rhs old_arity
new_arity2 = idCallArity bndr
new_arity = max new_arity1 new_arity2
, new_arity > old_arity -- And the current manifest arity isn't enough
= do { tick (EtaExpansion bndr)
; return (new_arity, etaExpand new_arity rhs) }
| otherwise
= return (old_arity, rhs)
old_arity = exprArity rhs -- See Note [Do not expand eta-expand PAPs]
old_id_arity = idArity bndr
{-
Note [Eta-expanding at let bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We now eta expand at let-bindings, which is where the payoff comes.
The most significant thing is that we can do a simple arity analysis
(in CoreArity.findRhsArity), which we can't do for free-floating lambdas
One useful consequence of not eta-expanding lambdas is this example:
genMap :: C a => ...
{-# INLINE genMap #-}
genMap f xs = ...
myMap :: D a => ...
{-# INLINE myMap #-}
myMap = genMap
Notice that 'genMap' should only inline if applied to two arguments.
In the stable unfolding for myMap we'll have the unfolding
(\d -> genMap Int (..d..))
We do not want to eta-expand to
(\d f xs -> genMap Int (..d..) f xs)
because then 'genMap' will inline, and it really shouldn't: at least
as far as the programmer is concerned, it's not applied to two
arguments!
Note [Do not eta-expand PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to have old_arity = manifestArity rhs, which meant that we
would eta-expand even PAPs. But this gives no particular advantage,
and can lead to a massive blow-up in code size, exhibited by Trac #9020.
Suppose we have a PAP
foo :: IO ()
foo = returnIO ()
Then we can eta-expand do
foo = (\eta. (returnIO () |> sym g) eta) |> g
where
g :: IO () ~ State# RealWorld -> (# State# RealWorld, () #)
But there is really no point in doing this, and it generates masses of
coercions and whatnot that eventually disappear again. For T9020, GHC
allocated 6.6G beore, and 0.8G afterwards; and residency dropped from
1.8G to 45M.
But note that this won't eta-expand, say
f = \g -> map g
Does it matter not eta-expanding such functions? I'm not sure. Perhaps
strictness analysis will have less to bite on?
************************************************************************
* *
\subsection{Floating lets out of big lambdas}
* *
************************************************************************
Note [Floating and type abstraction]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:
x = /\a. C e1 e2
We'd like to float this to
y1 = /\a. e1
y2 = /\a. e2
x = /\a. C (y1 a) (y2 a)
for the usual reasons: we want to inline x rather vigorously.
You may think that this kind of thing is rare. But in some programs it is
common. For example, if you do closure conversion you might get:
data a :-> b = forall e. (e -> a -> b) :$ e
f_cc :: forall a. a :-> a
f_cc = /\a. (\e. id a) :$ ()
Now we really want to inline that f_cc thing so that the
construction of the closure goes away.
So I have elaborated simplLazyBind to understand right-hand sides that look
like
/\ a1..an. body
and treat them specially. The real work is done in SimplUtils.abstractFloats,
but there is quite a bit of plumbing in simplLazyBind as well.
The same transformation is good when there are lets in the body:
/\abc -> let(rec) x = e in b
==>
let(rec) x' = /\abc -> let x = x' a b c in e
in
/\abc -> let x = x' a b c in b
This is good because it can turn things like:
let f = /\a -> letrec g = ... g ... in g
into
letrec g' = /\a -> ... g' a ...
in
let f = /\ a -> g' a
which is better. In effect, it means that big lambdas don't impede
let-floating.
This optimisation is CRUCIAL in eliminating the junk introduced by
desugaring mutually recursive definitions. Don't eliminate it lightly!
[May 1999] If we do this transformation *regardless* then we can
end up with some pretty silly stuff. For example,
let
st = /\ s -> let { x1=r1 ; x2=r2 } in ...
in ..
becomes
let y1 = /\s -> r1
y2 = /\s -> r2
st = /\s -> ...[y1 s/x1, y2 s/x2]
in ..
Unless the "..." is a WHNF there is really no point in doing this.
Indeed it can make things worse. Suppose x1 is used strictly,
and is of the form
x1* = case f y of { (a,b) -> e }
If we abstract this wrt the tyvar we then can't do the case inline
as we would normally do.
That's why the whole transformation is part of the same process that
floats let-bindings and constructor arguments out of RHSs. In particular,
it is guarded by the doFloatFromRhs call in simplLazyBind.
Note [Which type variables to abstract over]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Abstract only over the type variables free in the rhs wrt which the
new binding is abstracted. Note that
* The naive approach of abstracting wrt the
tyvars free in the Id's /type/ fails. Consider:
/\ a b -> let t :: (a,b) = (e1, e2)
x :: a = fst t
in ...
Here, b isn't free in x's type, but we must nevertheless
abstract wrt b as well, because t's type mentions b.
Since t is floated too, we'd end up with the bogus:
poly_t = /\ a b -> (e1, e2)
poly_x = /\ a -> fst (poly_t a *b*)
* We must do closeOverKinds. Example (Trac #10934):
f = /\k (f:k->*) (a:k). let t = AccFailure @ (f a) in ...
Here we want to float 't', but we must remember to abstract over
'k' as well, even though it is not explicitly mentioned in the RHS,
otherwise we get
t = /\ (f:k->*) (a:k). AccFailure @ (f a)
which is obviously bogus.
-}
abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
abstractFloats main_tvs body_env body
= ASSERT( notNull body_floats )
do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
; return (float_binds, CoreSubst.substExpr (text "abstract_floats1") subst body) }
where
main_tv_set = mkVarSet main_tvs
body_floats = getFloatBinds body_env
empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
abstract subst (NonRec id rhs)
= do { (poly_id, poly_app) <- mk_poly tvs_here id
; let poly_rhs = mkLams tvs_here rhs'
subst' = CoreSubst.extendIdSubst subst id poly_app
; return (subst', (NonRec poly_id poly_rhs)) }
where
rhs' = CoreSubst.substExpr (text "abstract_floats2") subst rhs
-- tvs_here: see Note [Which type variables to abstract over]
tvs_here = varSetElemsKvsFirst $
intersectVarSet main_tv_set $
closeOverKinds $
exprSomeFreeVars isTyVar rhs'
abstract subst (Rec prs)
= do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
poly_rhss = [mkLams tvs_here (CoreSubst.substExpr (text "abstract_floats3") subst' rhs)
| rhs <- rhss]
; return (subst', Rec (poly_ids `zip` poly_rhss)) }
where
(ids,rhss) = unzip prs
-- For a recursive group, it's a bit of a pain to work out the minimal
-- set of tyvars over which to abstract:
-- /\ a b c. let x = ...a... in
-- letrec { p = ...x...q...
-- q = .....p...b... } in
-- ...
-- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
-- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.
-- Since it's a pain, we just use the whole set, which is always safe
--
-- If you ever want to be more selective, remember this bizarre case too:
-- x::a = x
-- Here, we must abstract 'x' over 'a'.
tvs_here = sortQuantVars main_tvs
mk_poly tvs_here var
= do { uniq <- getUniqueM
; let poly_name = setNameUnique (idName var) uniq -- Keep same name
poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
mkLocalId poly_name poly_ty
; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
-- In the olden days, it was crucial to copy the occInfo of the original var,
-- because we were looking at occurrence-analysed but as yet unsimplified code!
-- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
-- at already simplified code, so it doesn't matter
--
-- It's even right to retain single-occurrence or dead-var info:
-- Suppose we started with /\a -> let x = E in B
-- where x occurs once in B. Then we transform to:
-- let x' = /\a -> E in /\a -> let x* = x' a in B
-- where x* has an INLINE prag on it. Now, once x* is inlined,
-- the occurrences of x' will be just the occurrences originally
-- pinned on x.
{-
Note [Abstract over coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
type variable a. Rather than sort this mess out, we simply bale out and abstract
wrt all the type variables if any of them are coercion variables.
Historical note: if you use let-bindings instead of a substitution, beware of this:
-- Suppose we start with:
--
-- x = /\ a -> let g = G in E
--
-- Then we'll float to get
--
-- x = let poly_g = /\ a -> G
-- in /\ a -> let g = poly_g a in E
--
-- But now the occurrence analyser will see just one occurrence
-- of poly_g, not inside a lambda, so the simplifier will
-- PreInlineUnconditionally poly_g back into g! Badk to square 1!
-- (I used to think that the "don't inline lone occurrences" stuff
-- would stop this happening, but since it's the *only* occurrence,
-- PreInlineUnconditionally kicks in first!)
--
-- Solution: put an INLINE note on g's RHS, so that poly_g seems
-- to appear many times. (NB: mkInlineMe eliminates
-- such notes on trivial RHSs, so do it manually.)
************************************************************************
* *
prepareAlts
* *
************************************************************************
prepareAlts tries these things:
1. Eliminate alternatives that cannot match, including the
DEFAULT alternative.
2. If the DEFAULT alternative can match only one possible constructor,
then make that constructor explicit.
e.g.
case e of x { DEFAULT -> rhs }
===>
case e of x { (a,b) -> rhs }
where the type is a single constructor type. This gives better code
when rhs also scrutinises x or e.
3. Returns a list of the constructors that cannot holds in the
DEFAULT alternative (if there is one)
Here "cannot match" includes knowledge from GADTs
It's a good idea to do this stuff before simplifying the alternatives, to
avoid simplifying alternatives we know can't happen, and to come up with
the list of constructors that are handled, to put into the IdInfo of the
case binder, for use when simplifying the alternatives.
Eliminating the default alternative in (1) isn't so obvious, but it can
happen:
data Colour = Red | Green | Blue
f x = case x of
Red -> ..
Green -> ..
DEFAULT -> h x
h y = case y of
Blue -> ..
DEFAULT -> [ case y of ... ]
If we inline h into f, the default case of the inlined h can't happen.
If we don't notice this, we may end up filtering out *all* the cases
of the inner case y, which give us nowhere to go!
-}
prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
-- The returned alternatives can be empty, none are possible
prepareAlts scrut case_bndr' alts
-- Case binder is needed just for its type. Note that as an
-- OutId, it has maximum information; this is important.
-- Test simpl013 is an example
= do { us <- getUniquesM
; let (imposs_deflt_cons', refined_deflt, alts')
= filterAlts us (varType case_bndr') imposs_cons alts
(combining_done, imposs_deflt_cons'', alts'')
= combineIdenticalAlts imposs_deflt_cons' alts'
; when refined_deflt $ tick (FillInCaseDefault case_bndr')
; when combining_done $ tick (AltMerge case_bndr')
; return (imposs_deflt_cons'', alts'') }
where
imposs_cons = case scrut of
Var v -> otherCons (idUnfolding v)
_ -> []
{- Note [Combine identical alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If several alternatives are identical, merge them into a single
DEFAULT alternative. I've occasionally seen this making a big
difference:
case e of =====> case e of
C _ -> f x D v -> ....v....
D v -> ....v.... DEFAULT -> f x
DEFAULT -> f x
The point is that we merge common RHSs, at least for the DEFAULT case.
[One could do something more elaborate but I've never seen it needed.]
To avoid an expensive test, we just merge branches equal to the *first*
alternative; this picks up the common cases
a) all branches equal
b) some branches equal to the DEFAULT (which occurs first)
The case where Combine Identical Alternatives transformation showed up
was like this (base/Foreign/C/Err/Error.lhs):
x | p `is` 1 -> e1
| p `is` 2 -> e2
...etc...
where @is@ was something like
p `is` n = p /= (-1) && p == n
This gave rise to a horrible sequence of cases
case p of
(-1) -> $j p
1 -> e1
DEFAULT -> $j p
and similarly in cascade for all the join points!
NB: it's important that all this is done in [InAlt], *before* we work
on the alternatives themselves, because Simpify.simplAlt may zap the
occurrence info on the binders in the alternatives, which in turn
defeats combineIdenticalAlts (see Trac #7360).
Note [Care with impossible-constructors when combining alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have (Trac #10538)
data T = A | B | C
... case x::T of
DEFAULT -> e1
A -> e2
B -> e1
When calling combineIdentialAlts, we'll have computed that the "impossible
constructors" for the DEFAULT alt is {A,B}, since if x is A or B we'll
take the other alternatives. But suppose we combine B into the DEFAULT,
to get
... case x::T of
DEFAULT -> e1
A -> e2
Then we must be careful to trim the impossible constructors to just {A},
else we risk compiling 'e1' wrong!
-}
combineIdenticalAlts :: [AltCon] -> [InAlt] -> (Bool, [AltCon], [InAlt])
-- See Note [Combine identical alternatives]
-- See Note [Care with impossible-constructors when combining alternatives]
-- True <=> we did some combining, result is a single DEFAULT alternative
combineIdenticalAlts imposs_cons ((_con1,bndrs1,rhs1) : con_alts)
| all isDeadBinder bndrs1 -- Remember the default
, not (null eliminated_alts) -- alternative comes first
= (True, imposs_cons', deflt_alt : filtered_alts)
where
(eliminated_alts, filtered_alts) = partition identical_to_alt1 con_alts
deflt_alt = (DEFAULT, [], mkTicks (concat tickss) rhs1)
imposs_cons' = imposs_cons `minusList` map fstOf3 eliminated_alts
cheapEqTicked e1 e2 = cheapEqExpr' tickishFloatable e1 e2
identical_to_alt1 (_con,bndrs,rhs)
= all isDeadBinder bndrs && rhs `cheapEqTicked` rhs1
tickss = map (stripTicksT tickishFloatable . thirdOf3) eliminated_alts
combineIdenticalAlts imposs_cons alts
= (False, imposs_cons, alts)
{-
************************************************************************
* *
mkCase
* *
************************************************************************
mkCase tries these things
1. Merge Nested Cases
case e of b { ==> case e of b {
p1 -> rhs1 p1 -> rhs1
... ...
pm -> rhsm pm -> rhsm
_ -> case b of b' { pn -> let b'=b in rhsn
pn -> rhsn ...
... po -> let b'=b in rhso
po -> rhso _ -> let b'=b in rhsd
_ -> rhsd
}
which merges two cases in one case when -- the default alternative of
the outer case scrutises the same variable as the outer case. This
transformation is called Case Merging. It avoids that the same
variable is scrutinised multiple times.
2. Eliminate Identity Case
case e of ===> e
True -> True;
False -> False
and similar friends.
-}
mkCase, mkCase1, mkCase2
:: DynFlags
-> OutExpr -> OutId
-> OutType -> [OutAlt] -- Alternatives in standard (increasing) order
-> SimplM OutExpr
--------------------------------------------------
-- 1. Merge Nested Cases
--------------------------------------------------
mkCase dflags scrut outer_bndr alts_ty ((DEFAULT, _, deflt_rhs) : outer_alts)
| gopt Opt_CaseMerge dflags
, (ticks, Case (Var inner_scrut_var) inner_bndr _ inner_alts)
<- stripTicksTop tickishFloatable deflt_rhs
, inner_scrut_var == outer_bndr
= do { tick (CaseMerge outer_bndr)
; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args )
(con, args, wrap_rhs rhs)
-- Simplifier's no-shadowing invariant should ensure
-- that outer_bndr is not shadowed by the inner patterns
wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs
-- The let is OK even for unboxed binders,
wrapped_alts | isDeadBinder inner_bndr = inner_alts
| otherwise = map wrap_alt inner_alts
merged_alts = mergeAlts outer_alts wrapped_alts
-- NB: mergeAlts gives priority to the left
-- case x of
-- A -> e1
-- DEFAULT -> case x of
-- A -> e2
-- B -> e3
-- When we merge, we must ensure that e1 takes
-- precedence over e2 as the value for A!
; fmap (mkTicks ticks) $
mkCase1 dflags scrut outer_bndr alts_ty merged_alts
}
-- Warning: don't call mkCase recursively!
-- Firstly, there's no point, because inner alts have already had
-- mkCase applied to them, so they won't have a case in their default
-- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
-- in munge_rhs may put a case into the DEFAULT branch!
mkCase dflags scrut bndr alts_ty alts = mkCase1 dflags scrut bndr alts_ty alts
--------------------------------------------------
-- 2. Eliminate Identity Case
--------------------------------------------------
mkCase1 _dflags scrut case_bndr _ alts@((_,_,rhs1) : _) -- Identity case
| all identity_alt alts
= do { tick (CaseIdentity case_bndr)
; return (mkTicks ticks $ re_cast scrut rhs1) }
where
ticks = concatMap (stripTicksT tickishFloatable . thirdOf3) (tail alts)
identity_alt (con, args, rhs) = check_eq rhs con args
check_eq (Cast rhs co) con args
= not (any (`elemVarSet` tyCoVarsOfCo co) args) && check_eq rhs con args
-- See Note [RHS casts]
check_eq (Lit lit) (LitAlt lit') _ = lit == lit'
check_eq (Var v) _ _ | v == case_bndr = True
check_eq (Var v) (DataAlt con) [] = v == dataConWorkId con
-- Optimisation only
check_eq (Tick t e) alt args = tickishFloatable t &&
check_eq e alt args
check_eq rhs (DataAlt con) args = cheapEqExpr' tickishFloatable rhs $
mkConApp con (arg_tys ++
varsToCoreExprs args)
check_eq _ _ _ = False
arg_tys = map Type (tyConAppArgs (idType case_bndr))
-- Note [RHS casts]
-- ~~~~~~~~~~~~~~~~
-- We've seen this:
-- case e of x { _ -> x `cast` c }
-- And we definitely want to eliminate this case, to give
-- e `cast` c
-- So we throw away the cast from the RHS, and reconstruct
-- it at the other end. All the RHS casts must be the same
-- if (all identity_alt alts) holds.
--
-- Don't worry about nested casts, because the simplifier combines them
re_cast scrut (Cast rhs co) = Cast (re_cast scrut rhs) co
re_cast scrut _ = scrut
mkCase1 dflags scrut bndr alts_ty alts = mkCase2 dflags scrut bndr alts_ty alts
--------------------------------------------------
-- Catch-all
--------------------------------------------------
mkCase2 _dflags scrut bndr alts_ty alts
= return (Case scrut bndr alts_ty alts)
{-
Note [Dead binders]
~~~~~~~~~~~~~~~~~~~~
Note that dead-ness is maintained by the simplifier, so that it is
accurate after simplification as well as before.
Note [Cascading case merge]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Case merging should cascade in one sweep, because it
happens bottom-up
case e of a {
DEFAULT -> case a of b
DEFAULT -> case b of c {
DEFAULT -> e
A -> ea
B -> eb
C -> ec
==>
case e of a {
DEFAULT -> case a of b
DEFAULT -> let c = b in e
A -> let c = b in ea
B -> eb
C -> ec
==>
case e of a {
DEFAULT -> let b = a in let c = b in e
A -> let b = a in let c = b in ea
B -> let b = a in eb
C -> ec
However here's a tricky case that we still don't catch, and I don't
see how to catch it in one pass:
case x of c1 { I# a1 ->
case a1 of c2 ->
0 -> ...
DEFAULT -> case x of c3 { I# a2 ->
case a2 of ...
After occurrence analysis (and its binder-swap) we get this
case x of c1 { I# a1 ->
let x = c1 in -- Binder-swap addition
case a1 of c2 ->
0 -> ...
DEFAULT -> case x of c3 { I# a2 ->
case a2 of ...
When we simplify the inner case x, we'll see that
x=c1=I# a1. So we'll bind a2 to a1, and get
case x of c1 { I# a1 ->
case a1 of c2 ->
0 -> ...
DEFAULT -> case a1 of ...
This is corect, but we can't do a case merge in this sweep
because c2 /= a1. Reason: the binding c1=I# a1 went inwards
without getting changed to c1=I# c2.
I don't think this is worth fixing, even if I knew how. It'll
all come out in the next pass anyway.
-}
| alexander-at-github/eta | compiler/ETA/SimplCore/SimplUtils.hs | bsd-3-clause | 82,879 | 0 | 18 | 24,955 | 8,743 | 4,679 | 4,064 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Data.Aeson.Parser.Unescape
(
unescapeText
) where
#ifdef CFFI
import Data.Aeson.Parser.UnescapeFFI (unescapeText)
#else
import Data.Aeson.Parser.UnescapePure (unescapeText)
#endif
| dmjio/aeson | src/Data/Aeson/Parser/Unescape.hs | bsd-3-clause | 217 | 0 | 5 | 29 | 29 | 21 | 8 | 5 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>Groovy Support</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/groovy/src/main/javahelp/org/zaproxy/zap/extension/groovy/resources/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 959 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ms-MY">
<title>Encode/Decode/Hash Add-on</title>
<maps>
<homeID>encoder</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/encoder/src/main/javahelp/org/zaproxy/addon/encoder/resources/help_ms_MY/helpset_ms_MY.hs | apache-2.0 | 974 | 77 | 69 | 156 | 419 | 212 | 207 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Prompt.RunOrRaise
-- Copyright : (C) 2008 Justin Bogner
-- License : BSD3
--
-- Maintainer : mail@justinbogner.com
-- Stability : unstable
-- Portability : unportable
--
-- A prompt for XMonad which will run a program, open a file,
-- or raise an already running program, depending on context.
--
-----------------------------------------------------------------------------
module XMonad.Prompt.RunOrRaise
( -- * Usage
-- $usage
runOrRaisePrompt,
RunOrRaisePrompt,
) where
import XMonad hiding (config)
import XMonad.Prompt
import XMonad.Prompt.Shell
import XMonad.Actions.WindowGo (runOrRaise)
import XMonad.Util.Run (runProcessWithInput)
import Control.Exception as E
import Control.Monad (liftM, liftM2)
import System.Directory (doesDirectoryExist, doesFileExist, executable, getPermissions)
econst :: Monad m => a -> IOException -> m a
econst = const . return
{- $usage
1. In your @~\/.xmonad\/xmonad.hs@:
> import XMonad.Prompt
> import XMonad.Prompt.RunOrRaise
2. In your keybindings add something like:
> , ((modm .|. controlMask, xK_x), runOrRaisePrompt def)
For detailed instruction on editing the key binding see
"XMonad.Doc.Extending#Editing_key_bindings". -}
data RunOrRaisePrompt = RRP
instance XPrompt RunOrRaisePrompt where
showXPrompt RRP = "Run or Raise: "
runOrRaisePrompt :: XPConfig -> X ()
runOrRaisePrompt c = do cmds <- io getCommands
mkXPrompt RRP c (getShellCompl cmds) open
open :: String -> X ()
open path = io (isNormalFile path) >>= \b ->
if b
then spawn $ "xdg-open \"" ++ path ++ "\""
else uncurry runOrRaise . getTarget $ path
where
isNormalFile f = exists f >>= \e -> if e then notExecutable f else return False
exists f = fmap or $ sequence [doesFileExist f,doesDirectoryExist f]
notExecutable = fmap (not . executable) . getPermissions
getTarget x = (x,isApp x)
isApp :: String -> Query Bool
isApp "firefox" = className =? "Firefox-bin" <||> className =? "Firefox"
isApp "thunderbird" = className =? "Thunderbird-bin" <||> className =? "Thunderbird"
isApp x = liftM2 (==) pid $ pidof x
pidof :: String -> Query Int
pidof x = io $ (runProcessWithInput "pidof" [x] [] >>= readIO) `E.catch` econst 0
pid :: Query Int
pid = ask >>= (\w -> liftX $ withDisplay $ \d -> getPID d w)
where getPID d w = getAtom "_NET_WM_PID" >>= \a -> io $
liftM getPID' (getWindowProperty32 d a w)
getPID' (Just (x:_)) = fromIntegral x
getPID' (Just []) = -1
getPID' (Nothing) = -1
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Prompt/RunOrRaise.hs | bsd-2-clause | 2,722 | 0 | 12 | 593 | 661 | 355 | 306 | 42 | 3 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
module Yesod.Core.Content
( -- * Content
Content (..)
, emptyContent
, ToContent (..)
, ToFlushBuilder (..)
-- * Mime types
-- ** Data type
, ContentType
, typeHtml
, typePlain
, typeJson
, typeXml
, typeAtom
, typeRss
, typeJpeg
, typePng
, typeGif
, typeSvg
, typeJavascript
, typeCss
, typeFlv
, typeOgv
, typeOctet
-- * Utilities
, simpleContentType
, contentTypeTypes
-- * Evaluation strategy
, DontFullyEvaluate (..)
-- * Representations
, TypedContent (..)
, ToTypedContent (..)
, HasContentType (..)
-- ** Specific content types
, RepHtml
, RepJson (..)
, RepPlain (..)
, RepXml (..)
-- ** Smart constructors
, repJson
, repPlain
, repXml
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.Text.Lazy (Text, pack)
import qualified Data.Text as T
import Control.Monad (liftM)
import Blaze.ByteString.Builder (Builder, fromByteString, fromLazyByteString)
import Data.Monoid (mempty)
import Text.Hamlet (Html)
import Text.Blaze.Html.Renderer.Utf8 (renderHtmlBuilder)
import Data.Conduit (Source, Flush (Chunk), ResumableSource, mapOutput)
import Control.Monad.Trans.Resource (ResourceT)
import Data.Conduit.Internal (ResumableSource (ResumableSource))
import qualified Data.Conduit.Internal as CI
import qualified Data.Aeson as J
#if MIN_VERSION_aeson(0, 7, 0)
import Data.Aeson.Encode (encodeToTextBuilder)
#else
import Data.Aeson.Encode (fromValue)
#endif
import qualified Blaze.ByteString.Builder.Char.Utf8 as Blaze
import Data.Text.Lazy.Builder (toLazyText)
import Yesod.Core.Types
import Text.Lucius (Css, renderCss)
import Text.Julius (Javascript, unJavascript)
-- | Zero-length enumerator.
emptyContent :: Content
emptyContent = ContentBuilder mempty $ Just 0
-- | Anything which can be converted into 'Content'. Most of the time, you will
-- want to use the 'ContentBuilder' constructor. An easier approach will be to use
-- a pre-defined 'toContent' function, such as converting your data into a lazy
-- bytestring and then calling 'toContent' on that.
--
-- Please note that the built-in instances for lazy data structures ('String',
-- lazy 'L.ByteString', lazy 'Text' and 'Html') will not automatically include
-- the content length for the 'ContentBuilder' constructor.
class ToContent a where
toContent :: a -> Content
instance ToContent Content where
toContent = id
instance ToContent Builder where
toContent = flip ContentBuilder Nothing
instance ToContent B.ByteString where
toContent bs = ContentBuilder (fromByteString bs) $ Just $ B.length bs
instance ToContent L.ByteString where
toContent = flip ContentBuilder Nothing . fromLazyByteString
instance ToContent T.Text where
toContent = toContent . Blaze.fromText
instance ToContent Text where
toContent = toContent . Blaze.fromLazyText
instance ToContent String where
toContent = toContent . Blaze.fromString
instance ToContent Html where
toContent bs = ContentBuilder (renderHtmlBuilder bs) Nothing
instance ToContent () where
toContent () = toContent B.empty
instance ToContent (ContentType, Content) where
toContent = snd
instance ToContent TypedContent where
toContent (TypedContent _ c) = c
instance ToContent Css where
toContent = toContent . renderCss
instance ToContent Javascript where
toContent = toContent . toLazyText . unJavascript
instance ToFlushBuilder builder => ToContent (CI.Pipe () () builder () (ResourceT IO) ()) where
toContent src = ContentSource $ CI.ConduitM (CI.mapOutput toFlushBuilder src >>=)
instance ToFlushBuilder builder => ToContent (Source (ResourceT IO) builder) where
toContent src = ContentSource $ mapOutput toFlushBuilder src
instance ToFlushBuilder builder => ToContent (ResumableSource (ResourceT IO) builder) where
toContent (ResumableSource src _) = toContent src
-- | A class for all data which can be sent in a streaming response. Note that
-- for textual data, instances must use UTF-8 encoding.
--
-- Since 1.2.0
class ToFlushBuilder a where toFlushBuilder :: a -> Flush Builder
instance ToFlushBuilder (Flush Builder) where toFlushBuilder = id
instance ToFlushBuilder Builder where toFlushBuilder = Chunk
instance ToFlushBuilder (Flush B.ByteString) where toFlushBuilder = fmap fromByteString
instance ToFlushBuilder B.ByteString where toFlushBuilder = Chunk . fromByteString
instance ToFlushBuilder (Flush L.ByteString) where toFlushBuilder = fmap fromLazyByteString
instance ToFlushBuilder L.ByteString where toFlushBuilder = Chunk . fromLazyByteString
instance ToFlushBuilder (Flush Text) where toFlushBuilder = fmap Blaze.fromLazyText
instance ToFlushBuilder Text where toFlushBuilder = Chunk . Blaze.fromLazyText
instance ToFlushBuilder (Flush T.Text) where toFlushBuilder = fmap Blaze.fromText
instance ToFlushBuilder T.Text where toFlushBuilder = Chunk . Blaze.fromText
instance ToFlushBuilder (Flush String) where toFlushBuilder = fmap Blaze.fromString
instance ToFlushBuilder String where toFlushBuilder = Chunk . Blaze.fromString
instance ToFlushBuilder (Flush Html) where toFlushBuilder = fmap renderHtmlBuilder
instance ToFlushBuilder Html where toFlushBuilder = Chunk . renderHtmlBuilder
repJson :: ToContent a => a -> RepJson
repJson = RepJson . toContent
repPlain :: ToContent a => a -> RepPlain
repPlain = RepPlain . toContent
repXml :: ToContent a => a -> RepXml
repXml = RepXml . toContent
class ToTypedContent a => HasContentType a where
getContentType :: Monad m => m a -> ContentType
instance HasContentType RepJson where
getContentType _ = typeJson
deriving instance ToContent RepJson
instance HasContentType RepPlain where
getContentType _ = typePlain
deriving instance ToContent RepPlain
instance HasContentType RepXml where
getContentType _ = typeXml
deriving instance ToContent RepXml
typeHtml :: ContentType
typeHtml = "text/html; charset=utf-8"
typePlain :: ContentType
typePlain = "text/plain; charset=utf-8"
typeJson :: ContentType
typeJson = "application/json; charset=utf-8"
typeXml :: ContentType
typeXml = "text/xml"
typeAtom :: ContentType
typeAtom = "application/atom+xml"
typeRss :: ContentType
typeRss = "application/rss+xml"
typeJpeg :: ContentType
typeJpeg = "image/jpeg"
typePng :: ContentType
typePng = "image/png"
typeGif :: ContentType
typeGif = "image/gif"
typeSvg :: ContentType
typeSvg = "image/svg+xml"
typeJavascript :: ContentType
typeJavascript = "text/javascript; charset=utf-8"
typeCss :: ContentType
typeCss = "text/css; charset=utf-8"
typeFlv :: ContentType
typeFlv = "video/x-flv"
typeOgv :: ContentType
typeOgv = "video/ogg"
typeOctet :: ContentType
typeOctet = "application/octet-stream"
-- | Removes \"extra\" information at the end of a content type string. In
-- particular, removes everything after the semicolon, if present.
--
-- For example, \"text/html; charset=utf-8\" is commonly used to specify the
-- character encoding for HTML data. This function would return \"text/html\".
simpleContentType :: ContentType -> ContentType
simpleContentType = fst . B.breakByte 59 -- 59 == ;
-- Give just the media types as a pair.
-- For example, \"text/html; charset=utf-8\" returns ("text", "html")
contentTypeTypes :: ContentType -> (B.ByteString, B.ByteString)
contentTypeTypes ct = (main, fst $ B.breakByte semicolon (tailEmpty sub))
where
tailEmpty x = if B.null x then "" else B.tail x
(main, sub) = B.breakByte slash ct
slash = 47
semicolon = 59
instance HasContentType a => HasContentType (DontFullyEvaluate a) where
getContentType = getContentType . liftM unDontFullyEvaluate
instance ToContent a => ToContent (DontFullyEvaluate a) where
toContent (DontFullyEvaluate a) = ContentDontEvaluate $ toContent a
instance ToContent J.Value where
toContent = flip ContentBuilder Nothing
. Blaze.fromLazyText
. toLazyText
#if MIN_VERSION_aeson(0, 7, 0)
. encodeToTextBuilder
#else
. fromValue
#endif
instance HasContentType J.Value where
getContentType _ = typeJson
instance HasContentType Html where
getContentType _ = typeHtml
instance HasContentType Text where
getContentType _ = typePlain
instance HasContentType T.Text where
getContentType _ = typePlain
instance HasContentType Css where
getContentType _ = typeCss
instance HasContentType Javascript where
getContentType _ = typeJavascript
-- | Any type which can be converted to 'TypedContent'.
--
-- Since 1.2.0
class ToContent a => ToTypedContent a where
toTypedContent :: a -> TypedContent
instance ToTypedContent TypedContent where
toTypedContent = id
instance ToTypedContent () where
toTypedContent () = TypedContent typePlain (toContent ())
instance ToTypedContent (ContentType, Content) where
toTypedContent (ct, content) = TypedContent ct content
instance ToTypedContent RepJson where
toTypedContent (RepJson c) = TypedContent typeJson c
instance ToTypedContent RepPlain where
toTypedContent (RepPlain c) = TypedContent typePlain c
instance ToTypedContent RepXml where
toTypedContent (RepXml c) = TypedContent typeXml c
instance ToTypedContent J.Value where
toTypedContent v = TypedContent typeJson (toContent v)
instance ToTypedContent Html where
toTypedContent h = TypedContent typeHtml (toContent h)
instance ToTypedContent T.Text where
toTypedContent t = TypedContent typePlain (toContent t)
instance ToTypedContent [Char] where
toTypedContent = toTypedContent . pack
instance ToTypedContent Text where
toTypedContent t = TypedContent typePlain (toContent t)
instance ToTypedContent a => ToTypedContent (DontFullyEvaluate a) where
toTypedContent (DontFullyEvaluate a) =
let TypedContent ct c = toTypedContent a
in TypedContent ct (ContentDontEvaluate c)
instance ToTypedContent Css where
toTypedContent = TypedContent typeCss . toContent
instance ToTypedContent Javascript where
toTypedContent = TypedContent typeJavascript . toContent
| ygale/yesod | yesod-core/Yesod/Core/Content.hs | mit | 10,375 | 0 | 10 | 1,776 | 2,324 | 1,269 | 1,055 | 221 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_HADDOCK hide #-}
module Distribution.Compat.Environment
( getEnvironment, lookupEnv, setEnv, unsetEnv )
where
import Prelude ()
import qualified Prelude
import Distribution.Compat.Prelude
#ifndef mingw32_HOST_OS
#if __GLASGOW_HASKELL__ < 708
import Foreign.C.Error (throwErrnoIf_)
#endif
#endif
import qualified System.Environment as System
#if __GLASGOW_HASKELL__ >= 706
import System.Environment (lookupEnv)
#if __GLASGOW_HASKELL__ >= 708
import System.Environment (unsetEnv)
#endif
#else
import Distribution.Compat.Exception (catchIO)
#endif
import Distribution.Compat.Stack
#ifdef mingw32_HOST_OS
import Foreign.C
import GHC.Windows
#else
import Foreign.C.Types
import Foreign.C.String
import Foreign.C.Error (throwErrnoIfMinus1_)
import System.Posix.Internals ( withFilePath )
#endif /* mingw32_HOST_OS */
getEnvironment :: NoCallStackIO [(String, String)]
#ifdef mingw32_HOST_OS
-- On Windows, the names of environment variables are case-insensitive, but are
-- often given in mixed-case (e.g. "PATH" is "Path"), so we have to normalise
-- them.
getEnvironment = fmap upcaseVars System.getEnvironment
where
upcaseVars = map upcaseVar
upcaseVar (var, val) = (map toUpper var, val)
#else
getEnvironment = System.getEnvironment
#endif
#if __GLASGOW_HASKELL__ < 706
-- | @lookupEnv var@ returns the value of the environment variable @var@, or
-- @Nothing@ if there is no such value.
lookupEnv :: String -> IO (Maybe String)
lookupEnv name = (Just `fmap` System.getEnv name) `catchIO` const (return Nothing)
#endif /* __GLASGOW_HASKELL__ < 706 */
-- | @setEnv name value@ sets the specified environment variable to @value@.
--
-- Throws `Control.Exception.IOException` if either @name@ or @value@ is the
-- empty string or contains an equals sign.
setEnv :: String -> String -> IO ()
setEnv key value_ = setEnv_ key value
where
-- NOTE: Anything that follows NUL is ignored on both POSIX and Windows. We
-- still strip it manually so that the null check above succeeds if a value
-- starts with NUL.
value = takeWhile (/= '\NUL') value_
setEnv_ :: String -> String -> IO ()
#ifdef mingw32_HOST_OS
setEnv_ key value = withCWString key $ \k -> withCWString value $ \v -> do
success <- c_SetEnvironmentVariable k v
unless success (throwGetLastError "setEnv")
where
_ = callStack -- TODO: attach CallStack to exception
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif /* i386_HOST_ARCH */
foreign import WINDOWS_CCONV unsafe "windows.h SetEnvironmentVariableW"
c_SetEnvironmentVariable :: LPTSTR -> LPTSTR -> Prelude.IO Bool
#else
setEnv_ key value = do
withFilePath key $ \ keyP ->
withFilePath value $ \ valueP ->
throwErrnoIfMinus1_ "setenv" $
c_setenv keyP valueP (fromIntegral (fromEnum True))
where
_ = callStack -- TODO: attach CallStack to exception
foreign import ccall unsafe "setenv"
c_setenv :: CString -> CString -> CInt -> Prelude.IO CInt
#endif /* mingw32_HOST_OS */
#if __GLASGOW_HASKELL__ < 708
-- | @unsetEnv name@ removes the specified environment variable from the
-- environment of the current process.
--
-- Throws `Control.Exception.IOException` if @name@ is the empty string or
-- contains an equals sign.
--
-- @since 4.7.0.0
unsetEnv :: String -> IO ()
#ifdef mingw32_HOST_OS
unsetEnv key = withCWString key $ \k -> do
success <- c_SetEnvironmentVariable k nullPtr
unless success $ do
-- We consider unsetting an environment variable that does not exist not as
-- an error, hence we ignore eRROR_ENVVAR_NOT_FOUND.
err <- c_GetLastError
unless (err == eRROR_ENVVAR_NOT_FOUND) $ do
throwGetLastError "unsetEnv"
#else
unsetEnv key = withFilePath key (throwErrnoIf_ (/= 0) "unsetEnv" . c_unsetenv)
#if __GLASGOW_HASKELL__ > 706
foreign import ccall unsafe "__hsbase_unsetenv" c_unsetenv :: CString -> Prelude.IO CInt
#else
-- HACK: We hope very hard that !UNSETENV_RETURNS_VOID
foreign import ccall unsafe "unsetenv" c_unsetenv :: CString -> Prelude.IO CInt
#endif
#endif
#endif
| mydaum/cabal | Cabal/Distribution/Compat/Environment.hs | bsd-3-clause | 4,234 | 14 | 14 | 699 | 530 | 315 | 215 | 36 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Css.About
(aboutStyles) where
import Clay
import Prelude hiding ((**))
import Data.Monoid
import Css.Constants
{- aboutStyles
- Generates CSS for the about page. -}
aboutStyles :: Css
aboutStyles = "#aboutDiv" ? do
maxWidth (px 1000)
padding 0 (em 1) 0 (em 1)
margin nil auto nil auto
textAlign justify
h1 <> h2 <> h3 <? do
color blue3
| tamaralipowski/courseography | hs/Css/About.hs | gpl-3.0 | 414 | 0 | 11 | 98 | 126 | 65 | 61 | 15 | 1 |
{-# LANGUAGE TemplateHaskellQuotes, RankNTypes, ScopedTypeVariables #-}
module A where
x = \(y :: forall a. a -> a) -> [|| y ||]
| ezyang/ghc | testsuite/tests/quotes/T10384.hs | bsd-3-clause | 129 | 1 | 9 | 22 | 38 | 25 | 13 | -1 | -1 |
{-# LANGUAGE Safe #-}
module Main where
import M_SafePkg5
main = do
putStrLn $ show bigInt
| urbanslug/ghc | testsuite/tests/safeHaskell/check/pkg01/ImpSafeOnly06.hs | bsd-3-clause | 98 | 0 | 8 | 23 | 23 | 13 | 10 | 5 | 1 |
module Octal
( readOct
, showOct
) where
import Data.List (foldl')
readOct :: (Integral a) => String -> a
readOct = foldl' f 0 where
f n x = n * 8 + fromIntegral (fromEnum x - 48)
showOct :: (Integral a) => a -> String
showOct = reverse . showOct' where
showOct' 0 = ""
showOct' n = toEnum (fromIntegral r + 48) : showOct' q where
(q, r) = n `quotRem` 8
| tfausak/exercism-solutions | haskell/octal/Octal.hs | mit | 375 | 0 | 11 | 95 | 168 | 90 | 78 | 12 | 2 |
-- | 'Database.Redis.Commands' contains functions that mirror the set
-- of Redis commands. These functions take and return 'Prelude' data types,
-- abstracting away the need to deal with 'RedisData' directly.
module Database.Redis.Commands where
import Database.Redis.Connection (Connection, request, request')
import Database.Redis.Data (FromRedis, fromRedis, commandData)
-- * Arbitrary commands
-- | 'command' returns an action that executes a Redis command given as a list
-- of strings, where the first string is the command name and the following
-- strings are the arguments.
command :: (FromRedis a) => Connection -> [String] -> IO a
command connection args = do
reply <- request connection (commandData args)
case fromRedis reply of
Left err -> ioError err
Right x -> return x
-- * Standard commands
-- ** Connection
auth :: Connection -> String -> IO String
auth c s = command c ["AUTH", s]
echo :: Connection -> String -> IO (Maybe String)
echo c s = command c ["ECHO", s]
ping :: Connection -> IO String
ping c = command c ["PING"]
quit :: Connection -> IO ()
quit c = request' c $ commandData ["QUIT"]
select :: Connection -> Int -> IO String
select c i = command c ["SELECT", show i]
-- ** Lists
blpop :: Connection -> [String] -> Int -> IO (Maybe (String, String))
blpop c keys timeout = do
reply <- command c $ ["BLPOP"] ++ keys ++ [show timeout]
return $ case reply of
Just [Just key, Just value] -> Just (key, value)
_ -> Nothing
brpop :: Connection -> [String] -> Int -> IO (Maybe (String, String))
brpop c keys timeout = do
reply <- command c $ ["BRPOP"] ++ keys ++ [show timeout]
return $ case reply of
Just [Just key, Just value] -> Just (key, value)
_ -> Nothing
brpoplpush :: Connection -> String -> String -> Int -> IO (Maybe String)
brpoplpush c src dst timeout = command c ["BRPOPLPUSH", src, dst, show timeout]
lindex :: Connection -> String -> Int -> IO (Maybe String)
lindex c key index = command c ["LINDEX", key, show index]
llen :: Connection -> String -> IO Int
llen c key = command c ["LLEN", key]
lpop :: Connection -> String -> IO (Maybe String)
lpop c key = command c ["LPOP", key]
lpush :: Connection -> String -> [String] -> IO Int
lpush c key values = command c $ ["LPUSH", key] ++ values
lpushx :: Connection -> String -> String -> IO Int
lpushx c key value = command c ["LPUSHX", key, value]
lrange :: Connection -> String -> Int -> Int -> IO (Maybe [Maybe String])
lrange c key start stop = command c ["LRANGE", key, show start, show stop]
lrem :: Connection -> String -> Int -> String -> IO Int
lrem c key count value = command c ["LREM", key, show count, value]
lset :: Connection -> String -> Int -> String -> IO String
lset c key index value = command c ["LSET", key, show index, value]
ltrim :: Connection -> String -> Int -> Int -> IO String
ltrim c key start stop = command c ["LTRIM", key, show start, show stop]
rpop :: Connection -> String -> IO (Maybe String)
rpop c key = command c ["RPOP", key]
rpoplpush :: Connection -> String -> String -> IO (Maybe String)
rpoplpush c source destination = command c ["RPOPLPUSH", source, destination]
rpush :: Connection -> String -> [String] -> IO Int
rpush c key values = command c $ ["RPUSH", key] ++ values
rpushx :: Connection -> String -> String -> IO Int
rpushx c key value = command c ["RPUSHX", key, value]
-- ** Strings
append :: Connection -> String -> String -> IO Int
append c key value = command c ["APPEND", key, value]
get :: Connection -> String -> IO (Maybe String)
get c key = command c ["GET", key]
set :: Connection -> String -> String -> IO String
set c key value = command c ["SET", key, value]
-- ** Server
flushdb :: Connection -> IO String
flushdb c = command c ["FLUSHDB"]
| brow/redis-iteratee | src/Database/Redis/Commands.hs | mit | 3,765 | 2 | 13 | 748 | 1,481 | 765 | 716 | 67 | 2 |
{-# htermination (minTup0 :: Tup0 -> Tup0 -> Tup0) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup0 = Tup0 ;
data Ordering = LT | EQ | GT ;
compareTup0 :: Tup0 -> Tup0 -> Ordering
compareTup0 Tup0 Tup0 = EQ;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
ltEsTup0 :: Tup0 -> Tup0 -> MyBool
ltEsTup0 x y = fsEsOrdering (compareTup0 x y) GT;
min0 x y MyTrue = y;
otherwise :: MyBool;
otherwise = MyTrue;
min1 x y MyTrue = x;
min1 x y MyFalse = min0 x y otherwise;
min2 x y = min1 x y (ltEsTup0 x y);
minTup0 :: Tup0 -> Tup0 -> Tup0
minTup0 x y = min2 x y;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/min_1.hs | mit | 1,081 | 0 | 8 | 246 | 408 | 223 | 185 | 32 | 1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.HAServiceProtocolProtos.TransitionToActiveResponseProto (TransitionToActiveResponseProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data TransitionToActiveResponseProto = TransitionToActiveResponseProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable TransitionToActiveResponseProto where
mergeAppend TransitionToActiveResponseProto TransitionToActiveResponseProto = TransitionToActiveResponseProto
instance P'.Default TransitionToActiveResponseProto where
defaultValue = TransitionToActiveResponseProto
instance P'.Wire TransitionToActiveResponseProto where
wireSize ft' self'@(TransitionToActiveResponseProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(TransitionToActiveResponseProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> TransitionToActiveResponseProto) TransitionToActiveResponseProto where
getVal m' f' = f' m'
instance P'.GPB TransitionToActiveResponseProto
instance P'.ReflectDescriptor TransitionToActiveResponseProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.common.TransitionToActiveResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"HAServiceProtocolProtos\"], baseName = MName \"TransitionToActiveResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"HAServiceProtocolProtos\",\"TransitionToActiveResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType TransitionToActiveResponseProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg TransitionToActiveResponseProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/HAServiceProtocolProtos/TransitionToActiveResponseProto.hs | mit | 3,078 | 1 | 16 | 541 | 554 | 291 | 263 | 53 | 0 |
import Data.Char (isAlpha, ord)
import Data.List (sort)
import Data.List.Split (splitOn)
main = do ls <- readFile "p022_names.txt"
putStrLn $ show $ process ls
return 0
process x = score x
score x = sum $ zipWith (*) [1..n] values
where values = map stringValue namesList
namesList = sort $ split $ sanitize x
n = length namesList
sanitize x = filter (\y -> isAlpha y || y==',') x
split x = splitOn "," x
stringValue s = sum $ map charValue s
charValue c = (ord c) - (ord 'A') + 1
| arekfu/project_euler | p0022/p0022.hs | mit | 544 | 0 | 10 | 155 | 233 | 117 | 116 | 15 | 1 |
module Graphics.ThreeJs.Objects.Mesh
(
ThreeJsMesh,
mkMesh,
setMeshRot
) where
import Haste.Foreign
import Haste.Prim
type ThreeJsMesh = JSAny
mkMesh :: (ToAny a) => a -> a -> IO (ThreeJsMesh)
mkMesh = ffi $ toJSStr "(function (geometry, material) { return new THREE.Mesh(geometry, material); })"
setMeshRot :: Float -> Float -> Float -> ThreeJsMesh -> IO ()
setMeshRot = ffi $ toJSStr "(function (x, y, z, mesh) { mesh.rotation.x = x; mesh.rotation.y = y; mesh.rotation.z = z; })";
| sanghakchun/three-js-haste | src/Graphics/ThreeJs/Objects/Mesh.hs | mit | 503 | 0 | 10 | 94 | 114 | 64 | 50 | 12 | 1 |
-- Can you get the loop ?
-- http://www.codewars.com/kata/52a89c2ea8ddc5547a000863/
module CanYouGetTheLoop where
import CanYouGetTheLoop.Types
import Data.List (elemIndices)
import Control.Arrow ((***))
loopSize :: Eq a => Node a -> Int
loopSize a = (\(x:y:_) -> y-x) . elemIndices (fst . head . dropWhile (uncurry (/=)) . tail . iterate (next *** next . next) $ (a, a)) . iterate next $ a
| gafiatulin/codewars | src/3 kyu/CanYouGetTheLoop.hs | mit | 394 | 0 | 16 | 64 | 155 | 85 | 70 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
module Text.Escapes.ANSI where
import Data.Char(isDigit)
import qualified System.IO as SIO
import qualified System.Console.ANSI as A
-- TODO:
-- * Add some simple smoke tests to parseANSI and stripANSI
-- * Take a look at http://www.isthe.com/chongo/tech/comp/ansi_escapes.html
-- - need 02 faint, 03 is standout, 01 is bold on, 00 is normal display
-- - Fiddle with the other SGR commands to see if it's better
printDiff :: (Eq a, Show a) => [a] -> [a] -> IO ()
printDiff = printDiff0 (0::Int)
where printDiff0 _ [] [] = return ()
printDiff0 i aas bbs = ppA >> printDiff0 (i + 1) as bs
where (b,bs) = (head bbs, if null bbs then [] else tail bbs)
(a,as) = (head aas, if null aas then [] else tail aas)
ppA = do
if i > 0 then putStr "," else return ()
if null aas then putStrC A.Red "***"
else if null bbs || a /= b then putStrC A.Red (show a) -- ++ "(" ++ show b ++ ")")
else putStr (show a)
-- Wraps some IO op between a color set and reset command.
-- See 'hPutStrANSI' for a better API.
withColor :: A.Color -> IO b -> IO b
withColor c op = do { A.setSGR [A.SetColor A.Foreground A.Vivid c]; r <- op; A.setSGR [A.Reset]; return r }
-- Prints some text in color.
-- See 'hPutStrANSI' for a better API.
putStrC :: A.Color -> String -> IO ()
putStrC c = withColor c . putStr
-- Prints some text in color.
-- See 'hPutStrANSI' for a better API.
putStrLnC :: A.Color -> String -> IO ()
putStrLnC c = withColor c . putStrLn
-- ! Exactly like 'hPutStr', but permits ANSI escapes. It interprets these
-- and sets the underlying console if necessary. Hence, this works on
-- Windows and Unix.
hPutStrANSI :: SIO.Handle -> String -> IO ()
hPutStrANSI h = body
where body s = do
isa_tty <- SIO.hIsTerminalDevice h
if isa_tty then colorString s
else dontColorString s
colorString = mapM_ handleANSI . parseANSI
dontColorString = SIO.hPutStr h . stripANSI
handleANSI (AString str) = SIO.hPutStr h str
handleANSI (AEscape sgr) = A.hSetSGR h sgr
handleANSI (AError _) = return ()
-- handleANSI (AError err) = SIO.hPutStrLn SIO.stderr ("Tim.ANSI.hPutStrANSI: " ++ err)
-- ! See 'hPutStrANSI'. Just adds a newline.
hPutStrLnANSI :: SIO.Handle -> String -> IO ()
hPutStrLnANSI h cs = hPutStrANSI h (cs ++ "\n")
-- ! Strips all the ANSI esacpes from a string. Erroneous escape sequences
-- are dropped non-deterministically.
stripANSI :: String -> String
stripANSI str = concatMap handleANSI (parseANSI str)
where handleANSI (AString s) = s
handleANSI (AEscape _) = ""
handleANSI (AError _) = ""
-- 0 is normal, 1 is bold, 2 is faint
aNSI_RESET = "\ESC[0m"
aNSI_RED = "\ESC[1;31m"
aNSI_DK_RED = "\ESC[0;31m"
aNSI_GRN = "\ESC[1;32m"
aNSI_DK_GRN = "\ESC[0;32m"
aNSI_YEL = "\ESC[1;33m"
aNSI_DK_YEL = "\ESC[0;33m"
aNSI_BLU = "\ESC[1;34m"
aNSI_DK_BLU = "\ESC[0;34m"
aNSI_MAG = "\ESC[1;35m"
aNSI_DK_MAG = "\ESC[0;35m"
aNSI_CYN = "\ESC[1;36m"
aNSI_DK_CYN = "\ESC[0;36m"
aNSI_WHI = "\ESC[1;37m"
aNSI_DK_WHI = "\ESC[0;37m"
printColorTable :: IO ()
printColorTable = do
let cs = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"]
flip mapM_ (zip [(0 ::Int)..] cs) $ \(ci, cstr) -> do
-- hPutStrLnANSI SIO.stdout cstr
let cstr_padded = replicate (16 - length cstr) ' ' ++ cstr
str1 = ("\ESC[1;" ++ show (30+ci) ++ "m" ++ "******" ++ aNSI_RESET)
str2 = ("\ESC[2;" ++ show (30+ci) ++ "m" ++ "******" ++ aNSI_RESET)
str3 = ("\ESC[1;" ++ show (40+ci) ++ "m" ++ "******" ++ aNSI_RESET)
str4 = ("\ESC[2;" ++ show (40+ci) ++ "m" ++ "******" ++ aNSI_RESET)
putStr $ cstr_padded ++ " "
SIO.hFlush SIO.stdout
hPutStrANSI SIO.stdout (str1++" ")
A.hSetSGR SIO.stdout [A.Reset]
hPutStrANSI SIO.stdout (str2++" ")
A.hSetSGR SIO.stdout [A.Reset]
hPutStrANSI SIO.stdout (str3++" ")
A.hSetSGR SIO.stdout [A.Reset]
hPutStrANSI SIO.stdout (str4++" ")
A.hSetSGR SIO.stdout [A.Reset]
putStrLn ""
-- 30 black, 31 red, 32 green, 33 yellow, 34 blue, 35 magenta, 36 cyan, 37 white
-- A chunk in an ANSI string.
-- Either an escape or a bit of string
data ANSI = AString String -- | A chunk of normal printable chars.
| AEscape [A.SGR] -- | An ANSI escape decoded
| AError String -- | A malformed, illegal, or unsupported escape
deriving Show
parseANSI :: String -> [ANSI]
parseANSI str = reverse (goStr 0 [] "" str)
where -- This state indicates that we are scanning a string (which may be empty
goStr :: Int -> [ANSI] -> String -> String -> [ANSI]
-- EOS
goStr _ as str [] = mkStr as str
-- Handle RESETs separate from normal escapes
goStr !o as str ('\ESC':'[':'0':'m':cs) = goStr (o + 4) (AEscape [A.Reset] : mkStr as str) "" cs
-- Start of a new escape sequence (non reset)
goStr !o as str s@('\ESC':'[':cs) = goEsc (o+2) (mkStr as str) s A.Dull [] 2 cs
-- Normal case: append a non-escape character
goStr !o as str (c:cs) = goStr (o + 1) as (c:str) cs
mkStr as str = if null str then as else AString (reverse str) : as
-- goEsc indicates we've just seen a "\ESC[" and now expect to see some escapes
-- (<int>;)*<int>m
-- ARguments:
-- string offset
-- ansi chunks so far
-- string from the start of the encoding (for error messages)
-- list of escapes from this sequence so far
-- the num chars read in this escape (for errors)
-- the string we're parsing the escape from
-- \ESC[<int>;<int>m
goEsc :: Int -> [ANSI] -> String -> A.ColorIntensity -> [A.SGR] -> Int -> String -> [ANSI]
goEsc !o as estr ci es !k cs
| null cs = escErr "unterminated escape" 0 ""
-- | head cs == 'm' = goStr (o + length ds) (AEscape (reverse es) : as)
| null ds = escErr "expected escape code" 0 cs
| null cs' = escErr "unterminated escape" (length ds) ""
| head cs' == 'm' = addEsc $ \_ es -> goStr (o + length ds + 1) (mkEsc es : as) "" (tail cs')
| head cs' == ';' = addEsc $ \ci es -> goEsc (o + length ds + 1) as estr ci es (k + length ds + 1) (tail cs')
| otherwise = escErr "expected ';' or 'm'" (length ds) cs'
where escErr m i cs
| null es = goStr (o + i) (AError emsg : as) "" cs
| otherwise = goStr (o + i) (AError emsg : AEscape (reverse es) : as) "" cs
where emsg = show (o + i) ++ ". \"" ++ take (k + i) estr ++ "\"" ++ m
mkEsc [] = AEscape [A.Reset]
mkEsc es = AEscape (reverse es)
(ds,cs') = span isDigit cs
addEsc :: (A.ColorIntensity -> [A.SGR] -> [ANSI]) -> [ANSI]
addEsc c = case reads ds :: [(Int,String)] of
-- A.SetConsoleIntensity A.NormalIntensity -- 0
[(0,"")] -> c ci (A.Reset : es)
-- A.SetConsoleIntensity A.BoldIntensity -- 1
[(1,"")] -> c A.Vivid es
-- A.SetConsoleIntensity A.FaintIntensity -- 2
[(2,"")] -> c A.Dull es
[(30,"")] -> c ci (A.SetColor A.Foreground ci A.Black : es)
[(31,"")] -> c ci (A.SetColor A.Foreground ci A.Red : es)
[(32,"")] -> c ci (A.SetColor A.Foreground ci A.Green : es)
[(33,"")] -> c ci (A.SetColor A.Foreground ci A.Yellow : es)
[(34,"")] -> c ci (A.SetColor A.Foreground ci A.Blue : es)
[(35,"")] -> c ci (A.SetColor A.Foreground ci A.Magenta : es)
[(36,"")] -> c ci (A.SetColor A.Foreground ci A.Cyan : es)
[(37,"")] -> c ci (A.SetColor A.Foreground ci A.White : es)
[(40,"")] -> c ci (A.SetColor A.Background ci A.Black : es)
[(41,"")] -> c ci (A.SetColor A.Background ci A.Red : es)
[(42,"")] -> c ci (A.SetColor A.Background ci A.Green : es)
[(43,"")] -> c ci (A.SetColor A.Background ci A.Yellow : es)
[(44,"")] -> c ci (A.SetColor A.Background ci A.Blue : es)
[(45,"")] -> c ci (A.SetColor A.Background ci A.Magenta : es)
[(46,"")] -> c ci (A.SetColor A.Background ci A.Cyan : es)
[(47,"")] -> c ci (A.SetColor A.Background ci A.White : es)
_ -> escErr ("unsupported escape " ++ show ds) 0 (tail cs')
| trbauer/ansi-color | Text/Escapes/ANSI.hs | mit | 9,106 | 0 | 21 | 2,989 | 2,865 | 1,491 | 1,374 | 124 | 25 |
module Text.Ponder.Pos
( SourceName, Line, Column
, SourcePos
, sourceLine, sourceColumn, sourceName
, newPos, initialPos
, updatePosChar, backPosChar
) where
type SourceName = String
type Line = Int
type Column = Int
data SourcePos = SourcePos SourceName !Line !Column
deriving ( Eq, Ord )
newPos :: SourceName -> Line -> Column -> SourcePos
newPos name line column = SourcePos name line column
initialPos :: SourceName -> SourcePos
initialPos name = newPos name 1 1
sourceName :: SourcePos -> SourceName
sourceName (SourcePos name _line _column) = name
sourceLine :: SourcePos -> Line
sourceLine (SourcePos _name line _column) = line
sourceColumn :: SourcePos -> Column
sourceColumn (SourcePos _name _line column) = column
updatePosChar :: SourcePos -> SourcePos
updatePosChar (SourcePos name line column)
= SourcePos name line (column+1)
backPosChar :: SourcePos -> SourcePos
backPosChar (SourcePos name line column)
= SourcePos name line (column-1)
instance Show SourcePos where
show (SourcePos name line column)
| null name = showLineColumn
| otherwise = "\"" ++ name ++ "\" " ++ showLineColumn
where
showLineColumn = " (line " ++ show line ++
", column " ++ show column ++
")"
| matt76k/ponder | Text/Ponder/Pos.hs | mit | 1,275 | 0 | 12 | 275 | 394 | 207 | 187 | 38 | 1 |
module Util
( whisper
, escapeStr
, unescapeStr
, prop_unescape_escape
, prop_escape_notnull
, prop_escape_nonewlines
, prop_unescape_total
) where
import System.Console.CmdArgs.Verbosity (whenLoud)
import System.IO (hPutStrLn, stderr)
whisper :: String -> IO ()
whisper msg = whenLoud $ hPutStrLn stderr msg
escapeStr :: String -> String
escapeStr = show
unescapeStr :: String -> String
unescapeStr str =
case reads str of
[(a, "")] -> a
_ -> str
prop_unescape_escape :: String -> Bool
prop_unescape_escape str = str == (unescapeStr . escapeStr) str
prop_escape_notnull :: String -> Bool
prop_escape_notnull str = (not . null) (escapeStr str)
prop_escape_nonewlines :: String -> Bool
prop_escape_nonewlines str = notElem '\n' (escapeStr str)
prop_unescape_total :: String -> Bool
prop_unescape_total str = length (unescapeStr str) >= 0 -- Force evaluation
| bitc/instantrun | src/Util.hs | mit | 918 | 0 | 9 | 182 | 265 | 144 | 121 | 27 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Conduit.Simple.Compat
( ($=), (=$), (=$=), ($$)
, sequenceSources
-- , toFoldM, fromFoldM
-- , adaptFrom, adaptTo
) where
import Conduit.Simple.Core
-- import Control.Category (Category)
-- import Control.Exception.Lifted (finally)
-- import Control.Foldl (FoldM(..))
-- import Control.Monad (liftM)
-- import Control.Monad.CC hiding (control)
-- import Control.Monad.Cont
-- import Control.Monad.Logic
-- import Control.Monad.Trans.Class (lift)
-- import Control.Monad.Trans.Control
-- import Control.Monad.Trans.Either (EitherT(..))
-- import Control.Monad.Trans.Maybe
-- import Crypto.Hash
-- import qualified Data.ByteString as B
-- import Data.Foldable
-- import Data.Functor.Identity
-- import qualified Data.Machine as M
import Data.Traversable
-- import qualified Data.Conduit.Internal as C (Source, Producer,
-- ConduitM(..), Pipe(..))
-- | Compose a 'Source' and a 'Conduit' into a new 'Source'. Note that this
-- is just flipped function application, so ($) can be used to achieve the
-- same thing.
infixl 1 $=
($=) :: a -> (a -> b) -> b
($=) = flip ($)
-- | Compose a 'Conduit' and a 'Sink' into a new 'Sink'. Note that this is
-- just function composition, so (.) can be used to achieve the same thing.
infixr 2 =$
(=$) :: (a -> b) -> (b -> c) -> a -> c
(=$) = flip (.)
-- | Compose two 'Conduit'. This is also just function composition.
infixr 2 =$=
(=$=) :: (a -> b) -> (b -> c) -> a -> c
(=$=) = flip (.)
-- | Compose a 'Source' and a 'Sink' and compute the result. Note that this
-- is just flipped function application, so ($) can be used to achieve the
-- same thing.
infixr 0 $$
($$) :: a -> (a -> b) -> b
($$) = flip ($)
-- | Sequence a collection of sources.
--
-- >>> sinkList $ sequenceSources [yieldOne 1, yieldOne 2, yieldOne 3]
-- [[1,2,3]]
sequenceSources :: (Traversable f, Monad m) => f (Source m a) -> Source m (f a)
sequenceSources = sequenceA
{-
-- | Convert a 'Control.Foldl.FoldM' fold abstraction into a Sink.
--
-- NOTE: This requires ImpredicativeTypes in the code that uses it.
--
-- >>> fromFoldM (FoldM ((return .) . (+)) (return 0) return) $ yieldMany [1..10]
-- 55
fromFoldM :: Monad m => FoldM m a b -> Sink a m b
fromFoldM (FoldM step start done) src =
start >>= (\r -> sink r ((lift .) . step) src) >>= done
-- | Convert a Sink into a 'Control.Foldl.FoldM', passing it as a continuation
-- over the elements.
--
-- >>> toFoldM sumC (\f -> Control.Foldl.foldM f [1..10])
-- 55
toFoldM :: Monad m => Sink a m b -> (forall r. FoldM m a r -> m r) -> m b
toFoldM s f = s $ source $ \z yield ->
lift $ f $ FoldM ((unwrap .) . yield) (return z) return
-- | Turns any conduit 'Producer' into a simple-conduit 'Source'.
-- Finalization is taken care of, as is processing of leftovers, provided
-- the base monad implements @MonadBaseControl IO@.
adaptFrom :: forall m a. MonadBaseControl IO m => C.Producer m a -> Source m a
adaptFrom (C.ConduitM m) = source go
where
go :: r -> (r -> a -> EitherT r m r) -> EitherT r m r
go z yield = f z m
where
f r (C.HaveOutput p c o) = yield r o >>= \r' -> f r' p `finally` lift c
f r (C.NeedInput _ u) = f r (u ())
f r (C.Done ()) = return r
f r (C.PipeM mp) = lift mp >>= f r
f r (C.Leftover p l) = yield r l >>= flip f p
-- | Turn a non-resource dependent simple-conduit into a conduit 'Source'.
--
-- Finalization data would be lost in this transfer, and so is denied by
-- lack of an instance for @MonadBaseControl IO@. Further, the resulting
-- pipeline must be run under 'Control.Monad.CC.runCCT', so really this is
-- more a curiosity than anything else.
adaptTo :: MonadDelimitedCont p s m => Source m a -> C.Source m a
adaptTo src = C.ConduitM $ C.PipeM $ reset $ \p ->
liftM C.Done $ unwrap $ runSource src () $ \() x ->
lift $ shift p $ \k ->
return $ C.HaveOutput (C.PipeM $ k (return ())) (return ()) x
fromLogicT :: Monad m => LogicT m a -> Source m a
fromLogicT (LogicT await) = source $ \z yield ->
lift $ await (go yield) (return z)
where
go yield x mr = do
r <- mr
eres <- runEitherT $ yield r x
case eres of
Left e -> return e -- no short-circuiting here!
Right r -> return r
-- toLogicT :: forall m a. Monad m => Source m a -> LogicT m a
-- toLogicT (Source (ContT await)) = LogicT $ \yield mz -> do
-- z <- mz
-- liftM (either id id) . runEitherT $
-- runIdentity (await (\x -> Identity $ liftM lift $ yield x . return)) z
fromMachine :: forall m k a. Monad m => M.MachineT m k a -> Source m a
fromMachine mach = source go
where
go :: forall r. r -> (r -> a -> EitherT r m r) -> EitherT r m r
go z yield = loop mach z
where
loop :: M.MachineT m k a -> r -> EitherT r m r
loop (M.MachineT m) r = do
step <- lift m
case step of
M.Stop -> return r
M.Yield x k -> loop k r >>= flip yield x
M.Await _ _ e -> loop e r
-- toMachine :: forall m k s a. (Category k, Monad m)
-- => Source m a -> s -> M.MachineT m (k a) s
-- toMachine (Source (ContT await)) seed =
-- M.construct $ M.PlanT
-- (\r -> )
-- (\a mr -> )
-- (\f kz mr -> )
-- (return seed)
-- liftM (either id id) . runEitherT $
-- runIdentity (await go) seed
-- where
-- go :: a -> Identity (s -> EitherT s (M.PlanT (k a) a m) ())
-- go x = Identity $ liftM lift $ \r -> M.yield x
-- | A 'Sink' that hashes a stream of 'B.ByteString'@s@ and creates a digest
-- @d@.
sinkHash :: (Monad m, HashAlgorithm hash) => Sink B.ByteString m (Digest hash)
sinkHash = liftM hashFinalize . sink hashInit ((return .) . hashUpdate)
-- | Hashes the whole contents of the given file in constant memory. This
-- function is just a convenient wrapper around 'sinkHash'.
hashFile :: (MonadIO m, HashAlgorithm hash) => FilePath -> m (Digest hash)
hashFile = liftIO . sinkHash . sourceFile
-}
| jwiegley/simple-conduit | Conduit/Simple/Compat.hs | mit | 6,376 | 0 | 9 | 1,763 | 309 | 202 | 107 | 22 | 1 |
{-# LANGUAGE RankNTypes #-}
{-
Copyright (C) 2012-2014 Kacper Bak, Jimmy Liang, Michal Antkiewicz <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{- |
This is in a separate module from the module "Language.Clafer" so that other modules that require
ClaferEnv can just import this module without all the parsing/compiline/generating functionality.
-}
module Language.ClaferT (
ClaferEnv(..),
makeEnv,
getAst,
getIr,
ClaferM,
ClaferT,
CErr(..),
CErrs(..),
ClaferErr,
ClaferErrs,
ClaferSErr,
ClaferSErrs,
ErrPos(..),
PartialErrPos(..),
throwErrs,
throwErr,
catchErrs,
getEnv,
getsEnv,
modifyEnv,
putEnv,
runClafer,
runClaferT,
Throwable(..),
Span(..),
Pos(..)
) where
import Control.Monad.Error
import Control.Monad.State
import Control.Monad.Identity
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Language.Clafer.Common
import Language.Clafer.Front.Absclafer
import Language.Clafer.Intermediate.Tracing
import Language.Clafer.Intermediate.Intclafer
import Language.Clafer.ClaferArgs
{-
- Examples.
-
- If you need ClaferEnv:
- runClafer args $
- do
- env <- getEnv
- env' = ...
- putEnv env'
-
- Remember to putEnv if you do any modification to the ClaferEnv or else your updates
- are lost!
-
-
- Throwing errors:
-
- throwErr $ ParseErr (ErrFragPos fragId fragPos) "failed parsing"
- throwErr $ ParseErr (ErrModelPos modelPos) "failed parsing"
-
- There is two ways of defining the position of the error. Either define the position
- relative to a fragment, or relative to the model. Pick the one that is convenient.
- Once thrown, the "partial" positions will be automatically updated to contain both
- the model and fragment positions.
- Use throwErrs to throw multiple errors.
- Use catchErrs to catch errors (usually not needed).
-
-}
data ClaferEnv = ClaferEnv {
args :: ClaferArgs,
modelFrags :: [String], -- original text of the model fragments
cAst :: Maybe Module,
cIr :: Maybe (IModule, GEnv, Bool),
frags :: [Pos], -- line numbers of fragment markers
irModuleTrace :: Map Span [Ir],
astModuleTrace :: Map Span [Ast]
} deriving Show
getAst :: (Monad m) => ClaferT m Module
getAst = do
env <- getEnv
case cAst env of
(Just a) -> return a
_ -> throwErr (ClaferErr "No AST. Did you forget to add fragments or parse?" :: CErr Span) -- Indicates a bug in the Clafer translator.
getIr :: (Monad m) => ClaferT m (IModule, GEnv, Bool)
getIr = do
env <- getEnv
case cIr env of
(Just i) -> return i
_ -> throwErr (ClaferErr "No IR. Did you forget to compile?" :: CErr Span) -- Indicates a bug in the Clafer translator.
makeEnv :: ClaferArgs -> ClaferEnv
makeEnv args' = ClaferEnv { args = args'',
modelFrags = [],
cAst = Nothing,
cIr = Nothing,
frags = [],
irModuleTrace = Map.empty,
astModuleTrace = Map.empty}
where
args'' = if (CVLGraph `elem` (mode args') ||
Html `elem` (mode args') ||
Graph `elem` (mode args'))
then args'{keep_unused=True}
else args'
-- | Monad for using Clafer.
type ClaferM = ClaferT Identity
-- | Monad Transformer for using Clafer.
type ClaferT m = ErrorT ClaferErrs (StateT ClaferEnv m)
type ClaferErr = CErr ErrPos
type ClaferErrs = CErrs ErrPos
type ClaferSErr = CErr Span
type ClaferSErrs = CErrs Span
-- | Possible errors that can occur when using Clafer
-- | Generate errors using throwErr/throwErrs:
data CErr p =
-- | Generic error
ClaferErr {
msg :: String
} |
-- | Error generated by the parser
ParseErr {
-- | Position of the error
pos :: p,
msg :: String
} |
-- | Error generated by semantic analysis
SemanticErr {
pos :: p,
msg :: String
}
deriving Show
-- | Clafer keeps track of multiple errors.
data CErrs p =
ClaferErrs {errs :: [CErr p]}
deriving Show
instance Error (CErr p) where
strMsg = ClaferErr
instance Error (CErrs p) where
strMsg m = ClaferErrs [strMsg m]
data ErrPos =
ErrPos {
-- | The fragment where the error occurred.
fragId :: Int,
-- | Error positions are relative to their fragments.
-- | For example an error at (Pos 2 3) means line 2 column 3 of the fragment, not the entire model.
fragPos :: Pos,
-- | The error position relative to the model.
modelPos :: Pos
}
deriving Show
-- | The full ErrPos requires lots of information that needs to be consistent. Every time we throw an error,
-- | we need BOTH the (fragId, fragPos) AND modelPos. This makes it easier for developers using ClaferT so they
-- | only need to provide part of the information and the rest is automatically calculated. The code using
-- | ClaferT is more concise and less error-prone.
-- |
-- | modelPos <- modelPosFromFragPos fragdId fragPos
-- | throwErr $ ParserErr (ErrPos fragId fragPos modelPos)
-- |
-- | vs
-- |
-- | throwErr $ ParseErr (ErrFragPos fragId fragPos)
-- |
-- | Hopefully making the error handling easier will make it more universal.
data PartialErrPos =
-- | Position relative to the start of the fragment. Will calculate model position automatically.
-- | fragId starts at 0
-- | The position is relative to the start of the fragment.
ErrFragPos {
pFragId :: Int,
pFragPos :: Pos
} |
ErrFragSpan {
pFragId :: Int,
pFragSpan :: Span
} |
-- | Position relative to the start of the complete model. Will calculate fragId and fragPos automatically.
-- | The position is relative to the entire complete model.
ErrModelPos {
pModelPos :: Pos
}
|
ErrModelSpan {
pModelSpan :: Span
}
deriving Show
class ClaferErrPos p where
toErrPos :: Monad m => p -> ClaferT m ErrPos
instance ClaferErrPos Span where
toErrPos = toErrPos . ErrModelSpan
instance ClaferErrPos ErrPos where
toErrPos = return . id
instance ClaferErrPos PartialErrPos where
toErrPos (ErrFragPos frgId frgPos) =
do
f <- getsEnv frags
let pos' = ((Pos 1 1 : f) !! frgId) `addPos` frgPos
return $ ErrPos frgId frgPos pos'
toErrPos (ErrFragSpan frgId (Span frgPos _)) = toErrPos $ ErrFragPos frgId frgPos
toErrPos (ErrModelPos modelPos') =
do
f <- getsEnv frags
let fragSpans = zipWith Span (Pos 1 1 : f) f
case findFrag modelPos' fragSpans of
Just (frgId, Span fragStart _) -> return $ ErrPos frgId (modelPos' `minusPos` fragStart) modelPos'
Nothing -> error $ show modelPos' ++ " not within any frag spans: " ++ show fragSpans -- Indicates a bug in the Clafer translator
where
findFrag pos'' spans =
find (inSpan pos'' . snd) (zip [0..] spans)
toErrPos (ErrModelSpan (Span modelPos'' _)) = toErrPos $ ErrModelPos modelPos''
class Throwable t where
toErr :: t -> Monad m => ClaferT m ClaferErr
instance ClaferErrPos p => Throwable (CErr p) where
toErr (ClaferErr mesg) = return $ ClaferErr mesg
toErr err =
do
pos' <- toErrPos $ pos err
return $ err{pos = pos'}
-- | Throw many errors.
throwErrs :: (Monad m, Throwable t) => [t] -> ClaferT m a
throwErrs throws =
do
errors <- mapM toErr throws
throwError $ ClaferErrs errors
-- | Throw one error.
throwErr :: (Monad m, Throwable t) => t -> ClaferT m a
throwErr throw = throwErrs [throw]
-- | Catch errors
catchErrs :: Monad m => ClaferT m a -> ([ClaferErr] -> ClaferT m a) -> ClaferT m a
catchErrs e h = e `catchError` (h . errs)
addPos :: Pos -> Pos -> Pos
addPos (Pos l c) (Pos 1 d) = Pos l (c + d - 1) -- Same line
addPos (Pos l _) (Pos m d) = Pos (l + m - 1) d -- Different line
minusPos :: Pos -> Pos -> Pos
minusPos (Pos l c) (Pos 1 d) = Pos l (c - d + 1) -- Same line
minusPos (Pos l c) (Pos m _) = Pos (l - m + 1) c -- Different line
inSpan :: Pos -> Span -> Bool
inSpan pos' (Span start end) = pos' >= start && pos' <= end
-- | Get the ClaferEnv
getEnv :: Monad m => ClaferT m ClaferEnv
getEnv = get
getsEnv :: Monad m => (ClaferEnv -> a) -> ClaferT m a
getsEnv = gets
-- | Modify the ClaferEnv
modifyEnv :: Monad m => (ClaferEnv -> ClaferEnv) -> ClaferT m ()
modifyEnv = modify
-- | Set the ClaferEnv. Remember to set the env after every change.
putEnv :: Monad m => ClaferEnv -> ClaferT m ()
putEnv = put
-- | Uses the ErrorT convention:
-- | Left is for error (a string containing the error message)
-- | Right is for success (with the result)
runClaferT :: Monad m => ClaferArgs -> ClaferT m a -> m (Either [ClaferErr] a)
runClaferT args' exec =
mapLeft errs `liftM` evalStateT (runErrorT exec) (makeEnv args')
where
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft f (Left l) = Left (f l)
mapLeft _ (Right r) = Right r
-- | Convenience
runClafer :: ClaferArgs -> ClaferM a -> Either [ClaferErr] a
runClafer args' = runIdentity . runClaferT args'
| juodaspaulius/clafer-old-customBNFC | src/Language/ClaferT.hs | mit | 10,880 | 0 | 16 | 3,233 | 2,126 | 1,166 | 960 | 178 | 2 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.HTMLSelectElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.HTMLSelectElement
#else
module Graphics.UI.Gtk.WebKit.DOM.HTMLSelectElement
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.HTMLSelectElement
#else
import Graphics.UI.Gtk.WebKit.DOM.HTMLSelectElement
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/HTMLSelectElement.hs | mit | 470 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
-- |
-- Module : BattleHack.Utilities.Vector
-- Description :
-- Copyright : (c) Jonatan H Sundqvist, 2015
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
--
-- Created September 14 2015
-- TODO | - Is it silly to use Complex Double for everything because of Cairo (yes it is; fixed) (✓)
-- - Many of these functions should probably be moved to Southpaw
-- SPEC | -
-- -
--------------------------------------------------------------------------------------------------------------------------------------------
-- GHC Pragmas
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------------------------------------------------------------------
module BattleHack.Utilities.Vector where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
import Data.Complex
import BattleHack.Types
import BattleHack.Lenses
--------------------------------------------------------------------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
dotwise :: (a -> a -> a) -> Complex a -> Complex a -> Complex a
dotwise f (x:+y) (x':+y') = f x x':+f y y'
-- |
dotmap :: (a -> a) -> Complex a -> Complex a
dotmap f (x:+y) = f x:+f y
-- |
toscalar :: (a -> a -> a) -> Complex a -> a
toscalar f (x:+y) = f x y
-- | Converts a 2-tuple to a vector
tovector :: (a, a) -> Complex a
tovector = uncurry (:+)
-- |
vectorise :: RealFloat f => (f -> f -> a) -> Complex f -> a
vectorise f (x:+y) = f x y
| SwiftsNamesake/BattleHack-2015 | src/BattleHack/Utilities/Vector.hs | mit | 2,243 | 0 | 9 | 277 | 316 | 178 | 138 | 14 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Control.Auto.Generate
-- Description : 'Auto's that act as generators or "producers", ignoring input.
-- Copyright : (c) Justin Le 2015
-- License : MIT
-- Maintainer : justin@jle.im
-- Stability : unstable
-- Portability : portable
--
-- This module contains various 'Auto's that act as "producing" streams;
-- they all ignore their input streams and produce output streams through
-- a pure or monadic process.
--
module Control.Auto.Generate (
-- * From lists
fromList
, fromList_
, fromLongList
-- * Constant producers
-- $constant
, pure
, effect
-- * From functions
-- ** Iterating
, iterator
, iterator_
, iteratorM
, iteratorM_
-- ** Enumerating results of a function
, discreteF
, discreteF_
-- ** Unfolding
-- | "Iterating with state".
, unfold
, unfold_
, unfoldM
, unfoldM_
-- * Enumerating
, enumFromA
, enumFromA_
) where
import Control.Applicative
import Control.Auto.Core
import Control.Auto.Interval
import Control.Category
import Data.Serialize
import Prelude hiding ((.), id)
-- | An 'Interval' that ignores the input stream and just outputs items
-- from the given list. Is "on" as long as there are still items in the
-- list left, and "off" after there is nothing left in the list to output.
--
-- Serializes itself by storing the entire rest of the list in binary, so
-- if your list is long, it might take up a lot of space upon
-- storage. If your list is infinite, it makes an infinite binary, so be
-- careful!
--
-- 'fromLongList' can be used for longer lists or infinite lists; or, if
-- your list can be boild down to an 'unfoldr', you can use 'unfold'.
--
-- * Storing: O(n) time and space on length of remaining list
-- * Loading: O(1) time in the number of times the 'Auto' has been
-- stepped + O(n) time in the length of the remaining list.
--
fromList :: Serialize b
=> [b] -- ^ list to output element-by-element
-> Interval m a b
fromList = mkState (const _uncons)
-- | A version of 'fromList' that is safe for long or infinite lists, or
-- lists with unserializable elements.
--
-- There is a small cost in the time of loading/resuming, which is @O(n)@
-- on the number of times the Auto had been stepped at the time of
-- saving. This is because it has to drop the @n@ first elements in the
-- list, to "resume" to the proper position.
--
-- * Storing: O(1) time and space on the length of the remaining list
-- * Loading: O(n) time on the number of times the 'Auto' has been
-- stepped, maxing out at O(n) on the length of the entire input list.
--
fromLongList :: [b] -- ^ list to output element-by-element
-> Interval m a b
fromLongList xs = go 0 xs
where
loader = do
stopped <- get
if stopped
then return finished
else do
i <- get
return (go i (drop i xs))
finished = mkAuto loader
(put True)
(const (Nothing, finished))
go i ys = mkAuto loader
(put (False, i))
$ \_ -> case ys of
(y':ys') -> (Just y', go (i + 1) ys')
[] -> (Nothing, finished)
-- | The non-resuming/non-serializing version of 'fromList'.
fromList_ :: [b] -- ^ list to output element-by-element
-> Interval m a b
fromList_ = mkState_ (const _uncons)
_uncons :: [a] -> (Maybe a, [a])
_uncons [] = (Nothing, [])
_uncons (x:xs) = (Just x , xs)
-- | Analogous to 'unfoldr' from "Prelude". Creates an 'Interval'
-- (that ignores its input) by maintaining an internal accumulator of type
-- @c@ and, at every step, applying to the unfolding function to the
-- accumulator. If the result is 'Nothing', then the 'Interval' will turn
-- "off" forever (output 'Nothing' forever); if the result is @'Just' (y,
-- acc)@, then it will output @y@ and store @acc@ as the new accumulator.
--
-- Given an initial accumulator.
--
-- >>> let countFromTil n m = flip unfold n $ \i -> if i <= m
-- then Just (i, i+1)
-- else Nothing
-- >>> take 8 . streamAuto' (countFromTil 5 10) $ repeat ()
-- [Just 5, Just 6, Just 7, Just 8, Just 9, Just 10, Nothing, Nothing]
--
-- @'unfold' f c0@ behaves like @'overList' ('unfoldr' f c0)@.
--
unfold :: Serialize c
=> (c -> Maybe (b, c)) -- ^ unfolding function
-> c -- ^ initial accumulator
-> Interval m a b
unfold f = mkState (_unfoldF f) . Just
-- | Like 'unfold', but the unfolding function is monadic.
unfoldM :: (Serialize c, Monad m)
=> (c -> m (Maybe (b, c))) -- ^ unfolding function
-> c -- ^ initial accumulator
-> Interval m a b
unfoldM f = mkStateM (_unfoldMF f) . Just
-- | The non-resuming & non-serializing version of 'unfold'.
unfold_ :: (c -> Maybe (b, c)) -- ^ unfolding function
-> c -- ^ initial accumulator
-> Interval m a b
unfold_ f = mkState_ (_unfoldF f) . Just
-- | The non-resuming & non-serializing version of 'unfoldM'.
unfoldM_ :: Monad m
=> (c -> m (Maybe (b, c))) -- ^ unfolding function
-> c -- ^ initial accumulator
-> Interval m a b
unfoldM_ f = mkStateM_ (_unfoldMF f) . Just
_unfoldF :: (c -> Maybe (b, c))
-> a
-> Maybe c
-> (Maybe b, Maybe c)
_unfoldF _ _ Nothing = (Nothing, Nothing)
_unfoldF f _ (Just x) = case f x of
Just (y, x') -> (Just y, Just x')
Nothing -> (Nothing, Nothing)
_unfoldMF :: Monad m
=> (c -> m (Maybe (b, c)))
-> a
-> Maybe c
-> m (Maybe b, Maybe c)
_unfoldMF _ _ Nothing = return (Nothing, Nothing)
_unfoldMF f _ (Just x) = do
res <- f x
return $ case res of
Just (y, x') -> (Just y, Just x')
Nothing -> (Nothing, Nothing)
-- | Analogous to 'iterate' from "Prelude". Keeps accumulator value and
-- continually applies the function to the accumulator at every step,
-- outputting the result.
--
-- The first result is the initial accumulator value.
--
-- >>> take 10 . streamAuto' (iterator (*2) 1) $ repeat ()
-- [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
iterator :: Serialize b
=> (b -> b) -- ^ iterating function
-> b -- ^ starting value and initial output
-> Auto m a b
iterator f = accumD (\x _ -> f x)
-- | Like 'iterator', but with a monadic function.
iteratorM :: (Serialize b, Monad m)
=> (b -> m b) -- ^ (monadic) iterating function
-> b -- ^ starting value and initial output
-> Auto m a b
iteratorM f = accumMD (\x _ -> f x)
-- | The non-resuming/non-serializing version of 'iterator'.
iterator_ :: (b -> b) -- ^ iterating function
-> b -- ^ starting value and initial output
-> Auto m a b
iterator_ f = accumD_ (\x _ -> f x)
-- | The non-resuming/non-serializing version of 'iteratorM'.
iteratorM_ :: Monad m
=> (b -> m b) -- ^ (monadic) iterating function
-> b -- ^ starting value and initial output
-> Auto m a b
iteratorM_ f = accumMD_ (\x _ -> f x)
-- | Continually enumerate from the starting value, using `succ`.
enumFromA :: (Serialize b, Enum b)
=> b -- ^ initial value
-> Auto m a b
enumFromA = iterator succ
-- | The non-serializing/non-resuming version of `enumFromA`.
enumFromA_ :: Enum b
=> b -- ^ initial value
-> Auto m a b
enumFromA_ = iterator_ succ
-- | Given a function from discrete enumerable inputs, iterates through all
-- of the results of that function.
--
-- >>> take 10 . streamAuto' (discreteF (^2) 0) $ repeat ()
-- [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
discreteF :: (Enum c, Serialize c)
=> (c -> b) -- ^ discrete function
-> c -- ^ initial input
-> Auto m a b
discreteF f = mkState $ \_ x -> (f x, succ x)
-- | The non-resuming/non-serializing version of `discreteF`.
discreteF_ :: Enum c
=> (c -> b) -- ^ discrete function
-> c -- ^ initial input
-> Auto m a b
discreteF_ f = mkState_ $ \_ x -> (f x, succ x)
-- $constant
--
-- Here we have the "constant producers": 'Auto's whose output is always
-- the same value, or the result of executing the same monadic action.
--
-- @
-- 'pure' :: 'Monad' m => b -> 'Auto' m a b
-- 'effect' :: 'Monad' m => m b -> 'Auto' m a b
-- @
--
-- 'pure' always outputs the same value, ignoring its input, and 'effect'
-- always outputs the result of executing the same monadic action, ignoring
-- its input.
-- | To get every output, executes the monadic action and returns the
-- result as the output. Always ignores input.
--
-- This is basically like an "effectful" 'pure':
--
-- @
-- 'pure' :: b -> 'Auto' m a b
-- 'effect' :: m b -> 'Auto' m a b
-- @
--
-- The output of 'pure' is always the same, and the output of 'effect' is
-- always the result of the same monadic action. Both ignore their inputs.
--
-- Fun times when the underling 'Monad' is, for instance, 'Reader'.
--
-- >>> let a = effect ask :: Auto (Reader b) a b
-- >>> let r = evalAuto a () :: Reader b b
-- >>> runReader r "hello"
-- "hello"
-- >>> runReader r 100
-- 100
--
-- If your underling monad has effects ('IO', 'State', 'Maybe', 'Writer',
-- etc.), then it might be fun to take advantage of '*>' from
-- "Control.Applicative" to "tack on" an effect to a normal 'Auto':
--
-- >>> let a = effect (modify (+1)) *> sumFrom 0 :: Auto (State Int) Int Int
-- >>> let st = streamAuto a [1..10]
-- >>> let (ys, s') = runState st 0
-- >>> ys
-- [1,3,6,10,15,21,28,36,45,55]
-- >>> s'
-- 10
--
-- Our 'Auto' @a@ behaves exactly like @'sumFrom' 0@, except at each step,
-- it also increments the underlying/global state by one. It is @'sumFrom'
-- 0@ with an "attached effect".
--
effect :: m b -- ^ monadic action to contually execute.
-> Auto m a b
effect = mkConstM
{-# INLINE effect #-}
| mstksg/auto | src/Control/Auto/Generate.hs | mit | 10,364 | 0 | 16 | 3,042 | 1,649 | 940 | 709 | 132 | 3 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
module Apollo.Monad.Types where
import Apollo.Types
import Apollo.YoutubeDl
import Control.Concurrent.MVar
import Control.Monad.Except
import Control.Monad.Trans.Control
import Data.Aeson ( ToJSON(..), object, (.=) )
import Data.Default.Class
import Data.IORef
import Data.List.NonEmpty ( NonEmpty )
import Data.Text ( Text )
import qualified Data.Text as T
import qualified Network.MPD as MPD
import Network.URI ( URI )
------------------------------------------------------------------------
--- Core Apollo Monad actions ---
------------------------------------------------------------------------
-- | An Apollo monad can control asynchronous jobs, runs in the IO monad, and
-- can perform a number of distinguished actions.
class (MonadJobControl m, MonadBaseControl IO m) => MonadApollo m where
-- | Call youtube-dl on the given URL and store all the generated tracks into
-- the given music directory.
youtubeDl
:: MusicDir -- ^ directory into which to place the downloaded files
-> YoutubeDlUrl -- ^ url to download
-> YoutubeDlSettings -- ^ settings for the download
-> ((Int, Int) -> m ()) -- ^ action to perform on progress updates
-> m (NonEmpty Entry)
-- | Gets the playback status.
getPlayerStatus :: m PlayerStatus
-- | Enqueues the given tracks for playback after the current playing track,
-- if any.
enqueueTracks
:: PositionBetweenTracks -> NonEmpty FilePath -> m (NonEmpty PlaylistItemId)
-- | Deletes the given tracks from the playlist.
deleteTracks
:: [PlaylistItemId]
-> m ()
-- | Gets the current playlist.
getPlaylist :: m Playlist
-- | Transcodes a given track with given transcoding parameters.
-- The unique identifier for the track is returned.
makeTranscode :: FilePath -> TranscodingParameters -> m TrackId
-- | Reads a track lazily.
readTrackLazily :: FilePath -> m LazyTrackData
-- | Reads a transcode lazily.
-- A transcode is identified by its sourc track id and its parameters.
readTranscodeLazily :: TrackId -> TranscodingParameters -> m LazyTrackData
-- | Reads an archive lazily.
readArchiveLazily :: ArchiveId -> m LazyArchiveData
-- | Constructs an archive with the given entries.
makeArchive :: Compressor -> NonEmpty ArchiveEntry -> m ArchiveId
-- | Gets a URL to a static resource such as an archive.
getStaticUrl :: StaticResource -> m Url
getApiLink :: URI -> m Url
-- getMusicDir :: Apollo k e a FilePath
-- getMusicDir = liftF $ GetMusicDir id
--
-- getTranscodeDir :: Apollo k e a FilePath
-- getTranscodeDir = liftF $ GetTranscodeDir id
--
-- getArchiveDir :: Apollo k e a FilePath
-- getArchiveDir = liftF $ GetArchiveDir id
------------------------------------------------------------------------
--- Derived actions ---
------------------------------------------------------------------------
-- | Essentially 'forM' but as a 'Job' that updates the progress after each
-- item processed. The length of the traversable to process must be specified.
-- If you're just going to use 'length' provided by 'Traversable', then use
-- 'forAsync' which does this for you.
forUpdateLen :: Traversable t => Int -> t x -> (x -> Job e a) -> Job e (t a)
forUpdateLen n xs f = do
-- we're forced to use IORefs here instead of just zipping with [1..] beacuse
-- the container is an arbitrary Traversable and I can't figure out a nice
-- way to achieve the zipping.
v <- liftIO (newIORef 0)
forM xs $ \x -> do
y <- f x
i <- liftIO $ atomicModifyIORef v (\i -> (i + 1, i))
reportProgress (Progress i n)
pure y
-- | Essentially 'forM' but as a 'Job' that updates the progress after each
-- item processed.
forUpdate :: Traversable t => t x -> (x -> Job e a) -> Job e (t a)
forUpdate xs = forUpdateLen (length xs) xs
------------------------------------------------------------------------
--- Locks & Settings & Errors ---
------------------------------------------------------------------------
-- | A lock for MPD access. This lock enforces a sort of transactional
-- processing of MPD actions. The 'interpretApolloIO' interpreter batches all
-- MPD actions performed via 'mpd' into one transaction protected by this lock,
-- so that concurrent web requests will block for MPD access.
newtype MpdLock = MpdLock (MVar ())
-- | Guards an IO action with the MPD lock.
withMpdLock :: MpdLock -> IO a -> IO a
withMpdLock (MpdLock d) = withMVar d . const
-- | Constructs an MPD lock.
makeMpdLock :: IO MpdLock
makeMpdLock = MpdLock <$> newMVar ()
-- | Connection settings for MPD.
data MpdSettings
= MpdSettings
{ mpdHost :: !String
-- ^ The hostname to connect to.
, mpdPort :: !Integer
-- ^ The port to connect to.
, mpdPassword :: !String
-- ^ The password to authenticate with the MPD instance.
}
-- | Localhost, post 6600, no password.
instance Default MpdSettings where
def = MpdSettings
{ mpdHost = "localhost"
, mpdPort = 6600
, mpdPassword = ""
}
newtype MpdError = MpdError MPD.MPDError deriving Show
-- | Settings of a server.
data ServerSettings
= ServerSettings
{ serverDomain :: Text
, serverScheme :: Text
, serverPort :: Int
}
-- | Converts server settings into a /base/ URL onto which a path and query
-- string may be appended to obtain a /full/ URL.
serverSettingsBaseUrl :: ServerSettings -> Url
serverSettingsBaseUrl ServerSettings{..} = Url u where
u = serverScheme <> "://" <> serverDomain <> ":" <> T.pack (show serverPort)
-- | The overall configuration for the 'ApolloIO' interpretation of 'Apollo'.
data ApolloSettings k e a
= ApolloSettings
{ apolloApiServerSettings :: ServerSettings
, apolloStaticServerSettings :: ServerSettings
, apolloMpdLock :: MpdLock
, apolloMpdSettings :: MpdSettings
, apolloJobBank :: MVar (JobBank k e a)
, apolloMusicDirP :: FilePath
, apolloTranscodeDirP :: FilePath
, apolloArchiveDirP :: FilePath
, apolloTmpDir :: FilePath
}
-- | Errors that can arise during the IO interpretation of the 'Apollo' monad,
-- 'runApolloIO'.
data ApolloError k
-- | When an internal MPD error occurs, we just forward it along.
= ApolloMpdError MpdError
-- | A transcode was requested, but it could not be located.
| NoSuchTranscode TrackId TranscodingParameters
-- | A job was requested, but it could not be located.
| NoSuchJob k
-- | An async result was found, but it was of the wrong type.
| WrongAsyncResult
String
String
-- | A youtube-dl subprocess produced no output files.
| EmptyYoutubeDlResult
-- | A subprocess failed unexpectedly.
| SubprocessDied String
-- | An unknown error occurred.
-- (Used to implement a MonadFail instance.)
| Failure String
instance ToJSON k => ToJSON (ApolloError k) where
toJSON = \case
ApolloMpdError e -> object
[ "type" .= (id @Text "mpd")
, "message" .= show e
]
NoSuchTranscode tid params -> object
[ "type" .= (id @Text "transcode not found")
, "message" .= (id @Text "no such transcode")
, "trackId" .= tid
, "params" .= params
]
NoSuchJob k -> object
[ "type" .= (id @Text "job not found")
, "message" .= (id @Text "no such job")
, "jobId" .= k
]
WrongAsyncResult expected actual -> object
[ "type" .= (id @Text "wrong async result")
, "message" .= (id @Text "an async job completed with an unexpected type")
, "expected" .= expected
, "actual" .= actual
]
EmptyYoutubeDlResult -> object
[ "type" .= id @Text "empty youtube-dl result"
, "message" .= id @Text "youtube-dl subprocess produced no output files"
]
SubprocessDied msg -> object
[ "type" .= id @Text "subprocess died"
, "message" .= msg
]
Failure msg -> object
[ "type" .= id @Text "unknown error"
, "message" .= msg
]
| tsani/apollo | src/Apollo/Monad/Types.hs | mit | 8,279 | 0 | 17 | 1,832 | 1,358 | 758 | 600 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.