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
-- | These graph traversal functions mirror the ones in Cabal, but work with -- the more complete (and fine-grained) set of dependencies provided by -- PackageFixedDeps rather than only the library dependencies provided by -- PackageInstalled. {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE CPP #-} module Distribution.Client.PlanIndex ( -- * FakeMap and related operations FakeMap , fakeDepends , fakeLookupComponentId -- * Graph traversal functions , brokenPackages , dependencyClosure , dependencyCycles , dependencyGraph , dependencyInconsistencies , reverseDependencyClosure , reverseTopologicalOrder , topologicalOrder ) where import Prelude hiding (lookup) import qualified Data.Map as Map import qualified Data.Tree as Tree import qualified Data.Graph as Graph import Data.Array ((!)) import Data.Map (Map) import Data.Maybe (isNothing, fromMaybe, fromJust) import Data.Either (rights) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (Monoid(..)) #endif import Distribution.Package ( PackageName(..), PackageIdentifier(..), ComponentId(..) , Package(..), packageName, packageVersion ) import Distribution.Version ( Version ) import Distribution.Client.ComponentDeps (ComponentDeps) import qualified Distribution.Client.ComponentDeps as CD import Distribution.Client.Types ( PackageFixedDeps(..) ) import Distribution.Simple.PackageIndex ( PackageIndex, allPackages, insert, lookupComponentId ) import Distribution.Package ( HasComponentId(..), PackageId ) -- Note [FakeMap] ----------------- -- We'd like to use the PackageIndex defined in this module for -- cabal-install's InstallPlan. However, at the moment, this -- data structure is indexed by ComponentId, which we don't -- know until after we've compiled a package (whereas InstallPlan -- needs to store not-compiled packages in the index.) Eventually, -- an ComponentId will be calculatable prior to actually -- building the package (making it something of a misnomer), but -- at the moment, the "fake installed package ID map" is a workaround -- to solve this problem while reusing PackageIndex. The basic idea -- is that, since we don't know what an ComponentId is -- beforehand, we just fake up one based on the package ID (it only -- needs to be unique for the particular install plan), and fill -- it out with the actual generated ComponentId after the -- package is successfully compiled. -- -- However, there is a problem: in the index there may be -- references using the old package ID, which are now dangling if -- we update the ComponentId. We could map over the entire -- index to update these pointers as well (a costly operation), but -- instead, we've chosen to parametrize a variety of important functions -- by a FakeMap, which records what a fake installed package ID was -- actually resolved to post-compilation. If we do a lookup, we first -- check and see if it's a fake ID in the FakeMap. -- -- It's a bit grungy, but we expect this to only be temporary anyway. -- (Another possible workaround would have been to *not* update -- the installed package ID, but I decided this would be hard to -- understand.) -- | Map from fake package keys to real ones. See Note [FakeMap] type FakeMap = Map ComponentId ComponentId -- | Variant of `depends` which accepts a `FakeMap` -- -- Analogous to `fakeInstalledDepends`. See Note [FakeMap]. fakeDepends :: PackageFixedDeps pkg => FakeMap -> pkg -> ComponentDeps [ComponentId] fakeDepends fakeMap = fmap (map resolveFakeId) . depends where resolveFakeId :: ComponentId -> ComponentId resolveFakeId ipid = Map.findWithDefault ipid ipid fakeMap --- | Variant of 'lookupComponentId' which accepts a 'FakeMap'. See Note --- [FakeMap]. fakeLookupComponentId :: FakeMap -> PackageIndex a -> ComponentId -> Maybe a fakeLookupComponentId fakeMap index pkg = lookupComponentId index (Map.findWithDefault pkg pkg fakeMap) -- | All packages that have dependencies that are not in the index. -- -- Returns such packages along with the dependencies that they're missing. -- brokenPackages :: (PackageFixedDeps pkg) => FakeMap -> PackageIndex pkg -> [(pkg, [ComponentId])] brokenPackages fakeMap index = [ (pkg, missing) | pkg <- allPackages index , let missing = [ pkg' | pkg' <- CD.nonSetupDeps (depends pkg) , isNothing (fakeLookupComponentId fakeMap index pkg') ] , not (null missing) ] -- | Compute all roots of the install plan, and verify that the transitive -- plans from those roots are all consistent. -- -- NOTE: This does not check for dependency cycles. Moreover, dependency cycles -- may be absent from the subplans even if the larger plan contains a dependency -- cycle. Such cycles may or may not be an issue; either way, we don't check -- for them here. dependencyInconsistencies :: forall pkg. (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> Bool -> PackageIndex pkg -> [(PackageName, [(PackageIdentifier, Version)])] dependencyInconsistencies fakeMap indepGoals index = concatMap (dependencyInconsistencies' fakeMap) subplans where subplans :: [PackageIndex pkg] subplans = rights $ map (dependencyClosure fakeMap index) (rootSets fakeMap indepGoals index) -- | Compute the root sets of a plan -- -- A root set is a set of packages whose dependency closure must be consistent. -- This is the set of all top-level library roots (taken together normally, or -- as singletons sets if we are considering them as independent goals), along -- with all setup dependencies of all packages. rootSets :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> Bool -> PackageIndex pkg -> [[ComponentId]] rootSets fakeMap indepGoals index = if indepGoals then map (:[]) libRoots else [libRoots] ++ setupRoots index where libRoots = libraryRoots fakeMap index -- | Compute the library roots of a plan -- -- The library roots are the set of packages with no reverse dependencies -- (no reverse library dependencies but also no reverse setup dependencies). libraryRoots :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [ComponentId] libraryRoots fakeMap index = map (installedComponentId . toPkgId) roots where (graph, toPkgId, _) = dependencyGraph fakeMap index indegree = Graph.indegree graph roots = filter isRoot (Graph.vertices graph) isRoot v = indegree ! v == 0 -- | The setup dependencies of each package in the plan setupRoots :: PackageFixedDeps pkg => PackageIndex pkg -> [[ComponentId]] setupRoots = filter (not . null) . map (CD.setupDeps . depends) . allPackages -- | Given a package index where we assume we want to use all the packages -- (use 'dependencyClosure' if you need to get such a index subset) find out -- if the dependencies within it use consistent versions of each package. -- Return all cases where multiple packages depend on different versions of -- some other package. -- -- Each element in the result is a package name along with the packages that -- depend on it and the versions they require. These are guaranteed to be -- distinct. -- dependencyInconsistencies' :: forall pkg. (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [(PackageName, [(PackageIdentifier, Version)])] dependencyInconsistencies' fakeMap index = [ (name, [ (pid,packageVersion dep) | (dep,pids) <- uses, pid <- pids]) | (name, ipid_map) <- Map.toList inverseIndex , let uses = Map.elems ipid_map , reallyIsInconsistent (map fst uses) ] where -- For each package name (of a dependency, somewhere) -- and each installed ID of that that package -- the associated package instance -- and a list of reverse dependencies (as source IDs) inverseIndex :: Map PackageName (Map ComponentId (pkg, [PackageId])) inverseIndex = Map.fromListWith (Map.unionWith (\(a,b) (_,b') -> (a,b++b'))) [ (packageName dep, Map.fromList [(ipid,(dep,[packageId pkg]))]) | -- For each package @pkg@ pkg <- allPackages index -- Find out which @ipid@ @pkg@ depends on , ipid <- CD.nonSetupDeps (fakeDepends fakeMap pkg) -- And look up those @ipid@ (i.e., @ipid@ is the ID of @dep@) , Just dep <- [fakeLookupComponentId fakeMap index ipid] ] -- If, in a single install plan, we depend on more than one version of a -- package, then this is ONLY okay in the (rather special) case that we -- depend on precisely two versions of that package, and one of them -- depends on the other. This is necessary for example for the base where -- we have base-3 depending on base-4. reallyIsInconsistent :: [pkg] -> Bool reallyIsInconsistent [] = False reallyIsInconsistent [_p] = False reallyIsInconsistent [p1, p2] = let pid1 = installedComponentId p1 pid2 = installedComponentId p2 in Map.findWithDefault pid1 pid1 fakeMap `notElem` CD.nonSetupDeps (fakeDepends fakeMap p2) && Map.findWithDefault pid2 pid2 fakeMap `notElem` CD.nonSetupDeps (fakeDepends fakeMap p1) reallyIsInconsistent _ = True -- | Find if there are any cycles in the dependency graph. If there are no -- cycles the result is @[]@. -- -- This actually computes the strongly connected components. So it gives us a -- list of groups of packages where within each group they all depend on each -- other, directly or indirectly. -- dependencyCycles :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [[pkg]] dependencyCycles fakeMap index = [ vs | Graph.CyclicSCC vs <- Graph.stronglyConnComp adjacencyList ] where adjacencyList = [ (pkg, installedComponentId pkg, CD.nonSetupDeps (fakeDepends fakeMap pkg)) | pkg <- allPackages index ] -- | Tries to take the transitive closure of the package dependencies. -- -- If the transitive closure is complete then it returns that subset of the -- index. Otherwise it returns the broken packages as in 'brokenPackages'. -- -- * Note that if the result is @Right []@ it is because at least one of -- the original given 'PackageIdentifier's do not occur in the index. dependencyClosure :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [ComponentId] -> Either [(pkg, [ComponentId])] (PackageIndex pkg) dependencyClosure fakeMap index pkgids0 = case closure mempty [] pkgids0 of (completed, []) -> Right completed (completed, _) -> Left (brokenPackages fakeMap completed) where closure completed failed [] = (completed, failed) closure completed failed (pkgid:pkgids) = case fakeLookupComponentId fakeMap index pkgid of Nothing -> closure completed (pkgid:failed) pkgids Just pkg -> case fakeLookupComponentId fakeMap completed (installedComponentId pkg) of Just _ -> closure completed failed pkgids Nothing -> closure completed' failed pkgids' where completed' = insert pkg completed pkgids' = CD.nonSetupDeps (depends pkg) ++ pkgids topologicalOrder :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [pkg] topologicalOrder fakeMap index = map toPkgId . Graph.topSort $ graph where (graph, toPkgId, _) = dependencyGraph fakeMap index reverseTopologicalOrder :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [pkg] reverseTopologicalOrder fakeMap index = map toPkgId . Graph.topSort . Graph.transposeG $ graph where (graph, toPkgId, _) = dependencyGraph fakeMap index -- | Takes the transitive closure of the packages reverse dependencies. -- -- * The given 'PackageIdentifier's must be in the index. -- reverseDependencyClosure :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> [ComponentId] -> [pkg] reverseDependencyClosure fakeMap index = map vertexToPkg . concatMap Tree.flatten . Graph.dfs reverseDepGraph . map (fromMaybe noSuchPkgId . pkgIdToVertex) where (depGraph, vertexToPkg, pkgIdToVertex) = dependencyGraph fakeMap index reverseDepGraph = Graph.transposeG depGraph noSuchPkgId = error "reverseDependencyClosure: package is not in the graph" -- | Builds a graph of the package dependencies. -- -- Dependencies on other packages that are not in the index are discarded. -- You can check if there are any such dependencies with 'brokenPackages'. -- dependencyGraph :: (PackageFixedDeps pkg, HasComponentId pkg) => FakeMap -> PackageIndex pkg -> (Graph.Graph, Graph.Vertex -> pkg, ComponentId -> Maybe Graph.Vertex) dependencyGraph fakeMap index = (graph, vertexToPkg, idToVertex) where (graph, vertexToPkg', idToVertex) = Graph.graphFromEdges edges vertexToPkg = fromJust . (\((), key, _targets) -> lookupComponentId index key) . vertexToPkg' pkgs = allPackages index edges = map edgesFrom pkgs resolve pid = Map.findWithDefault pid pid fakeMap edgesFrom pkg = ( () , resolve (installedComponentId pkg) , CD.nonSetupDeps (fakeDepends fakeMap pkg) )
thoughtpolice/cabal
cabal-install/Distribution/Client/PlanIndex.hs
bsd-3-clause
14,140
0
18
3,512
2,410
1,345
1,065
181
5
{-# LANGUAGE MagicHash #-} ------------------------------------------------------------------------ -- | -- Module : Kask.Math -- Copyright : (c) 2016 Konrad Grzanek -- License : BSD-style (see the file LICENSE) -- Created : 2016-09-25 -- Maintainer : kongra@gmail.com -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------ module Kask.Math ( nthNaiveFib , nthNaiveUnpackedFib , nthFib , fib ) where import GHC.Exts import RIO import RIO.List (iterate) nthNaiveFib :: Word64 -> Word64 nthNaiveFib 0 = 0 nthNaiveFib 1 = 1 nthNaiveFib n = nthNaiveFib (n - 1) + nthNaiveFib (n - 2) nthNaiveUnpackedFib :: Int# -> Int# nthNaiveUnpackedFib 0# = 0# nthNaiveUnpackedFib 1# = 1# nthNaiveUnpackedFib n = nthNaiveUnpackedFib (n -# 1#) +# nthNaiveUnpackedFib (n -# 2#) nthFib :: Word64 -> Integer nthFib 0 = 0 nthFib 1 = 1 nthFib n = loop 0 1 n where loop !a !_ 0 = a loop !a !b !n' = loop b (a + b) (n' - 1) {-# INLINABLE nthFib #-} -- INFINITE FIB SEQUENCE data FibGen = FibGen !Integer !Integer fibgen :: FibGen -> FibGen fibgen (FibGen a b) = FibGen b (a + b) fibfst :: FibGen -> Integer fibfst (FibGen a _) = a fib :: () -> [Integer] fib _ = map fibfst $ iterate fibgen $ FibGen 0 1 {-# INLINABLE fib #-}
kongra/kask-base
src/Kask/Math.hs
bsd-3-clause
1,391
0
9
331
375
199
176
-1
-1
import System.Environment import System.IO import Text.ParserCombinators.Parsec import Control.Monad import Data.ByteString.Lazy.Char8 as BS hiding (length,take,drop,filter,head,concat) import Control.Applicative hiding ((<|>), many) {-- getfirst(Open usp Tukubai) designed by Nobuaki Tounaka written by Ryuichi Ueda The MIT License Copyright (C) 2012 Universal Shell Programming Laboratory 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. --} showUsage :: IO () showUsage = do System.IO.hPutStr stderr ("Usage : getfirst <f1> <f2> <file>\n" ++ "Tue Aug 6 10:09:16 JST 2013\n" ++ "Open usp Tukubai (LINUX+FREEBSD), Haskell ver.\n") main :: IO () main = do args <- getArgs case args of ["-h"] -> showUsage ["--help"] -> showUsage [one,two] -> readF "-" >>= mainProc (read one::Int) (read two::Int) [one,two,file] -> readF file >>= mainProc (read one::Int) (read two::Int) mainProc :: Int -> Int -> BS.ByteString -> IO () mainProc f t str = BS.putStr $ BS.unlines $ getFirst ks (BS.pack "") where lns = BS.lines str ks = [ splitLine (myWords ln) f t | ln <- lns ] data Record = Record BS.ByteString BS.ByteString BS.ByteString splitLine :: [BS.ByteString] -> Int -> Int -> Record splitLine ws f t = Record pre key post where pre = BS.unwords $ take (f-1) ws post = BS.unwords $ drop t ws key = BS.unwords $ drop (f-1) $ take t ws getFirst :: [Record] -> BS.ByteString -> [BS.ByteString] getFirst [] key = [] getFirst ((Record pr k po):rs) key = if k == key then getFirst rs key else (decode pr k po) : getFirst rs k decode :: BS.ByteString -> BS.ByteString -> BS.ByteString -> BS.ByteString decode pr k po = BS.unwords $ filter (/= (BS.pack "")) [pr,k,po] readF :: String -> IO BS.ByteString readF "-" = BS.getContents readF f = BS.readFile f myWords :: BS.ByteString -> [BS.ByteString] myWords line = filter (/= BS.pack "") $ BS.split ' ' line
ShellShoccar-jpn/Open-usp-Tukubai
COMMANDS.HS/getfirst.hs
mit
3,182
0
13
815
726
384
342
39
4
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif {- | Maintainer : judah.jacobson@gmail.com Stability : experimental Portability : portable (FFI) -} module System.Console.Terminfo( module System.Console.Terminfo.Base, module System.Console.Terminfo.Keys, module System.Console.Terminfo.Cursor, module System.Console.Terminfo.Effects, module System.Console.Terminfo.Edit, module System.Console.Terminfo.Color ) where import System.Console.Terminfo.Base import System.Console.Terminfo.Keys import System.Console.Terminfo.Cursor import System.Console.Terminfo.Edit import System.Console.Terminfo.Effects import System.Console.Terminfo.Color
DavidAlphaFox/ghc
libraries/terminfo/System/Console/Terminfo.hs
bsd-3-clause
702
0
5
86
104
77
27
14
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE ViewPatterns #-} module Database.Persist.Quasi ( parse , PersistSettings (..) , upperCaseSettings , lowerCaseSettings , nullable #if TEST , Token (..) , tokenize , parseFieldType #endif ) where import Prelude hiding (lines) import Database.Persist.Types import Data.Char import Data.Maybe (mapMaybe, fromMaybe, maybeToList) import Data.Text (Text) import qualified Data.Text as T import Control.Arrow ((&&&)) import qualified Data.Map as M import Data.List (foldl') import Data.Monoid (mappend) import Control.Monad (msum, mplus) data ParseState a = PSDone | PSFail String | PSSuccess a Text deriving Show parseFieldType :: Text -> Either String FieldType parseFieldType t0 = case parseApplyFT t0 of PSSuccess ft t' | T.all isSpace t' -> Right ft PSFail err -> Left $ "PSFail " ++ err other -> Left $ show other where parseApplyFT t = case goMany id t of PSSuccess (ft:fts) t' -> PSSuccess (foldl' FTApp ft fts) t' PSSuccess [] _ -> PSFail "empty" PSFail err -> PSFail err PSDone -> PSDone parseEnclosed :: Char -> (FieldType -> FieldType) -> Text -> ParseState FieldType parseEnclosed end ftMod t = let (a, b) = T.break (== end) t in case parseApplyFT a of PSSuccess ft t' -> case (T.dropWhile isSpace t', T.uncons b) of ("", Just (c, t'')) | c == end -> PSSuccess (ftMod ft) (t'' `mappend` t') (x, y) -> PSFail $ show (b, x, y) x -> PSFail $ show x parse1 t = case T.uncons t of Nothing -> PSDone Just (c, t') | isSpace c -> parse1 $ T.dropWhile isSpace t' | c == '(' -> parseEnclosed ')' id t' | c == '[' -> parseEnclosed ']' FTList t' | isUpper c -> let (a, b) = T.break (\x -> isSpace x || x `elem` ("()[]"::String)) t in PSSuccess (getCon a) b | otherwise -> PSFail $ show (c, t') getCon t = case T.breakOnEnd "." t of (_, "") -> FTTypeCon Nothing t ("", _) -> FTTypeCon Nothing t (a, b) -> FTTypeCon (Just $ T.init a) b goMany front t = case parse1 t of PSSuccess x t' -> goMany (front . (x:)) t' PSFail err -> PSFail err PSDone -> PSSuccess (front []) t -- _ -> data PersistSettings = PersistSettings { psToDBName :: !(Text -> Text) , psStrictFields :: !Bool -- ^ Whether fields are by default strict. Default value: @True@. -- -- Since 1.2 , psIdName :: !Text -- ^ The name of the id column. Default value: @id@ -- The name of the id column can also be changed on a per-model basis -- <https://github.com/yesodweb/persistent/wiki/Persistent-entity-syntax> -- -- Since 2.0 } defaultPersistSettings, upperCaseSettings, lowerCaseSettings :: PersistSettings defaultPersistSettings = PersistSettings { psToDBName = id , psStrictFields = True , psIdName = "id" } upperCaseSettings = defaultPersistSettings lowerCaseSettings = defaultPersistSettings { psToDBName = let go c | isUpper c = T.pack ['_', toLower c] | otherwise = T.singleton c in T.dropWhile (== '_') . T.concatMap go } -- | Parses a quasi-quoted syntax into a list of entity definitions. parse :: PersistSettings -> Text -> [EntityDef] parse ps = parseLines ps . removeSpaces . filter (not . empty) . map tokenize . T.lines -- | A token used by the parser. data Token = Spaces !Int -- ^ @Spaces n@ are @n@ consecutive spaces. | Token Text -- ^ @Token tok@ is token @tok@ already unquoted. deriving (Show, Eq) -- | Tokenize a string. tokenize :: Text -> [Token] tokenize t | T.null t = [] | "--" `T.isPrefixOf` t = [] -- Comment until the end of the line. | "#" `T.isPrefixOf` t = [] -- Also comment to the end of the line, needed for a CPP bug (#110) | T.head t == '"' = quotes (T.tail t) id | T.head t == '(' = parens 1 (T.tail t) id | isSpace (T.head t) = let (spaces, rest) = T.span isSpace t in Spaces (T.length spaces) : tokenize rest -- support mid-token quotes and parens | Just (beforeEquals, afterEquals) <- findMidToken t , not (T.any isSpace beforeEquals) , Token next : rest <- tokenize afterEquals = Token (T.concat [beforeEquals, "=", next]) : rest | otherwise = let (token, rest) = T.break isSpace t in Token token : tokenize rest where findMidToken t' = case T.break (== '=') t' of (x, T.drop 1 -> y) | "\"" `T.isPrefixOf` y || "(" `T.isPrefixOf` y -> Just (x, y) _ -> Nothing quotes t' front | T.null t' = error $ T.unpack $ T.concat $ "Unterminated quoted string starting with " : front [] | T.head t' == '"' = Token (T.concat $ front []) : tokenize (T.tail t') | T.head t' == '\\' && T.length t' > 1 = quotes (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):)) | otherwise = let (x, y) = T.break (`elem` ['\\','\"']) t' in quotes y (front . (x:)) parens count t' front | T.null t' = error $ T.unpack $ T.concat $ "Unterminated parens string starting with " : front [] | T.head t' == ')' = if count == (1 :: Int) then Token (T.concat $ front []) : tokenize (T.tail t') else parens (count - 1) (T.tail t') (front . (")":)) | T.head t' == '(' = parens (count + 1) (T.tail t') (front . ("(":)) | T.head t' == '\\' && T.length t' > 1 = parens count (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):)) | otherwise = let (x, y) = T.break (`elem` ['\\','(',')']) t' in parens count y (front . (x:)) -- | A string of tokens is empty when it has only spaces. There -- can't be two consecutive 'Spaces', so this takes /O(1)/ time. empty :: [Token] -> Bool empty [] = True empty [Spaces _] = True empty _ = False -- | A line. We don't care about spaces in the middle of the -- line. Also, we don't care about the ammount of indentation. data Line = Line { lineIndent :: Int , tokens :: [Text] } -- | Remove leading spaces and remove spaces in the middle of the -- tokens. removeSpaces :: [[Token]] -> [Line] removeSpaces = map toLine where toLine (Spaces i:rest) = toLine' i rest toLine xs = toLine' 0 xs toLine' i = Line i . mapMaybe fromToken fromToken (Token t) = Just t fromToken Spaces{} = Nothing -- | Divide lines into blocks and make entity definitions. parseLines :: PersistSettings -> [Line] -> [EntityDef] parseLines ps lines = fixForeignKeysAll $ toEnts lines where toEnts (Line indent (name:entattribs) : rest) = let (x, y) = span ((> indent) . lineIndent) rest in mkEntityDef ps name entattribs x : toEnts y toEnts (Line _ []:rest) = toEnts rest toEnts [] = [] fixForeignKeysAll :: [UnboundEntityDef] -> [EntityDef] fixForeignKeysAll unEnts = map fixForeignKeys unEnts where ents = map unboundEntityDef unEnts entLookup = M.fromList $ map (\e -> (entityHaskell e, e)) ents fixForeignKeys :: UnboundEntityDef -> EntityDef fixForeignKeys (UnboundEntityDef foreigns ent) = ent { entityForeigns = map (fixForeignKey ent) foreigns } -- check the count and the sqltypes match and update the foreignFields with the names of the primary columns fixForeignKey :: EntityDef -> UnboundForeignDef -> ForeignDef fixForeignKey ent (UnboundForeignDef foreignFieldTexts fdef) = case M.lookup (foreignRefTableHaskell fdef) entLookup of Just pent -> case entityPrimary pent of Just pdef -> if length foreignFieldTexts /= length (compositeFields pdef) then lengthError pdef else let fds_ffs = zipWith (toForeignFields pent) foreignFieldTexts (compositeFields pdef) in fdef { foreignFields = map snd fds_ffs , foreignNullable = setNull $ map fst fds_ffs } Nothing -> error $ "no explicit primary key fdef="++show fdef++ " ent="++show ent Nothing -> error $ "could not find table " ++ show (foreignRefTableHaskell fdef) ++ " fdef=" ++ show fdef ++ " allnames=" ++ show (map (unHaskellName . entityHaskell . unboundEntityDef) unEnts) ++ "\n\nents=" ++ show ents where setNull :: [FieldDef] -> Bool setNull [] = error "setNull: impossible!" setNull (fd:fds) = let nullSetting = isNull fd in if all ((nullSetting ==) . isNull) fds then nullSetting else error $ "foreign key columns must all be nullable or non-nullable" ++ show (map (unHaskellName . fieldHaskell) (fd:fds)) isNull = (NotNullable /=) . nullable . fieldAttrs toForeignFields pent fieldText pfd = case chktypes fd haskellField (entityFields pent) pfh of Just err -> error err Nothing -> (fd, ((haskellField, fieldDB fd), (pfh, pfdb))) where fd = getFd (entityFields ent) haskellField haskellField = HaskellName fieldText (pfh, pfdb) = (fieldHaskell pfd, fieldDB pfd) chktypes :: FieldDef -> HaskellName -> [FieldDef] -> HaskellName -> Maybe String chktypes ffld _fkey pflds pkey = if fieldType ffld == fieldType pfld then Nothing else Just $ "fieldType mismatch: " ++ show (fieldType ffld) ++ ", " ++ show (fieldType pfld) where pfld = getFd pflds pkey entName = entityHaskell ent getFd [] t = error $ "foreign key constraint for: " ++ show (unHaskellName entName) ++ " unknown column: " ++ show t getFd (f:fs) t | fieldHaskell f == t = f | otherwise = getFd fs t lengthError pdef = error $ "found " ++ show (length foreignFieldTexts) ++ " fkeys and " ++ show (length (compositeFields pdef)) ++ " pkeys: fdef=" ++ show fdef ++ " pdef=" ++ show pdef data UnboundEntityDef = UnboundEntityDef { _unboundForeignDefs :: [UnboundForeignDef] , unboundEntityDef :: EntityDef } lookupKeyVal :: Text -> [Text] -> Maybe Text lookupKeyVal key = lookupPrefix $ key `mappend` "=" lookupPrefix :: Text -> [Text] -> Maybe Text lookupPrefix prefix = msum . map (T.stripPrefix prefix) -- | Construct an entity definition. mkEntityDef :: PersistSettings -> Text -- ^ name -> [Attr] -- ^ entity attributes -> [Line] -- ^ indented lines -> UnboundEntityDef mkEntityDef ps name entattribs lines = UnboundEntityDef foreigns $ EntityDef entName (DBName $ getDbName ps name' entattribs) -- idField is the user-specified Id -- otherwise useAutoIdField -- but, adjust it if the user specified a Primary (setComposite primaryComposite $ fromMaybe autoIdField idField) entattribs cols uniqs [] derives extras isSum where entName = HaskellName name' (isSum, name') = case T.uncons name of Just ('+', x) -> (True, x) _ -> (False, name) (attribs, extras) = splitExtras lines attribPrefix = flip lookupKeyVal entattribs idName | Just _ <- attribPrefix "id" = error "id= is deprecated, ad a field named 'Id' and use sql=" | otherwise = Nothing (idField, primaryComposite, uniqs, foreigns) = foldl' (\(mid, mp, us, fs) attr -> let (i, p, u, f) = takeConstraint ps name' cols attr squish xs m = xs `mappend` maybeToList m in (just1 mid i, just1 mp p, squish us u, squish fs f)) (Nothing, Nothing, [],[]) attribs derives = concat $ mapMaybe takeDerives attribs cols :: [FieldDef] cols = mapMaybe (takeColsEx ps) attribs autoIdField = mkAutoIdField ps entName (DBName `fmap` idName) idSqlType idSqlType = maybe SqlInt64 (const $ SqlOther "Primary Key") primaryComposite setComposite Nothing fd = fd setComposite (Just c) fd = fd { fieldReference = CompositeRef c } just1 :: (Show x) => Maybe x -> Maybe x -> Maybe x just1 (Just x) (Just y) = error $ "expected only one of: " `mappend` show x `mappend` " " `mappend` show y just1 x y = x `mplus` y mkAutoIdField :: PersistSettings -> HaskellName -> Maybe DBName -> SqlType -> FieldDef mkAutoIdField ps entName idName idSqlType = FieldDef { fieldHaskell = HaskellName "Id" -- this should be modeled as a Maybe -- but that sucks for non-ID field -- TODO: use a sumtype FieldDef | IdFieldDef , fieldDB = fromMaybe (DBName $ psIdName ps) idName , fieldType = FTTypeCon Nothing $ keyConName $ unHaskellName entName , fieldSqlType = idSqlType -- the primary field is actually a reference to the entity , fieldReference = ForeignRef entName defaultReferenceTypeCon , fieldAttrs = [] , fieldStrict = True } defaultReferenceTypeCon :: FieldType defaultReferenceTypeCon = FTTypeCon (Just "Data.Int") "Int64" keyConName :: Text -> Text keyConName entName = entName `mappend` "Id" splitExtras :: [Line] -> ([[Text]], M.Map Text [[Text]]) splitExtras [] = ([], M.empty) splitExtras (Line indent [name]:rest) | not (T.null name) && isUpper (T.head name) = let (children, rest') = span ((> indent) . lineIndent) rest (x, y) = splitExtras rest' in (x, M.insert name (map tokens children) y) splitExtras (Line _ ts:rest) = let (x, y) = splitExtras rest in (ts:x, y) takeColsEx :: PersistSettings -> [Text] -> Maybe FieldDef takeColsEx = takeCols (\ft perr -> error $ "Invalid field type " ++ show ft ++ " " ++ perr) takeCols :: (Text -> String -> Maybe FieldDef) -> PersistSettings -> [Text] -> Maybe FieldDef takeCols _ _ ("deriving":_) = Nothing takeCols onErr ps (n':typ:rest) | not (T.null n) && isLower (T.head n) = case parseFieldType typ of Left err -> onErr typ err Right ft -> Just FieldDef { fieldHaskell = HaskellName n , fieldDB = DBName $ getDbName ps n rest , fieldType = ft , fieldSqlType = SqlOther $ "SqlType unset for " `mappend` n , fieldAttrs = rest , fieldStrict = fromMaybe (psStrictFields ps) mstrict , fieldReference = NoReference } where (mstrict, n) | Just x <- T.stripPrefix "!" n' = (Just True, x) | Just x <- T.stripPrefix "~" n' = (Just False, x) | otherwise = (Nothing, n') takeCols _ _ _ = Nothing getDbName :: PersistSettings -> Text -> [Text] -> Text getDbName ps n [] = psToDBName ps n getDbName ps n (a:as) = fromMaybe (getDbName ps n as) $ T.stripPrefix "sql=" a takeConstraint :: PersistSettings -> Text -> [FieldDef] -> [Text] -> (Maybe FieldDef, Maybe CompositeDef, Maybe UniqueDef, Maybe UnboundForeignDef) takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint' where takeConstraint' | n == "Unique" = (Nothing, Nothing, Just $ takeUniq ps tableName defs rest, Nothing) | n == "Foreign" = (Nothing, Nothing, Nothing, Just $ takeForeign ps tableName defs rest) | n == "Primary" = (Nothing, Just $ takeComposite defs rest, Nothing, Nothing) | n == "Id" = (Just $ takeId ps tableName (n:rest), Nothing, Nothing, Nothing) | otherwise = (Nothing, Nothing, Just $ takeUniq ps "" defs (n:rest), Nothing) -- retain compatibility with original unique constraint takeConstraint _ _ _ _ = (Nothing, Nothing, Nothing, Nothing) -- TODO: this is hacky (the double takeCols, the setFieldDef stuff, and setIdName. -- need to re-work takeCols function takeId :: PersistSettings -> Text -> [Text] -> FieldDef takeId ps tableName (n:rest) = fromMaybe (error "takeId: impossible!") $ setFieldDef $ takeCols (\_ _ -> addDefaultIdType) ps (field:rest `mappend` setIdName) where field = case T.uncons n of Nothing -> error "takeId: empty field" Just (f, ield) -> toLower f `T.cons` ield addDefaultIdType = takeColsEx ps (field : keyCon : rest `mappend` setIdName) setFieldDef = fmap (\fd -> let refFieldType = if fieldType fd == FTTypeCon Nothing keyCon then defaultReferenceTypeCon else fieldType fd in fd { fieldReference = ForeignRef (HaskellName tableName) $ refFieldType }) keyCon = keyConName tableName -- this will be ignored if there is already an existing sql= -- TODO: I think there is a ! ignore syntax that would screw this up setIdName = ["sql=" `mappend` psIdName ps] takeId _ tableName _ = error $ "empty Id field for " `mappend` show tableName takeComposite :: [FieldDef] -> [Text] -> CompositeDef takeComposite fields pkcols = CompositeDef (map (getDef fields) pkcols) attrs where (_, attrs) = break ("!" `T.isPrefixOf`) pkcols getDef [] t = error $ "Unknown column in primary key constraint: " ++ show t getDef (d:ds) t | nullable (fieldAttrs d) /= NotNullable = error $ "primary key column cannot be nullable: " ++ show t | fieldHaskell d == HaskellName t = d | otherwise = getDef ds t -- Unique UppercaseConstraintName list of lowercasefields takeUniq :: PersistSettings -> Text -> [FieldDef] -> [Text] -> UniqueDef takeUniq ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = UniqueDef (HaskellName n) (DBName $ psToDBName ps (tableName `T.append` n)) (map (HaskellName &&& getDBName defs) fields) attrs where (fields,attrs) = break ("!" `T.isPrefixOf`) rest getDBName [] t = error $ "Unknown column in unique constraint: " ++ show t getDBName (d:ds) t | fieldHaskell d == HaskellName t = fieldDB d | otherwise = getDBName ds t takeUniq _ tableName _ xs = error $ "invalid unique constraint on table[" ++ show tableName ++ "] expecting an uppercase constraint name xs=" ++ show xs data UnboundForeignDef = UnboundForeignDef { _unboundFields :: [Text] -- ^ fields in other entity , _unboundForeignDef :: ForeignDef } takeForeign :: PersistSettings -> Text -> [FieldDef] -> [Text] -> UnboundForeignDef takeForeign ps tableName _defs (refTableName:n:rest) | not (T.null n) && isLower (T.head n) = UnboundForeignDef fields $ ForeignDef (HaskellName refTableName) (DBName $ psToDBName ps refTableName) (HaskellName n) (DBName $ psToDBName ps (tableName `T.append` n)) [] attrs False where (fields,attrs) = break ("!" `T.isPrefixOf`) rest takeForeign _ tableName _ xs = error $ "invalid foreign key constraint on table[" ++ show tableName ++ "] expecting a lower case constraint name xs=" ++ show xs takeDerives :: [Text] -> Maybe [Text] takeDerives ("deriving":rest) = Just rest takeDerives _ = Nothing nullable :: [Text] -> IsNullable nullable s | "Maybe" `elem` s = Nullable ByMaybeAttr | "nullable" `elem` s = Nullable ByNullableAttr | otherwise = NotNullable
jasonzoladz/persistent
persistent/Database/Persist/Quasi.hs
mit
20,244
0
20
6,206
6,360
3,282
3,078
399
13
{-# LANGUAGE UnboxedSums #-} module Main where import T14051a main :: IO () main = print $ case func () of (# True | #) -> 123 _ -> 321
ezyang/ghc
testsuite/tests/unboxedsums/T14051.hs
bsd-3-clause
143
0
9
37
51
28
23
7
2
-- Killed 6.2.2 -- The trouble was that 1 was instantiated to a type (t::?) -- and the constraint (Foo (t::? -> s::*)) didn't match Foo (a::* -> b::*). -- Solution is to zap the expected type in TcEpxr.tc_expr(HsOverLit). module ShouldCompile where class Foo a where foo :: a instance Foo (a -> b) where foo = error "urk" test :: () test = foo 1
ezyang/ghc
testsuite/tests/typecheck/should_compile/tc186.hs
bsd-3-clause
362
0
7
81
60
34
26
7
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Compiler -- Copyright : Isaac Jones 2003-2004 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This has an enumeration of the various compilers that Cabal knows about. It -- also specifies the default compiler. Sadly you'll often see code that does -- case analysis on this compiler flavour enumeration like: -- -- > case compilerFlavor comp of -- > GHC -> GHC.getInstalledPackages verbosity packageDb progconf -- > JHC -> JHC.getInstalledPackages verbosity packageDb progconf -- -- Obviously it would be better to use the proper 'Compiler' abstraction -- because that would keep all the compiler-specific code together. -- Unfortunately we cannot make this change yet without breaking the -- 'UserHooks' api, which would break all custom @Setup.hs@ files, so for the -- moment we just have to live with this deficiency. If you're interested, see -- ticket #57. module Distribution.Compiler ( -- * Compiler flavor CompilerFlavor(..), buildCompilerId, buildCompilerFlavor, defaultCompilerFlavor, parseCompilerFlavorCompat, -- * Compiler id CompilerId(..), -- * Compiler info CompilerInfo(..), unknownCompilerInfo, AbiTag(..), abiTagString ) where import Distribution.Compat.Binary (Binary) import Data.Data (Data) import Data.Typeable (Typeable) import Data.Maybe (fromMaybe) import Distribution.Version (Version(..)) import GHC.Generics (Generic) import Language.Haskell.Extension (Language, Extension) import qualified System.Info (compilerName, compilerVersion) import Distribution.Text (Text(..), display) import qualified Distribution.Compat.ReadP as Parse import qualified Text.PrettyPrint as Disp import Text.PrettyPrint ((<>)) import qualified Data.Char as Char (toLower, isDigit, isAlphaNum) import Control.Monad (when) data CompilerFlavor = GHC | GHCJS | NHC | YHC | Hugs | HBC | Helium | JHC | LHC | UHC | HaskellSuite String -- string is the id of the actual compiler | OtherCompiler String deriving (Generic, Show, Read, Eq, Ord, Typeable, Data) instance Binary CompilerFlavor knownCompilerFlavors :: [CompilerFlavor] knownCompilerFlavors = [GHC, GHCJS, NHC, YHC, Hugs, HBC, Helium, JHC, LHC, UHC] instance Text CompilerFlavor where disp (OtherCompiler name) = Disp.text name disp (HaskellSuite name) = Disp.text name disp NHC = Disp.text "nhc98" disp other = Disp.text (lowercase (show other)) parse = do comp <- Parse.munch1 Char.isAlphaNum when (all Char.isDigit comp) Parse.pfail return (classifyCompilerFlavor comp) classifyCompilerFlavor :: String -> CompilerFlavor classifyCompilerFlavor s = fromMaybe (OtherCompiler s) $ lookup (lowercase s) compilerMap where compilerMap = [ (display compiler, compiler) | compiler <- knownCompilerFlavors ] --TODO: In some future release, remove 'parseCompilerFlavorCompat' and use -- ordinary 'parse'. Also add ("nhc", NHC) to the above 'compilerMap'. -- | Like 'classifyCompilerFlavor' but compatible with the old ReadS parser. -- -- It is compatible in the sense that it accepts only the same strings, -- eg "GHC" but not "ghc". However other strings get mapped to 'OtherCompiler'. -- The point of this is that we do not allow extra valid values that would -- upset older Cabal versions that had a stricter parser however we cope with -- new values more gracefully so that we'll be able to introduce new value in -- future without breaking things so much. -- parseCompilerFlavorCompat :: Parse.ReadP r CompilerFlavor parseCompilerFlavorCompat = do comp <- Parse.munch1 Char.isAlphaNum when (all Char.isDigit comp) Parse.pfail case lookup comp compilerMap of Just compiler -> return compiler Nothing -> return (OtherCompiler comp) where compilerMap = [ (show compiler, compiler) | compiler <- knownCompilerFlavors , compiler /= YHC ] buildCompilerFlavor :: CompilerFlavor buildCompilerFlavor = classifyCompilerFlavor System.Info.compilerName buildCompilerVersion :: Version buildCompilerVersion = System.Info.compilerVersion buildCompilerId :: CompilerId buildCompilerId = CompilerId buildCompilerFlavor buildCompilerVersion -- | The default compiler flavour to pick when compiling stuff. This defaults -- to the compiler used to build the Cabal lib. -- -- However if it's not a recognised compiler then it's 'Nothing' and the user -- will have to specify which compiler they want. -- defaultCompilerFlavor :: Maybe CompilerFlavor defaultCompilerFlavor = case buildCompilerFlavor of OtherCompiler _ -> Nothing _ -> Just buildCompilerFlavor -- ------------------------------------------------------------ -- * Compiler Id -- ------------------------------------------------------------ data CompilerId = CompilerId CompilerFlavor Version deriving (Eq, Generic, Ord, Read, Show) instance Binary CompilerId instance Text CompilerId where disp (CompilerId f (Version [] _)) = disp f disp (CompilerId f v) = disp f <> Disp.char '-' <> disp v parse = do flavour <- parse version <- (Parse.char '-' >> parse) Parse.<++ return (Version [] []) return (CompilerId flavour version) lowercase :: String -> String lowercase = map Char.toLower -- ------------------------------------------------------------ -- * Compiler Info -- ------------------------------------------------------------ -- | Compiler information used for resolving configurations. Some fields can be -- set to Nothing to indicate that the information is unknown. data CompilerInfo = CompilerInfo { compilerInfoId :: CompilerId, -- ^ Compiler flavour and version. compilerInfoAbiTag :: AbiTag, -- ^ Tag for distinguishing incompatible ABI's on the same architecture/os. compilerInfoCompat :: Maybe [CompilerId], -- ^ Other implementations that this compiler claims to be compatible with, if known. compilerInfoLanguages :: Maybe [Language], -- ^ Supported language standards, if known. compilerInfoExtensions :: Maybe [Extension] -- ^ Supported extensions, if known. } deriving (Generic, Show, Read) instance Binary CompilerInfo data AbiTag = NoAbiTag | AbiTag String deriving (Generic, Show, Read) instance Binary AbiTag instance Text AbiTag where disp NoAbiTag = Disp.empty disp (AbiTag tag) = Disp.text tag parse = do tag <- Parse.munch (\c -> Char.isAlphaNum c || c == '_') if null tag then return NoAbiTag else return (AbiTag tag) abiTagString :: AbiTag -> String abiTagString NoAbiTag = "" abiTagString (AbiTag tag) = tag -- | Make a CompilerInfo of which only the known information is its CompilerId, -- its AbiTag and that it does not claim to be compatible with other -- compiler id's. unknownCompilerInfo :: CompilerId -> AbiTag -> CompilerInfo unknownCompilerInfo compilerId abiTag = CompilerInfo compilerId abiTag (Just []) Nothing Nothing
DavidAlphaFox/ghc
libraries/Cabal/Cabal/Distribution/Compiler.hs
bsd-3-clause
7,244
0
15
1,380
1,301
728
573
104
2
{-# LANGUAGE RecordWildCards #-} {-| Module : Stats Description : Compute various simple statistics on a FASTA file. Copyright : (c) Bernie Pope, 2016 License : MIT Maintainer : bjpope@unimelb.edu.au Stability : experimental Portability : POSIX Read a single FASTA file as input and compute: * Num sequences. * Total number of bases in all sequences. * Minimum sequence length. * Maximum sequence length. * Average sequence length, as an integer , rounded towards zero. Sequences whose length is less than a specified minimum length are ignored (skipped) and not included in the calculation of the statistics. The basic statistics cannot be computed for empty files, and those with no reads that meet the mimimum length requirement. In such cases the result is Nothing. We do not make any assumptions about the type of data stored in the FASTA file, it could be DNA, proteins or anything else. No checks are made to ensure that the FASTA file makes sense biologically. Whitespace within the sequences will be ignored. -} module Stats (sequenceStats, Stats(..), average) where import Bio.Sequence.Fasta (seqlength, Sequence) import Data.List (foldl') -- | Basic statistics computed for a FASTA file. Note: average is -- not included, but can be computed from the 'average' function. -- Note that all values are with respect to only those reads whose -- length is at least as long as the minimum. data Stats = Stats { -- | Total number of sequences in the file. numSequences :: !Integer -- | Total number of bases from all the sequences in the file. , numBases :: !Integer -- | Minimum length of all sequences in the file. , minSequenceLength :: !Integer -- | Maximum length of all sequences in the file. , maxSequenceLength :: !Integer } deriving (Eq, Ord, Show) -- | Average length of all sequences in a FASTA file. -- Returns Nothing if the number of counted sequences is zero. -- Average is rounded to an integer towards zero. average :: Stats -> Maybe Integer average (Stats {..}) | numSequences > 0 = Just $ floor (fromIntegral numBases / fromIntegral numSequences) | otherwise = Nothing -- | Compute basic statistics for a list of sequences taken from -- a FASTA file. Sequences whose length is less than the specified minimum -- are ignored. sequenceStats :: Integer -- ^ Minimum sequence length. Sequences shorter -- than this are ignored (skipped). -> [Sequence] -- ^ A list of all the sequences from a FASTA file. -> Maybe Stats -- ^ Basic statistics for all the sequences. Is Nothing -- if the list of sequences does not contain any -- elements which are at least as long as the minimum. sequenceStats minLength sequences = case filteredLengths of [] -> Nothing first:rest -> Just $ foldl' updateStats (initStats first) rest where -- Collect all sequences whose length is at least as long as the -- minumum. Lazy evaluation means that this can be done in a streaming -- fashion, so we don't have to read the entire file at once. filteredLengths = filter (\x -> sequenceLengthInteger x >= minLength) sequences -- | Initial value for statistics, given the first sequence. initStats :: Sequence -> Stats initStats sequence = Stats { numSequences = 1 , numBases = thisLength , minSequenceLength = thisLength , maxSequenceLength = thisLength } where thisLength = sequenceLengthInteger sequence -- | Update the stats given the next sequence from the FASTA file. updateStats :: Stats -- ^ Current value of stats. -> Sequence -- ^ Next sequence from the FASTA file. -> Stats -- ^ New, updated stats. updateStats oldStats@(Stats {..}) sequence = Stats newNumSequences newNumBases newMinSequenceLength newMaxSequenceLength where newNumSequences = numSequences + 1 thisLength = sequenceLengthInteger sequence newNumBases = numBases + thisLength newMinSequenceLength = min thisLength minSequenceLength newMaxSequenceLength = max thisLength maxSequenceLength sequenceLengthInteger :: Sequence -> Integer sequenceLengthInteger = fromIntegral . seqlength
supernifty/biotool
haskell/src/Stats.hs
mit
4,327
0
11
1,015
451
256
195
58
2
module Database.PostgreSQL.Protocol.Codecs.Time ( dayToPgj , utcToMicros , localTimeToMicros , timeOfDayToMcs , pgjToDay , microsToUTC , microsToLocalTime , mcsToTimeOfDay , mcsToDiffTime , intervalToDiffTime , diffTimeToInterval , diffTimeToMcs ) where import Data.Int (Int64, Int32, Int64) import Data.Time (Day(..), UTCTime(..), LocalTime(..), DiffTime, TimeOfDay, picosecondsToDiffTime, timeToTimeOfDay, diffTimeToPicoseconds, timeOfDayToTime) {-# INLINE dayToPgj #-} dayToPgj :: Integral a => Day -> a dayToPgj = fromIntegral .(+ (modifiedJulianEpoch - postgresEpoch)) . toModifiedJulianDay {-# INLINE utcToMicros #-} utcToMicros :: UTCTime -> Int64 utcToMicros (UTCTime day diffTime) = dayToMcs day + diffTimeToMcs diffTime {-# INLINE localTimeToMicros #-} localTimeToMicros :: LocalTime -> Int64 localTimeToMicros (LocalTime day time) = dayToMcs day + timeOfDayToMcs time {-# INLINE pgjToDay #-} pgjToDay :: Integral a => a -> Day pgjToDay = ModifiedJulianDay . fromIntegral . subtract (modifiedJulianEpoch - postgresEpoch) {-# INLINE microsToUTC #-} microsToUTC :: Int64 -> UTCTime microsToUTC mcs = let (d, r) = mcs `divMod` microsInDay in UTCTime (pgjToDay d) (mcsToDiffTime r) {-# INLINE microsToLocalTime #-} microsToLocalTime :: Int64 -> LocalTime microsToLocalTime mcs = let (d, r) = mcs `divMod` microsInDay in LocalTime (pgjToDay d) (mcsToTimeOfDay r) {-# INLINE intervalToDiffTime #-} intervalToDiffTime :: Int64 -> Int32 -> Int32 -> DiffTime intervalToDiffTime mcs days months = picosecondsToDiffTime . mcsToPcs $ microsInDay * (fromIntegral months * daysInMonth + fromIntegral days) + fromIntegral mcs {-# INLINE diffTimeToInterval #-} diffTimeToInterval :: DiffTime -> (Int64, Int32, Int32) diffTimeToInterval dt = (fromIntegral $ diffTimeToMcs dt, 0, 0) -- -- Utils -- {-# INLINE dayToMcs #-} dayToMcs :: Integral a => Day -> a dayToMcs = (microsInDay *) . dayToPgj {-# INLINE diffTimeToMcs #-} diffTimeToMcs :: Integral a => DiffTime -> a diffTimeToMcs = fromIntegral . pcsToMcs . diffTimeToPicoseconds {-# INLINE timeOfDayToMcs #-} timeOfDayToMcs :: Integral a => TimeOfDay -> a timeOfDayToMcs = diffTimeToMcs . timeOfDayToTime {-# INLINE mcsToDiffTime #-} mcsToDiffTime :: Integral a => a -> DiffTime mcsToDiffTime = picosecondsToDiffTime . fromIntegral . mcsToPcs {-# INLINE mcsToTimeOfDay #-} mcsToTimeOfDay :: Integral a => a -> TimeOfDay mcsToTimeOfDay = timeToTimeOfDay . mcsToDiffTime {-# INLINE pcsToMcs #-} pcsToMcs :: Integral a => a -> a pcsToMcs = (`div` 10 ^ 6) {-# INLINE mcsToPcs #-} mcsToPcs :: Integral a => a -> a mcsToPcs = (* 10 ^ 6) {-# INLINE modifiedJulianEpoch #-} modifiedJulianEpoch :: Num a => a modifiedJulianEpoch = 2400001 {-# INLINE postgresEpoch #-} postgresEpoch :: Num a => a postgresEpoch = 2451545 {-# INLINE microsInDay #-} microsInDay :: Num a => a microsInDay = 24 * 60 * 60 * 10 ^ 6 {-# INLINE daysInMonth #-} daysInMonth :: Num a => a daysInMonth = 30
postgres-haskell/postgres-wire
src/Database/PostgreSQL/Protocol/Codecs/Time.hs
mit
3,087
1
10
590
785
437
348
82
1
{-| Module : Network.CircleCI.Cache Copyright : (c) Denis Shevchenko, 2016 License : MIT Maintainer : me@dshevchenko.biz Stability : alpha API call for work with project build's cache. -} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiWayIf #-} module Network.CircleCI.Cache ( -- * API call clearCache -- * Type for response , CacheCleared (..) , module Network.CircleCI.Common.Types , module Network.CircleCI.Common.Run ) where import Network.CircleCI.Common.URL import Network.CircleCI.Common.Types import Network.CircleCI.Common.HTTPS import Network.CircleCI.Common.Run import Control.Monad ( mzero ) import Control.Monad.Except ( runExceptT ) import Control.Monad.Reader ( ask ) import Control.Monad.IO.Class ( liftIO ) import Data.Aeson import Data.Aeson.Types import qualified Data.Proxy as P import Data.Text ( Text ) import Network.HTTP.Client ( Manager ) import Servant.API import Servant.Client -- | Clears build cache. Based on https://circleci.com/docs/api/#clear-cache. -- -- Usage example: -- -- @ -- {-\# LANGUAGE OverloadedStrings \#-} -- {-\# LANGUAGE LambdaCase \#-} -- -- import Network.CircleCI -- -- main :: IO () -- main = runCircleCI (clearCache $ ProjectPoint "denisshevchenko" "circlehs") -- (AccountAPIToken "e64c674195bbc0dbe3f9676c6ba2whatever") -- >>= \\case -- Left problem -> print problem -- Right isCleared -> print isCleared -- @ clearCache :: ProjectPoint -- ^ Names of GitHub user/project. -> CircleCIResponse CacheCleared -- ^ Info about clearing. clearCache project = do AccountAPIToken token <- ask liftIO . runExceptT $ do manager <- httpsManager servantClearCache (userName project) (projectName project) (Just token) manager apiBaseUrl -- | Cache clearing status. data CacheCleared = CacheSuccessfullyCleared | UnableToClearCache ErrorMessage deriving (Show) -- How to make CacheCleared from JSON. instance FromJSON CacheCleared where parseJSON (Object o) = o .: "status" >>= toCacheCleared parseJSON _ = mzero toCacheCleared :: Text -> Parser CacheCleared toCacheCleared rawStatus = return $ if | rawStatus `elem` okMessages -> CacheSuccessfullyCleared | otherwise -> UnableToClearCache rawStatus where okMessages = [ "build dependency caches deleted" , "build caches deleted" ] ------------------------------------------------------------------------------- -- API types for Servant ------------------------------------------------------ ------------------------------------------------------------------------------- -- Complete API for work with build cache. type CacheAPI = ClearCacheCall -- Clears build cache. type ClearCacheCall = "project" :> Capture "username" UserName :> Capture "project" ProjectName :> "build-cache" :> QueryParam "circle-token" Token :> Delete '[JSON] CacheCleared -- DELETE: /project/:username/:project/build-cache?circle-token=:token ------------------------------------------------------------------------------- -- API client calls for Servant ----------------------------------------------- ------------------------------------------------------------------------------- servantClearCache :: UserName -> ProjectName -> Maybe Token -> Manager -> BaseUrl -> ClientM CacheCleared servantClearCache = client cacheAPI cacheAPI :: P.Proxy CacheAPI cacheAPI = P.Proxy
denisshevchenko/circlehs
src/Network/CircleCI/Cache.hs
mit
4,019
0
12
1,099
508
299
209
65
2
-- lastButOne :: [a] -> a lastButOne x = if length x <= 2 then Nothing else Just (x !! (length x -2))
rglew/rwh
ch2/lastButOne.hs
mit
123
2
11
44
47
24
23
3
2
import Data.Char import Data.List -- 1) Define your own version of Data.List.Intercalate, called intercalate’ intercalate' :: [a] -> [[a]] -> [a] intercalate' _ [] = [] intercalate' [] yss = concat yss intercalate' xs (ys:yss) = ys ++ xs ++ intercalate' xs yss -- 2) type Probability = Double type DiscreteRandVar = [(Int, Probability)] x :: DiscreteRandVar x = [(1, 0.2), (2, 0.4), (3, 0.1), (4, 0.2), (5, 0.05), (6, 0.05)] -- 2a) Define an explicitly recursive function mean and an accumulator-style recursive function mean’ that calculate the mean (or expected value) of a discrete random variable mean :: DiscreteRandVar -> Double mean [] = 0 mean ((x,p):xs) = fromIntegral x * p + mean xs mean' :: DiscreteRandVar -> Double mean' [] = 0 mean' xs = mean'' xs 0 where mean'' [] acc = acc mean'' ((x,p):xs) acc = mean'' xs (fromIntegral x * p + acc) -- 2b) Define an explicitly recursive function variance and an accumulator-style recursive function variance' that calculate the variance of a discrete random variable variance :: DiscreteRandVar -> Double variance [] = 0 variance x = fun x (mean' x) where fun [] _ = 0 fun ((x,p):xs) mi = (fromIntegral x - mi)*(fromIntegral x - mi)*p + fun xs mi variance' :: DiscreteRandVar -> Double variance' [] = 0 variance' x = fun x (mean' x) 0 where fun [] _ acc = acc fun ((x,p):xs) mi acc = fun xs mi ((fromIntegral x - mi)*(fromIntegral x - mi)*p + acc) -- 2c) Define an explicitly recursive function probabilityFilter and an accumulatorstyle recursive function probabilityFilter’ that take a probability and a random variable and return a list of values that have at least the given probability of appearing, in the same order in which they appear in the random variable definition. probabilityFilter :: Probability -> DiscreteRandVar -> [Int] probabilityFilter _ [] = [] probabilityFilter tr ((x,p):xs) | p >= tr = x : probabilityFilter tr xs | otherwise = probabilityFilter tr xs probabilityFilter' :: Probability -> DiscreteRandVar -> [Int] probabilityFilter' _ [] = [] probabilityFilter' tr xs = fun tr xs [] where fun _ [] acc = acc fun tr ((x,p):xs) acc | p >= tr = fun tr xs (acc ++ [x]) | otherwise = fun tr xs acc -- 3a) Define a function chunk that splits up a list xs into sublist of length n. If the length of xs is not a multiple of n, the last sublist will be shorter than n. chunk :: Int -> [a] -> [[a]] chunk 0 _ = [] chunk _ [] = [] chunk n xs = take n xs : chunk n (drop n xs) -- 3b) Define a function chunkBy that splits up a list xs into sublists of lengths given in a list of indices is. If the lengths in is do not add up to the length of xs, the remaining part of xs will remain unchunked. chunkBy :: [Int] -> [a] -> [[a]] chunkBy [] _ = [] chunkBy _ [] = [] chunkBy (n:ns) xs | n > 0 = take n xs : chunkBy ns (drop n xs) | otherwise = chunkBy ns xs -- 3c) Define a function chunkInto that splits up a list xs into n sublists of equal length. If the length of xs is not divisible by n, chunk the remainder into the last sublist. chunkInto :: Int -> [a] -> [[a]] chunkInto 0 _ = [] chunkInto _ [] = [] chunkInto n xs | q > 0 = take q xs : chunkInto (n-1) (drop q xs) | otherwise = chunkInto (n-1) xs where q = quot (length xs) n -- 4) Define a function rpnCalc that takes a mathematical expression written in Reverse Polish notation and calculates its result. The expression is limited to 1–digit positive integers and operators +,-,*,/, and ^ where / is integer division and ^ is exponentiation rpnCalc :: String -> Int rpnCalc [] = 0 rpnCalc xs = calc xs [] where throw = error "Invalid RPN expression" calc [] stack = if length stack /= 1 then throw else head stack calc (x:xs) stack | x == '+' = if length stack < 2 then throw else calc xs ((x1+x2):stack2) | x == '-' = if length stack < 2 then throw else calc xs ((x2-x1):stack2) | x == '*' = if length stack < 2 then throw else calc xs ((x1*x2):stack2) | x == '/' = if length stack < 2 then throw else calc xs ((div x2 x1):stack2) | x == '^' = if length stack < 2 then throw else calc xs ((x2^x1):stack2) | isDigit x = calc xs (digitToInt x:stack) | otherwise = throw where x1 = head stack x2 = head $ tail stack stack2 = tail $ tail stack -- 5a) Define a function gcd' that calculates the greatest common divisor of two integers, using explicit recursion and the Euclidean algorithm gcd' :: Int -> Int -> Int gcd' 0 b = abs b gcd' a 0 = abs a gcd' a b = gcd' b $ mod a b -- 5b) Define a function gcdAll that calculates the greatest common divisor of an arbitrary number of integers given in a list. gcdAll :: [Int] -> Int gcdAll = foldr gcd' 0 -- 5c) Define a function extendedGcd which uses the extended Euclidean algorithm to calculate the Bezout coefficients along with the gcd. Given the constants a and b, it calculates x, y and gcd(a,b) that satisfy the expression a*x + b*y = gcd(a,b), returning them in a tuple, in that order. extendedGcd :: Int -> Int -> (Int, Int, Int) extendedGcd a 0 = (1, 0, a) extendedGcd a b = let (x, y, g) = extendedGcd b $ mod a b in (y, x - (div a b) * y, g) -- 6) Implement a function isBipartite that takes an unweighted graph represented as an adjacency list and checks whether the given graph is a bipartite graph type AdjacencyList = [Int] type Graph = [AdjacencyList] isBipartite :: Graph -> Bool isBipartite [] = True isBipartite xs = and [not (elem x redl)| x <- blackl] where list = map nub $ stuff [1..length xs] xs [1] [] [1] redl = list !! 0 blackl = list !! 1 stuff [] _ red black _ = [red, black] stuff _ _ red black [] = [red, black] stuff v al red black (x:q) | elem x red = stuff [y|y<-v, y/=x] al red ((al!!(x-1)) ++ black) ([y|y<-al!!(x-1), elem y v] ++ q) | elem x black = stuff [y|y<-v, y/=x] al ((al!!(x-1)) ++ red) black ([y|y<-al!!(x-1), elem y v] ++ q) -- 7) Define a function permutations' that, given a list, returns a list of all its permutations permutations' :: [a] -> [[a]] permutations' [] = [[]] permutations' (x:xs) = concat [insert ys x | ys <- permutations xs] where insert xs x = [insertAt xs n x | n <- [0 .. length xs]] insertAt xs n x = concat [[xs !! i | i <- [0 .. n - 1]] ++ x : [xs !! i | i <- [n .. length xs - 1]]] -- 8) Your job is to define a function frogJumps that, given a number of frogs n, computes the minimal number of jumps necessary for all n frogs to reach the third lily pad frogJumps :: Int -> Integer frogJumps 1 = 2 frogJumps n | n >= 2 = 3 * frogJumps (n-1) + 2 | otherwise = error "Not enough frogs"
kbiscanic/PUH
hw05/homework.hs
mit
6,769
14
15
1,601
2,313
1,214
1,099
106
8
import Test.HUnit import Q13 assertEqualEntryList :: String -> [Entry Int] -> [Entry Int] -> Assertion assertEqualEntryList = assertEqual test1 = TestCase (assertEqualEntryList "encodeDirect [] should be [] ." ([] ) (encodeDirect [] )) test2 = TestCase (assertEqualEntryList "encodeDirect [1] should be [(Single 1)] ." ([(Single 1)] ) (encodeDirect [1] )) test3 = TestCase (assertEqualEntryList "encodeDirect [1,2] should be [(Single 1),(Single 2)] ." ([(Single 1),(Single 2)] ) (encodeDirect [1,2] )) test4 = TestCase (assertEqualEntryList "encodeDirect [1,2,1] should be [(Single 1),(Single 2),(Single 1)]." ([(Single 1),(Single 2),(Single 1)]) (encodeDirect [1,2,1])) test5 = TestCase (assertEqualEntryList "encodeDirect [1,1,2] should be [(Multiple 2 1),(Single 2)] ." ([(Multiple 2 1),(Single 2)] ) (encodeDirect [1,1,2])) test6 = TestCase (assertEqualEntryList "encodeDirect [1,2,2] should be [(Single 1),(Multiple 2 2)] ." ([(Single 1),(Multiple 2 2)] ) (encodeDirect [1,2,2])) main = runTestTT $ TestList [test1,test2,test3,test4,test5,test6]
cshung/MiscLab
Haskell99/q13.test.hs
mit
1,220
0
11
302
369
203
166
11
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.NavigatorUserMediaErrorCallback (newNavigatorUserMediaErrorCallback, newNavigatorUserMediaErrorCallbackSync, newNavigatorUserMediaErrorCallbackAsync, NavigatorUserMediaErrorCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaErrorCallback Mozilla NavigatorUserMediaErrorCallback documentation> newNavigatorUserMediaErrorCallback :: (MonadIO m) => (Maybe NavigatorUserMediaError -> IO ()) -> m NavigatorUserMediaErrorCallback newNavigatorUserMediaErrorCallback callback = liftIO (NavigatorUserMediaErrorCallback <$> syncCallback1 ThrowWouldBlock (\ error -> fromJSValUnchecked error >>= \ error' -> callback error')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaErrorCallback Mozilla NavigatorUserMediaErrorCallback documentation> newNavigatorUserMediaErrorCallbackSync :: (MonadIO m) => (Maybe NavigatorUserMediaError -> IO ()) -> m NavigatorUserMediaErrorCallback newNavigatorUserMediaErrorCallbackSync callback = liftIO (NavigatorUserMediaErrorCallback <$> syncCallback1 ContinueAsync (\ error -> fromJSValUnchecked error >>= \ error' -> callback error')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaErrorCallback Mozilla NavigatorUserMediaErrorCallback documentation> newNavigatorUserMediaErrorCallbackAsync :: (MonadIO m) => (Maybe NavigatorUserMediaError -> IO ()) -> m NavigatorUserMediaErrorCallback newNavigatorUserMediaErrorCallbackAsync callback = liftIO (NavigatorUserMediaErrorCallback <$> asyncCallback1 (\ error -> fromJSValUnchecked error >>= \ error' -> callback error'))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/NavigatorUserMediaErrorCallback.hs
mit
2,966
0
13
723
532
316
216
50
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeFamilies #-} module Database.Persist.Types ( module Database.Persist.Types.Base , SomePersistField (..) , Update (..) , SelectOpt (..) , BackendSpecificFilter , Filter (..) , Key , Entity (..) ) where import Database.Persist.Types.Base import Database.Persist.Class.PersistField import Database.Persist.Class.PersistEntity
gbwey/persistentold
persistent/Database/Persist/Types.hs
mit
420
0
5
77
81
58
23
14
0
module Control.Concurrent.Transactional.Channel.Broadcast ( BroadcastChannel (), newBroadcastChannel, broadcast, enroll, BroadcastListener (), listen ) where import Control.Concurrent.Transactional.Event import Control.Concurrent.Transactional.EventHandle import Data.List.Util import Control.Applicative ((<$>), (<$), (<|>)) import Control.Monad (forM, msum) data BroadcastChannel i o = Broadcast { broadcast :: i -> Event [o], enroll :: Event (BroadcastListener i o) } data BroadcastListener i o = Listener { listen :: o -> Event i } data BroadcastConnection i o = Connection { sendConnection :: i -> Event o, closeConnection :: Event () } newBroadcastChannel :: Event (BroadcastChannel i o) newBroadcastChannel = do (createConnection, requestConnection) <- swap (requestBroadcast, receiveBroadcast) <- swap let send xs = do (input, respond) <- receiveBroadcast () output <- forM xs $ flip sendConnection input respond output return xs add xs = (: xs) <$> requestConnection () close = msum . map (\(x, xs) -> xs <$ closeConnection x) . deletions (_, handle) <- forkServer [] $ \xs -> send xs <|> add xs <|> close xs return Broadcast { broadcast = \value -> wrapEvent handle $ do (respond, wait) <- swap requestBroadcast (value, respond) wait (), enroll = wrapEvent handle $ do (sendListener, receiveListener) <- swap (listenerHandle, closeListener) <- newEventHandle createConnection Connection { sendConnection = sendListener, closeConnection = closeListener } return Listener { listen = wrapEvent listenerHandle . wrapEvent handle . receiveListener } }
YellPika/Hannel
src/Control/Concurrent/Transactional/Channel/Broadcast.hs
mit
1,865
0
18
523
549
298
251
46
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} -- uses packages: comonad-transformers,streams,MonadRandom import Prelude hiding (iterate,tail,repeat,sequence,take,zip,unzip) import Data.Stream.Infinite (Stream ((:>)),iterate,tail,repeat,take,zip,unzip,unfold) import Data.Foldable import Data.Traversable (Traversable(..), sequence) import Control.Applicative import Control.Comonad import Control.Comonad.Trans.Class (lower) import Control.Comonad.Trans.Env (EnvT(..),ask) import System.Random (StdGen,mkStdGen) import Control.Monad.Random import Control.Monad.Random.Class -- Inspired by http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html -- and http://demonstrations.wolfram.com/SimpleProbabilisticCellularAutomata/ data U x = U (Stream x) x (Stream x) deriving (Functor,Foldable) -- The default instance of Traversable generated by DeriveTraversable wasn't working -- well with MonadRandom, because U contains infinite structures. If I used the default -- "sequence" function to transform a U (Rand StdGen Bool) into a Rand StdGen (U Bool), -- the subsequent call to evalRand would hang. -- I had to resort to this trick of traversing the left and right streams jointly as -- a "zip stream" and unzipping them afterwards. -- Is there a standard, generally accepted way of dealing with these situations? instance Traversable U where traverse f (U lstream focus rstream) = let pairs = liftA unzip . sequenceA . fmap (traversepair f) $ zip lstream rstream traversepair f (a,b) = (,) <$> f a <*> f b rebuild c (u,v) = U u c v in rebuild <$> f focus <*> pairs right (U a b (c:>cs)) = U (b:>a) c cs left (U (a:>as) b c) = U as a (b:>c) instance Comonad U where extract (U _ b _) = b duplicate a = U (tail $ iterate left a) a (tail $ iterate right a) type Probs = (Float,Float,Float,Float) localRule :: EnvT Probs U Bool -> Rand StdGen Bool localRule ca = let (tt,tf,ft,ff) = ask ca black prob = (<prob) <$> getRandomR (0,1) in case lower ca of U (True:>_) _ (True:>_) -> black tt U (True:>_) _ (False:>_) -> black tf U (False:>_) _ (True:>_) -> black ft U (False:>_) _ (False:>_) -> black ff -- Advances the cellular automata by one iteration, and returns a result -- wrapped in the Rand monad, which can be later evaluated with evalRand. -- Note the use of "sequence" to aggregate the random effects of each -- individual cell. evolve :: EnvT Probs U Bool -> Rand StdGen (EnvT Probs U Bool) evolve ca = sequence $ extend localRule ca -- Returns an infinite stream with all the succesive states of the cellular automata. history :: StdGen -> EnvT Probs U Bool -> Stream (EnvT Probs U Bool) history seed initialca = -- We need to split the generator because we are lazily evaluating -- an infinite random structure. The updated generator never "comes out"! -- If we changed runRand for evalRand and tried to reuse the -- updated generator for the next iteration, the call would hang. let unfoldf (ca,seed) = let (seed',seed'') = runRand getSplit seed nextca = evalRand (evolve ca) seed' in (nextca,(nextca,seed'')) in unfold unfoldf (initialca,seed) showca :: Int -> U Bool -> String showca margin ca = let char b = if b then '#' else '_' U left center right = fmap char ca in (reverse $ take margin left) ++ [center] ++ (take margin right) main :: IO () main = do let probs = (0.0,0.6,0.7,0.0) initialca = EnvT probs $ U (repeat False) True (repeat False) seed = 77 iterations = 10 margin = 8 sequence . fmap (putStrLn . showca margin . lower) . take iterations . history (mkStdGen seed) $ initialca return ()
danidiaz/haskell-sandbox
probca.hs
mit
3,841
0
15
864
1,125
602
523
61
4
module Stackage.Tarballs ( makeTarballs ) where import qualified Codec.Archive.Tar as Tar import qualified Data.ByteString.Lazy as L import qualified Data.Map as Map import qualified Data.Set as Set import Stackage.Types import Stackage.Util import System.Directory (createDirectoryIfMissing) import System.FilePath (takeDirectory) makeTarballs :: BuildPlan -> IO () makeTarballs bp = do putStrLn "Building tarballs" tarName <- getTarballName origEntries <- fmap Tar.read $ L.readFile tarName (stableEntries, extraEntries) <- loop id id origEntries (stableTar, extraTar) <- getStackageTarballNames createDirectoryIfMissing True $ takeDirectory stableTar L.writeFile stableTar $ Tar.write stableEntries createDirectoryIfMissing True $ takeDirectory extraTar L.writeFile extraTar $ Tar.write extraEntries where -- Using "error . show" for compatibility with tar 0.3 and 0.4 loop _ _ (Tar.Fail err) = error $ show err loop stable extra Tar.Done = return (stable [], extra []) loop stable extra (Tar.Next e es) = loop stable' extra' es where (stable', extra') = case getPackageVersion e of Nothing -> (stable, extra) Just (package, version) -> case Map.lookup package $ bpPackages bp of Just spi | version == spiVersion spi -> (stable . (e:), extra) | otherwise -> (stable, extra) Nothing | package `Set.member` bpCore bp -> (stable, extra) | otherwise -> (stable, extra . (e:))
sinelaw/stackage
Stackage/Tarballs.hs
mit
1,764
0
19
579
483
249
234
36
5
{-| Module : Language.GoLite.Pretty Description : Pretty-printer definition and combinators. Copyright : (c) Jacob Errington and Frederic Lafrance, 2016 License : MIT Maintainer : goto@mail.jerrington.me Stability : experimental Specific definitions for GoLite pretty-printing. -} module Language.GoLite.Pretty ( module Language.Common.Pretty , goLiteStyle , renderGoLite ) where import Language.Common.Pretty -- | Renders a 'Doc' with GoLite-specific settings. -- -- In particular, line length is set to infinity to avoid dangerous line -- wrapping that could introduce erroneous semicolons. renderGoLite :: Doc -> String renderGoLite = renderStyle goLiteStyle -- | The rendering style for GoLite 'Doc's. goLiteStyle :: Style goLiteStyle = style { lineLength = maxBound }
djeik/goto
libgoto/Language/GoLite/Pretty.hs
mit
801
0
6
132
69
45
24
10
1
{-# LANGUAGE ConstraintKinds, DeriveFunctor, DeriveFoldable, DeriveTraversable, FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, ImplicitParams, LambdaCase, MultiParamTypeClasses, OverloadedStrings, PackageImports, ScopedTypeVariables, TemplateHaskell, TupleSections #-} module Formura.MPIFortran.Translate where import Control.Applicative import Control.Concurrent(threadDelay) import qualified Control.Exception as X import Control.Lens import Control.Monad import "mtl" Control.Monad.RWS import Data.Char (toUpper, isAlphaNum) import Data.Foldable (toList) import Data.Function (on) import Data.List (zip4, isPrefixOf, sort, groupBy, sortBy) import qualified Data.Map as M import Data.Maybe import Data.String import Data.String.ToString import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.Lens as T import qualified Data.Text.IO as T import System.Directory import System.FilePath.Lens import System.Process import Text.Trifecta (failed, raiseErr) import Formura.Utilities (readYamlDef, zipWithFT) import qualified Formura.Annotation as A import Formura.Annotation.Boundary import Formura.Annotation.Representation import Formura.Compiler import Formura.CommandLineOption import Formura.Geometry import Formura.GlobalEnvironment import Formura.Language.Combinator (subFix) import Formura.NumericalConfig import Formura.OrthotopeMachine.Graph import Formura.OrthotopeMachine.TemporalBlocking import Formura.Syntax import Formura.Vec import qualified Formura.MPICxx.Language as C import Formura.MPICxx.Cut hiding (cut) newtype VariableName = VariableName C.Src type FortranBinding = M.Map C.Src C.Src -- Mapping from variable name to type name -- | The struct for generating unique names, and holds already given names. data NamingState = NamingState { _alreadyGivenNames :: S.Set C.Src , _alreadyGivenLocalNames :: S.Set C.Src , _alreadyDeclaredResourceNames :: S.Set C.Src , _freeNameCounter :: Integer , _freeLocalNameCounter :: Integer , _nodeIDtoLocalName :: M.Map MMNodeID C.Src , _loopIndexNames :: Vec C.Src , _loopIndexOffset :: Vec Int , _loopExtentNames :: Vec C.Src } makeClassy ''NamingState defaultNamingState = NamingState { _alreadyGivenNames = S.empty , _alreadyGivenLocalNames = S.empty , _alreadyDeclaredResourceNames = S.empty , _freeNameCounter = 0 , _freeLocalNameCounter = 0 , _nodeIDtoLocalName = M.empty , _loopIndexNames = PureVec "" , _loopIndexOffset = 0 , _loopExtentNames = PureVec "" } type MPIPlanSelector = Bool data TranState = TranState { _tranSyntacticState :: CompilerSyntacticState , _tsNumericalConfig :: NumericalConfig , _tsNamingState :: NamingState , _theProgram :: Program , _theMMProgram :: MMProgram , _theGraph :: MMGraph , _tsMPIPlanSelection :: MPIPlanSelector , _tsMPIPlanMap :: M.Map MPIPlanSelector MPIPlan , _tsCommonStaticBox :: Box , _tsCommonOMNodeBox :: Box , _tsCxxTemplateWithMacro :: C.Src } makeClassy ''TranState instance HasCompilerSyntacticState TranState where compilerSyntacticState = tranSyntacticState instance HasNumericalConfig TranState where numericalConfig = tsNumericalConfig instance HasMachineProgram TranState MMInstruction OMNodeType where machineProgram = theMMProgram instance HasNamingState TranState where namingState = tsNamingState instance HasMPIPlan TranState where mPIPlan = let gettr s = fromJust $ M.lookup (s^.tsMPIPlanSelection) (s^.tsMPIPlanMap) settr s a = s & tsMPIPlanMap %~ M.insert (s^.tsMPIPlanSelection) a in lens gettr settr data CProgramF a = CProgram { _headerFileContent :: a, _sourceFileContent :: a, _auxFilesContent :: M.Map FilePath a} deriving (Eq, Ord, Show, Functor, Foldable, Traversable) type CProgram = CProgramF C.Src makeLenses ''CProgramF tellH :: (MonadWriter CProgram m) => C.Src -> m () tellH txt = tell $ CProgram txt "" M.empty tellC :: (MonadWriter CProgram m) => C.Src -> m () tellC txt = tell $ CProgram "" txt M.empty tellF :: (MonadWriter CProgram m) => FilePath -> C.Src -> m () tellF fn txt = tell $ CProgram "" "" (M.singleton fn txt) tellHBlock :: (MonadWriter CProgram m) => C.Src -> C.Src -> m () -> m () tellHBlock btype bname con = do tellHLn $ btype <> " " <> bname con tellHLn $ "end " <> btype <> " " <> bname tellCLn "" tellCBlock :: (MonadWriter CProgram m) => C.Src -> C.Src -> m () -> m () tellCBlock btype bname con = do tellCLn $ btype <> " " <> bname con tellCLn $ "end " <> btype <> " " <> bname tellCLn "" tellCBlockArg :: (MonadWriter CProgram m) => C.Src -> C.Src -> C.Src -> m () -> m () tellCBlockArg btype bname arg con = do tellCLn $ btype <> " " <> bname <> " " <> arg con tellCLn $ "end " <> btype <> " " <> bname tellCLn "" fortranBlockArg :: C.Src -> C.Src -> C.Src -> C.Src -> C.Src fortranBlockArg btype bname arg con = C.unlines [btype <> " " <> bname <> " " <> arg, con, "end " <> btype <> " " <> bname, "" ] tellHLn :: (MonadWriter CProgram m) => C.Src -> m () tellHLn txt = tellH $ txt <> "\n" tellCLn :: (MonadWriter CProgram m) => C.Src -> m () tellCLn txt = tellC $ txt <> "\n" tellFLn :: (MonadWriter CProgram m) => FilePath -> C.Src -> m () tellFLn fn txt = tellF fn $ txt <> "\n" instance Monoid CProgram where mempty = CProgram "" "" M.empty mappend (CProgram h1 c1 f1) (CProgram h2 c2 f2) = CProgram (h1 <> h2) (c1 <> c2) (M.unionWith (<>) f1 f2) type TranM = CompilerMonad GlobalEnvironment CProgram TranState -- * Parallel code generation -- | generate new free global name based on given identifier, -- and prevent further generation of that name genFreeName :: IdentName -> TranM C.Src genFreeName = genFreeName' True -- | generate new free local name based on given identifier, -- and prevent further generation of that name within current scope genFreeLocalName :: IdentName -> TranM C.Src genFreeLocalName = genFreeName' False -- | base function for giving names genFreeName' :: Bool -> IdentName -> TranM C.Src genFreeName' isGlobal ident = do aggNames <- use alreadyGivenNames aglNames <- use alreadyGivenLocalNames let initName = fromString ident agNames = aggNames <> aglNames nCounter :: Lens' TranState Integer nCounter = if isGlobal then freeNameCounter else freeLocalNameCounter go = do ctr <- use nCounter let tmpName = initName <> "_" <> C.show ctr if S.member tmpName agNames then (nCounter += 1) >> go else return tmpName givenName <- if S.member initName agNames then go else return initName (if isGlobal then alreadyGivenNames else alreadyGivenLocalNames) %= S.insert givenName return givenName -- | read all numerical config from the Formura source program setNumericalConfig :: WithCommandLineOption => TranM () setNumericalConfig = do dim <- view dimension ivars <- view axesNames prog <- use theProgram let nc = prog ^. programNumericalConfig tsNumericalConfig .= nc when (length (nc ^. ncMPIGridShape) /= dim) $ raiseErr $ failed $ "mpi_grid_shape needs exactly " ++ show dim ++ " elements." when (length (nc ^. ncIntraNodeShape) /= dim) $ raiseErr $ failed $ "intra_node_shape needs exactly " ++ show dim ++ " elements." return () -- | prepare unique name for everyone setNamingState :: TranM () setNamingState = do stateVars <- use omStateSignature alreadyGivenNames .= (S.fromList $ map fromString $ M.keys stateVars) ans <- view axesNames lins <- traverse (genFreeName . ("i"++)) ans loopIndexNames .= lins luns <- traverse (genFreeName . ("N"++) . map toUpper) ans loopExtentNames .= luns let nameNode :: MMNode -> TranM MMNode nameNode nd = do let initName = case A.viewMaybe nd of Just (SourceName n) -> n _ -> "g" cName <- genFreeName initName return $ nd & A.annotation %~ A.set (VariableName cName) gr <- use omInitGraph gr2 <- flip traverse gr $ nameNode omInitGraph .= gr2 gr <- use omStepGraph gr2 <- flip traverse gr $ nameNode omStepGraph .= gr2 -- | Generate C type declaration for given language. genTypeDecl :: IdentName -> TypeExpr -> TranM C.Src genTypeDecl name typ = case typ of ElemType "void" -> return "" ElemType "Rational" -> return $ "double precision " <> fromString name ElemType "double" -> return $ "double precision " <> fromString name ElemType x -> return $ fromString x <> " " <> fromString name GridType _ x -> do body <- genTypeDecl name x if body == "" then return "" else do sz <- use ncIntraNodeShape let szpt = foldMap (C.brackets . C.show) sz return $ body <> szpt _ -> raiseErr $ failed $ "Cannot translate type to C: " ++ show typ elemTypeOfResource :: ResourceT a b -> TranM TypeExpr elemTypeOfResource (ResourceStatic sname _) = do ssMap <- use omStateSignature let Just typ = M.lookup sname ssMap case typ of ElemType _ -> return typ GridType _ etyp -> return etyp elemTypeOfResource (ResourceOMNode nid _) = do mmProg <- use omStepGraph let Just nd = M.lookup nid mmProg case nd ^.nodeType of ElemType x -> return $ ElemType x GridType _ etyp -> return $ subFix etyp tellMPIRequestDecl :: C.Src -> TranM () tellMPIRequestDecl name = do adrn <- use alreadyDeclaredResourceNames case S.member name adrn of True -> return () False -> do alreadyDeclaredResourceNames %= S.insert name tellHLn $ "integer :: "<>name<>"\n" tellResourceDecl :: C.Src -> ResourceT a b -> Box -> TranM () tellResourceDecl = tellResourceDecl' False tellResourceDecl' :: Bool -> C.Src -> ResourceT a b -> Box -> TranM () tellResourceDecl' isInClass name rsc box0 = do adrn <- use alreadyDeclaredResourceNames case S.member name adrn || name == "" of True -> return () False -> do alreadyDeclaredResourceNames %= S.insert name typ <- elemTypeOfResource rsc let szpt = ("dimension"<>) $ C.parens $ C.intercalate ", " $ map C.show $ toList sz sz = box0 ^.upperVertex - box0 ^. lowerVertex decl <- case typ of ElemType "void" -> return "" ElemType "Rational" -> return $ "double precision, " <> szpt <> " :: " <>name ElemType x -> return $ fromString x <> " precision, " <> szpt <> " :: " <>name _ -> raiseErr $ failed $ "Cannot translate type to Fortran: " ++ show typ when (decl /= "") $ do tellHLn decl tellFacetDecl :: FacetID -> [RidgeID] -> TranM () tellFacetDecl f rs = do let name = fromString $ toCName f tellHBlock "type" name $ do ralloc <- use planRidgeAlloc forM_ rs $ \rk -> do name <- nameRidgeResource' True rk SendRecv let Just box0 = M.lookup rk ralloc tellResourceDecl' True name (rk ^. ridgeDelta) box0 tellHLn $ "type(" <> name <> ") :: " <> name <> "_Send" tellHLn $ "type(" <> name <> ") :: " <> name <> "_Recv" return () toCName :: Show a => a -> IdentName toCName a = postfix $ fix $ go False $ prefix $ show a where go _ [] = [] go b (x:xs) = case isAlphaNum x of True -> x : go False xs False -> if b then go b xs else '_' : go True xs postfix :: IdentName -> IdentName postfix = reverse . dropWhile (=='_') . reverse prefix :: IdentName -> IdentName prefix = T.packed %~ (T.replace "-" "m") fix :: IdentName -> IdentName fix = T.packed %~ (T.replace "ResourceOMNode" "Om" . T.replace "ResourceStatic" "St" . T.replace "IRank" "r". T.replace "ridgeDelta_" "". T.replace "MPIRank" "". T.replace "RidgeID_ridgeDeltaMPI_MPIRank" "Ridge" . T.replace "facetIRSrc_IRank" "src" . T.replace "facetIRDest_IRank" "dest" . T.replace "FacetID_facetDeltaMPI_" "Facet". T.replace "IRankCompareStraight" "". T.replace "IRankCompareReverse" "". id ) -- | Give name to Resources nameArrayResource :: (ResourceT () IRank) -> TranM C.Src nameArrayResource rsc = case rsc of ResourceStatic sn _ -> do let ret = fromString sn planResourceNames %= M.insert rsc ret return ret _ -> do sharing <- use planResourceSharing dict <- use planResourceNames sdict <- use planSharedResourceNames ret <- case M.lookup rsc sharing of Nothing -> return "" -- These are OMNode for Store instruction; do not need array decl Just rsid -> do ret <- case M.lookup rsid sdict of Just ret -> return ret Nothing -> do genFreeName $ "Rsc" ++ show (fromResourceSharingID rsid) planSharedResourceNames %= M.insert rsid ret return ret planResourceNames %= M.insert rsc ret return ret nameRidgeResource :: RidgeID -> SendOrRecv -> TranM C.Src nameRidgeResource = nameRidgeResource' False nameRidgeResource' :: Bool -> RidgeID -> SendOrRecv -> TranM C.Src nameRidgeResource' isInClass r sr0 = do dict <- use planRidgeNames fdict <- use planFacetAssignment prefix <- if not (doesRidgeNeedMPI r) || isInClass then return "" else do let Just f = M.lookup r fdict fname <- nameFacet f sr0 return $ fname <> "%" let (sr1, suffix) = (SendRecv, "") -- let (sr1, suffix) = case doesRidgeNeedMPI r of -- True -> (sr0, "_" ++ show sr0) -- False -> (SendRecv, "") case M.lookup (r,sr1) dict of Just ret -> return $ prefix <> ret Nothing -> do ret <- genFreeName $ toCName r ++ suffix planRidgeNames %= M.insert (r,sr1) ret return $ prefix <> ret nameFacetRequest :: FacetID -> TranM C.Src nameFacetRequest f = do dict <- use planMPIRequestNames case M.lookup f dict of Just ret -> return ret Nothing -> do ret <- genFreeName $ "req_" ++ toCName f planMPIRequestNames %= M.insert f ret return ret nameDeltaMPIRank :: MPIRank -> C.Src nameDeltaMPIRank r = "mpi_rank_" <> fromString (toCName r) nameFacet :: FacetID -> SendOrRecv -> TranM C.Src nameFacet f sr = do let name = fromString $ toCName f case sr of SendRecv -> return $ name _ -> return $ name <> "_" <> C.show sr -- | Generate Declaration for State Arrays tellArrayDecls :: TranM () tellArrayDecls = do aalloc <- use planArrayAlloc commonBox <- use planSharedResourceExtent let szpt = foldMap (C.brackets . C.show) (drop 1 $ toList sz) sz = commonBox ^.upperVertex - commonBox ^. lowerVertex forM_ (M.toList aalloc) $ \(rsc, box0) -> do name <- nameArrayResource rsc let box1 = case rsc of ResourceOMNode _ _ -> commonBox _ -> box0 tellResourceDecl name rsc box1 falloc <- use planFacetAlloc forM_ (M.toList falloc) $ \(fr@(f, rs)) -> do tellFacetDecl f rs name <- nameFacetRequest f tellMPIRequestDecl name ralloc <- use planRidgeAlloc forM_ (M.toList ralloc) $ \(rk@(RidgeID _ rsc), box0) -> do when (not $ doesRidgeNeedMPI rk) $ do name <- nameRidgeResource rk SendRecv tellResourceDecl name rsc box0 -- | Generate Declarations for intermediate variables tellIntermediateVariables :: TranM () tellIntermediateVariables = do g1 <- use omInitGraph g2 <- use omStepGraph forM_ [g1, g2] $ \gr -> do forM_ (M.toList gr) $ \(_, node) -> do let typ = subFix $ node ^. nodeType Just (VariableName vname) = A.viewMaybe node decl <- genTypeDecl (toString vname) typ when (decl /= "") $ tellCLn $ "static " <> decl <> "\n" -- | lookup node by its index lookupNode :: OMNodeID -> TranM MMNode lookupNode i = do g <- use theGraph case M.lookup i g of Nothing -> raiseErr $ failed $ "out-of-bound node reference: #" ++ show i Just n -> do case A.viewMaybe n of Just meta -> compilerFocus %= (meta <|>) Nothing -> return () return n nPlusK :: C.Src -> Int -> C.Src nPlusK i d = i <> "+" <> C.parens (C.parameter "int" d) --- nPlusK i d | d == 0 = i --- | d < 0 = i <> C.show d --- | otherwise = i <> "+" <> C.show d -- | generate bindings, and the final expression that contains the result of evaluation. genMMInstruction :: (?ncOpts :: [String]) => IRank -> MMInstruction -> TranM ((FortranBinding, C.Src), [(C.Src,Vec Int)]) genMMInstruction ir0 mminst = do axvars <- fmap fromString <$> view axesNames nc <- view envNumericalConfig indNames <- use loopIndexNames indOffset <- use loopIndexOffset -- indNames + indOffset = real addr arrayDict <- use planArrayAlloc resourceDict <- use planResourceNames let -- how to access physical coordinate indNames + indOffset -- in array allocated with margin box0 accAtMargin :: Box -> Vec Int -> C.Src accAtMargin box0 vi = accAt (indOffset + vi - (box0 ^. lowerVertex)) accAt :: Vec Int -> C.Src accAt v = C.parensTuple $ nPlusK <$> indNames <*> v alreadyGivenLocalNames .= S.empty freeLocalNameCounter .= 0 nodeIDtoLocalName .= M.empty let refCount :: MMNodeID -> Int refCount nid = fromMaybe 0 $ M.lookup nid refCntMap refCntMap :: M.Map MMNodeID Int refCntMap = M.unionsWith (+) $ concat $ map (map (flip M.singleton 1) . genRefCnt . _nodeInst) $ M.elems mminst genRefCnt :: MicroInstruction -> [MMNodeID] genRefCnt (Imm _) = [] genRefCnt (Uniop _ a) = [a] genRefCnt (Binop _ a b) = [a,b] genRefCnt (Triop _ a b c) = [a,b,c] genRefCnt (Naryop "<%" xs) = xs ++ xs genRefCnt (Naryop _ xs) = xs genRefCnt (Store _ x) = [x] genRefCnt (LoadIndex _) = [] genRefCnt (LoadExtent _) = [] genRefCnt (LoadCursor _ _) = [] genRefCnt (LoadCursorStatic _ _) = [] doesSpine :: MMNodeID -> Bool doesSpine nid = case A.viewMaybe $ fromJust $ M.lookup nid mminst of Just (NBUSpine False) -> False _ -> True doesBind :: MMNodeID -> Bool doesBind nid = doesBind' (refCount nid) (fromJust (M.lookup nid mminst) ^. nodeInst) doesBind' :: Int -> MicroInstruction -> Bool doesBind' _ (Imm _) = False doesBind' _ (Store _ x) = False doesBind' n _ = n >= exprBindSize nc -- TODO : Implement CSE and then reduce n let orderedMMInst :: [(MMNodeID, MicroNode)] orderedMMInst = sortBy (compare `on` (loc . snd)) $ M.toList mminst loc :: MicroNode -> MMLocation loc = fromJust . A.viewMaybe txts <- forM orderedMMInst $ \(nid0, Node inst microTyp _) -> do microTypDecl <- genTypeDecl "" (subFix microTyp) let thisEq :: C.Src -> TranM (FortranBinding, C.Src) thisEq code = case doesBind nid0 of True -> do thisName <- genFreeLocalName "a" nodeIDtoLocalName %= M.insert nid0 thisName return $ (M.singleton thisName microTypDecl,) $ thisName <> "=" <> code <> "\n" False -> do nodeIDtoLocalName %= M.insert nid0 code return (M.empty, "") query :: MMNodeID -> TranM C.Src query nid1 = do nmap <- use nodeIDtoLocalName case M.lookup nid1 nmap of Just vname -> return vname Nothing -> raiseErr $ failed $ "genExpr: missing graph node " ++ show nid1 case inst of LoadCursorStatic vi name -> do let key = ResourceStatic name () :: ArrayResourceKey let Just abox = M.lookup key arrayDict Just rscName = M.lookup key resourceDict thisEq $ rscName <> accAtMargin abox vi LoadCursor vi nid -> do node <- lookupNode nid let Just abox = M.lookup key arrayDict Just rscName0 = M.lookup key resourceDict key = ResourceOMNode nid ir0 rscName :: C.Src rscName = C.typedHole rscPtrTypename (C.toText rscName0) case node ^. nodeType of ElemType _ -> thisEq $ rscName _ -> thisEq $ rscName <> accAtMargin abox vi Imm r -> thisEq $ C.show (realToFrac r :: Double) Uniop op a -> do a_code <- query a if "external-call/" `isPrefixOf` op then thisEq $ C.parens $ fromString (T.packed %~ T.replace "external-call/" "" $ op) <> C.parens a_code else thisEq $ C.parens $ fromString op <> a_code Binop op a b -> do a_code <- query a b_code <- query b case op of "**" -> thisEq $ ("pow"<>) $ C.parens $ a_code <> ", " <> b_code _ -> thisEq $ C.parens $ C.unwords [" ", a_code, fromString op, b_code, " "] Triop "ite" a b c -> do a_code <- query a b_code <- query b c_code <- query c thisEq $ C.parens $ a_code <> "?" <> b_code <> ":" <> c_code Naryop op xs -> do xs_code <- mapM query xs let chain fname cs = foldr1 (\a b -> fname <> C.parens (a <> ", " <> b) ) cs case op of ">?" -> thisEq $ chain "fmax" xs_code "<?" -> thisEq $ chain "fmin" xs_code "<%" -> thisEq $ chain "fmin" ["0.0", chain "fmax" xs_code] <> "+" <> chain "fmax" ["0.0", chain "fmin" xs_code] _ -> raiseErr $ failed $ "unsupported N-ary operator: " ++ show op LoadIndex ax -> do let ofs_i = "navi.offset_" <> i i = toList axvars !! ax ix= toList indNames !! ax thisEq $ C.parens $ nPlusK (ofs_i <> "+" <> ix) (toList indOffset !! ax) Store _ x -> do x_code <- query x thisEq x_code x -> raiseErr $ failed $ "mpicxx codegen unimplemented for keyword: " ++ show x nmap <- use nodeIDtoLocalName let (tailID, _) = M.findMax mminst Just tailName = M.lookup tailID nmap retPairs = [ (tailName,c) | (i,c) <- mmFindTailIDs mminst , tailName <- maybeToList $ M.lookup i nmap] return $ ((M.unions $ map fst txts, C.unwords $ map snd txts), retPairs) mmFindTailIDs :: MMInstruction -> [(MMNodeID, Vec Int)] mmFindTailIDs mminst = rets where rets = [ (i, c) | (i,nd) <- M.toList mminst, let Just (MMLocation omnid2 c) = A.viewMaybe nd, omnid2==omnid ] Just (MMLocation omnid _) = A.viewMaybe maxNode maxNode :: MicroNode maxNode = snd $ M.findMax mminst ompEveryLoopPragma :: (?ncOpts :: [String]) => [C.Src] -> Int -> C.Src ompEveryLoopPragma privVars n | "omp-collapse" `elem` ?ncOpts = "!$omp do collapse(" <> C.show n <> ") private(" <> C.intercalate ", " privVars <>")" | "omp" `elem` ?ncOpts = "!$omp do private(" <> C.intercalate ", " privVars <>")" | otherwise = "" withFineBench :: (?ncOpts :: [String]) => C.Src -> C.Src -> C.Src withFineBench benchLabel = addColl . addFapp where addColl src = case "bench-fine-collection" `elem` ?ncOpts of False -> src True -> C.unlines ["call start_collection(\"" <> benchLabel <> "\")" , src , "call stop_collection(\"" <> benchLabel <> "\")" ] addFapp src = case "bench-fine-fapp" `elem` ?ncOpts of False -> src True -> C.unlines ["call fapp_start(\"" <> benchLabel <> "\",0,0)" , src , "call fapp_stop(\"" <> benchLabel <> "\",0,0)" ] -- | generate a formura function body. genComputation :: (?ncOpts :: [String]) => (IRank, OMNodeID) -> ArrayResourceKey -> TranM (FortranBinding, C.Src) genComputation (ir0, nid0) destRsc0 = do dim <- view dimension ivars <- use loopIndexNames regionDict <- use planRegionAlloc arrayDict <- use planArrayAlloc stepGraph <- use omStepGraph nc <- view envNumericalConfig let regionBox :: Box marginBox :: Box Just regionBox = M.lookup (ir0, nid0) regionDict Just marginBox = M.lookup destRsc0 arrayDict loopFroms :: Vec Int loopFroms = regionBox^.lowerVertex - marginBox^.lowerVertex loopTos :: Vec Int loopTos = regionBox^.upperVertex - marginBox^.lowerVertex mmInst :: MMInstruction Just (Node mmInst typ annot) = M.lookup nid0 stepGraph loopIndexOffset .= marginBox^. lowerVertex systemOffset0 <- use planSystemOffset let nbux = nbuSize "x" nc nbuy = nbuSize "y" nc nbuz = nbuSize "z" nc gridStride = [nbux, nbuy, nbuz] let genGrid useSystemOffset lhsName2 = do let openLoops = reverse $ [ C.unwords ["do ", i, "=", C.parameter "int" (l+1) ,", ", C.parameter "int" h, ", ", C.show s ,"\n"] | (i,s,l,h) <- zip4 (toList ivars) gridStride (toList loopFroms) (toList loopTos)] closeLoops = ["end do" | _ <- toList ivars] ((fortranBinds,letBs),rhss) <- genMMInstruction ir0 mmInst let bodyExpr = C.unlines [ lhsName2 <> C.parensTuple (nPlusK <$> ivarExpr <*> c) <> "=" <> rhs | (rhs, c) <- rhss ] ivarExpr | useSystemOffset = nPlusK <$> ivars <*> negate systemOffset0 | otherwise = ivars privVars = M.keys fortranBinds return $ (fortranBinds, ) $ C.potentialSubroutine $ C.unlines $ [ompEveryLoopPragma (toList ivars ++ privVars) $ dim-1] ++ openLoops ++ [letBs,bodyExpr] ++ closeLoops case typ of ElemType "void" -> case head $ mmInstTails mmInst of Store n _ -> do lhsName <- nameArrayResource (ResourceStatic n ()) genGrid True lhsName _ -> return (M.empty, "// void") GridType _ typ -> do lhsName <- nameArrayResource (ResourceOMNode nid0 ir0) genGrid False (C.typedHole rscPtrTypename (C.toText lhsName)) _ -> do return (M.empty, fromString $ "// dunno how gen " ++ show mmInst) -- | generate a staging/unstaging code genStagingCode :: (?ncOpts :: [String]) => Bool -> RidgeID -> TranM (FortranBinding, C.Src) genStagingCode isStaging rid = do dim <- view dimension ridgeDict <- use planRidgeAlloc arrDict <- use planArrayAlloc intraShape <- use ncIntraNodeShape let Just box0 = M.lookup rid ridgeDict src :: ArrayResourceKey src = case rid of RidgeID _ (ResourceOMNode nid (irS,irD)) -> ResourceOMNode nid (if isStaging then irS else irD) RidgeID _ (ResourceStatic sn ()) -> ResourceStatic sn () Just box1 = M.lookup src arrDict MPIRank mpivec = rid ^. ridgeDeltaMPI arrName <- nameArrayResource src rdgNameSend <- nameRidgeResource rid Send rdgNameRecv <- nameRidgeResource rid Recv ivars <- use loopIndexNames let offset :: Vec Int offset = box0^.lowerVertex loopFroms :: Vec Int loopFroms = box0^.lowerVertex - offset loopTos :: Vec Int loopTos = box0^.upperVertex - offset otherOffset :: Vec Int otherOffset = offset - box1^.lowerVertex - (if isStaging then mpivec * intraShape else 0) let openLoops = reverse $ [ C.unwords ["do", i, "=", C.show (l+1) ,", ", C.show h] | (i,(l,h)) <- (toList ivars) `zip` zip (toList loopFroms) (toList loopTos)] closeLoops = ["end do" | _ <- toList ivars] rdgName = if isStaging then rdgNameSend else rdgNameRecv rdgTerm = rdgName <> C.parensTuple ivars arrTerm = arrName <> C.parensTuple (liftVec2 nPlusK ivars otherOffset) body | isStaging = rdgTerm <> "=" <> arrTerm | otherwise = arrTerm <> "=" <> rdgTerm let pragma = if "collapse-ridge" `elem` ?ncOpts then ompEveryLoopPragma (toList ivars) dim else ompEveryLoopPragma (toList ivars) (dim -1) fortranBinds = M.fromList [(i, "integer") |i <- toList ivars] return $ (fortranBinds,) $ pragma <> "\n" <> C.unlines openLoops <> body <> "\n" <> C.unlines closeLoops genMPISendRecvCode :: FacetID -> TranM (FortranBinding, C.Src) genMPISendRecvCode f = do reqName <- nameFacetRequest f facetNameSend <- nameFacet f Send facetNameRecv <- nameFacet f Recv facetTypeName <- nameFacet f SendRecv mpiTagDict <- use planFacetMPITag let dmpi = f ^. facetDeltaMPI mpiIsendIrecv :: C.Src mpiIsendIrecv = C.unwords $ [ "mpi_sizeof_value = " <> "sizeof(" <> facetNameRecv <> ") \n" , "mpi_comm_value = navi%mpi_comm\n" , "mpi_src_value = " <> "navi%" <> nameDeltaMPIRank dmpi <> "\n" , "mpi_dest_value = " <> "navi%" <> nameDeltaMPIRank (negate dmpi) <> "\n" ] ++ [ "call mpi_irecv( " <> facetNameRecv, ", " , "mpi_sizeof_value," , "MPI_BYTE," , "mpi_src_value," , let Just t = M.lookup f mpiTagDict in C.show t, ", " , "mpi_comm_value," , reqName <> ",mpi_err )\n"] ++ [ "call mpi_isend(" <> facetNameSend, ", " , "mpi_sizeof_value," , "MPI_BYTE," , "mpi_dest_value," , let Just t = M.lookup f mpiTagDict in C.show t, ", " , "mpi_comm_value," , reqName <> ",mpi_err )\n"] return (M.empty, mpiIsendIrecv) genMPIWaitCode :: (?ncOpts :: [String]) => FacetID -> TranM (FortranBinding, C.Src) genMPIWaitCode f = do reqName <- nameFacetRequest f let dmpi = f ^. facetDeltaMPI mpiWait :: C.Src mpiWait = C.unwords $ ["call mpi_wait(" <> reqName <> ",MPI_STATUS_IGNORE,mpi_err)\n"] return (M.empty, mpiWait) -- | generate a distributed program genDistributedProgram :: (?ncOpts :: [String]) => [DistributedInst] -> TranM C.Src genDistributedProgram insts0 = do stepGraph <- use omStepGraph theGraph .= stepGraph let insts1 = filter (not . isNop) insts0 insts2 = grp [] $ insts1 when (insts1 /= concat insts2) $ raiseErr $ failed $ "Detected instruction order mismatch!" bodies <- mapM (mapM go2) $ insts2 ps <- mapM genCall bodies return $ mconcat ps where isNop (FreeResource _) = True isNop _ = False sticks :: DistributedInst -> DistributedInst -> Bool sticks | "stick-all-comp" `elem` ?ncOpts = sticksB | "stick-single-comp" `elem` ?ncOpts = sticksA | otherwise = sticksB sticksA :: DistributedInst -> DistributedInst -> Bool sticksA (Unstage _) (Unstage _ ) = True sticksA (Unstage _) (Computation _ _ ) = True sticksA (Computation _ _ ) (Stage _) = True sticksA (Stage _) (Stage _) = True sticksA _ _ = False sticksB :: DistributedInst -> DistributedInst -> Bool sticksB a b = let isComp (CommunicationWait _) = False isComp (CommunicationSendRecv _) = False isComp _ = True in isComp a && isComp b grp :: [DistributedInst] -> [DistributedInst] -> [[DistributedInst]] grp accum [] = [reverse accum] grp [] (x:xs) = grp [x] xs grp accum@(a:aa) (x:xs) | sticks a x = grp (x:accum) xs | otherwise = reverse accum : grp [] (x:xs) go2 :: DistributedInst -> TranM (DistributedInst, (FortranBinding, C.Src)) go2 i = do j <- go i return (i,j) 剔算 = knockout $ "knockout-computation" `elem` ?ncOpts 剔通 = knockout $ "knockout-communication" `elem` ?ncOpts knockout :: Bool -> TranM (FortranBinding, C.Src) -> TranM (FortranBinding, C.Src) knockout flag m = do t <- m return $ if flag then (M.empty, "") else t (⏲) :: TranM (FortranBinding, C.Src) -> C.Src -> TranM (FortranBinding, C.Src) m ⏲ str = (_2 %~ withFineBench str) <$> m go :: DistributedInst -> TranM (FortranBinding, C.Src) go (Computation cmp destRsc) = 剔算 $ genComputation cmp destRsc ⏲ "computation" go (Unstage rid) = 剔算 $ genStagingCode False rid ⏲ "stageOut" go (Stage rid) = 剔算 $ genStagingCode True rid ⏲ "stageIn" go (FreeResource _) = 剔算 $ return (M.empty, "") go (CommunicationSendRecv f) = 剔通 $ genMPISendRecvCode f ⏲ "mpiSendrecv" go (CommunicationWait f) = 剔通 $ genMPIWaitCode f ⏲ "mpiWait" genCall :: [(DistributedInst, (FortranBinding, C.Src))] -> TranM C.Src genCall instPairs = do let body = map (snd. snd) instPairs isGenerateFunction = case map fst instPairs of [(CommunicationWait _)] -> False [(CommunicationSendRecv _)] -> False _ -> True binds = [ t <> " :: " <> v | (v,t) <- M.toList $ M.unions $ map (fst . snd) instPairs] case isGenerateFunction of True -> do funName <- genFreeName "Formura_internal" tellF (toString $ funName <> ".f90") $ fortranBlockArg "subroutine" funName "()" $ C.unlines $ binds ++ (if "omp" `elem` ?ncOpts then ["!$omp parallel\n"] else []) ++ body ++ (if "omp" `elem` ?ncOpts then ["!$omp end parallel\n"] else []) return $ "call " <> funName <> "()\n" False -> do return $ C.unlines $ binds ++ body -- | Let the plans collaborate collaboratePlans :: TranM () collaboratePlans = do plans0 <- use tsMPIPlanMap nc <- view envNumericalConfig let nbux = nbuSize "x" nc nbuy = nbuSize "y" nc nbuz = nbuSize "z" nc nbuMargin = Vec [nbux-1+2, nbuy-1+2, nbuz-1+2] let commonStaticBox :: Box commonStaticBox = upperVertex %~ (+nbuMargin) $ foldr1 (|||) [ b | p <- M.elems plans0 , (ResourceStatic snName (), b) <- M.toList $ p ^. planArrayAlloc ] newPlans = M.map rewritePlan plans0 rewritePlan :: MPIPlan -> MPIPlan rewritePlan p = p & planArrayAlloc %~ M.mapWithKey go -- & planSharedResourceExtent .~ commonRscBox -- TODO: Flipping the comment of this line changes the behavior. go (ResourceStatic snName ()) _ = commonStaticBox go _ b = b commonRscBox = upperVertex %~ (+nbuMargin) $ foldr1 (|||) [ p ^. planSharedResourceExtent | p <- M.elems plans0] tsCommonStaticBox .= commonStaticBox tsMPIPlanMap .= newPlans -- | The main translation logic tellProgram :: WithCommandLineOption => TranM () tellProgram = do setNumericalConfig setNamingState nc <- use tsNumericalConfig let ?ncOpts = nc ^. ncOptionStrings mpiGrid0 <- use ncMPIGridShape mmprog <- use theMMProgram (ivars :: Vec C.Src) <- fmap fromString <$> view axesNames intraExtents <- use ncIntraNodeShape let cxxTemplateWithMacro :: C.Src cxxTemplateWithMacro = cxxTemplate tsCxxTemplateWithMacro .= cxxTemplateWithMacro tsMPIPlanSelection .= False plan <- liftIO $ makePlan nc mmprog mPIPlan .= plan tsMPIPlanSelection .= True plan <- liftIO $ makePlan (nc & ncWallInverted .~ Just True) mmprog mPIPlan .= plan collaboratePlans tellH $ "implicit none\n" tellH "\n\n" tellH $ C.unlines [ "integer, parameter :: " <> nx <> " = " <> C.show (i*g) | (x,i,g) <- zip3 (toList ivars) (toList intraExtents) (toList mpiGrid0) , let nx = "N" <> (fromString $ map toUpper $ toString x) ] tsMPIPlanSelection .= False tellArrayDecls srmap0 <- use planSharedResourceNames tsMPIPlanSelection .= True planSharedResourceNames .= srmap0 -- share the shared resource among plans tellArrayDecls allRidges0 <- use planRidgeAlloc let deltaMPIs :: [MPIRank] deltaMPIs = S.toList $ S.fromList $ concat [ [dmpi, negate dmpi] | rdg <- M.keys allRidges0 , let dmpi = rdg ^. ridgeDeltaMPI] -- how to define struct : http://www.nag-j.co.jp/fortran/FI_4.html#ExtendedTypes tellHBlock "type" "Formura_Navigator" $ do tellHLn $ "integer :: time_step" forM_ ivars $ \i -> do tellHLn $ "integer :: lower_" <> i <> "" tellHLn $ "integer :: upper_" <> i <> "" tellHLn $ "integer :: offset_" <> i <> "" tellHLn $ "integer :: mpi_comm" tellHLn $ "integer :: mpi_my_rank" forM_ deltaMPIs $ \r -> do tellHLn $ "integer :: " <> nameDeltaMPIRank r <> "" tellCLn $ "!INSERT_USE_INTERNAL_HERE" tellCLn $ "implicit none" tellCLn $ "include \"mpif.h\"" tellCLn $ "integer :: mpi_err" tellCLn $ "integer :: mpi_sizeof_value, mpi_comm_value" tellCLn $ "integer :: mpi_src_value, mpi_dest_value" tellCLn "contains" tellCBlockArg "subroutine" "Formura_decode_mpi_rank" ("(s" <> C.unwords[", i" <> x | x<-toList ivars] <> ")") $ do tellCLn $ C.unlines["integer :: i" <> x | x<-toList ivars] tellCLn "integer :: s" forM_ (zip (reverse $ toList ivars) (reverse $ toList mpiGrid0)) $ \(x, g) -> do tellCLn $ "i" <> x <> "=mod(s," <> C.show g <> ")" tellCLn $ "s=s/" <> C.show g tellC "integer " tellCBlockArg "function" "Formura_encode_mpi_rank" ("(" <> C.intercalate ", " ["i" <> x | x<-toList ivars] <> ")") $ do tellCLn $ C.unlines["integer :: i" <> x | x<-toList ivars] tellCLn "integer :: s" tellCLn "s = 0" forM_ (zip (toList ivars) (toList mpiGrid0)) $ \(x, ig) -> do let g=C.show ig tellCLn $ "s = s * " <>g<>"" tellCLn $ "s = s + mod((mod(i"<>x<>", "<>g<>")+"<>g<>"),"<>g<>")" tellCLn "Formura_encode_mpi_rank = s" tellCBlockArg "subroutine" "Formura_Init" "(navi,comm)" $ do tellCLn "type(Formura_Navigator) :: navi" tellCLn "integer :: comm, mpi_my_rank_tmp" csb0 <- use tsCommonStaticBox let mpiivars = fmap ("i"<>) ivars lower_offset = negate $ csb0 ^.lowerVertex tellCLn $ "integer :: " <> C.intercalate ", " (toList mpiivars) tellCLn $ "navi%mpi_comm = comm" tellCLn $ "call MPI_Comm_rank(comm,mpi_my_rank_tmp,mpi_err)\n navi%mpi_my_rank=mpi_my_rank_tmp" tellCLn $ "call Formura_decode_mpi_rank( mpi_my_rank_tmp" <> C.unwords [ ", " <> x| x<- toList mpiivars] <> ")" forM_ deltaMPIs $ \r@(MPIRank rv) -> do let terms = zipWith nPlusK (toList mpiivars) (toList rv) tellC $ "navi%" <> nameDeltaMPIRank r <> "=" tellCLn $ "Formura_encode_mpi_rank( " <> C.intercalate ", " terms <> ")" tellCLn "navi%time_step=0" forM_ (zip3 (toList ivars) (toList intraExtents) (toList lower_offset)) $ \(x, e, o) -> do tellCLn $ "navi%offset_" <> x <> "=" <> "i"<> x <> "*"<>C.show e <> "-" <> C.show o <> "" tellCLn $ "navi%lower_" <> x <> "=" <> C.show o<>"" tellCLn $ "navi%upper_" <> x <> "=" <> C.show o <> "+"<>C.show e <> "" tellCLn "\n\n" cprogcon <- forM [False, True] $ \ mps -> do tsMPIPlanSelection .= mps dProg <- use planDistributedProgram genDistributedProgram dProg monitorInterval0 <- use ncMonitorInterval temporalBlockingInterval0 <- use ncTemporalBlockingInterval timeStepVarName <- genFreeName "timestep" when ((monitorInterval0`mod`(2*temporalBlockingInterval0))/=0) $ liftIO $ putStrLn "Warning : Monitor interval must be multiple of (2 * temporal blocking interval)" let monitorInterval2 = head $ filter (\x -> x`mod`(2*temporalBlockingInterval0)==0)[monitorInterval0 ..] let openTimeLoop = "do " <> timeStepVarName <> "=0," <> C.show (monitorInterval2`div`(2*temporalBlockingInterval0)-1) closeTimeLoop = "end do" tellCBlockArg "subroutine" "Formura_Forward" "(navi)" $ do tellCLn "type(Formura_Navigator) :: navi" tellCLn $ "integer :: " <> timeStepVarName tellC $ C.unlines [ openTimeLoop , C.unlines [cprogcon!!0,"! HALFWAYS " , cprogcon!!1] , closeTimeLoop , "navi%time_step = navi%time_step + " <> C.show monitorInterval2 <> "" , "\n" ] useSubroutineCalls :: WithCommandLineOption => M.Map C.Src String -> CProgram -> IO CProgram useSubroutineCalls subroutineMap cprog0 = traverse (useSubroutineInSrc subroutineMap) cprog0 useSubroutineInSrc :: WithCommandLineOption => M.Map C.Src String -> C.Src -> IO C.Src useSubroutineInSrc subroutineMap (C.Src xs) = C.Src <$> mapM go xs where go :: C.Word -> IO C.Word go x@(C.Raw _) = return x go x@(C.Hole _) = return x go (C.PotentialSubroutine pssrc) = do let tmpl = C.template pssrc Just funName = M.lookup tmpl subroutineMap argList :: [T.Text] argList = [(argN ^. C.holeExpr) | argN <-toList pssrc] return $ C.Raw $ "call " <> fromString funName <> "(" <> T.intercalate ", " argList <> ")\n" joinSubroutines :: WithCommandLineOption => CProgram -> IO CProgram joinSubroutines cprog0 = do when (?commandLineOption ^. verbose) $ do putStrLn $ "## Subroutine Analysis" when (elem "show-subroutines" $ ?commandLineOption ^. auxFlags) $ do forM_ (zip [1..] subs1) $ \(i, ss) -> do forM_ (zip [1..] ss) $ \(j, s) -> do putStrLn $ "# Subroutine group" ++ show i ++ ": member " ++ show j T.putStrLn $ C.pretty s putStrLn $ show $ C.template s print $ sum $ map fromEnum $ show $ C.template s putStrLn $ "Found " ++ show (length subs0) ++ " subroutines." putStrLn $ "Found " ++ show (length subs1) ++ " subroutine groups." forM_ (zip [1..] subs1) $ \(i, ss) -> do let C.Src xs = head ss cnt (C.Hole _) = 1 cnt _ = 0 print ("Count of typed holes #",i, sum $ map cnt xs) -- forM_ (take 2 ss) $ T.putStrLn . C.pretty cprog1 <- useSubroutineCalls subroutineNameMap cprog0 return $ cprog1 & headerFileContent %~ (C.replace "/*INSERT SUBROUTINES HERE*/" hxxSubroutineDecls) & auxFilesContent %~ (M.union auxSubroutineDefs) where subs0 :: [C.Src] subs0 = foldMap getSub cprog0 getSub :: C.Src -> [C.Src] getSub (C.Src xs) = xs >>= toSub toSub :: C.Word -> [C.Src] toSub (C.PotentialSubroutine s) = [s] toSub _ = [] -- (subroutine template, the list of codes that uses the subroutine) submap1 = M.unionsWith (++) [ M.singleton (C.template s) [s] | s <- subs0] subs1 :: [[C.Src]] subs1 = M.elems $ submap1 subTemplates :: [C.Src] subTemplates = M.keys submap1 -- map a Potential Subroutine template to its subroutine name subroutineNameMap :: M.Map C.Src String subroutineNameMap = M.fromList [(tmpl, "Formura_subroutine_" ++ show i) | (i,tmpl) <- zip [0..] subTemplates] argvNames :: [C.Src] argvNames = ["argx" <> C.show i | i <- [0..]] genSubroutine :: String -> C.Src -> (C.Src, C.Src) genSubroutine fname tmpl = let header = "void " <> fromString fname <> "(" <> C.intercalate ", " argvList <> ")" argvList = [C.raw (h ^. C.holeType) <> " " <> argN | (h, argN) <- zip (toList tmpl) argvNames] sbody :: C.Src sbody = zipWithFT (\arg hole -> hole & C.holeExpr .~ C.toText arg) argvNames tmpl in (header <> ";", header <> C.braces sbody) subroutineCodes :: [(String, C.Src, C.Src)] subroutineCodes = [ (fnBody ++ ".f90", hxx, cxx) | (tmpl, fnBody) <- M.toList subroutineNameMap , let (hxx,cxx) = genSubroutine fnBody tmpl] hxxSubroutineDecls :: C.Src hxxSubroutineDecls = C.unlines [ hc ^. _2 | hc <- subroutineCodes] auxSubroutineDefs :: M.Map FilePath C.Src auxSubroutineDefs = M.fromList [ (hc ^. _1, hc ^. _3) | hc <- subroutineCodes] writeFortranModule :: FilePath -> T.Text -> IO () writeFortranModule fn con = do let modName = T.pack $ fn^.basename T.writeFile fn $ T.unlines ["module " <> modName, con, "end module " <> modName] genFortranFiles :: WithCommandLineOption => Program -> MMProgram -> IO () genFortranFiles formuraProg mmProg0 = do let nc = formuraProg ^. programNumericalConfig tbFoldingNumber = nc ^. ncTemporalBlockingInterval mmProgTB = temporalBlocking tbFoldingNumber mmProg0 tranState0 = TranState { _tranSyntacticState = defaultCompilerSyntacticState{ _compilerStage = "C++ code generation"} , _tsNamingState = defaultNamingState , _theProgram = formuraProg , _theMMProgram = mmProgTB , _tsNumericalConfig = nc , _theGraph = M.empty , _tsMPIPlanSelection = False , _tsMPIPlanMap = M.empty , _tsCommonStaticBox = error "_tsCommonStaticBox is unset" , _tsCxxTemplateWithMacro = error "_tsCxxTemplateWithMacro is unset" } (_, tranState1 , cprog0) <- runCompilerRight tellProgram (mmProgTB ^. omGlobalEnvironment) tranState0 (CProgram hxxContent cxxContent auxFilesContent) <- if (elem "no-subroutine" $ tranState1 ^. ncOptionStrings) then return cprog0 else joinSubroutines cprog0 createDirectoryIfMissing True (cxxFilePath ^. directory) let funcs = cluster [] $ M.elems auxFilesContent cluster :: [C.Src] -> [C.Src] -> [C.Src] cluster accum [] = reverse accum cluster [] (x:xs) = cluster [x] xs cluster (ac:acs) (x:xs) | ac /= "" && C.length (ac<>x) > 64000 = cluster ("":ac:acs) (x:xs) | otherwise = cluster (ac <> x : acs) xs writeAuxFile :: Int -> C.Src -> IO FilePath writeAuxFile i con = do let fn = cxxFileBodyPath ++ "_internal_" ++ show i ++ ".f90" internalModuleHeader = C.unlines [ "use " <> (C.raw $ T.pack $ (fortranHeaderFilePath ^. basename)) , "contains"] putStrLn $ "writing to file: " ++ fn writeFortranModule fn $ C.toText $ internalModuleHeader<>con return fn auxFilePaths <- zipWithM writeAuxFile [0..] funcs let insertUseInternals :: T.Text -> T.Text insertUseInternals = T.replace "!INSERT_USE_INTERNAL_HERE" useInternals useInternals = T.unlines [ T.pack $ "use " <> (fn ^. basename) | fn <- fortranHeaderFilePath : auxFilePaths] writeFortranModule fortranHeaderFilePath $ C.toText hxxContent writeFortranModule cxxFilePath $ insertUseInternals $ C.toText cxxContent let wait = ?commandLineOption ^. sleepAfterGen when (wait>0) $ threadDelay (1000000 * wait) mapM_ indent ([fortranHeaderFilePath, cxxFilePath] ++ auxFilePaths) where indent fn = X.handle ignore $ callProcess "./scripts/wrap-fortran.py" [fn] ignore :: X.SomeException -> IO () ignore _ = return () fortranHeaderFilePath = cxxFilePath & basename %~ (<> "_header") cxxTemplate :: WithCommandLineOption => C.Src cxxTemplate = C.unlines [ "" --, "#include \"" <> fromString hxxFileName <> "\"" , "include \"mpif.h\"" , "" ] rscPtrTypename :: T.Text rscPtrTypename = rscSfcTypename <> " * __restrict " rscSfcTypename :: T.Text rscSfcTypename = "rsc_surface"
nushio3/formura
src/Formura/MPIFortran/Translate.hs
mit
47,185
54
26
12,586
15,223
7,570
7,653
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Codex.Tester ( oneOf, tester, nullTester, -- * module re-exports Meta, Code(..), lookupFromMeta, module Codex.Tester.Monad, module Codex.Tester.Result, module Codex.Tester.Utils, module Codex.Tester.Limits, -- * generic stuff module Control.Monad, module Control.Monad.Trans, module System.FilePath, module System.Exit, module Data.Monoid, ) where import Codex.Types import Codex.Page (lookupFromMeta) import Text.Pandoc (Meta) import Codex.Tester.Monad import Codex.Tester.Limits import Codex.Tester.Result import Codex.Tester.Utils import Control.Applicative import Control.Monad import Control.Monad.Trans import System.FilePath import System.Exit import Data.Monoid import Data.Text (Text) -- | Try testers in order, return the first one that suceedds. -- This is just `asum` from Control.Applicative.Alternative -- renamed for readability oneOf :: [Tester a] -> Tester a oneOf = foldr (<|>) empty -- | label a tester and ignore submissions that don't match tester :: Text -> Tester a -> Tester a tester name cont = do meta <- testMetadata guard (lookupFromMeta "tester" meta == Just name) cont -- | trivial tester (accepts all submissions) nullTester :: Tester Result nullTester = tester "accept" $ return $ accepted "Submission recorded"
pbv/codex
src/Codex/Tester.hs
mit
1,477
0
10
355
305
182
123
39
1
-- Copyright © 2013 Julian Blake Kongslie <jblake@jblake.org> -- Licensed under the MIT license. {-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -Wall -Werror -fno-warn-unused-imports #-} module Main where import Control.DeepSeq import Control.Monad import qualified Data.ByteString.Lazy as BS import Data.Data import Data.Generics.Uniplate.Operations import System.Console.CmdArgs.Implicit import System.Exit import Language.GBAsm.ByteGen import Language.GBAsm.CompileOps import Language.GBAsm.File import Language.GBAsm.Globals import Language.GBAsm.IncBin import Language.GBAsm.Lexer import Language.GBAsm.Locals import Language.GBAsm.Math import Language.GBAsm.Macros import Language.GBAsm.Opcodes import Language.GBAsm.OutputPos import Language.GBAsm.Parser import Language.GBAsm.Relative import Language.GBAsm.Types import Language.GBAsm.Unresolved import Language.GBAsm.UnresolvedMacros data GBAsm = GBAsm { inputFiles :: [String] , outputFile :: String } deriving (Data, Eq, Ord, Read, Show, Typeable) main :: IO () main = do params <- cmdArgs $ GBAsm { inputFiles = [] &= args &= typ "FILE ..." , outputFile = "out.gbc" &= explicit &= name "o" &= name "output" &= typFile &= help "The output file to create." } &= summary "Assembler for GameBoy" let cmdLineSP = SourcePos "<command line>" 0 0 let initialAST = Scope cmdLineSP [ File cmdLineSP file | file <- inputFiles params ] parsedAST <- filePass initialAST -- Note that these passes are lasted from last to first. compiledAST <- incBinPass $!! compileOpsPass $!! mathPass $!! unresolvedPass $!! localsPass $!! globalsPass $!! relativePass $!! outputPosPass $!! mathPass $!! unresolvedMacrosPass $!! macrosPass $!! parsedAST case [ (p, msg) | Err (p, _) msg <- universe compiledAST ] of [] -> BS.writeFile (outputFile params) $ byteGenPass compiledAST errs -> do putStrLn "Unable to compile!\n" forM_ errs $ \(p, msg) -> putStrLn $ show (sourceName p) ++ " (line " ++ show (sourceLine p) ++ ", column " ++ show (sourceCol p) ++ "):\n " ++ msg ++ "\n" exitFailure
jblake/gbasm
src/Main.hs
mit
2,154
0
24
396
557
302
255
58
2
{-#LANGUAGE OverloadedStrings #-} module Main where import Control.Lens import Control.Monad import Control.Monad.Reader import Control.Monad.Writer import System.Environment import System.Exit import System.IO import System.Console.CmdArgs.Implicit import Crystal.AST import Crystal.Check import Crystal.Config import Crystal.Infer import Crystal.Misc import Crystal.Parser import Crystal.Post import Crystal.Pretty import Crystal.Transform import Crystal.Type type Pipeline = Expr Label -> Step DeclExpr pipeline :: Pipeline pipeline = transformC >=> infer >=> addChecks >=> postprocess runPipeline :: Pipeline -> Expr Label -> Config -> IO (DeclExpr, [StepResult]) runPipeline pipe ast cfg = runReaderT (runWriterT (pipe ast)) cfg process config fname cts = case parseCrystal fname cts of Left err -> hPrint stderr err >> exitFailure Right ast -> do (ast', results) <- runPipeline pipeline ast config putStrLn $ prettyD $ ast' when (not (null results)) $ do hPutStr stderr "<extra-information>\n" forM_ results $ uncurry report_result hPutStr stderr "\n</extra-information>\n" main = do config <- cmdArgs defaultArgs case config^.cfgInputFile of "" -> process config "-" =<< force `liftM` getContents file -> process config file =<< readFile file force x = length x `seq` x
Botje/crystal
Crystal.hs
gpl-2.0
1,461
0
15
353
410
211
199
39
2
{-# OPTIONS -w -O0 #-} {-# LANGUAGE CPP, StandaloneDeriving, DeriveDataTypeable #-} {- | Module : Alloy/ATC_Alloy.der.hs Description : generated Typeable, ShATermConvertible instances Copyright : (c) DFKI GmbH 2012 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable(derive Typeable instances) Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible for the type(s): 'Alloy.AS_Alloy.X' 'Alloy.AS_Alloy.Sen' 'Alloy.AS_Alloy.Symbol' 'Alloy.AS_Alloy.RawSymbol' 'Alloy.AS_Alloy.SymbItems' 'Alloy.AS_Alloy.SymbMapItems' 'Alloy.AlloySign.Sign' 'Alloy.AlloySign.Mor' -} {- Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!! dependency files: Alloy/AS_Alloy.hs Alloy/AlloySign.hs -} module Alloy.ATC_Alloy () where import ATC.AS_Annotation import ATerm.Lib import Alloy.AS_Alloy import Alloy.AlloySign import Common.Id import Data.Monoid import Data.Typeable {-! for Alloy.AS_Alloy.X derive : Typeable !-} {-! for Alloy.AS_Alloy.Sen derive : Typeable !-} {-! for Alloy.AS_Alloy.Symbol derive : Typeable !-} {-! for Alloy.AS_Alloy.RawSymbol derive : Typeable !-} {-! for Alloy.AS_Alloy.SymbItems derive : Typeable !-} {-! for Alloy.AS_Alloy.SymbMapItems derive : Typeable !-} {-! for Alloy.AlloySign.Sign derive : Typeable !-} {-! for Alloy.AlloySign.Mor derive : Typeable !-} {-! for Alloy.AS_Alloy.X derive : ShATermConvertible !-} {-! for Alloy.AS_Alloy.Sen derive : ShATermConvertible !-} {-! for Alloy.AS_Alloy.Symbol derive : ShATermConvertible !-} {-! for Alloy.AS_Alloy.RawSymbol derive : ShATermConvertible !-} {-! for Alloy.AS_Alloy.SymbItems derive : ShATermConvertible !-} {-! for Alloy.AS_Alloy.SymbMapItems derive : ShATermConvertible !-} {-! for Alloy.AlloySign.Sign derive : ShATermConvertible !-} {-! for Alloy.AlloySign.Mor derive : ShATermConvertible !-} -- Generated by DrIFT, look but don't touch! instance ShATermConvertible SymbMapItems where toShATermAux att0 xv = case xv of SymbMapItems -> return $ addATerm (ShAAppl "SymbMapItems" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "SymbMapItems" [] _ -> (att0, SymbMapItems) u -> fromShATermError "SymbMapItems" u instance ShATermConvertible SymbItems where toShATermAux att0 xv = case xv of SymbItems -> return $ addATerm (ShAAppl "SymbItems" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "SymbItems" [] _ -> (att0, SymbItems) u -> fromShATermError "SymbItems" u instance ShATermConvertible RawSymbol where toShATermAux att0 xv = case xv of RawSymbol -> return $ addATerm (ShAAppl "RawSymbol" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "RawSymbol" [] _ -> (att0, RawSymbol) u -> fromShATermError "RawSymbol" u instance ShATermConvertible Symbol where toShATermAux att0 xv = case xv of Symbol -> return $ addATerm (ShAAppl "Symbol" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Symbol" [] _ -> (att0, Symbol) u -> fromShATermError "Symbol" u instance ShATermConvertible Sen where toShATermAux att0 xv = case xv of Sen -> return $ addATerm (ShAAppl "Sen" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Sen" [] _ -> (att0, Sen) u -> fromShATermError "Sen" u instance ShATermConvertible X where toShATermAux att0 xv = case xv of X -> return $ addATerm (ShAAppl "X" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "X" [] _ -> (att0, X) u -> fromShATermError "X" u deriving instance Typeable SymbMapItems deriving instance Typeable SymbItems deriving instance Typeable RawSymbol deriving instance Typeable Symbol deriving instance Typeable Sen deriving instance Typeable X deriving instance Typeable Sign deriving instance Typeable Mor instance ShATermConvertible Sign where toShATermAux att0 xv = case xv of Sign -> return $ addATerm (ShAAppl "Sign" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Sign" [] _ -> (att0, Sign) u -> fromShATermError "Sign" u instance ShATermConvertible Mor where toShATermAux att0 xv = case xv of Mor -> return $ addATerm (ShAAppl "Mor" [] []) att0 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Mor" [] _ -> (att0, Mor) u -> fromShATermError "Mor" u
nevrenato/HetsAlloy
Alloy/ATC_Alloy.hs
gpl-2.0
4,444
0
13
765
945
480
465
66
0
module ItemsSpec (spec) where import Test.Hspec import Items import Data.Map (fromList) spec = do describe "changeItem" $ it "changes something about the item" $ changeItem "open" (const "closed") Item { itemName = "box", itemInfo = fromList [("open", "open")], itemActions=[]} `shouldBe` Item { itemName = "box", itemInfo = fromList [("open", "closed")], itemActions=[]}
emhoracek/explora
test-suite/ItemsSpec.hs
gpl-2.0
445
0
14
124
136
79
57
11
1
{-# LANGUAGE ScopedTypeVariables #-} -- Copyright (C) 2007-8 JP Bernardy -- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons -- Originally derived from: riot/UI.hs Copyright (c) Tuomo Valkonen 2004. -- | This module defines a user interface implemented using vty. module Yi.UI.Vty (start) where import Yi.Prelude hiding ((<|>)) import Prelude (map, take, zip, repeat, length, break, splitAt) import Control.Arrow import Control.Concurrent import Control.Exception import Control.Monad (forever) import Control.Monad.State (runState, get, put) import Control.Monad.Trans (liftIO, MonadIO) import Data.Char (ord,chr) import Data.Foldable import Data.IORef import Data.List (partition, sort, nub) import qualified Data.List.PointedList.Circular as PL import Data.Maybe import Data.Monoid import Data.Traversable import System.Exit import System.Posix.Signals (raiseSignal, sigTSTP) import System.Posix.Terminal import System.Posix.IO (stdInput) import Yi.Buffer import Yi.Editor import Yi.Event import Yi.Monad import Yi.Style import qualified Yi.UI.Common as Common import Yi.Config import Yi.Window import Yi.Style as Style import Graphics.Vty as Vty hiding (refresh, Default) import qualified Graphics.Vty as Vty import Yi.Keymap (makeAction, YiM) import Yi.UI.Utils import Yi.UI.TabBar data Rendered = Rendered { picture :: !Image -- ^ the picture currently displayed. , cursor :: !(Maybe (Int,Int)) -- ^ cursor point on the above } data UI = UI { vty :: Vty -- ^ Vty , scrsize :: IORef (Int,Int) -- ^ screen size , uiThread :: ThreadId , uiEnd :: MVar () , uiRefresh :: MVar () , uiEditor :: IORef Editor -- ^ Copy of the editor state, local to the UI, used to show stuff when the window is resized. , config :: Config , oAttrs :: TerminalAttributes } mkUI :: UI -> Common.UI mkUI ui = Common.dummyUI { Common.main = main ui, Common.end = end ui, Common.suspend = raiseSignal sigTSTP, Common.refresh = refresh ui, Common.layout = layout ui, Common.userForceRefresh = userForceRefresh ui } -- | Initialise the ui start :: UIBoot start cfg ch outCh editor = do liftIO $ do oattr <- getTerminalAttributes stdInput v <- mkVtyEscDelay $ configVtyEscDelay $ configUI $ cfg nattr <- getTerminalAttributes stdInput setTerminalAttributes stdInput (withoutMode nattr ExtendedFunctions) Immediately -- remove the above call to setTerminalAttributes when vty does it. Vty.DisplayRegion x0 y0 <- Vty.display_bounds $ Vty.terminal v sz <- newIORef (fromEnum y0, fromEnum x0) -- fork input-reading thread. important to block *thread* on getKey -- otherwise all threads will block waiting for input tid <- myThreadId endUI <- newEmptyMVar tuiRefresh <- newEmptyMVar editorRef <- newIORef editor let result = UI v sz tid endUI tuiRefresh editorRef cfg oattr -- | Action to read characters into a channel getcLoop = maybe (getKey >>= ch >> getcLoop) (const (return ())) =<< tryTakeMVar endUI -- | Read a key. UIs need to define a method for getting events. getKey = do event <- Vty.next_event v case event of (EvResize x y) -> do logPutStrLn $ "UI: EvResize: " ++ show (x,y) writeIORef sz (y,x) outCh [makeAction (layoutAction result :: YiM ())] -- since any action will force a refresh, return () is probably -- sufficient instead of "layoutAction result" getKey _ -> return (fromVtyEvent event) forkIO getcLoop return (mkUI result) main :: UI -> IO () main ui = do let -- | When the editor state isn't being modified, refresh, then wait for -- it to be modified again. refreshLoop :: IO () refreshLoop = forever $ do logPutStrLn "waiting for refresh" takeMVar (uiRefresh ui) handle (\(except :: IOException) -> do logPutStrLn "refresh crashed with IO Error" logError $ show $ except) (readRef (uiEditor ui) >>= refresh ui >> return ()) logPutStrLn "refreshLoop started" refreshLoop -- | Clean up and go home end :: UI -> Bool -> IO () end i reallyQuit = do Vty.shutdown (vty i) setTerminalAttributes stdInput (oAttrs i) Immediately tryPutMVar (uiEnd i) () when reallyQuit $ throwTo (uiThread i) ExitSuccess return () fromVtyEvent :: Vty.Event -> Yi.Event.Event fromVtyEvent (EvKey Vty.KBackTab mods) = Event Yi.Event.KTab (sort $ nub $ Yi.Event.MShift : map fromVtyMod mods) fromVtyEvent (EvKey k mods) = Event (fromVtyKey k) (sort $ map fromVtyMod mods) fromVtyEvent _ = error "fromVtyEvent: unsupported event encountered." fromVtyKey :: Vty.Key -> Yi.Event.Key fromVtyKey (Vty.KEsc ) = Yi.Event.KEsc fromVtyKey (Vty.KFun x ) = Yi.Event.KFun x fromVtyKey (Vty.KPrtScr ) = Yi.Event.KPrtScr fromVtyKey (Vty.KPause ) = Yi.Event.KPause fromVtyKey (Vty.KASCII '\t') = Yi.Event.KTab fromVtyKey (Vty.KASCII c ) = Yi.Event.KASCII c fromVtyKey (Vty.KBS ) = Yi.Event.KBS fromVtyKey (Vty.KIns ) = Yi.Event.KIns fromVtyKey (Vty.KHome ) = Yi.Event.KHome fromVtyKey (Vty.KPageUp ) = Yi.Event.KPageUp fromVtyKey (Vty.KDel ) = Yi.Event.KDel fromVtyKey (Vty.KEnd ) = Yi.Event.KEnd fromVtyKey (Vty.KPageDown) = Yi.Event.KPageDown fromVtyKey (Vty.KNP5 ) = Yi.Event.KNP5 fromVtyKey (Vty.KUp ) = Yi.Event.KUp fromVtyKey (Vty.KMenu ) = Yi.Event.KMenu fromVtyKey (Vty.KLeft ) = Yi.Event.KLeft fromVtyKey (Vty.KDown ) = Yi.Event.KDown fromVtyKey (Vty.KRight ) = Yi.Event.KRight fromVtyKey (Vty.KEnter ) = Yi.Event.KEnter fromVtyKey (Vty.KBackTab ) = error "This should be handled in fromVtyEvent" fromVtyMod :: Vty.Modifier -> Yi.Event.Modifier fromVtyMod Vty.MShift = Yi.Event.MShift fromVtyMod Vty.MCtrl = Yi.Event.MCtrl fromVtyMod Vty.MMeta = Yi.Event.MMeta fromVtyMod Vty.MAlt = Yi.Event.MMeta -- This re-computes the heights and widths of all the windows. layout :: UI -> Editor -> IO Editor layout ui e = do (rows,cols) <- readIORef (scrsize ui) let ws = windows e tabBarHeight = if hasTabBar e ui then 1 else 0 (cmd, _) = statusLineInfo e niceCmd = arrangeItems cmd cols (maxStatusHeight e) cmdHeight = length niceCmd ws' = applyHeights (computeHeights (rows - tabBarHeight - cmdHeight + 1) ws) ws ws'' = fmap (apply . discardOldRegion) ws' discardOldRegion w = w { winRegion = emptyRegion } -- Discard this field, otherwise we keep retaining reference to -- old Window objects (leak) apply win = win { winRegion = getRegionImpl win (configUI $ config ui) e cols (height win) } return $ windowsA ^= ws'' $ e -- Do Vty layout inside the Yi event loop layoutAction :: (MonadEditor m, MonadIO m) => UI -> m () layoutAction ui = do withEditor . put =<< io . layout ui =<< withEditor get withEditor $ mapM_ (flip withWindowE snapInsB) =<< getA windowsA -- | Redraw the entire terminal from the UI. refresh :: UI -> Editor -> IO () refresh ui e = do (_,xss) <- readRef (scrsize ui) let ws = windows e tabBarHeight = if hasTabBar e ui then 1 else 0 windowStartY = tabBarHeight (cmd, cmdSty) = statusLineInfo e niceCmd = arrangeItems cmd xss (maxStatusHeight e) formatCmdLine text = withAttributes statusBarStyle (take xss $ text ++ repeat ' ') renders = fmap (renderWindow (configUI $ config ui) e xss) (PL.withFocus ws) startXs = scanrT (+) windowStartY (fmap height ws) wImages = fmap picture renders statusBarStyle = ((appEndo <$> cmdSty) <*> baseAttributes) $ configStyle $ configUI $ config $ ui tabBarImages = renderTabBar e ui xss logPutStrLn "refreshing screen." logPutStrLn $ "startXs: " ++ show startXs Vty.update (vty $ ui) ( pic_for_image ( vert_cat tabBarImages <-> vert_cat (toList wImages) <-> vert_cat (fmap formatCmdLine niceCmd) ) ) { pic_cursor = case cursor (PL.focus renders) of Just (y,x) -> Cursor (toEnum x) (toEnum $ y + PL.focus startXs) -- Add the position of the window to the position of the cursor Nothing -> NoCursor -- This case can occur if the user resizes the window. -- Not really nice, but upon the next refresh the cursor will show. } return () -- | Construct images for the tabbar if at least one tab exists. renderTabBar :: Editor -> UI -> Int -> [Image] renderTabBar e ui xss = if hasTabBar e ui then [tabImages <|> extraImage] else [] where tabImages = foldr1 (<|>) $ fmap tabToVtyImage $ tabBarDescr e extraImage = withAttributes (tabBarAttributes uiStyle) (replicate (xss - fromEnum totalTabWidth) ' ') totalTabWidth = Vty.image_width tabImages uiStyle = configStyle $ configUI $ config $ ui tabTitle text = " " ++ text ++ " " baseAttr b sty = if b then attributesToAttr (appEndo (tabInFocusStyle uiStyle) sty) Vty.def_attr else attributesToAttr (appEndo (tabNotFocusedStyle uiStyle) sty) Vty.def_attr `Vty.with_style` Vty.underline tabAttr b = baseAttr b $ tabBarAttributes uiStyle tabToVtyImage _tab@(TabDescr text inFocus) = Vty.string (tabAttr inFocus) (tabTitle text) -- | Determine whether it is necessary to render the tab bar hasTabBar :: Editor -> UI -> Bool hasTabBar e ui = (not . configAutoHideTabBar . configUI . config $ ui) || (PL.length $ e ^. tabsA) > 1 -- As scanr, but generalized to a traversable (TODO) scanrT :: (Int -> Int -> Int) -> Int -> PL.PointedList Int -> PL.PointedList Int scanrT (+*+) k t = fst $ runState (mapM f t) k where f x = do s <- get let s' = s +*+ x put s' return s getRegionImpl :: Window -> UIConfig -> Editor -> Int -> Int -> Region getRegionImpl win cfg e w h = snd $ drawWindow cfg e (error "focus must not be used") win w h -- | Return a rendered wiew of the window. renderWindow :: UIConfig -> Editor -> Int -> (Window, Bool) -> Rendered renderWindow cfg e width (win,hasFocus) = let (rendered,_) = drawWindow cfg e hasFocus win width (height win) in rendered -- | Draw a window -- TODO: horizontal scrolling. drawWindow :: UIConfig -> Editor -> Bool -> Window -> Int -> Int -> (Rendered, Region) drawWindow cfg e focused win w h = (Rendered { picture = pict,cursor = cur}, mkRegion fromMarkPoint toMarkPoint') where b = findBufferWith (bufkey win) e sty = configStyle cfg notMini = not (isMini win) -- off reserves space for the mode line. The mini window does not have a mode line. off = if notMini then 1 else 0 h' = h - off ground = baseAttributes sty wsty = attributesToAttr ground Vty.def_attr eofsty = appEndo (eofStyle sty) ground (point, _) = runBuffer win b pointB (eofPoint, _) = runBuffer win b sizeB region = mkSizeRegion fromMarkPoint (Size (w*h')) -- Work around a problem with the mini window never displaying it's contents due to a -- fromMark that is always equal to the end of the buffer contents. (Just (MarkSet fromM _ _), _) = runBuffer win b (getMarks win) fromMarkPoint = if notMini then fst $ runBuffer win b (getMarkPointB fromM) else Point 0 (text, _) = runBuffer win b (indexedAnnotatedStreamB fromMarkPoint) -- read chars from the buffer, lazily (attributes, _) = runBuffer win b $ attributesPictureAndSelB sty (currentRegex e) region -- TODO: I suspect that this costs quite a lot of CPU in the "dry run" which determines the window size; -- In that case, since attributes are also useless there, it might help to replace the call by a dummy value. -- This is also approximately valid of the call to "indexedAnnotatedStreamB". colors = map (second (($ Vty.def_attr) . attributesToAttr)) attributes bufData = -- trace (unlines (map show text) ++ unlines (map show $ concat strokes)) $ paintChars Vty.def_attr colors text tabWidth = tabSize . fst $ runBuffer win b indentSettingsB prompt = if isMini win then miniIdentString b else "" (rendered,toMarkPoint',cur) = drawText h' w fromMarkPoint point tabWidth ([(c,(wsty, (-1))) | c <- prompt] ++ bufData ++ [(' ',(wsty, eofPoint))]) -- we always add one character which can be used to position the cursor at the end of file (modeLine0, _) = runBuffer win b $ getModeLine (commonNamePrefix e) modeLine = if notMini then Just modeLine0 else Nothing modeLines = map (withAttributes modeStyle . take w . (++ repeat ' ')) $ maybeToList $ modeLine modeStyle = (if focused then appEndo (modelineFocusStyle sty) else id) (modelineAttributes sty) filler = take w (configWindowFill cfg : repeat ' ') pict = vert_cat (take h' (rendered ++ repeat (withAttributes eofsty filler)) ++ modeLines) -- | Renders text in a rectangle. -- This also returns -- * the index of the last character fitting in the rectangle -- * the position of the Point in (x,y) coordinates, if in the window. drawText :: Int -- ^ The height of the part of the window we are in -> Int -- ^ The width of the part of the window we are in -> Point -- ^ The position of the first character to draw -> Point -- ^ The position of the cursor -> Int -- ^ The number of spaces to represent a tab character with. -> [(Char,(Vty.Attr,Point))] -- ^ The data to draw. -> ([Image], Point, Maybe (Int,Int)) drawText h w topPoint point tabWidth bufData | h == 0 || w == 0 = ([], topPoint, Nothing) | otherwise = (rendered_lines, bottomPoint, pntpos) where lns0 = take h $ concatMap (wrapLine w) $ map (concatMap expandGraphic) $ take h $ lines' $ bufData bottomPoint = case lns0 of [] -> topPoint _ -> snd $ snd $ last $ last $ lns0 pntpos = listToMaybe [(y,x) | (y,l) <- zip [0..] lns0, (x,(_char,(_attr,p))) <- zip [0..] l, p == point] -- fill lines with blanks, so the selection looks ok. rendered_lines = map fillColorLine lns0 colorChar (c, (a, _aPoint)) = Vty.char a c fillColorLine :: [(Char, (Vty.Attr, Point))] -> Image fillColorLine [] = char_fill Vty.def_attr ' ' w 1 fillColorLine l = horiz_cat (map colorChar l) <|> char_fill a ' ' (w - length l) 1 where (_,(a,_x)) = last l -- | Cut a string in lines separated by a '\n' char. Note -- that we add a blank character where the \n was, so the -- cursor can be positioned there. lines' :: [(Char,a)] -> [[(Char,a)]] lines' [] = [] lines' s = case s' of [] -> [l] ((_,x):s'') -> (l++[(' ',x)]) : lines' s'' where (l, s') = break ((== '\n') . fst) s wrapLine :: Int -> [x] -> [[x]] wrapLine _ [] = [] wrapLine n l = let (x,rest) = splitAt n l in x : wrapLine n rest expandGraphic ('\t', p) = replicate tabWidth (' ', p) expandGraphic (c,p) | ord c < 32 = [('^',p),(chr (ord c + 64),p)] | otherwise = [(c,p)] withAttributes :: Attributes -> String -> Image withAttributes sty str = Vty.string (attributesToAttr sty Vty.def_attr) str ------------------------------------------------------------------------ userForceRefresh :: UI -> IO () userForceRefresh = Vty.refresh . vty -- | Schedule a refresh of the UI. scheduleRefresh :: UI -> Editor -> IO () scheduleRefresh ui e = do writeRef (uiEditor ui) e logPutStrLn "scheduleRefresh" tryPutMVar (uiRefresh ui) () return () -- | Calculate window heights, given all the windows and current height. -- (No specific code for modelines) computeHeights :: Int -> PL.PointedList Window -> [Int] computeHeights totalHeight ws = ((y+r-1) : repeat y) where (mwls, wls) = partition isMini (toList ws) (y,r) = getY (totalHeight - length mwls) (length wls) getY :: Int -> Int -> (Int,Int) getY screenHeight 0 = (screenHeight, 0) getY screenHeight numberOfWindows = screenHeight `quotRem` numberOfWindows ------------------------------ -- Low-level stuff ------------------------------------------------------------------------ -- | Convert a Yi Attr into a Vty attribute change. colorToAttr :: (Vty.Color -> Vty.Attr -> Vty.Attr) -> Vty.Color -> Style.Color -> (Vty.Attr -> Vty.Attr) colorToAttr set unknown c = case c of RGB 0 0 0 -> set Vty.black RGB 128 128 128 -> set Vty.bright_black RGB 139 0 0 -> set Vty.red RGB 255 0 0 -> set Vty.bright_red RGB 0 100 0 -> set Vty.green RGB 0 128 0 -> set Vty.bright_green RGB 165 42 42 -> set Vty.yellow RGB 255 255 0 -> set Vty.bright_yellow RGB 0 0 139 -> set Vty.blue RGB 0 0 255 -> set Vty.bright_blue RGB 128 0 128 -> set Vty.magenta RGB 255 0 255 -> set Vty.bright_magenta RGB 0 139 139 -> set Vty.cyan RGB 0 255 255 -> set Vty.bright_cyan RGB 165 165 165 -> set Vty.white RGB 255 255 255 -> set Vty.bright_white Default -> id _ -> set unknown -- NB attributesToAttr :: Attributes -> (Vty.Attr -> Vty.Attr) attributesToAttr (Attributes fg bg reverse bd _itlc underline') = (if reverse then (flip Vty.with_style Vty.reverse_video) else id) . (if bd then (flip Vty.with_style Vty.bold) else id) . (if underline' then (flip Vty.with_style Vty.underline) else id) . colorToAttr (flip Vty.with_fore_color) Vty.black fg . colorToAttr (flip Vty.with_back_color) Vty.white bg --------------------------------- -- | Apply the attributes in @sty@ and @changes@ to @cs@. If the -- attributes are not used, @sty@ and @changes@ are not evaluated. paintChars :: a -> [(Point,a)] -> [(Point,Char)] -> [(Char, (a,Point))] paintChars sty changes cs = [(c,(s,p)) | ((p,c),s) <- zip cs attrs] where attrs = lazy (stys sty changes cs) lazy :: [a] -> [a] lazy l = head l : lazy (tail l) stys :: a -> [(Point,a)] -> [(Point,Char)] -> [a] stys sty [] cs = [ sty | _ <- cs ] stys sty ((endPos,sty'):xs) cs = [ sty | _ <- previous ] ++ stys sty' xs later where (previous, later) = break ((endPos <=) . fst) cs
codemac/yi-editor
src/Yi/UI/Vty.hs
gpl-2.0
19,502
0
25
5,605
5,696
3,000
2,696
334
18
-- vim: set expandtab: import XMonad import XMonad.Layout.Spacing import XMonad.Hooks.FadeInactive import XMonad.Util.CustomKeys import XMonad.Hooks.Place import XMonad.Hooks.DynamicLog import XMonad.Util.Paste inskey _ = [ ((noModMask, 0x1008ff13), spawn "amixer set Master 5%+") , ((noModMask, 0x1008ff11), spawn "amixer set Master 5%-") , ((noModMask, 0x1008ff02), spawn "xbacklight -inc 10 -time 0 -steps 1") , ((noModMask, 0x1008ff03), spawn "xbacklight -dec 10 -time 0 -steps 1") , ((shiftMask, 0xff61), spawn "sleep 0.2; scrot -s -e 'mv $f ~/Screenshots/'") , ((noModMask, 0xff61), spawn "sleep 0.2; scrot -e 'mv $f ~/Screenshots/'") , ((mod4Mask, 0x6c), spawn "xscreensaver-command -lock") , ((mod1Mask .|. shiftMask, 0x20), spawn "xterm ranger") ] myWorkspaces = [ "1:main" , "2:web" , "3:mail" , "4:music" , "5:office" , "6" , "7" , "8" , "9" , "0" , "-" , "=" ] myManageHook = composeAll [ className =? "XClock" --> placeHook (withGaps (10, 10, 10, 10) $ fixed (1, 0)) <+> doShift (myWorkspaces !! 0) <+> doFloat , className =? "Audacious" --> placeHook (withGaps (50, 10, 10, 10) $ fixed (1, 0)) <+> doShift (myWorkspaces !! 0) <+> doFloat , className =? "spotify" --> doShift (myWorkspaces !! 3) , className =? "Thunderbird" --> doShift (myWorkspaces !! 2) , className =? "Chromium" --> doFloat <+> doShift (myWorkspaces !! 1) , className =? "Hexchat" --> doShift (myWorkspaces !! 1) , className =? "Xmessage" --> placeHook (fixed (0.5, 0.5)) <+> doFloat , appName =? "irssi" --> doShift (myWorkspaces !! 1) , className =? "feh" --> placeHook (fixed (0.5, 0.5)) <+> doFloat ] myLayoutHook = spacing 1 $ let tall = Tall 1 (3/100) (1/2) in tall ||| Mirror tall ||| Full main = xmonad =<< xmobar defaultConfig { terminal = "uxterm" --, modMask = mod4Mask , borderWidth = 5 , normalBorderColor = "#000000" , focusedBorderColor = "#000000" , workspaces = myWorkspaces , manageHook = myManageHook <+> manageHook defaultConfig , layoutHook = myLayoutHook , logHook = fadeInactiveLogHook 0.8 , keys = customKeys (const []) inskey }
lngauthier/LEAA.6
xmonad.hs
gpl-2.0
2,604
0
14
881
688
390
298
49
1
{-# LANGUAGE MonadComprehensions #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} module Language.ArrayForth.Interpreter where import Data.Bits import Data.Functor ((<$>)) import Data.Maybe (fromJust, fromMaybe, mapMaybe) import Language.ArrayForth.NativeProgram import Language.ArrayForth.Opcode import Language.ArrayForth.State -- | A trace of a progam is the state after every word is executed. type Trace = [State] -- | Runs a single word's worth of instructions starting from the -- given state, returning the intermediate states for each executed -- opcode. wordAll :: Instrs -> State -> [State] wordAll (Instrs a b c d) state = let s₁ = [execute a state] s₂ = if endWord a then s₁ else run b s₁ s₃ = if endWord a || endWord b then s₂ else run c s₂ in if endWord a || endWord b || endWord c then s₃ else s₃ ++ run d s₃ wordAll (Jump3 a b c addr) state = let s₁ = [execute a state] s₂ = if endWord a then s₁ else run b s₁ in if endWord a || endWord b then s₂ else s₂ ++ [jump c addr (last s₂)] wordAll (Jump2 a b addr) state = let s' = execute a state in if endWord a then [s'] else [s', jump b addr s'] wordAll (Jump1 a addr) state = [jump a addr state] wordAll (Constant _) _ = error "Cannot execute a constant!" -- | Runs a single word's worth of instructions, returning only the -- final state. word :: Instrs -> State -> State word instr σ = last $ wordAll instr σ -- | Executes a single word in the given state, incrementing -- the program counter and returning all the intermediate states. stepAll :: State -> [State] stepAll state = fromMaybe [] $ go <$> next state where go instrs = wordAll instrs . incrP $ state {i = toBits <$> next state} -- | Executes a single word in the given state, returning the last -- resulting state.q step :: State -> State step = last . stepAll -- | Trace the given program, including all the intermediate states. traceAll :: State -> Trace traceAll program = let steps = stepAll program in steps ++ traceAll (last steps) -- | Returns a trace of the program's execution. The trace is a list -- of the state of the chip after each step. traceProgram :: State -> Trace traceProgram = iterate step -- | Trace a program until it either hits four nops or all 0s. stepProgram :: State -> Trace stepProgram = takeWhile (not . done) . traceProgram where done state = i state == Just 0x39ce7 || i state == Just 0 -- | Runs the program unil it hits a terminal state, returning only -- the resulting state. eval :: State -> State eval state = last $ state : stepProgram state -- | Executes the specified program on the given state until it hits a -- "terminal" word--a word made up of four nops or all 0s. runNativeProgram :: State -> NativeProgram -> State runNativeProgram start program = eval $ setProgram 0 program start -- | Estimates the execution time of a program trace. countTime :: Trace -> Double countTime = runningTime . mapMaybe (fmap fromBits . i) -- | Checks that the program trace terminated in at most n steps, -- returning Nothing otherwise. throttle :: Int -> Trace -> Either Trace Trace throttle n states | null res = Right [startState] | length res == n = Left res | otherwise = Right res where res = take n states -- | Does the given opcode cause the current word to stop executing? endWord :: Opcode -> Bool endWord = (`elem` [Ret, Exec, Jmp, Call, Unext, Next, If, MinusIf]) -- | Extends the given trace by a single execution step. The trace -- cannot be empty. run :: Opcode -> [State] -> [State] run op trace = trace ++ [execute op $ last trace] -- | Executes an opcode on the given state. If the state is blocked on -- some communication, nothing changes. execute :: Opcode -> State -> State execute op state@State {..} = fromMaybe state [ res | res <- result, not $ blocked res ] where result = case op of FetchP -> dpush (incrP state) <$> memory ! p FetchPlus -> dpush (state {a = a + 1}) <$> memory ! a FetchB -> dpush state <$> memory ! b Fetch -> dpush state <$> memory ! a _ -> Just normal normal = case op of Ret -> fst . rpop $ state {p = r} Exec -> state {r = p, p = r} Unext -> if r == 0 then fst $ rpop state else state {r = r - 1, p = p - 1} StoreP -> incrP $ set state' p top StorePlus -> set (state' { a = a + 1 }) a top StoreB -> set state' b top Store -> set state' a top MultiplyStep -> multiplyStep Times2 -> state {t = t `shift` 1} Div2 -> state {t = t `shift` (-1)} Not -> state {t = complement t} Plus -> state' {t = s + t} And -> state' {t = s .&. t} Or -> state' {t = s `xor` t} Drop -> fst $ dpop state Dup -> dpush state t Pop -> uncurry dpush $ rpop state Over -> dpush state s ReadA -> dpush state a Nop -> state Push -> rpush state' top SetB -> state' {b = top} SetA -> state' {a = top} _ -> error "Cannot jump without an address!" (state', top) = dpop state -- TODO: support different word sizes? multiplyStep | even a = let t0 = (t .&. 1) `shift` (size - 1) in state { a = t0 .|. a `shift` (-1) , t = t .&. bit (size - 1) .|. t `shift` (-1)} | otherwise = let sum0 = (s + t) `shift` (size - 1) sum17 = (s + t) .&. bit (size - 1) in state { a = sum0 .|. a `shift` (-1) , t = sum17 .|. (s + t) `shift` (-1) } size = bitSize t -- | Execute a jump instruction to the given address. jump :: Opcode -> F18Word -> State -> State jump op addr state@State{p, r, t} = case op of Jmp -> state {p = addr} Call -> (rpush state p) {p = addr} Next -> if r == 0 then fst $ rpop state else state {r = r - 1, p = addr} If -> if t /= 0 then state {p = addr} else state MinusIf -> if t `testBit` pred size then state else state {p = addr} _ -> error "Non-jump instruction given a jump address!" where size = bitSize (0 :: F18Word)
TikhonJelvis/array-forth
src/Language/ArrayForth/Interpreter.hs
gpl-3.0
6,810
34
17
2,290
2,022
1,078
944
108
29
module HEP.Automation.MadGraph.Dataset.Set20110713set2 where import HEP.Storage.WebDAV.Type import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Model.SChanC8Vschmaltz import HEP.Automation.MadGraph.Dataset.Processes import HEP.Automation.JobQueue.JobType processSetup :: ProcessSetup SChanC8Vschmaltz processSetup = PS { model = SChanC8Vschmaltz , process = preDefProcess TTBar0or1J , processBrief = "TTBar0or1J" , workname = "713_SChanC8Vschmaltz_TTBar0or1J_LHC" } paramSet :: [ModelParam SChanC8Vschmaltz] paramSet = [ SChanC8VschmaltzParam { mnp = m, mphi = 100.0, ga = g, nphi= 3.0 } | m <- [ 400, 420, 440 ] , g <- [ 0.1,0.2..1.2 ] ] {- | (m,g) <- (map (\x->(200,x)) [0.4,0.45,0.50,0.55,0.60] ) ++ (map (\x->(300,x)) [0.4,0.45..1.0] ) ++ (map (\x->(400,x)) [0.6,0.65..1.10] ) ++ (map (\x->(600,x)) [1.0,1.05..1.60] ) ++ (map (\x->(800,x)) [1.30,1.35..1.50] ) ] -} -- [ (200,0.5), (200,1.0) -- , (400,0.5), (400,1.0), (400,1.5), (400,2.0) -- , (600,0.5), (600,1.0), (600,1.5), (600,2.0), (600,2.5) -- , (800,0.5), (800,1.0), (800,1.5), (800,2.0), (800,2.5), (800,3.0), (800,3.5) -- , (1000,0.5), (1000,1.0), (1000,1.5), (1000,2.0), (1000,2.5), (1000,3.0), (1000,3.5), (1000,4.0) ] ] sets :: [Int] sets = [1] ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 2.7 , uc_etcutlep = 18.0 , uc_etacutjet = 2.7 , uc_etcutjet = 15.0 } eventsets :: [EventSet] eventsets = [ EventSet processSetup (RS { param = p , numevent = 100000 , machine = LHC7 ATLAS , rgrun = Fixed , rgscale = 200.0 , match = MLM , cut = DefCut , pythia = RunPYTHIA , usercut = UserCutDef ucut -- NoUserCutDef -- , pgs = RunPGS , jetalgo = AntiKTJet 0.4 , uploadhep = NoUploadHEP , setnum = num }) | p <- paramSet , num <- sets ] webdavdir :: WebDAVRemoteDir webdavdir = WebDAVRemoteDir "paper3/ttbar_LHC_schmaltz_pgsscan"
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110713set2.hs
gpl-3.0
2,508
0
10
830
394
250
144
47
1
import Data.HashMap as M import Data.IORef import Data.Maybe import Graphics.UI.Gtk import Graphics.UI.Gtk.Glade import Graphics.Rendering.Cairo import Graphics.UI.Gtk.Gdk.Events import System.Random type HM = M.Map (Integer,Integer) Integer type BranchObject = (Integer, BranchColor) type Board = [Bush BranchObject] data BranchColor = Red | Green | Blue | White deriving (Read, Show, Enum, Eq, Ord) data Bush a = Empty | Branch a [Bush a] deriving (Read, Show, Eq, Ord) data GameType = Single | Multiple deriving (Read, Show, Eq, Ord) data GameState = GameState { board :: Board, playerNames :: [String] , activePlayer :: Int, mp :: HM, gameType :: GameType , randomGen :: Int} data GUI = GUI { getPlayBoard :: IO DrawingArea, drawWindow :: IO DrawWindow, disableBoard :: IO (), enableBoard :: IO (), resetBoard :: IO (), showPlayDialog :: IO (), getRadioButtonValue :: Int -> IO Bool, showPlayerDialog :: GameType -> IO (), getPlayerNames :: GameType -> IO [String], showDifficultyDialog :: IO (), getDifficulty :: IO Int, hideDialog :: Int -> IO (), setStatus :: String -> IO () } data RGB = RGB { r :: Double, g :: Double, b :: Double } branchLength = -60 boardWidth = 1160 :: Double boardHeight = 600 :: Double main :: IO () main = do initGUI g <- newStdGen Just xml <- xmlNew "haskenbush.glade" window <- xmlGetWidget xml castToWindow "mWindow" window `onDestroy` mainQuit newgame <- xmlGetWidget xml castToMenuItem "newGame" quit <- xmlGetWidget xml castToMenuItem "quit" help <- xmlGetWidget xml castToMenuItem "about" gameBoard <- xmlGetWidget xml castToDrawingArea "gameBoard" statusBar <- xmlGetWidget xml castToStatusbar "gameStatus" buttons <- mapM (xmlGetWidget xml castToButton) ["bPlayOk", "bPlayerOk", "bDiffOk"] radioButtons <- mapM (xmlGetWidget xml castToRadioButton) ["rbSingle", "rbMultiple"] dialogs <- mapM (xmlGetWidget xml castToDialog) ["playDialog", "playerDialog", "difficultyDialog"] playerNameEntry <- mapM (xmlGetWidget xml castToEntry) ["player1Entry","player2Entry"] aboutDialog <- xmlGetWidget xml castToAboutDialog "aboutDialog" cBox <- xmlGetWidget xml castToComboBox "cbDifficulty" ctx <- statusbarGetContextId statusBar "state" gui <- guiActions buttons radioButtons dialogs cBox playerNameEntry gameBoard statusBar ctx widgetModifyBg gameBoard StateNormal (Color 65535 65535 65535) widgetShowAll window state <- newIORef GameState { board = [Empty], playerNames = ["Player 1", "Player 2"], activePlayer = 0, mp = M.empty :: HM, gameType = Multiple, randomGen = 0} let modifyState f = readIORef state >>= f >>= writeIORef state reset gui onActivateLeaf quit mainQuit onActivateLeaf newgame (reset gui) onActivateLeaf help (widgetShow aboutDialog) onButtonPress (buttons!!0) (\e -> do modifyState $ updateGameType gui return True ) onButtonPress (buttons!!1) (\e -> do modifyState $ updatePlayerNames gui return True ) onButtonPress (buttons!!2) (\e -> do modifyState $ updateDifficulty gui return True ) onButtonPress gameBoard (\e -> do let x = truncate (eventX e) let y = truncate (eventY e) modifyState $ removeBranch gui x y return True ) onExpose gameBoard (\x -> do modifyState $ drawCanvas gameBoard return True ) mainGUI guiActions buttons radioButtons dialogs cBox playerNameEntry gameBoard statusBar ctx = do return $ GUI {disableBoard = flip widgetSetSensitivity False gameBoard, enableBoard = flip widgetSetSensitivity True gameBoard, resetBoard = do drawWin <- widgetGetDrawWindow gameBoard drawWindowClear drawWin flip widgetSetSensitivity True gameBoard, getPlayBoard = do return gameBoard, drawWindow = do drawWin <- widgetGetDrawWindow gameBoard return drawWin, showPlayDialog = widgetShow (dialogs!!0), showDifficultyDialog = do comboBoxSetActive cBox 0 widgetShow (dialogs!!2), showPlayerDialog = \gameType -> do entrySetText (playerNameEntry!!1) "Player 1" if gameType == Single then do entrySetText (playerNameEntry!!1) "Jarvis" set (playerNameEntry!!1) [entryEditable := False] else do entrySetText (playerNameEntry!!1) "Player 2" set (playerNameEntry!!1) [entryEditable := False] widgetShow (dialogs!!1), hideDialog = \i -> do widgetHide (dialogs!!i), getDifficulty = comboBoxGetActive cBox, getPlayerNames = \gameType -> mapM (entryGetText) playerNameEntry, getRadioButtonValue = \i -> (toggleButtonGetActive (radioButtons!!i)), setStatus = \msg -> do statusbarPop statusBar ctx statusbarPush statusBar ctx msg return ()} reset :: GUI -> IO () reset gui = do resetBoard gui setStatus gui "" disableBoard gui showPlayDialog gui updateGameType :: GUI -> GameState -> IO GameState updateGameType gui st@(GameState board playerNames activePlayer mp gameType randomGen) = do isSingle <- getRadioButtonValue gui 0 hideDialog gui 0 let newGameType = if isSingle then Single else Multiple showPlayerDialog gui newGameType return (GameState board playerNames 0 mp newGameType randomGen) updatePlayerNames :: GUI -> GameState -> IO GameState updatePlayerNames gui st@(GameState board playerNames activePlayer mp gameType randomGen) = do newPlayerNames <- getPlayerNames gui Single hideDialog gui 1 showDifficultyDialog gui return (GameState board newPlayerNames activePlayer mp gameType randomGen) updateDifficulty :: GUI -> GameState -> IO GameState updateDifficulty gui st@(GameState board playerNames activePlayer mp gameType randomGen) = do g <- newStdGen selected <- getDifficulty gui hideDialog gui 2 let difficulty = 1 + toInteger selected let randTuple = randomNumber g (1 + difficulty) (2 + (4*difficulty + difficulty+1) `div` 3) let numberOfBushes = fst randTuple let g' = snd randTuple let newBoard = randomBoard numberOfBushes difficulty 0 g' drawingBoard <- drawWindow gui drawWindowClearAreaExpose drawingBoard 0 0 (truncate (boardWidth+50)) (truncate (boardHeight+50)) let s = " : Cut a " ++ show (getColor activePlayer)++ " / Green branch." :: String setStatus gui $ playerNames!!0 ++ s enableBoard gui return (GameState newBoard playerNames activePlayer mp gameType randomGen) removeBranch :: GUI -> Integer -> Integer -> GameState -> IO GameState removeBranch gui x y st@(GameState board playerName activePlayer mp gameType randomGen)= do let id = getId mp x y if id /= -1 then do let color = findInBushList board id if (isValidColor color activePlayer) then do let newBoard = cutBush board id let nextPlayer = mod ( activePlayer + 1 ) 2 drawingBoard <- drawWindow gui drawWindowClearAreaExpose drawingBoard 0 0 (truncate (boardWidth+50)) (truncate (boardHeight+50)) if wins newBoard $ getColor nextPlayer then do let s = " : Wins." :: String setStatus gui $ playerName!!(mod (nextPlayer+1) 2) ++ s disableBoard gui return (GameState newBoard playerName nextPlayer mp gameType randomGen) else do let s = " : Cut a " ++ show (getColor nextPlayer)++ " / Green branch." :: String setStatus gui $ playerName!!nextPlayer ++ s if gameType == Single then do let id = optimalplay (getColor nextPlayer) newBoard (randomGen+1) let newBoard' = cutBush newBoard id drawingBoard <- drawWindow gui drawWindowClearAreaExpose drawingBoard 0 0 (truncate (boardWidth+50)) (truncate (boardHeight+50)) if wins newBoard' $ getColor activePlayer then do let s' = " : Wins." :: String setStatus gui $ playerName!!nextPlayer ++ s' disableBoard gui else do let s' = " : Cut a " ++ show (getColor activePlayer)++ " / Green branch." :: String setStatus gui $ playerName!!activePlayer ++ s' return (GameState newBoard' playerName activePlayer mp gameType (randomGen+1)) else do return (GameState newBoard playerName nextPlayer mp gameType randomGen) else do return st else do return st wins :: Board -> BranchColor -> Bool wins board color | findColorInBushList board color = False | findColorInBushList board Green = False | otherwise = True getId :: HM -> Integer -> Integer -> Integer getId mp x y | member (x,y) mp = fromJust $ M.lookup (x,y) mp | member (x,y+1) mp = fromJust $ M.lookup (x,y+1) mp | member (x,y-1) mp = fromJust $ M.lookup (x,y-1) mp | member (x+1,y) mp = fromJust $ M.lookup (x+1,y) mp | member (x+1,y+1) mp = fromJust $ M.lookup (x+1,y+1) mp | member (x+1,y-1) mp = fromJust $ M.lookup (x+1,y-1) mp | member (x-1,y) mp = fromJust $ M.lookup (x-1,y) mp | member (x-1,y+1) mp = fromJust $ M.lookup (x-1,y+1) mp | member (x-1,y-1) mp = fromJust $ M.lookup (x-1,y-1) mp | otherwise = -1 getColor :: (Num a, Eq a) => a -> BranchColor getColor id | id == 0 = Red | id == 1 = Blue | otherwise = White isValidColor :: (Num a, Eq a) => BranchColor -> a -> Bool isValidColor color id | id == 0 && color == Red = True | id == 1 && color == Blue = True | color == Green = True | otherwise = False drawCanvas :: DrawingArea -> GameState -> IO GameState drawCanvas gameBoard st@(GameState board playerName activePlayer mp gameType randomGen) = do let numberOfBushes = fromIntegral $ (length board) let divLength = boardWidth / numberOfBushes let startPointX = 50 + divLength/2 let startPointY = boardHeight - 75 mp'<-drawBoard board mp gameBoard startPointX startPointY divLength drawBottomLine gameBoard return (GameState board playerName activePlayer mp' gameType randomGen) drawBoard :: Board -> HM -> DrawingArea -> Double -> Double -> Double -> IO HM drawBoard [] mp _ _ _ _= do return mp drawBoard (bush:board) mp canvas startPointX startPointY divLength= do mp' <- drawBush bush mp canvas startPointX startPointY 90 mp'' <- drawBoard board mp' canvas (startPointX + divLength) startPointY divLength return mp'' drawBush :: Bush BranchObject -> HM -> DrawingArea -> Double -> Double -> Double -> IO HM drawBush (Branch branch bushes) mp canvas startPointX startPointY angle = do let endPoints = getEndPoints startPointX startPointY angle branchLength let endPointX = fst endPoints let endPointY = snd endPoints mp' <- drawBranch branch mp canvas startPointX startPointY endPointX endPointY let numberOfSubBushes = fromIntegral $ length bushes if numberOfSubBushes > 0 then do let angleDiff = 180.0 / numberOfSubBushes let startAngle = angle - 90.0 + angleDiff / 2.0 mp'' <- drawBushList bushes mp' canvas endPointX endPointY startAngle angleDiff return mp'' else do mp'' <- drawBushList [] mp' canvas 0 0 0 0 return mp'' drawBush Empty mp _ _ _ _ = do return mp drawBushList :: Board -> HM -> DrawingArea -> Double -> Double -> Double -> Double -> IO HM drawBushList [] mp _ _ _ _ _ = do return mp drawBushList (bush:bushes) mp canvas startPointX startPointY angle angleDiff= do mp' <- drawBush bush mp canvas startPointX startPointY angle mp''<- drawBushList bushes mp' canvas startPointX startPointY (angle+angleDiff) angleDiff return mp'' drawBranch :: BranchObject -> HM -> DrawingArea -> Double -> Double -> Double -> Double -> IO HM drawBranch branch mp canvas startPointX startPointY endPointX endPointY= do let id = fst branch let color = getRGB $ snd branch drawWin <- widgetGetDrawWindow canvas renderWithDrawable drawWin $ do setSourceRGB (r color) (g color) (b color) setLineWidth 6 setLineCap LineCapRound setLineJoin LineJoinMiter moveTo startPointX startPointY lineTo endPointX endPointY stroke let mp' = updateMapMultiple 7 startPointX startPointY endPointX endPointY id mp return mp' drawBottomLine :: DrawingArea -> IO () drawBottomLine canvas = do drawWin <- widgetGetDrawWindow canvas renderWithDrawable drawWin $ do setSourceRGB 0.12 0.25 0.12 setLineWidth 6 setLineCap LineCapRound setLineJoin LineJoinMiter moveTo 50 $ boardHeight - 70 lineTo boardWidth $boardHeight - 70 stroke getEndPoints :: Double -> Double -> Double -> Double -> (Double, Double) getEndPoints x y angle length = (x2, y2) where radians = getRadians angle x2 = x + length * (cos radians) y2 = y + length * (sin radians) updateMapMultiple :: Double -> Double -> Double -> Double -> Double -> Integer -> HM -> HM updateMapMultiple t x1 y1 x2 y2 id mp | t < 0 = mp | otherwise = updateMapMultiple (t-1) x1 y1 x2 y2 id $ updateMap (x1+t) y1 (x2+t) y2 id mp updateMap :: Double -> Double -> Double -> Double -> Integer -> HM -> HM updateMap x1 y1 x2 y2 id mp = let yDiff = y2-y1 xDiff = x2-x1 points = if (abs yDiff) <= (abs xDiff) then let m = (y2 - y1) / (x2-x1) in if (x2-x1) >= 0 then [ ((x1 + x, y1 + x*m),id) | x <- [ (x2 -x1), (x2 - x1 - 1) .. 0] ] else [ ((x2 + x, y2 + x*m),id) | x <- [ (x1 -x2), (x1 - x2 - 1) .. 0] ] else let m = (x2 - x1) / (y2-y1) in if (y2-y1) >= 0 then [ ((x1 + m*y, y1 + y),id) | y <- [ (y2 - y1), (y2 - y1 - 1) .. 0] ] else [ ((x2 + m*y, y2 + y),id) | y <- [ (y1 - y2), (y1 - y2 - 1) .. 0] ] in insertIntoMap mp points insertIntoMap :: HM -> [((Double, Double) ,Integer)] -> HM insertIntoMap mp [] = mp insertIntoMap mp (idPoint:idPoints) = let point = fst idPoint rndX = round $ fst point rndY = round $ snd point rndP = (rndX, rndY) in M.insert rndP (snd idPoint) $ insertIntoMap mp idPoints getRGB :: BranchColor -> RGB getRGB branchColor | branchColor == Red = RGB 1 0 0 | branchColor == Green = RGB 0 1 0 | branchColor == Blue = RGB 0 0 1 | branchColor == White = RGB 1 1 1 getRadians :: Double -> Double getRadians degrees = radians where radians = (degrees * pi) / 180 randomColor :: RandomGen g => g -> (BranchColor, g) randomColor g = case randomR (0,2) g of (r, g') -> (toEnum r, g') randomNumber :: RandomGen g => g -> Integer -> Integer -> (Integer, g) randomNumber g st en = do randomR (st::Integer, en::Integer) g randomBushTuple :: (RandomGen g, Ord a, Num a) => a -> Integer -> Integer -> g -> (Bush BranchObject, g) randomBushTuple height level count g | height <= 0 = (Empty, g) | otherwise = let randColorTuple = randomColor g branchObject = ( count , fst randColorTuple ) g' = snd randColorTuple randTuple = randomNumber g' 0 (2*level-1) numberOfSubBushes = fst randTuple g'' = snd randTuple bush = Branch branchObject $ randomBushList numberOfSubBushes (height-1) level (count+1) g'' in (bush, g'') randomBushList :: (Num a, Ord a, RandomGen g) => Integer -> a -> Integer -> Integer -> g -> Board randomBushList 0 _ _ _ _ = [] randomBushList numberOfSubBushes height level count g= let bushTuple = randomBushTuple (height-1) level count g bush = fst bushTuple len = (findMaxId bush) + 1 g' = snd bushTuple in bush : randomBushList (numberOfSubBushes-1) height level (count+len) g' randomBoard :: (Num a, Ord a, RandomGen g) => a -> Integer -> Integer -> g -> Board randomBoard numberOfBushes level count g | numberOfBushes<=0 = [] | otherwise = let randTuple = randomNumber g 2 (2*level) height = fst randTuple g' = snd randTuple bushTuple = randomBushTuple height level count g' bush = fst bushTuple len = (findMaxId bush) + 1 g'' = snd bushTuple in bush : randomBoard (numberOfBushes-1) level (count+len) g'' flattenBushList :: Board -> [BranchObject] flattenBushList [] = [] flattenBushList (bush:bushes) = (flattenBush bush) ++ (flattenBushList bushes) flattenBush :: Bush BranchObject -> [BranchObject] flattenBush Empty = [] flattenBush (Branch a bushes)= a : (flattenBushList bushes) countNodes :: Board -> Int countNodes [] = 0 countNodes board = length $ flattenBushList board findMaxIdList :: Board -> Integer findMaxIdList [] = 0 findMaxIdList (bush:bushes) = max (findMaxId bush) (findMaxIdList bushes) findMaxId :: Bush BranchObject -> Integer findMaxId Empty = -1 findMaxId (Branch a bushes)= max (fst a) (findMaxIdList bushes) findInBushList :: Board -> Integer -> BranchColor findInBushList [] _ = White findInBushList (bush:bushes) id = if (findInBush bush id) /= White then (findInBush bush id) else findInBushList bushes id findInBush :: Bush BranchObject -> Integer -> BranchColor findInBush Empty _ = White findInBush (Branch branch bushes) id = if id == (fst branch) then (snd branch) else findInBushList bushes id findColorInBushList :: Board -> BranchColor -> Bool findColorInBushList [] _ = False findColorInBushList (bush:bushes) color = if (findColorInBush bush color) then True else findColorInBushList bushes color findColorInBush :: Bush BranchObject -> BranchColor -> Bool findColorInBush Empty _ = False findColorInBush (Branch branch bushes) color = if color == (snd branch) then True else findColorInBushList bushes color removeBushList :: Board -> Integer -> Board removeBushList [] id = [] removeBushList (bush:bushes) id = removeBush bush id : removeBushList bushes id removeBush :: Bush BranchObject -> Integer -> Bush BranchObject removeBush Empty _ = Empty removeBush (Branch branch bushes) id = if id==fst branch then Empty else Branch branch $removeBushList bushes id cutBush :: Board -> Integer -> Board cutBush [] _ = [] cutBush (bush:bushes) id = if(findInBush bush id) /= White then (removeBush bush id) : bushes else bush : cutBush bushes id findFirstIdBushList turn []=(-1) findFirstIdBushList turn (bush:bushrest)=if(findFirstIdBush turn bush/=(-1))then findFirstIdBush turn bush else findFirstIdBushList turn bushrest findFirstIdBush turn Empty=(-1) findFirstIdBush turn (Branch b bushes)=if(snd b==turn || snd b==Green)then fst b else findFirstIdBushList turn bushes findlistBush turn Empty=[] findlistBush turn (Branch b bushes)=if(snd b==turn || snd b==Green)then [fst b] ++ find_list turn bushes else find_list turn bushes find_list turn []= [] find_list turn (bush:bushrest)=findlistBush turn bush ++ find_list turn bushrest play_random_id turn [] _= (-1) play_random_id turn bush randomGen = let list = find_list turn bush in list !! fromIntegral (randomGen `mod` length list) extractIdBushes _ []=[] extractIdBushes turn (bush:bushrest)=(extract_id_bush turn bush++extractIdBushes turn bushrest) extract_id_bush turn Empty=[] extract_id_bush turn (Branch b bushes)=if(snd b==turn || snd b==Green)then ([fst b]++extractIdBushes turn bushes) else (extractIdBushes turn bushes) extractId _ []=[] extractId turn (bush:bushrest)=extract_id_bush turn bush++extractId turn bushrest isEmpty_bush Empty=True isEmpty_bush (Branch b bushes)=False isEmpty []=True isEmpty (bush:bushrest)=if(isEmpty_bush bush)then isEmpty bushrest else False findWinningPosition Blue [] _=(-1) findWinningPosition Red [] _=(-1) findWinningPosition Blue (x:xs) board=if(isWinningPosition Red (cutBush board x)==(-1))then x else findWinningPosition Blue xs board findWinningPosition Red (x:xs) board=if(isWinningPosition Blue (cutBush board x)==(-1))then x else findWinningPosition Red xs board isWinningPosition Blue board=if(isEmpty board)then (-1) else findWinningPosition Blue (extractId Blue board) board isWinningPosition Red board=if(isEmpty board)then (-1) else findWinningPosition Red (extractId Red board) board optimalpla turn board randomGen =if(isWinningPosition turn board /=(-1))then isWinningPosition turn board else play_random_id turn board randomGen optimalplay turn board randomGen =if(countNodes board<=20)then optimalpla turn board randomGen else play_random_id turn board randomGen
arihantsethia/Haskenbush
haskenbush.hs
gpl-3.0
22,747
10
25
6,940
7,693
3,840
3,853
417
6
{-# LANGUAGE RecordWildCards #-} module Main (main) where import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Data.Maybe import Foreign.C.Types import GHC.Word import Reactive import qualified Reactive.Banana as RB import Reactive.Banana.Frameworks as RB import SDL import Stage import System.Random import Test.Hspec data TestEvent a = TestValueEvent a | TestInputEvent EventPayload | TestTimeInputEvent Word32 | TestWindowResizeEvent (SDL.V2 CInt) testEventToMaybeValueEvent :: TestEvent a -> Maybe a testEventToMaybeValueEvent (TestValueEvent x) = Just x testEventToMaybeValueEvent _ = Nothing testEventToMaybeInputEvent :: TestEvent a -> Maybe EventPayload testEventToMaybeInputEvent (TestInputEvent x) = Just x testEventToMaybeInputEvent _ = Nothing testEventToMaybeTimeInputEvent :: TestEvent a -> Maybe Word32 testEventToMaybeTimeInputEvent (TestTimeInputEvent x) = Just x testEventToMaybeTimeInputEvent _ = Nothing testEventToMaybeWindowResizeEvent :: TestEvent a -> Maybe (V2 CInt) testEventToMaybeWindowResizeEvent (TestWindowResizeEvent x) = Just x testEventToMaybeWindowResizeEvent _ = Nothing interpret :: StdGen -> Stage -> (RB.Event a -> Game (RB.Event b)) -> [TestEvent a] -> IO [b] interpret randomGen inputStage networkSetupFunction inputEvents = catMaybes <$> RB.interpretFrameworks transformationFunction (map Just inputEvents) where transformationFunction testEvent = let inputValueEvents = RB.filterJust $ testEventToMaybeValueEvent <$> testEvent inputSdlEvents = RB.filterJust $ testEventToMaybeInputEvent <$> testEvent inputTimeEvents = RB.filterJust $ testEventToMaybeTimeInputEvent <$> testEvent inputWindowSizeEvents = RB.filterJust $ testEventToMaybeWindowResizeEvent <$> testEvent engineInputs = EngineInputs {..} gameNetwork = flip runReaderT engineInputs . runGameNetwork . flip evalStateT randomGen . runRandomNetwork $ networkSetupFunction inputValueEvents in gameNetwork main :: IO () main = do hspec $ do describe "cooldownTimer" $ do it "does not trigger before cooldown has passed" $ do randomSeed <- newStdGen let cooldownTime = pure 1000 * 1000 -- 1 second cooldownActiveB = pure True network triggerE = fst <$> cooldownTimer cooldownActiveB cooldownTime triggerE events = [ TestTimeInputEvent 100 , TestValueEvent 1 , TestTimeInputEvent 100 , TestValueEvent 2 , TestTimeInputEvent 800 , TestValueEvent 3 ] interpret randomSeed emptyStage network events >>= flip shouldBe ([3] :: [Int]) it "does not trigger when it is not active" $ do randomSeed <- newStdGen let cooldownTimeB = pure 1000 * 1000 cooldownActiveB = pure False network triggerE = fst <$> cooldownTimer cooldownActiveB cooldownTimeB triggerE events = [ TestTimeInputEvent 1000 , TestValueEvent 1 , TestTimeInputEvent 1000 , TestValueEvent 2 ] interpret randomSeed emptyStage network events >>= flip shouldBe ([] :: [Int])
seppeljordan/geimskell
tests/UnitTests.hs
gpl-3.0
3,685
0
20
1,188
771
393
378
85
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE MonadComprehensions #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeOperators #-} -- | This module defines a type representing the location of a core in -- the 8 × 18 grid. -- -- All of the actually interesting code is in the typeclass instances. module Language.ArrayForth.Core where import Data.Modular import Text.Printf (printf) -- | The address of a core. There are 144 cores in an 8 × 18 -- array. The address has the row number followed by the column -- number. -- -- As a string, the core addresses are displayed as a single -- three-digit number, just like in the GreenArray documentation. So -- @Core 7 17@ becomes @\"717\"@. -- -- Core addresses behave like numbers: you can use numeric literals -- and add them together. For example, @[0..] :: [Core]@ gets you the -- list of all the core addresses. @(move core = core + Core 1 1)@ is -- a function that moves you up and over by one core. data Core = Core !(ℤ/8) !(ℤ/18) -- | Returns all the neighbors of a core. Most cores have four -- neighbors; the ones along the edges only have three and the ones at -- the corners two. -- -- They always come in the order right, down, left up, with Nothing in -- place of non-existant cores. neighbors :: Core -> [Maybe Core] neighbors core@(Core row col) = [ [ core + Core 1 0 | row /= maxBound ] , [ core + Core 0 1 | col /= maxBound ] , [ core + Core (-1) 0 | row /= minBound ] , [ core + Core 0 (- 1) | col /= minBound ] ] -- Follows the same format as the documentation does: (7, 17) becomes 717. instance Show Core where show (Core row col) = printf "%d%.2d" (unMod row) (unMod col) deriving instance Eq Core deriving instance Ord Core instance Enum Core where fromEnum (Core r c) = fromInteger $ unMod r * 18 + unMod c toEnum n | n >= 0 && n < 144 = Core (toMod' $ n `div` 18) (toMod' $ n `mod` 18) | otherwise = error "Core index out of bounds." -- Taken directly from the documentation for Enum: enumFrom x = enumFromTo x maxBound enumFromThen x y = enumFromThenTo x y bound where bound | fromEnum y >= fromEnum x = maxBound | otherwise = minBound instance Bounded Core where minBound = Core 0 0 maxBound = Core 7 17 -- Core addresses from a group, eh? instance Num Core where fromInteger = toEnum . fromIntegral Core r₁ c₁ + Core r₂ c₂ = Core (r₁ + r₂) (c₁ + c₂) Core r₁ c₁ * Core r₂ c₂ = Core (r₁ * r₂) (c₁ * c₂) signum (Core r c) = Core (signum r) (signum c) abs (Core r c) = Core (abs r) (abs c) negate (Core r c) = Core (negate r) (negate c)
TikhonJelvis/array-forth
src/Language/ArrayForth/Core.hs
gpl-3.0
2,830
37
13
751
680
364
316
40
1
Config { font = "xft:Inconsolata Nerd Font Mono Medium:size=9:antialias=true" , additionalFonts = ["xft:FontAwesome:size=9:antialias=true" ] -- , bgColor = "#000000" -- , fgColor = "#ffffff" -- , borderColor = "#000000" -- Colors alt -- solarized dark: , bgColor = "#002b36" , fgColor = "#93a1a1" , borderColor = "#002b36" -- Colors alt -- solarized light: -- , bgColor = "#fdf6e3" -- , fgColor = "#586e75" -- , borderColor = "#fdf6e3" , iconRoot = "." , iconOffset = -1 , position = Top , border = BottomB , textOffset = -1 , allDesktops = True , sepChar = "%" , alignSep = "}{" , template = "<fn=1></fn> %StdinReader% }{ <fn=1></fn> %multicpu% | <fn=1></fn> %memory% | <fn=1></fn> %coretemp% | <fn=1></fn> %swap% | %battery% | %date% " , lowerOnStart = False , hideOnStart = False , overrideRedirect = True , pickBroadest = True , persistent = True , commands = [ Run MultiCpu [ "-t" , "Cpu:<total0> <total1> <total2> <total3> <total4> <total5> <total6> <total7>" , "-L" , "20" , "-H" , "50" , "-h" , "#dc322f" , "-n" , "#cb4b16" , "-l" , "#859900" , "-w" , "3" ] 10 , Run Memory [ "-t" , "Mem: <usedratio>%" , "-H" , "8192" , "-L" , "4096" , "-h" , "#dc322f" , "-n" , "#cb4b16" , "-l" , "#859900" ] 10 , Run Swap [ "-t" , "Swap: <usedratio>%" , "-H" , "1024" , "-L" , "512" , "-h" , "#dc322f" , "-n" , "#cb4b16" , "-l" , "#859900" ] 10 , Run Date "<fn=1></fn> %a, %B %_d | <fn=1></fn> %H:%M" "date" 10 , Run CoreTemp [ "--template" , "Temp: <core0>°C <core1>°C <core2>°C <core3>°C" , "--Low" , "60" , "--High" , "80" , "--high" , "#dc322f" , "--normal" , "#cb4b16" , "--low" , "#859900" ] 50 , Run Battery [ "--template" , "<fn=1></fn> Batt: <acstatus>" , "--Low" , "10" , "--High" , "80" , "--high" , "#859900" , "--normal" , "#cb4b16" , "--low" , "#dc322f" , "--" , "-o" , "<left>% (<timeleft>)" , "-O" , "<fc=#cb4b16>Charging</fc>" , "-i" , "<fc=#859900>Charged</fc>" ] 50 , Run StdinReader ] }
hnrck/dotfiles
wm/xmonad/xmobar.hs
gpl-3.0
3,369
0
9
1,781
416
266
150
-1
-1
module Geometry.Cube ( volume , area ) where import qualified Geometry.Cuboid as Cuboid volume :: Float -> Float volume side = Cuboid.volume side side side area :: Float -> Float area side = Cuboid.area side side side
medik/lang-hack
Haskell/LearnYouAHaskell/c06/Geometry/Cube.hs
gpl-3.0
227
0
6
46
74
41
33
8
1
module Examples.Power.QDSL where import Prelude import QFeldspar.QDSL hiding (div) power :: Int -> Qt (Float -> Float) power n = if n < 0 then [|| \x -> if x == 0 then 0 else 1 / ($$(power (-n)) x) ||] else if n == 0 then [|| \ _x -> 1 ||] else if even n then [|| \x -> $$sqr ($$(power (n `div` 2)) x) ||] else [|| \x -> x * ($$(power (n-1)) x) ||] sqr :: Qt (Float -> Float) sqr = [|| \ y -> y * y ||] power' :: Int -> Qt (Float -> Maybe Float) power' n = if n < 0 then [|| \x -> if x == 0 then Nothing else do y <- $$(power' (-n)) x; return (1 / y) ||] else if n == 0 then [|| \ _x -> return 1 ||] else if even n then [|| \x -> do y <- $$(power' (n `div` 2)) x; return ($$sqr y) ||] else [|| \x -> do y <- $$(power' (n-1)) x; return (x * y) ||] power'' :: Int -> Qt (Float -> Float) power'' n = [|| \ x -> maybe 0 (\y -> y) ($$(power' n) x)||]
shayan-najd/QFeldspar
Examples/Power/QDSL.hs
gpl-3.0
924
23
17
281
551
310
241
-1
-1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.MachineLearning -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Definition of the public APIs exposed by Amazon Machine Learning -- -- /See:/ <http://docs.aws.amazon.com/machine-learning/latest/APIReference/Welcome.html AWS API Reference> module Network.AWS.MachineLearning ( -- * Service Configuration machineLearning -- * Errors -- $errors -- ** InternalServerException , _InternalServerException -- ** InvalidInputException , _InvalidInputException -- ** IdempotentParameterMismatchException , _IdempotentParameterMismatchException -- ** PredictorNotMountedException , _PredictorNotMountedException -- ** ResourceNotFoundException , _ResourceNotFoundException -- ** LimitExceededException , _LimitExceededException -- * Waiters -- $waiters -- ** MLModelAvailable , mLModelAvailable -- ** BatchPredictionAvailable , batchPredictionAvailable -- ** DataSourceAvailable , dataSourceAvailable -- ** EvaluationAvailable , evaluationAvailable -- * Operations -- $operations -- ** UpdateDataSource , module Network.AWS.MachineLearning.UpdateDataSource -- ** DeleteDataSource , module Network.AWS.MachineLearning.DeleteDataSource -- ** CreateDataSourceFromRedshift , module Network.AWS.MachineLearning.CreateDataSourceFromRedshift -- ** CreateDataSourceFromS , module Network.AWS.MachineLearning.CreateDataSourceFromS -- ** CreateMLModel , module Network.AWS.MachineLearning.CreateMLModel -- ** DeleteBatchPrediction , module Network.AWS.MachineLearning.DeleteBatchPrediction -- ** UpdateBatchPrediction , module Network.AWS.MachineLearning.UpdateBatchPrediction -- ** GetMLModel , module Network.AWS.MachineLearning.GetMLModel -- ** GetDataSource , module Network.AWS.MachineLearning.GetDataSource -- ** UpdateEvaluation , module Network.AWS.MachineLearning.UpdateEvaluation -- ** DeleteEvaluation , module Network.AWS.MachineLearning.DeleteEvaluation -- ** DeleteMLModel , module Network.AWS.MachineLearning.DeleteMLModel -- ** UpdateMLModel , module Network.AWS.MachineLearning.UpdateMLModel -- ** GetBatchPrediction , module Network.AWS.MachineLearning.GetBatchPrediction -- ** DescribeBatchPredictions (Paginated) , module Network.AWS.MachineLearning.DescribeBatchPredictions -- ** CreateDataSourceFromRDS , module Network.AWS.MachineLearning.CreateDataSourceFromRDS -- ** CreateEvaluation , module Network.AWS.MachineLearning.CreateEvaluation -- ** Predict , module Network.AWS.MachineLearning.Predict -- ** DeleteRealtimeEndpoint , module Network.AWS.MachineLearning.DeleteRealtimeEndpoint -- ** CreateBatchPrediction , module Network.AWS.MachineLearning.CreateBatchPrediction -- ** GetEvaluation , module Network.AWS.MachineLearning.GetEvaluation -- ** DescribeEvaluations (Paginated) , module Network.AWS.MachineLearning.DescribeEvaluations -- ** CreateRealtimeEndpoint , module Network.AWS.MachineLearning.CreateRealtimeEndpoint -- ** DescribeMLModels (Paginated) , module Network.AWS.MachineLearning.DescribeMLModels -- ** DescribeDataSources (Paginated) , module Network.AWS.MachineLearning.DescribeDataSources -- * Types -- ** Algorithm , Algorithm (..) -- ** BatchPredictionFilterVariable , BatchPredictionFilterVariable (..) -- ** DataSourceFilterVariable , DataSourceFilterVariable (..) -- ** DetailsAttributes , DetailsAttributes (..) -- ** EntityStatus , EntityStatus (..) -- ** EvaluationFilterVariable , EvaluationFilterVariable (..) -- ** MLModelFilterVariable , MLModelFilterVariable (..) -- ** MLModelType , MLModelType (..) -- ** RealtimeEndpointStatus , RealtimeEndpointStatus (..) -- ** SortOrder , SortOrder (..) -- ** BatchPrediction , BatchPrediction , batchPrediction , bpStatus , bpLastUpdatedAt , bpCreatedAt , bpInputDataLocationS3 , bpMLModelId , bpBatchPredictionDataSourceId , bpBatchPredictionId , bpCreatedByIAMUser , bpName , bpMessage , bpOutputURI -- ** DataSource , DataSource , dataSource , dsStatus , dsNumberOfFiles , dsLastUpdatedAt , dsCreatedAt , dsDataSourceId , dsRDSMetadata , dsDataSizeInBytes , dsCreatedByIAMUser , dsName , dsDataLocationS3 , dsComputeStatistics , dsMessage , dsRedshiftMetadata , dsDataRearrangement , dsRoleARN -- ** Evaluation , Evaluation , evaluation , eStatus , ePerformanceMetrics , eLastUpdatedAt , eCreatedAt , eInputDataLocationS3 , eMLModelId , eCreatedByIAMUser , eName , eEvaluationId , eMessage , eEvaluationDataSourceId -- ** MLModel , MLModel , mLModel , mlmStatus , mlmLastUpdatedAt , mlmTrainingParameters , mlmScoreThresholdLastUpdatedAt , mlmCreatedAt , mlmInputDataLocationS3 , mlmMLModelId , mlmSizeInBytes , mlmScoreThreshold , mlmAlgorithm , mlmCreatedByIAMUser , mlmName , mlmEndpointInfo , mlmTrainingDataSourceId , mlmMessage , mlmMLModelType -- ** PerformanceMetrics , PerformanceMetrics , performanceMetrics , pmProperties -- ** Prediction , Prediction , prediction , pPredictedValue , pPredictedLabel , pPredictedScores , pDetails -- ** RDSDataSpec , RDSDataSpec , rdsDataSpec , rdsdsDataSchemaURI , rdsdsDataSchema , rdsdsDataRearrangement , rdsdsDatabaseInformation , rdsdsSelectSqlQuery , rdsdsDatabaseCredentials , rdsdsS3StagingLocation , rdsdsResourceRole , rdsdsServiceRole , rdsdsSubnetId , rdsdsSecurityGroupIds -- ** RDSDatabase , RDSDatabase , rdsDatabase , rdsdInstanceIdentifier , rdsdDatabaseName -- ** RDSDatabaseCredentials , RDSDatabaseCredentials , rdsDatabaseCredentials , rdsdcUsername , rdsdcPassword -- ** RDSMetadata , RDSMetadata , rdsMetadata , rmSelectSqlQuery , rmDataPipelineId , rmDatabase , rmDatabaseUserName , rmResourceRole , rmServiceRole -- ** RealtimeEndpointInfo , RealtimeEndpointInfo , realtimeEndpointInfo , reiCreatedAt , reiEndpointURL , reiEndpointStatus , reiPeakRequestsPerSecond -- ** RedshiftDataSpec , RedshiftDataSpec , redshiftDataSpec , rDataSchemaURI , rDataSchema , rDataRearrangement , rDatabaseInformation , rSelectSqlQuery , rDatabaseCredentials , rS3StagingLocation -- ** RedshiftDatabase , RedshiftDatabase , redshiftDatabase , rdDatabaseName , rdClusterIdentifier -- ** RedshiftDatabaseCredentials , RedshiftDatabaseCredentials , redshiftDatabaseCredentials , rdcUsername , rdcPassword -- ** RedshiftMetadata , RedshiftMetadata , redshiftMetadata , redSelectSqlQuery , redRedshiftDatabase , redDatabaseUserName -- ** S3DataSpec , S3DataSpec , s3DataSpec , sdsDataSchema , sdsDataSchemaLocationS3 , sdsDataRearrangement , sdsDataLocationS3 ) where import Network.AWS.MachineLearning.CreateBatchPrediction import Network.AWS.MachineLearning.CreateDataSourceFromRDS import Network.AWS.MachineLearning.CreateDataSourceFromRedshift import Network.AWS.MachineLearning.CreateDataSourceFromS import Network.AWS.MachineLearning.CreateEvaluation import Network.AWS.MachineLearning.CreateMLModel import Network.AWS.MachineLearning.CreateRealtimeEndpoint import Network.AWS.MachineLearning.DeleteBatchPrediction import Network.AWS.MachineLearning.DeleteDataSource import Network.AWS.MachineLearning.DeleteEvaluation import Network.AWS.MachineLearning.DeleteMLModel import Network.AWS.MachineLearning.DeleteRealtimeEndpoint import Network.AWS.MachineLearning.DescribeBatchPredictions import Network.AWS.MachineLearning.DescribeDataSources import Network.AWS.MachineLearning.DescribeEvaluations import Network.AWS.MachineLearning.DescribeMLModels import Network.AWS.MachineLearning.GetBatchPrediction import Network.AWS.MachineLearning.GetDataSource import Network.AWS.MachineLearning.GetEvaluation import Network.AWS.MachineLearning.GetMLModel import Network.AWS.MachineLearning.Predict import Network.AWS.MachineLearning.Types import Network.AWS.MachineLearning.UpdateBatchPrediction import Network.AWS.MachineLearning.UpdateDataSource import Network.AWS.MachineLearning.UpdateEvaluation import Network.AWS.MachineLearning.UpdateMLModel import Network.AWS.MachineLearning.Waiters {- $errors Error matchers are designed for use with the functions provided by <http://hackage.haskell.org/package/lens/docs/Control-Exception-Lens.html Control.Exception.Lens>. This allows catching (and rethrowing) service specific errors returned by 'MachineLearning'. -} {- $operations Some AWS operations return results that are incomplete and require subsequent requests in order to obtain the entire result set. The process of sending subsequent requests to continue where a previous request left off is called pagination. For example, the 'ListObjects' operation of Amazon S3 returns up to 1000 objects at a time, and you must send subsequent requests with the appropriate Marker in order to retrieve the next page of results. Operations that have an 'AWSPager' instance can transparently perform subsequent requests, correctly setting Markers and other request facets to iterate through the entire result set of a truncated API operation. Operations which support this have an additional note in the documentation. Many operations have the ability to filter results on the server side. See the individual operation parameters for details. -} {- $waiters Waiters poll by repeatedly sending a request until some remote success condition configured by the 'Wait' specification is fulfilled. The 'Wait' specification determines how many attempts should be made, in addition to delay and retry strategies. -}
fmapfmapfmap/amazonka
amazonka-ml/gen/Network/AWS/MachineLearning.hs
mpl-2.0
10,861
0
5
2,297
986
715
271
210
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.SiteVerification.WebResource.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Get the list of your verified websites and domains. -- -- /See:/ <https://developers.google.com/site-verification/ Google Site Verification API Reference> for @siteVerification.webResource.list@. module Network.Google.Resource.SiteVerification.WebResource.List ( -- * REST Resource WebResourceListResource -- * Creating a Request , webResourceList , WebResourceList ) where import Network.Google.Prelude import Network.Google.SiteVerification.Types -- | A resource alias for @siteVerification.webResource.list@ method which the -- 'WebResourceList' request conforms to. type WebResourceListResource = "siteVerification" :> "v1" :> "webResource" :> QueryParam "alt" AltJSON :> Get '[JSON] SiteVerificationWebResourceListResponse -- | Get the list of your verified websites and domains. -- -- /See:/ 'webResourceList' smart constructor. data WebResourceList = WebResourceList' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WebResourceList' with the minimum fields required to make a request. -- webResourceList :: WebResourceList webResourceList = WebResourceList' instance GoogleRequest WebResourceList where type Rs WebResourceList = SiteVerificationWebResourceListResponse type Scopes WebResourceList = '["https://www.googleapis.com/auth/siteverification"] requestClient WebResourceList'{} = go (Just AltJSON) siteVerificationService where go = buildClient (Proxy :: Proxy WebResourceListResource) mempty
brendanhay/gogol
gogol-siteverification/gen/Network/Google/Resource/SiteVerification/WebResource/List.hs
mpl-2.0
2,436
0
11
520
218
136
82
42
1
import System.Environment (getArgs) import Database.LMDB import Database.LMDB.Raw import Control.Applicative import qualified Data.ByteString.Char8 as B main = do args <- getArgs case args of [x] -> main' x _ -> putStrLn "Usage: mdblist <path>" where main' x = do tables <- listTables x mapM_ B.putStrLn tables
jimcrayne/lmdb-bindings
tools/mdblist.hs
agpl-3.0
381
0
10
115
106
55
51
13
2
module PGFTest where import PGF import Data.Maybe main :: IO () main = do pgf <- readPGF "lib/src/maltese/PGF/Lang.pgf" let mlt = head $ languages pgf let love = mkCId "love_V2" -- Parsing let (Just typ) = functionType pgf love let trees = parse pgf mlt typ "ħabb" print trees -- Linearize with table let table = head $ tabularLinearizes pgf mlt (mkApp love []) putStrLn $ unlines $ map (\(f,s) -> f ++ " = " ++ s) table -- Morpho analysis let morpho = buildMorpho pgf mlt print $ lookupMorpho morpho "ħabb"
johnjcamilleri/Maltese-GF-Resource-Grammar
scripts/PGFTest.hs
lgpl-3.0
554
0
14
137
207
99
108
15
1
{-# language ViewPatterns, ScopedTypeVariables, PackageImports, EmptyDataDecls, TypeSynonymInstances, FlexibleInstances, StandaloneDeriving, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Utils ( (<>), (<$>), (<*>), (<|>), (*>), (<*), pure, (>>>), (>=>), forM, forM_, when, (^.), (^=), (^:), (.>), module Utils, module Utils.Scripting, -- * accessor re-exports Accessor, (%=), (%:), -- * other re-exports on, Pair(..), POSIXTime, ) where import "MonadCatchIO-transformers" Control.Monad.CatchIO import "mtl" Control.Monad.State hiding (forM_) import "transformers" Control.Monad.Trans.Error (ErrorT(..)) import Control.Applicative ((<|>), Alternative(..)) import Control.Arrow ((>>>)) import Control.Concurrent import Control.DeepSeq import Control.Exception import Data.Accessor (Accessor, accessor, (^.), (^=), (^:), (.>)) import Data.Accessor.Monad.MTL.State ((%=), (%:)) import qualified Data.ByteString as SBS import Data.Data import Data.Foldable (Foldable, mapM_, forM_, any, sum) import qualified Data.Foldable as Foldable import Data.Function import Data.IORef import Data.List import Data.Map (Map, fromList, member, (!), findWithDefault, toList) import Data.Monoid import qualified Data.Set as Set import Data.Strict (Pair(..)) import qualified Data.Strict as Strict import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Text.Encoding.Error as Text import Data.Time.Clock.POSIX import Data.Traversable (Traversable, mapM) import Safe import System.FilePath import System.IO.Unsafe import Text.Logging import Text.Printf import Utils.Scripting -- * debugging stuff data Todo todo :: Todo todo = error "just working on this (Utils.todo)" todoError :: String -> a todoError = error -- | can be used to try out different values for constants without recompiling tweakValue :: Read a => FilePath -> a tweakValue file = System.IO.Unsafe.unsafePerformIO $ do value <- readFile file logg Debug (file ++ " = " ++ value) return $ case readMay value of Nothing -> error ("cannot read: " ++ value) Just x -> x {-# noinline tweakValue #-} -- | prints debug messages (as unsafe side effects) -- can be used at the end of expressions like this: -- (x * y + 3) << id -- something << getter (<<) :: Show s => a -> (a -> s) -> a a << f = trace (show $ f a) a -- | prints out an expression as a debugging message (unsafe side effect) -- with a given message (<<?) :: Show a => a -> String -> a a <<? msg = trace (msg ++ ": " ++ show a) a -- | useful for temporarily deactivating $<<?$ (<<|) :: Show a => a -> String -> a a <<| _ = a -- | re-implementation of trace that uses Text.Logging.logg trace :: String -> a -> a trace msg x = unsafePerformIO $ do logg Debug msg return x traceThis :: String -> (x -> String) -> x -> x traceThis "" showFun x = trace (showFun x) x traceThis msg showFun x = trace (msg ++ ": " ++ showFun x) x e :: String -> a e = error es :: Show s => String -> s -> a es msg x = error (msg ++ ": " ++ show x) nm :: Show s => String -> s -> a nm msg = es ("Non-exhaustive patterns: " ++ msg) assertIO :: Bool -> String -> IO () assertIO True _ = return () assertIO False msg = error ("ASSERTION ERROR: " ++ msg) -- | returns True every n-th time 'every' is called. -- (of course this involves unsafeIO-magick. every :: Int -> IO () -> IO () every n cmd = do c <- readIORef everyRef if c >= n then do writeIORef everyRef 0 cmd else do writeIORef everyRef (c + 1) return () {-# NOINLINE everyRef #-} everyRef :: IORef Int everyRef = unsafePerformIO $ newIORef 0 -- | @wait n@ waits for n seconds wait :: MonadIO m => Double -> m () wait n = io $ threadDelay $ round (n * 10 ^ (6 :: Int)) -- * re-named re-exports {-# inline fmapM #-} fmapM :: (Data.Traversable.Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) fmapM = Data.Traversable.mapM fmapM_ :: (Monad m, Data.Foldable.Foldable t) => (a -> m b) -> t a -> m () fmapM_ = Data.Foldable.mapM_ fany :: Foldable t => (a -> Bool) -> t a -> Bool fany = Data.Foldable.any fsum :: (Foldable t, Num a) => t a -> a fsum = Data.Foldable.sum -- | Efficiency talk: Both flength and fnull assume that it is -- faster to access the first elements than the last. flength :: (Functor t, Foldable t) => t a -> Int flength = Foldable.foldl (+) 0 . fmap (const 1) fnull :: (Functor t, Foldable t) => t a -> Bool fnull = Foldable.foldr (&&) True . fmap (const False) ftoList :: Foldable f => f a -> [a] ftoList = Foldable.toList -- * function composition stuff (|>) :: a -> (a -> b) -> b a |> f = f a -- fake kleisli stuff passThrough :: Monad m => (a -> m ()) -> (a -> m a) passThrough cmd a = cmd a >> return a secondKleisli :: Functor f => (a -> f b) -> ((x, a) -> f (x, b)) secondKleisli cmd (x, a) = fmap (tuple x) $ cmd a (<>>) :: Functor m => m a -> (a -> b) -> m b action <>> f = f <$> action -- * State monad stuff puts :: MonadState s m => (a -> s -> s) -> a -> m () puts setter a = do s <- get put (setter a s) modifies :: MonadState s m => (s -> a) -> (a -> s -> s) -> (a -> a) -> m () modifies getter setter fun = do a <- gets getter puts setter (fun a) modifiesT :: (Monad m, MonadTrans t, MonadState s (t m)) => (s -> a) -> (a1 -> s -> s) -> (a -> m a1) -> t m () modifiesT getter setter cmd = do x <- gets getter x' <- lift $ cmd x puts setter x' modifyState :: MonadState s m => (s -> s) -> m () modifyState f = get >>= (return . f) >>= put -- | runs a state monad on the content of an IORef -- (useful for embedding state monad in e.g callback functions) runStateTFromIORef :: IORef s -> StateT s IO a -> IO a runStateTFromIORef ref cmd = do s <- readIORef ref (o, s') <- runStateT cmd s writeIORef ref s' return o -- | is not atomic modifyIORefM :: IORef a -> (a -> IO a) -> IO () modifyIORefM ref cmd = readIORef ref >>= cmd >>= writeIORef ref -- * mvar stuff tryReadMVar :: MVar a -> IO (Maybe a) tryReadMVar mvar = do r <- tryTakeMVar mvar forM_ r $ putMVar mvar return r -- * Monad stuff chainAppM :: Monad m => (b -> a -> m a) -> [b] -> a -> m a chainAppM cmd (b : r) a = do a' <- cmd b a chainAppM cmd r a' chainAppM _ [] a = return a ignore :: Monad m => m a -> m () ignore = (>> return ()) {-# inline io #-} io :: MonadIO m => IO a -> m a io = liftIO -- applies a given monadic operation n times applyTimesM :: Monad m => Int -> (a -> m a) -> a -> m a applyTimesM 0 _ = return applyTimesM n m = m >=> applyTimesM (pred n) m infixl 8 ^^: (^^:) :: Functor m => Accessor r a -> (a -> m a) -> r -> m r acc ^^: f = \ r -> fmap (\ a' -> acc ^= a' $ r) (f (r ^. acc)) (>$>) :: Functor m => m a -> (a -> b) -> m b (>$>) = flip fmap catchSomeExceptionsErrorT :: MonadCatchIO m => (SomeException -> e) -> ErrorT e m a -> ErrorT e m a catchSomeExceptionsErrorT convert (ErrorT cmd) = ErrorT $ Control.Monad.CatchIO.catch cmd (return . Left . convert) convertErrorT :: Functor m => (a -> b) -> ErrorT a m o -> ErrorT b m o convertErrorT f (ErrorT action) = ErrorT $ (either (Left . f) Right <$> action) -- api stolen from the package 'errors' hush :: Either e a -> Maybe a hush = either (const Nothing) Just -- * either stuff mapLeft :: (a -> b) -> Either a c -> Either b c mapLeft f (Left a) = Left $ f a mapLeft _ (Right c) = Right c -- * list stuff infixl 4 +: (+:) :: [a] -> a -> [a] a +: b = a ++ [b] singleton :: a -> [a] singleton = (: []) -- | dropPrefix a b drops the longest prefix from b that is equal to a prefix of a. dropPrefix :: Eq a => [a] -> [a] -> [a] dropPrefix (a : aR) (b : bR) = if a == b then dropPrefix aR bR else b : bR dropPrefix _ b = b -- | drops the given prefix of a list, if prefix `isPrefixOf` list. dropPrefixMay :: Eq a => [a] -> [a] -> Maybe [a] dropPrefixMay prefix list = if prefix `isPrefixOf` list then Just $ drop (length prefix) list else Nothing chunks :: Int -> [a] -> [[a]] chunks _ [] = [] chunks n l = let (a, b) = splitAt n l in a : chunks n b -- returns the list of items that are in the given list more than once duplicates :: (Eq a, Ord a) => [a] -> [a] duplicates = nub . inner Set.empty where inner elements (a : r) = if Set.member a elements then a : rest else rest where rest = inner (Set.insert a elements) r inner _ [] = [] chainApp :: (b -> a -> a) -> [b] -> a -> a chainApp fun (b : r) a = chainApp fun r (fun b a) chainApp _ [] a = a toEitherList :: [a] -> [b] -> [Either a b] toEitherList as bs = map Left as ++ map Right bs single :: String -> [a] -> a single _ [a] = a single msg [] = error ("empty list in single: " ++ msg) single msg __ = error ("more than one element in list in single: " ++ msg) dropLast :: Int -> [a] -> [a] dropLast n = reverse . drop n . reverse wordsBy :: Eq a => [a] -> [a] -> [[a]] wordsBy seps ll = inner [] ll where inner akk [] = [reverse akk] inner akk (a : r) = if a `elem` seps then reverse akk : wordsBy seps r else inner (a : akk) r cartesian :: [a] -> [b] -> [(a, b)] cartesian al bl = concatMap (\ b -> map (\ a -> (a, b)) al) bl -- | returns every combination of given elements once. completeEdges :: [a] -> [(a, a)] completeEdges (a : r) = map (tuple a) r ++ completeEdges r completeEdges [] = [] adjacentCyclic :: [a] -> [(a, a)] adjacentCyclic [] = [] adjacentCyclic [_] = [] adjacentCyclic list@(head : _) = inner head list where inner first (a : b : r) = (a, b) : inner first (b : r) inner first [last] = [(last, first)] inner _ [] = error "adjacentCyclic" -- | merges pairs of elements for which the given function returns (Just a). -- removes the pair and inserts (the merged) as. -- Is idempotent. mergePairs :: Eq a => (a -> a -> Maybe [a]) -> [a] -> [a] mergePairs f = fixpoint merge where merge (a : r) = case inner a r of Nothing -> a : merge r Just r' -> r' merge [] = [] inner a (b : r) = case f a b <|> f b a of Nothing -> case inner a r of Nothing -> Nothing Just r' -> Just (b : r') Just newAs -> Just (newAs ++ r) inner _ [] = Nothing -- | like mergePairs, but only tries to merge adjacent elements -- (or the first and the last element) -- Is idempotent. mergeAdjacentCyclicPairs :: Eq a => (a -> a -> Maybe a) -> [a] -> [a] mergeAdjacentCyclicPairs f = fixpoint merge where merge = headAndLast . adjacent adjacent (a : b : r) = case f a b of Nothing -> a : adjacent (b : r) Just x -> adjacent (x : r) adjacent [x] = [x] adjacent [] = [] headAndLast [] = [] headAndLast [a] = [a] headAndLast l = case f (last l) (head l) of Nothing -> l Just x -> x : tail (init l) -- | returns the local minima of a list. localMinima :: Ord n => [n] -> [n] localMinima (a : b : c : r) = if a > b && c > b then b : localMinima (c : r) else localMinima (b : c : r) localMinima _ = [] -- * String stuff -- | adds an extension, if the path does not already have the same extension (<..>) :: FilePath -> String -> FilePath path <..> ext = if dotExt `isSuffixOf` path then path else path <.> ext where dotExt = if Just '.' == headMay ext then ext else '.' : ext -- | reads a Text from a file in forced unicode encoding readUnicodeText :: FilePath -> IO Text.Text readUnicodeText file = Text.decodeUtf8With Text.lenientDecode <$> SBS.readFile file -- * Map stuff fromKeys :: Ord k => (k -> a) -> [k] -> Map k a fromKeys f keys = fromList (map (\ key -> (key, f key)) keys) lookups :: Ord k => [k] -> Map k a -> Maybe a lookups [] _ = Nothing lookups (k : r) m = if k `member` m then Just (m ! k) else lookups r m -- | creates a mapping function with an error message toFunction :: (Show k, Ord k) => String -> Map k e -> k -> e toFunction msg m k = findWithDefault err k m where err = error ("key not found: " ++ show k ++ " from " ++ msg) mapPairs :: Ord k => (k -> a -> (k, a)) -> Map k a -> Map k a mapPairs f = fromList . map (uncurry f) . toList -- * Maybe stuff justWhen :: Bool -> a -> Maybe a justWhen True = Just justWhen False = const Nothing -- * math stuff (==>) :: Bool -> Bool -> Bool False ==> _ = True True ==> x = x infixr 2 ==> (~=) :: (Ord n, Fractional n) => n -> n -> Bool a ~= b = distance a b < epsilon epsilon :: Fractional n => n epsilon = 0.001 divide :: (RealFrac f, Integral i) => f -> f -> (i, f) divide a b = (n, f * b) where (n, f) = properFraction (a / b) -- | folds the given number to the given range -- range is including lower bound and excluding upper bound -- OPT: is O(a), could be constant (using properFraction) foldToRange :: (Ord n, Num n) => (n, n) -> n -> n foldToRange (lower, upper) _ | upper <= lower = e "foldToRange" foldToRange (lower, upper) a | a >= upper = foldToRange (lower, upper) (a - distance lower upper) foldToRange (lower, upper) a | a < lower = foldToRange (lower, upper) (a + distance lower upper) foldToRange _ a = a -- | returns, if two values are very near in a (floating) modulo body. rangeEpsilonEquals :: (Ord n, Fractional n) => (n, n) -> n -> n -> Bool rangeEpsilonEquals range a b = or (map (aR ~=) [bR, bR + diff, bR - diff]) where diff = uncurry distance range aR = foldToRange range a bR = foldToRange range b distance :: Num n => n -> n -> n distance a b = abs (a - b) -- | clips a number to a given range -- range is including both bounds clip :: (Ord n, Num n) => (n, n) -> n -> n clip (lower, _) x | x < lower = lower clip (lower, upper) x | x >= lower && x <= upper = x clip (_, upper) _ = upper -- * tuple stuff tuple :: a -> b -> (a, b) tuple a b = (a, b) swapTuple :: (a, b) -> (b, a) swapTuple (a, b) = (b, a) fst3 :: (a, b, c) -> a fst3 (a, _, _) = a snd3 :: (a, b, c) -> b snd3 (_, b, _) = b third :: (a, b, c) -> c third (_, _, x) = x -- * misc -- | Returns the current time in seconds. getTime :: IO POSIXTime getTime = getPOSIXTime uncurry3 :: (a -> b -> c -> d) -> ((a, b, c) -> d) uncurry3 f (a, b, c) = f a b c uncurry4 :: (a -> b -> c -> d -> e) -> ((a, b, c, d) -> e) uncurry4 f (a, b, c, d) = f a b c d swapOrdering :: Ordering -> Ordering swapOrdering LT = GT swapOrdering GT = LT swapOrdering EQ = EQ xor :: Bool -> Bool -> Bool xor True True = False xor a b = a || b -- | boolean implication infix 4 ~> (~>) :: Bool -> Bool -> Bool True ~> x = x False ~> _ = True infix 4 ~.> (~.>) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool) (a ~.> b) x = a x ~> b x fixpoint :: Eq e => (e -> e) -> e -> e fixpoint f x = if fx == x then x else fixpoint f fx where fx = f x -- | applies a function n times superApply :: Int -> (a -> a) -> a -> a superApply n f = foldr (.) id $ replicate n f -- | returns all possible values, sorted. allValues :: (Enum a, Bounded a) => [a] allValues = [minBound .. maxBound] -- * Pretty Printing class PP a where pp :: a -> String instance (PP a, PP b) => PP (a, b) where pp (a, b) = "(" ++ pp a ++ ", " ++ pp b ++ ")" instance (PP a, PP b) => PP (Pair a b) where pp (a :!: b) = "(" ++ pp a ++ " :!: " ++ pp b ++ ")" instance (PP a, PP b, PP c) => PP (a, b, c) where pp (a, b, c) = "(" ++ pp a ++ ", " ++ pp b ++ ", " ++ pp c ++ ")" instance (PP a, PP b, PP c, PP d) => PP (a, b, c, d) where pp (a, b, c, d) = "(" ++ pp a ++ ", " ++ pp b ++ ", " ++ pp c ++ ", " ++ pp d ++ ")" instance PP Bool where pp True = "|" pp False = "O" instance PP a => PP [a] where pp list = "[" ++ intercalate ", " (map (clipString . pp) list) ++ "]" where clipString s = if length s < limit then s else take (limit - length dots) s ++ dots limit = 20 dots = "..." instance PP a => PP (Set.Set a) where pp set = "{" ++ (tail (init (pp (Set.toList set)))) ++ "}" instance PP a => PP (Maybe a) where pp Nothing = "Nothing" pp (Just x) = "Just (" ++ pp x ++ ")" instance PP a => PP (Strict.Maybe a) where pp Strict.Nothing = "Strict.Nothing" pp (Strict.Just x) = "Strict.Just (" ++ pp x ++ ")" instance PP Double where pp = printf "%8.3f" instance PP Float where pp = printf "%8.3f" instance PP Int where pp = show ppp :: PP p => p -> IO () ppp = pp >>> logg Info -- * strict utils instance Applicative Strict.Maybe where pure = Strict.Just (Strict.Just f) <*> (Strict.Just x) = Strict.Just $ f x _ <*> _ = Strict.Nothing instance Alternative Strict.Maybe where empty = Strict.Nothing Strict.Nothing <|> x = x (Strict.Just x) <|> _ = Strict.Just x deriving instance Typeable2 Pair deriving instance (Data a, Data b) => Data (Pair a b) deriving instance Functor (Pair a) deriving instance Foldable (Pair a) deriving instance Traversable (Pair a) instance (NFData a, NFData b) => NFData (Pair a b) where rnf (a :!: b) = rnf a `seq` rnf b firstStrict :: (a -> b) -> (Pair a c) -> (Pair b c) firstStrict f (a :!: c) = f a :!: c firstAStrict :: Accessor (Pair a b) a firstAStrict = accessor (\ (a :!: _) -> a) (\ a (_ :!: b) -> (a :!: b)) zipStrict :: [a] -> [b] -> [Pair a b] zipStrict (a : ra) (b : rb) = (a :!: b) : zipStrict ra rb zipStrict _ _ = [] floorInteger :: Double -> Integer floorInteger = floor truncateInteger :: (RealFrac a) => a -> Integer truncateInteger = truncate
nikki-and-the-robots/nikki
src/Utils.hs
lgpl-3.0
17,979
0
16
4,815
7,579
4,014
3,565
-1
-1
{-# LANGUAGE FlexibleInstances, OverloadedStrings, UnicodeSyntax, CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.HTTP.LinkSpec where import Test.Hspec import Test.QuickCheck #if !MIN_VERSION_base(4,8,0) import Data.Monoid (mconcat) #endif import qualified Data.Text as T import Data.Maybe (fromJust) import Network.HTTP.Link import Network.URI (URI) instance Arbitrary (Link URI) where arbitrary = do urlScheme ← elements ["http://", "https://", "ftp://", "git+ssh://"] urlDomain ← listOf1 $ elements ['a'..'z'] urlTld ← elements ["com", "net", "org", "me", "is", "technology", "club"] urlPath ← listOf $ elements ['a'..'z'] params ← listOf genParam return $ fromJust $ lnk (mconcat [urlScheme, urlDomain, ".", urlTld, "/", urlPath]) params where genParam = do otherParamKey ← suchThat (listOf1 $ elements ['a'..'z']) (\x → x /= "rel" && x /= "rev" && x /= "title" && x /= "title*" && x /= "hreflang" && x /= "anchor" && x /= "media" && x /= "type") paramKey ← elements [Rel, Rev, Title, Hreflang, Anchor, Media, ContentType, Other (T.pack otherParamKey)] paramValue ← listOf $ elements ['a'..'z'] return (paramKey, T.pack paramValue) spec ∷ Spec spec = do describe "writeLinkHeader → parseLinkHeader" $ it "roundtrips successfully" $ property $ \x → parseLinkHeader (writeLinkHeader x) == Just (x :: [Link URI])
myfreeweb/http-link-header
test-suite/Network/HTTP/LinkSpec.hs
unlicense
1,519
0
28
354
472
253
219
29
1
import Data.Char enc 'z' = 'a' enc 'Z' = 'A' enc c = chr (ord c + 1) encode s = map enc s dec 'a' = 'z' dec 'A' = 'Z' dec c = chr (ord c - 1) decode s = map dec s main :: IO() main = do contents <- readFile "./encode/input.txt" --將讀到的內容存進一個自訂變數中 writeFile "./encode/output.txt" (encode contents) --編成密碼後寫入另一檔案 contents2 <- readFile "./encode/output.txt" --讀編成密碼後的一檔案 writeFile "./encode/output2.txt" (decode contents2) --解碼後寫入另一檔案
bestian/haskell-sandbox
encode.hs
unlicense
552
0
9
103
173
83
90
15
1
import Helpers.Subsets (allSubsets, eachPair) import Data.List -- See 2021-02-13T19:58:00 email from Richard. -- Number of irreflexive, antisymmetric, antitransitive -- a n = length $ filter (not . isAntitransitive) $ allAntisymmetricAndIrreflexive n -- map a [0..] -- [1,1,3,21,317,9735, -- Bounded above by 3^Binomial(n,2). allFlips :: [(Int, Int)] -> [[(Int, Int)]] allFlips [] = [[]] allFlips ((a,b):xs) = map ((a,b):) (allFlips xs) ++ map ((b,a):) (allFlips xs) ++ allFlips xs allFlips' :: [(Int, Int)] -> [[(Int, Int)]] allFlips' [] = [[]] allFlips' ((a,b):xs) = map ([(a,b),(b,a)]++) (allFlips' xs) ++ map ((a,b):) (allFlips' xs) ++ map ((b,a):) (allFlips' xs) ++ allFlips' xs allFlips'' :: [(Int, Int)] -> [[(Int, Int)]] allFlips'' [] = [[]] allFlips'' ((a,b):xs) = map ([(a,b),(b,a)]++) (allFlips'' xs) ++ map ((a,b):) (allFlips'' xs) ++ map ((b,a):) (allFlips'' xs) ++ allFlips'' xs -- irreflexive, antisymmetric relations allAntisymmetricAndIrreflexive n = allFlips $ eachPair [1..n] allRelations n = allSubsets [(x,y) | x <- [1..n], y <- [1..n]] allReflexiveRelations n = map (reflexive ++) $ allSubsets [(x,y) | x <- [1..n], y <- [1..n], x /= y] where reflexive = map (\x -> (x,x)) [1..n] isAntitransitive :: [(Int, Int)] -> Bool isAntitransitive xs = all (edgeAntitransitive xs) xs edgeAntitransitive :: [(Int, Int)] -> (Int, Int) -> Bool edgeAntitransitive edges (x, y) = null $ connectedEdges `intersect` edges where connectedEdges = map (\(_,y') -> (x,y')) $ filter (\(x',y') -> x' == y) edges isTransitive :: [(Int, Int)] -> Bool isTransitive xs = all (edgeTransitive xs) xs edgeTransitive :: [(Int, Int)] -> (Int, Int) -> Bool edgeTransitive edges (x, y) = all (`elem` edges) connectedEdges where connectedEdges = map (\(_,y') -> (x,y')) $ filter (\(x',y') -> x' == y) edges isSymmetric :: [(Int, Int)] -> Bool isSymmetric xs = all (\(a,b) -> (b,a) `elem` xs) xs isAntisymmetric :: [(Int, Int)] -> Bool isAntisymmetric xs = not $ any (\(a,b) -> (b,a) `elem` xs) xs isIrreflexive :: [(Int, Int)] -> Bool isIrreflexive = all (uncurry (/=))
peterokagey/haskellOEIS
src/Sandbox/Richard/antiequivalence.hs
apache-2.0
2,084
0
11
345
1,068
615
453
31
1
module Opts where import Data.Text (Text, pack) import Options.Applicative data Args = Args { inputDir :: !FilePath , stopList :: !(Maybe FilePath) } deriving (Show, Eq) parseArgs :: IO Args parseArgs = execParser opts opts' :: Parser Args opts' = Args <$> option fileOpt ( short 'c' <> long "corpus-dir" <> metavar "CORPUS_DIR" <> help "The root directory for the corpus files.") <*> optional (option fileOpt ( short 's' <> long "stoplist" <> metavar "STOPLIST_FILE" <> help "A file to use as a stoplist.")) opts :: ParserInfo Args opts = info (helper <*> opts') ( fullDesc <> progDesc "Program for working through Foundations of Statistical NLP." <> header "stat-nlp") fileOpt :: ReadM FilePath fileOpt = str textOpt :: ReadM Text textOpt = pack <$> str
erochest/stat-nlp
Opts.hs
apache-2.0
940
0
13
309
241
123
118
29
1
{-| Module : Marvin.API.Preprocess.OneHotEncode Description : Encoding nominal features to binaries. -} module Marvin.API.Preprocess.OneHotEncode where import qualified Data.Vector as Vec import Marvin.API.Fallible import Marvin.API.Table.Internal -- | Encodes a 'NominalColumn' to a 'BinaryTable' -- where each binary column represents a nominal value. -- An element in a certain binary column is true if it's the column representing the corresponding -- nominal value. oneHotEncodeColumn :: NominalColumn -> NominalColumn -> BinaryTable oneHotEncodeColumn fitCol testCol = unsafeFromCols $ Vec.fromList $ binCols where binCols = fmap (\val -> nameColumn' (mkName val) (mapColumnAtoB (== val) testCol)) $ nomVals nomVals = map expose $ distinctValues fitCol expose = exposure fitCol colName = either (const "") id $ columnName fitCol mkName name = colName ++ "_is_" ++ name -- | Encodes a 'NominalTable' to a 'BinaryTable'. -- An element in a certain binary column is true if it's the column representing the corresponding -- nominal value. oneHotEncode :: NominalTable -> NominalTable -> Fallible BinaryTable oneHotEncode train test = case transformTable (\col -> columns . (oneHotEncodeColumn col)) of Left (ColumnNameConflict _) -> transformTable (\col -> fmap (copyName Nothing) . columns . (oneHotEncodeColumn col)) x -> x where transformTable f = transformEveryColumn "When using oneHotEncode." f train test
gaborhermann/marvin
src/Marvin/API/Preprocess/OneHotEncode.hs
apache-2.0
1,474
0
15
257
302
162
140
17
2
{-# LANGUAGE OverloadedStrings #-} module Site.Map where import Data.Text (Text) data Page = Index | Talk | Meetup render :: Page -> [(Text, Text)] -> Text render Index _ = "/" render Talk _ = "/talk" render Meetup _ = "/meetup"
lucasdicioccio/haskell-paris-src
Site/Map.hs
apache-2.0
242
0
8
54
82
47
35
8
1
-- Copyright 2016 David Edwards -- -- 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 AST ( AST(..), formatAST ) where data AST = SymbolAST { name :: String } | NumberAST { value :: Double } | AddAST { l :: AST, r :: AST } | SubtractAST { l :: AST, r :: AST } | MultiplyAST { l :: AST, r :: AST } | DivideAST { l :: AST, r :: AST } | ModuloAST { l :: AST, r :: AST } | PowerAST { base :: AST, exp :: AST } | MinAST { l :: AST, r :: AST } | MaxAST { l :: AST, r :: AST } deriving (Eq, Show) formatAST :: AST -> String formatAST ast = format ast 0 where format ast depth = replicate (depth * 2) ' ' ++ case ast of SymbolAST name -> "Symbol(" ++ name ++ ")\n" NumberAST value -> "Number(" ++ show value ++ ")\n" AddAST l r -> "Add\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1) SubtractAST l r -> "Subtract\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1) MultiplyAST l r -> "Multiply\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1) DivideAST l r -> "Divide\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1) ModuloAST l r -> "Modulo\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1) PowerAST base exp -> "Power\n" ++ (format base $ depth + 1) ++ (format exp $ depth + 1) MinAST l r -> "Min\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1) MaxAST l r -> "Max\n" ++ (format l $ depth + 1) ++ (format r $ depth + 1)
davidledwards/rpn-haskell
src/AST.hs
apache-2.0
2,009
0
16
551
669
362
307
31
10
{- | Implements several tests to control the validy of the program -} module Test.Muste where import PGF import PGF.Internal import Muste.Grammar.Internal import Muste.Tree import Muste import Test.HUnit.Text import Test.HUnit.Base import Data.Maybe import qualified Data.Map as M import Control.Monad import Data.Set (Set(..),empty,fromList) import Test.QuickCheck import Test.Framework import Test.Data -- HUnit tests hunit_updateClick_test = -- -- | The function 'updateClick' either increases the counter when the position is the same as the previous one or sets the new position and sets the counter to 1 -- updateClick :: Maybe Click -> Pos -> Maybe Click let click1 = Nothing click2 = Just $ Click 0 0 click3 = Just $ Click 2 2 in TestList [ TestLabel "Nothing" ( updateClick click1 0 ~?= ( Just $ Click 0 1 ) ), TestLabel "Just Click same position 1" ( updateClick click2 0 ~?= ( Just $ Click 0 1 ) ) , TestLabel "Just Click same position 2" ( updateClick click3 2 ~?= ( Just $ Click 2 3 ) ) , TestLabel "Just Click different position" ( updateClick click3 0 ~?= ( Just $ Click 0 1 ) ) ] hunit_linearizeTree_test = -- The 'linearizeTree' function linearizes a MetaTTree to a list of tokens and pathes to the nodes that create it -- linearizeTree :: Grammar -> Language -> MetaTTree -> [LinToken] let pgf = readPGF "gf/ABCAbs.pgf" grammar = fmap pgfToGrammar pgf -- tree1 is in Test.Data tree2 = TNode "a" (Fun "A" []) [] -- MetaTTree (read "{a:A}") empty tree3 = TNode "s" (Fun "S" ["A"]) [TNode "a" (Fun "A" []) []] -- MetaTTree (read "{s:(A->S) {a:A}}") empty tree4 = TNode "s" (Fun "S" ["A"]) [TNode "f" (Fun "A" ["A","B"]) [TMeta "A", TNode "b" (Fun "B" []) []]] -- MetaTTree (read "{s:(A->S) {f:(A->B->A) {?A} {b:B}}}") empty tree5 = TNode "s" (Fun "S" ["A"]) [TNode "f" (Fun "A" ["A","B"]) [TNode "a" (Fun "A" []) [],TMeta "B"]] -- MetaTTree (read "{s:(A->S) {f:(A->B->A) {a:A} {?B}}}") empty tree6 = TNode "s" (Fun "S" ["A"]) [TNode "f" (Fun "A" ["A","B"]) [TMeta "A",TMeta "B"]] -- MetaTTree (read "{s:(A->S) {f:(A->B->A) {?A} {?B}}}") empty tree7 = TNode "s" (Fun "S" ["A"]) [TNode "f" (Fun "A" ["A","B"]) [TNode "a" (Fun "A" []) [], TNode "b" (Fun "B" []) []]] -- MetaTTree (read "{s:(A->S) {f:(A->B->A) {a:A} {b:B}}}") empty tree8 = TNode "s" (Fun "S" ["A"]) [TNode "h" (Fun "A" ["A","A","A"]) [TNode "a" (Fun "A" []) [],TNode "a" (Fun "A" []) [],TNode "a" (Fun "A" []) []]] -- MetaTTree (read "{s:(A->S) {h:(A->A->A->A) {a:A} {a:A} {a:A}}}") empty in TestList [ TestLabel "Empty Grammar" (linearizeTree emptyGrammar (mkCId "ABC1") tree2 ~?= [([],"?0")]), TestLabel "Empty Lang" ( TestCase $ grammar >>= (\g -> linearizeTree g wildCId tree1 @?= [([],"?0")]) ), TestLabel "Meta node" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree1 @?= [([],"?0")]) ), TestLabel "Simple node" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree2 @?= [([],"a")]) ), TestLabel "Simple tree" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree3 @?= [([0],"a")]) ), TestLabel "Tree 1" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree4 @?= [([0,0],"?0"),([0],"x"),([0,1],"b")]) ), TestLabel "Tree 2" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree5 @?= [([0,0],"a"),([0],"x"),([0,1],"?0")]) ), TestLabel "Tree 3" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree6 @?= [([0,0],"?0"),([0],"x"),([0,1],"?1")]) ), TestLabel "Tree 4" (TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree7 @?= [([0,0],"a"),([0],"x"),([0,1],"b")]) ), TestLabel "Tree 5" ( TestCase $ grammar >>= (\g -> linearizeTree g (mkCId "ABC1") tree8 @?= [([0,0],"a"),([0,1],"a"),([0,2],"a")])) ] hunit_linearizeList_test = -- The 'linearizeList' functions concatenates a token list to a string -- linearizeList :: Bool -> [LinToken] -> String let list1 = [] list2 = [([0],"a")] list3 = [([0,0],"a"),([0],"x"),([0,1],"b")] in TestList [ TestLabel "Empty List without Path" ( linearizeList False False list1 ~?= "" ), TestLabel "Empty List with Path" ( linearizeList True False list1 ~?= " []" ), TestLabel "One Element without Path" ( linearizeList False False list2 ~?= "a" ), TestLabel "One Element with Path" ( linearizeList True False list2 ~?= " [0] a [0] []" ), TestLabel "Simple List without Path" ( linearizeList False False list3 ~?= "a x b" ), TestLabel "Simple List with Path" ( linearizeList True False list3 ~?= " [0,0] a [0,0] [0] x [0] [0,1] b [0,1] []" ), TestLabel "Empty List without Path and Positions" ( linearizeList False True list1 ~?= "(0) " ), TestLabel "Empty List with Path and Positions" ( linearizeList True True list1 ~?= "(0) []" ), TestLabel "One Element without Path and Positions" ( linearizeList False True list2 ~?= "(0) (1) a (2) " ), TestLabel "One Element with Path and Positions" ( linearizeList True True list2 ~?= "(0) [0] (1) a [0] (2) []" ), TestLabel "Simple List without Path and Positions" ( linearizeList False True list3 ~?= "(0) (1) a (2) (3) x (4) (5) b (6) " ), TestLabel "Simple List with Path and Positions" ( linearizeList True True list3 ~?= "(0) [0,0] (1) a [0,0] (2) [0] (3) x [0] (4) [0,1] (5) b [0,1] (6) []" ) ] hunit_getNewTreeSet_test = -- TODO -- | The 'getNewTrees' function generates a set of related trees given a MetaTTree and a path -- getNewTrees :: Grammar -> MetaTTree -> Path -> S.Set MetaTTree let pgfFile = readPGF "gf/ABCAbs.pgf" grammar = fmap pgfToGrammar pgfFile -- tree1 is in Test.Data path1 = [] tree2 = TNode "a" (Fun "A" []) [] in TestList [ TestLabel "Tree 2" (TestCase $ grammar >>= (\g -> getNewTreesSet g (head $ languages $ pgf g) tree1 path1 3 @?= empty) ) ] hunit_treesToStrings_test = -- TODO -- The 'treesToStrings' generates a list of strings based on the differences in similar trees -- treesToStrings :: Grammar -> Language -> [TTree] -> [String] let pgfFile = readPGF "gf/ABCAbs.pgf" grammar = fmap pgfToGrammar pgfFile tree2 = TNode "a" (Fun "A" []) [] in TestList [ TestLabel "Empty tree list" (TestCase $ grammar >>= (\g -> treesToStrings g (head $ languages $ pgf g) [] @?= []) ), TestLabel "Meta tree in tree list" (TestCase $ grammar >>= (\g -> treesToStrings g (head $ languages $ pgf g) [tree1] @?= ["?0"]) ), TestLabel "Two trees in tree list 1" (TestCase $ grammar >>= (\g -> treesToStrings g (head $ languages $ pgf g) [tree1,tree2] @?= ["?0","a"]) ), TestLabel "Two trees in tree list 2" (TestCase $ grammar >>= (\g -> treesToStrings g (head $ languages $ pgf g) [tree2,tree1] @?= ["a","?0"]) ), TestLabel "Empty Grammar" (treesToStrings emptyGrammar (mkCId "ABC1") [tree2,tree1] ~?= ["?0","?0"]) -- Maybe strange result ] hunit_preAndSuffix_test = -- TODO -- -- Computes the longest common prefix and suffix for linearized trees -- preAndSuffix :: Eq a => [a] -> [a] -> ([a],[a]) TestList [ -- TestLabel "fail" (TestCase $ assertFailure "intended fail") ] hunit_getSuggestions_test = -- TODO -- The 'getSuggestions' function generates a list of similar trees given a tree and a position in the token list -- getSuggestions :: Grammar -> Language -> [LinToken] -> MetaTTree -> Pos -> S.Set String TestList [ ] -- QuickCheck tests prop_updateClick :: Maybe Click -> Pos -> Bool prop_updateClick click pos = isJust $ updateClick click pos various_tests = TestList [ TestLabel "updateClick" hunit_updateClick_test, TestLabel "preAndSuffix" hunit_preAndSuffix_test ] linearize_tests = TestList [ TestLabel "linearizeTree" hunit_linearizeTree_test, TestLabel "linearizeList" hunit_linearizeList_test -- This test fails at the moment ] suggestion_tests = TestList [ -- TestLabel "getNewTrees" hunit_getNewTrees_test, -- This test takes too long at the moment TestLabel "treesToStrings" hunit_treesToStrings_test, TestLabel "getSuggestions" hunit_getSuggestions_test ] hunit_tests = TestList [various_tests,linearize_tests, suggestion_tests] quickcheck_tests :: [(TestName,Property)] quickcheck_tests = [ ("Updated clicks are never Nothing",property prop_updateClick) ]
daherb/Haskell-Muste
muste-lib/Test/Muste.hs
artistic-2.0
8,365
0
18
1,672
2,487
1,358
1,129
105
1
{-# LANGUAGE PackageImports #-} import "cwezi" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsPort) import Control.Concurrent (forkIO) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay) main :: IO () main = do putStrLn "Starting devel application" (port, app) <- getApplicationDev forkIO $ runSettings defaultSettings { settingsPort = port } app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "dist/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
mossplix/CERP-Project
devel.hs
bsd-2-clause
699
0
10
123
186
101
85
23
2
module Jerimum.PostgreSQL.Types.Int32Array -- * CBOR codec ( int32ArrayEncoderV0 , int32ArrayDecoderV0 , encodeInt32Array -- * Text codec , parseInt32Array , formatInt32Array -- * Value constructors , fromInt32Array ) where import qualified Codec.CBOR.Decoding as D import qualified Codec.CBOR.Encoding as E import qualified Data.Attoparsec.Text as A import Data.Int import qualified Data.Text as T import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Builder import Data.Text.Lazy.Builder.Int import Jerimum.PostgreSQL.Types import Jerimum.PostgreSQL.Types.Encoding import Jerimum.PostgreSQL.Types.Numeric v0 :: Version v0 = 0 encodeInt32Array :: Maybe [Int32] -> E.Encoding encodeInt32Array = encodeWithVersion v0 int32ArrayEncoderV0 int32ArrayParser :: A.Parser [Int32] int32ArrayParser = array1Parser (A.signed A.decimal) parseInt32Array :: T.Text -> Maybe [Int32] parseInt32Array = runParser "parseInt32Array: parse error" int32ArrayParser formatInt32Array :: [Int32] -> T.Text formatInt32Array = toStrict . toLazyText . buildArray decimal fromInt32Array :: Maybe [Int32] -> Value fromInt32Array = mkValue (ArrayType 1 TInt32) encodeInt32Array int32ArrayEncoderV0 :: [Int32] -> E.Encoding int32ArrayEncoderV0 = arrayEncoderV0 int32EncoderV0 int32ArrayDecoderV0 :: D.Decoder s [Int32] int32ArrayDecoderV0 = arrayDecoderV0 int32DecoderV0
dgvncsz0f/nws
src/Jerimum/PostgreSQL/Types/Int32Array.hs
bsd-3-clause
1,532
0
8
335
320
191
129
34
1
{-# LANGUAGE DeriveFunctor #-} -- | Reimplementation of pipe's core data type as Free monad module Pipes.Free where import Control.Monad import Control.Monad.Free import Pipes.Void ---------------------------------------------------------------- -- Data type ---------------------------------------------------------------- -- | Bidirectional proxy type Proxy a' a b' b m r = Free (ProxyF a' a b' b m) r -- a' a b' b type Producer b m r = Proxy X () () b m r type Pipe a b m r = Proxy () a () b m r type Consumer a m r = Proxy () a () X m r -- | Functor for proxy which is represented as free monad data ProxyF a' a b' b m r = Request a' (a -> r) -- ^ Proxy blocked on requesting input from -- upstream (await for 1 directional case) | Respond b (b' -> r) -- ^ Proxy blocked on responding to -- downstream (yield for 1 directional case) | M (m r) -- ^ Carry monadic effect deriving (Functor) ---------------------------------------------------------------- -- Push-pull category ---------------------------------------------------------------- -- | Create proxy which is initially blocked on responding push :: a -> Proxy a' a a' a m r push a = Free (Respond a pull) -- | Create proxy which is initially blocked on requesting input from upstream pull :: a' -> Proxy a' a a' a m r pull a' = Free (Request a' push) (>>~) :: Functor m => Proxy a' a b' b m r -- ^ upstream -> (b -> Proxy b' b c' c m r) -- ^ downstream -> Proxy a' a c' c m r -- ^ Pure r >>~ _ = Pure r Free p >>~ fb = case p of Request a' fa -> Free $ Request a' (fa >~> fb) Respond b fb' -> fb' +>> fb b M m -> Free $ M (fmap (>>~ fb) m) (+>>) :: Functor m => (b' -> Proxy a' a b' b m r) -- ^ upstream -> Proxy b' b c' c m r -- ^ downstream -> Proxy a' a c' c m r -- ^ _ +>> Pure r = Pure r fb' +>> Free p = case p of Request b' fb -> fb' b' >>~ fb Respond c fc' -> Free $ Respond c (fb' >+> fc') M m -> Free $ M (fmap (fb' +>>) m) (>~>) :: Functor m => (_a -> Proxy a' a b' b m r) -- ^ -> ( b -> Proxy b' b c' c m r) -- ^ -> (_a -> Proxy a' a c' c m r) -- ^ (fa >~> fb) a = fa a >>~ fb (>+>) :: Functor m => ( b' -> Proxy a' a b' b m r) -- ^ -> (_c' -> Proxy b' b c' c m r) -- ^ -> (_c' -> Proxy a' a c' c m r) -- ^ (fb' >+> fc') c' = fb' +>> fc' c' ---------------------------------------------------------------- -- Request/responds category ---------------------------------------------------------------- respond :: a -> Proxy x' x a' a m a' respond a = Free $ Respond a Pure request :: a' -> Proxy a' a y' y m a request a' = Free $ Request a' Pure -- > (//>) ~ for (//>) :: (Functor m) => Proxy x' x b' b m a' -- ^ -> (b -> Proxy x' x c' c m b') -- ^ -> Proxy x' x c' c m a' -- ^ p0 //> fb = go p0 where go (Pure r) = Pure r go (Free p) = case p of Request x' fx -> Free $ Request x' (go . fx) Respond b fb' -> fb b >>= (go . fb') M m -> Free $ M (fmap go m) (>\\) :: (Functor m) => (b' -> Proxy a' a y' y m b) -- ^ -> Proxy b' b y' y m c -- ^ -> Proxy a' a y' y m c -- ^ fb' >\\ p0 = go p0 where go (Pure r) = Pure r go (Free p) = case p of Request b' fb -> fb' b' >>= \b -> go (fb b) Respond x fx' -> Free $ Respond x (\x' -> go (fx' x')) M m -> Free $ M (fmap go m) for :: (Functor m) => Proxy x' x b' b m a' -- ^ -> (b -> Proxy x' x c' c m b') -- ^ -> Proxy x' x c' c m a' -- ^ for = (//>)
Shimuuar/data-folds
Pipes/Free.hs
bsd-3-clause
3,731
0
16
1,224
1,441
747
694
-1
-1
-- | A number of invariant checks on the B-tree type module Data.BTree.Invariants ( invariants , nodeSizeInvariant , balancingInvariant ) where import Data.BTree.Internal import qualified Data.BTree.Array as A -- | Check all invariants invariants :: BTree k v -> Bool invariants btree = all ($ btree) [nodeSizeInvariant, balancingInvariant] -- | Size of the root node (number of keys in it) rootSize :: BTree k v -> Int rootSize (Leaf s _ _) = s rootSize (Node s _ _ _) = s -- | Get the children of the root node as a list rootChildren :: BTree k v -> [BTree k v] rootChildren (Leaf _ _ _) = [] rootChildren (Node s _ _ c) = A.toList (s + 1) c -- | Check if a tree is a leaf isLeaf :: BTree k v -> Bool isLeaf (Leaf _ _ _) = True isLeaf _ = False -- | Check that each node contains enough keys nodeSizeInvariant :: BTree k v -> Bool nodeSizeInvariant = all nodeSizeInvariant' . rootChildren where nodeSizeInvariant' btree = invariant (rootSize btree) && all nodeSizeInvariant' (rootChildren btree) invariant s | s >= maxNodeSize `div` 2 && s <= maxNodeSize = True | otherwise = False -- | Check for perfect balancing balancingInvariant :: BTree k v -> Bool balancingInvariant = equal . depths where -- Check if all elements in a list are equal equal (x : y : t) = x == y && equal (y : t) equal _ = True -- Depths of all leaves depths tree | isLeaf tree = [0 :: Int] | otherwise = rootChildren tree >>= map (+ 1) . depths
jaspervdj/b-tree
tests/Data/BTree/Invariants.hs
bsd-3-clause
1,557
0
13
410
468
245
223
32
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Data.Angle ( Angle , toAngle , fromAngle , AngleRange (..) ) where import Data.Fixed (mod') import Data.AdditiveGroup import Data.MetricSpace import Data.VectorSpace import System.Random newtype (Floating a, Real a) => Angle a = Angle a deriving (Eq) toAngle :: (Floating a, Real a) => a -> Angle a toAngle a = Angle $ mod' a (2*pi) data AngleRange = ZeroTwoPi | NegPiPosPi fromAngle :: (Floating a, Real a) => AngleRange -> Angle a -> a fromAngle ZeroTwoPi (Angle a) = a fromAngle NegPiPosPi (Angle a) | a <= pi = a | otherwise = a - 2*pi instance (Floating a, Real a, Show a) => Show (Angle a) where show = show . fromAngle ZeroTwoPi instance (Floating a, Real a) => AdditiveGroup (Angle a) where zeroV = Angle 0 Angle a ^+^ Angle b = toAngle $ a + b negateV (Angle a) = toAngle $ negate a instance (Floating a, Real a) => VectorSpace (Angle a) where type Scalar (Angle a) = a s *^ (Angle v) = toAngle $ s * v instance (Floating a, Real a) => MetricSpace (Angle a) where type Metric (Angle a) = a distance (Angle a) (Angle b) | x > pi = 2*pi - x | otherwise = x where x = abs $ b - a instance (Floating a, Real a, Random a) => Random (Angle a) where randomR (Angle 0, Angle 0) g = random g randomR (Angle l, Angle h) g = (toAngle a, g') where (a, g') = randomR (l, h) g random g = (toAngle $ a * 2 * pi, g') where (a, g') = random g
jdmarble/angle
src/Data/Angle.hs
bsd-3-clause
1,618
0
9
455
705
367
338
43
1
module SimpleTests where import TestHelpers import Control.Parallel.MPI.Simple import Control.Concurrent (threadDelay) import Data.Serialize () import Data.Maybe (isJust) root :: Rank root = 0 simpleTests :: Rank -> [(String,TestRunnerTest)] simpleTests rank = [ mpiTestCase rank "send+recv simple message" $ syncSendRecv send , mpiTestCase rank "send+recv simple message (with sending process blocking)" syncSendRecvBlock , mpiTestCase rank "send+recv simple message using anySource" $ syncSendRecvAnySource send , mpiTestCase rank "ssend+recv simple message" $ syncSendRecv ssend , mpiTestCase rank "rsend+recv simple message" $ syncRSendRecv , mpiTestCase rank "send+recvFuture simple message" syncSendRecvFuture , mpiTestCase rank "isend+recv simple message" $ asyncSendRecv isend , mpiTestCase rank "issend+recv simple message" $ asyncSendRecv issend , mpiTestCase rank "isend+recv two messages + test instead of wait" asyncSendRecv2 , mpiTestCase rank "isend+recvFuture two messages, out of order" asyncSendRecv2ooo , mpiTestCase rank "isend+recvFuture two messages (criss-cross)" crissCrossSendRecv , mpiTestCase rank "isend+issend+waitall two messages" waitallTest , mpiTestCase rank "broadcast message" broadcastTest , mpiTestCase rank "scatter message" scatterTest , mpiTestCase rank "gather message" gatherTest , mpiTestCase rank "allgather message" allgatherTest , mpiTestCase rank "alltoall message" alltoallTest ] syncSendRecv, syncSendRecvAnySource :: (Comm -> Rank -> Tag -> SmallMsg -> IO ()) -> Rank -> IO () asyncSendRecv :: (Comm -> Rank -> Tag -> BigMsg -> IO Request) -> Rank -> IO () syncRSendRecv, syncSendRecvBlock, syncSendRecvFuture, asyncSendRecv2, asyncSendRecv2ooo :: Rank -> IO () crissCrossSendRecv, broadcastTest, scatterTest, gatherTest, allgatherTest, alltoallTest :: Rank -> IO () waitallTest :: Rank -> IO () -- Serializable tests type SmallMsg = (Bool, Int, String, [()]) smallMsg :: SmallMsg smallMsg = (True, 12, "fred", [(), (), ()]) syncSendRecv sendf rank | rank == sender = sendf commWorld receiver 123 smallMsg | rank == receiver = do (result, status) <- recv commWorld sender 123 checkStatus status sender 123 result == smallMsg @? "Got garbled result " ++ show result | otherwise = return () -- idling syncSendRecvAnySource sendf rank | rank == sender = sendf commWorld receiver 234 smallMsg | rank == receiver = do (result, status) <- recv commWorld anySource 234 checkStatus status sender 234 result == smallMsg @? "Got garbled result " ++ show result | otherwise = return () -- idling syncRSendRecv rank | rank == sender = do threadDelay (2* 10^(6 :: Integer)) rsend commWorld receiver 123 smallMsg | rank == receiver = do (result, status) <- recv commWorld sender 123 checkStatus status sender 123 result == smallMsg @? "Got garbled result " ++ show result | otherwise = return () -- idling type BigMsg = [Int] bigMsg :: BigMsg bigMsg = [0..50000] syncSendRecvBlock rank | rank == sender = send commWorld receiver 456 bigMsg | rank == receiver = do (result, status) <- recv commWorld sender 456 checkStatus status sender 456 threadDelay (2* 10^(6 :: Integer)) (result::BigMsg) == bigMsg @? "Got garbled result: " ++ show (length result) | otherwise = return () -- idling syncSendRecvFuture rank | rank == sender = do send commWorld receiver 789 bigMsg | rank == receiver = do future <- recvFuture commWorld sender 789 result <- waitFuture future status <- getFutureStatus future checkStatus status sender 789 (result::BigMsg) == bigMsg @? "Got garbled result: " ++ show (length result) | otherwise = return () -- idling asyncSendRecv isendf rank | rank == sender = do req <- isendf commWorld receiver 123456 bigMsg status <- wait req checkStatusIfNotMPICH2 status sender 123456 | rank == receiver = do (result, status) <- recv commWorld sender 123456 checkStatus status sender 123456 (result::BigMsg) == bigMsg @? "Got garbled result: " ++ show (length result) | otherwise = return () -- idling asyncSendRecv2 rank | rank == sender = do req1 <- isend commWorld receiver 123 smallMsg req2 <- isend commWorld receiver 456 bigMsg threadDelay (10^(6 :: Integer)) status <- test req1 isJust status @? "Got Nothing out of test, expected Just" let Just stat1 = status checkStatusIfNotMPICH2 stat1 sender 123 stat2 <- wait req2 checkStatusIfNotMPICH2 stat2 sender 456 | rank == receiver = do (result1, stat1) <- recv commWorld sender 123 checkStatus stat1 sender 123 (result2, stat2) <- recv commWorld sender 456 checkStatus stat2 sender 456 (result2::BigMsg) == bigMsg && result1 == smallMsg @? "Got garbled result" | otherwise = return () -- idling asyncSendRecv2ooo rank | rank == sender = do req1 <- isend commWorld receiver 123 smallMsg req2 <- isend commWorld receiver 456 bigMsg stat1 <- wait req1 checkStatusIfNotMPICH2 stat1 sender 123 stat2 <- wait req2 checkStatusIfNotMPICH2 stat2 sender 456 | rank == receiver = do future2 <- recvFuture commWorld sender 456 future1 <- recvFuture commWorld sender 123 result2 <- waitFuture future2 result1 <- waitFuture future1 stat1 <- getFutureStatus future1 stat2 <- getFutureStatus future2 checkStatus stat1 sender 123 checkStatus stat2 sender 456 (length (result2::BigMsg) == length bigMsg) && (result1 == smallMsg) @? "Got garbled result" | otherwise = return () -- idling crissCrossSendRecv rank | rank == sender = do req <- isend commWorld receiver 123 smallMsg future <- recvFuture commWorld receiver 456 result <- waitFuture future (length (result::BigMsg) == length bigMsg) @? "Got garbled BigMsg" status <- getFutureStatus future checkStatus status receiver 456 status2 <- wait req checkStatusIfNotMPICH2 status2 sender 123 | rank == receiver = do req <- isend commWorld sender 456 bigMsg future <- recvFuture commWorld sender 123 result <- waitFuture future (result == smallMsg) @? "Got garbled SmallMsg" status <- getFutureStatus future checkStatus status sender 123 status2 <- wait req checkStatusIfNotMPICH2 status2 receiver 456 | otherwise = return () -- idling waitallTest rank | rank == sender = do req1 <- isend commWorld receiver 123 smallMsg req2 <- isend commWorld receiver 789 smallMsg [stat1, stat2] <- waitall [req1, req2] checkStatusIfNotMPICH2 stat1 sender 123 checkStatusIfNotMPICH2 stat2 sender 789 | rank == receiver = do (msg1,_) <- recv commWorld sender 123 (msg2,_) <- recv commWorld sender 789 msg1 == smallMsg @? "Got garbled msg1" msg2 == smallMsg @? "Got garbled msg2" | otherwise = return () -- idling broadcastTest rank | rank == root = bcastSend commWorld sender bigMsg | otherwise = do result <- bcastRecv commWorld sender (result::BigMsg) == bigMsg @? "Got garbled BigMsg" gatherTest rank | rank == root = do result <- gatherRecv commWorld root [fromRank rank :: Int] numProcs <- commSize commWorld let expected = concat $ reverse $ take numProcs $ iterate Prelude.init [0..numProcs-1] got = concat (result::[[Int]]) got == expected @? "Got " ++ show got ++ " instead of " ++ show expected | otherwise = gatherSend commWorld root [0..fromRank rank :: Int] scatterTest rank | rank == root = do numProcs <- commSize commWorld result <- scatterSend commWorld root $ map (^(2::Int)) [1..numProcs] result == 1 @? "Root got " ++ show result ++ " instead of 1" | otherwise = do result <- scatterRecv commWorld root let expected = (fromRank rank + 1::Int)^(2::Int) result == expected @? "Got " ++ show result ++ " instead of " ++ show expected allgatherTest rank = do let msg = [fromRank rank] numProcs <- commSize commWorld result <- allgather commWorld msg let expected = map (:[]) [0..numProcs-1] result == expected @? "Got " ++ show result ++ " instead of " ++ show expected -- Each rank sends its own number (Int) with sendCounts [1,2,3..] -- Each rank receives Ints with recvCounts [rank+1,rank+1,rank+1,...] -- Rank 0 should receive 0,1,2 -- Rank 1 should receive 0,0,1,1,2,2 -- Rank 2 should receive 0,0,0,1,1,1,2,2,2 -- etc alltoallTest myRank = do numProcs <- commSize commWorld let myRankNo = fromRank myRank msg = take numProcs $ map (`take` (repeat myRankNo)) [1..] expected = map (replicate (myRankNo+1)) (take numProcs [0..]) result <- alltoall commWorld msg result == expected @? "Got " ++ show result ++ " instead of " ++ show expected
bjpop/haskell-mpi
test/SimpleTests.hs
bsd-3-clause
10,324
0
14
3,404
2,817
1,346
1,471
173
1
{-# LANGUAGE TemplateHaskell #-} -- -- Pins.hs -- definition of GPIO pins -- -- Copyright (C) 2013, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32F405.GPIO.Pins where import Ivory.BSP.STM32.Peripheral.GPIOF4.Regs import Ivory.BSP.STM32.Peripheral.GPIOF4.TH import Ivory.BSP.STM32F405.GPIO.Ports -- Each mkGPIOPins creates 16 pin values (with 0..15) using TH. -- so, pins will have values pinA0, pinA1 ... pinA15, etc. mkGPIOPins 'gpioA "pinA" mkGPIOPins 'gpioB "pinB" mkGPIOPins 'gpioC "pinC" mkGPIOPins 'gpioD "pinD" mkGPIOPins 'gpioE "pinE" mkGPIOPins 'gpioF "pinF" mkGPIOPins 'gpioG "pinG" mkGPIOPins 'gpioH "pinH" mkGPIOPins 'gpioI "pinI"
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32F405/GPIO/Pins.hs
bsd-3-clause
665
0
5
88
125
72
53
14
0
{-# LANGUAGE OverloadedStrings, PackageImports #-} import "monads-tf" Control.Monad.State import Data.Pipe import Data.Pipe.ByteString import System.IO import Network.Sasl import Network.Sasl.Plain.Client import qualified Data.ByteString as BS data St = St [(BS.ByteString, BS.ByteString)] deriving Show instance SaslState St where getSaslState (St s) = s putSaslState s _ = St s serverFile :: String serverFile = "examples/plainSv.txt" main :: IO () main = do let (_, (_, p)) = sasl r <- runPipe (fromFileLn serverFile =$= input =$= p =$= toHandleLn stdout) `runStateT` St [("authcid", "yoshikuni"), ("password", "password")] print r input :: Pipe BS.ByteString (Either Success BS.ByteString) (StateT St IO) () input = await >>= \mbs -> case mbs of Just "success" -> yield . Left $ Success Nothing Just ch -> yield (Right ch) >> input _ -> return ()
YoshikuniJujo/sasl
examples/clientP.hs
bsd-3-clause
868
2
14
143
325
174
151
25
3
import Parser import Compiler main :: IO () main = do code <- getContents case parse code of Nothing -> error "Parse error" Just parsed -> putStrLn $ compile parsed
roboguy13/MetaForth
src/MetaForth.hs
bsd-3-clause
183
0
11
48
64
30
34
8
2
module MsgPack.RPC.Types where import MsgPack import Control.Applicative ((<$>),(<*>)) import Data.Int (Int32) type MsgId = Int32 type Method = String -- Message Tags ---------------------------------------------------------------- data MessageType = MsgRequest | MsgResponse | MsgNotify deriving (Show) instance ToObject MessageType where toObject msg = case msg of MsgRequest -> toObject (0 :: Int) MsgResponse -> toObject (1 :: Int) MsgNotify -> toObject (2 :: Int) instance FromObject MessageType where fromObject obj = do n <- destObjectInt obj case n of 0 -> return MsgRequest 1 -> return MsgResponse 2 -> return MsgNotify _ -> fail "Invalid message type" -- Requests -------------------------------------------------------------------- data Request = Request { requestId :: MsgId , requestMethod :: Method , requestParams :: [Object] } deriving (Show) instance ToObject Request where toObject req = toObject [ toObject MsgRequest , toObject (requestId req) , toObject (requestMethod req) , toObject (requestParams req) ] instance FromObject Request where fromObject obj = do [ty,i,m,ps] <- fromObject obj MsgRequest <- fromObject ty Request <$> fromObject i <*> fromObject m <*> fromObject ps -- Responses ------------------------------------------------------------------- data Response = Response { responseId :: MsgId , responseResult :: Either Object [Object] } deriving (Show) instance ToObject Response where toObject resp = toObject $ toObject MsgResponse : toObject (responseId resp) : case responseResult resp of Left err -> [ err, toObject () ] Right res -> [ toObject (), toObject res ] instance FromObject Response where fromObject obj = do [ty,i,err,r] <- fromObject obj MsgResponse <- fromObject ty Response <$> fromObject i <*> case destObjectNil err of Just () -> Right `fmap` fromObject r Nothing -> return (Left err) -- Notifications --------------------------------------------------------------- data Notify = Notify { notifyMethod :: Method , notifyParams :: [Object] } deriving (Show) instance ToObject Notify where toObject n = toObject [ toObject MsgNotify , toObject (notifyMethod n) , toObject (notifyParams n) ] instance FromObject Notify where fromObject obj = do [ty,m,ps] <- fromObject obj MsgNotify <- fromObject ty Notify <$> fromObject m <*> fromObject ps
GaloisInc/msf-haskell
src/MsgPack/RPC/Types.hs
bsd-3-clause
2,625
0
14
650
749
387
362
76
0
module Sword.ViewPorter where import Sword.Utils import Sword.Hero type ViewPort = (Coord, Coord) insideViewPort :: ViewPort -> Coord -> Bool insideViewPort ((x1, y1), (x2, y2)) (x, y) = xinside && yinside where xinside = (x1 <= x) && (x < x2) yinside = (y1 <= y) && (y < y2) updateViewPort :: ViewPort -> Maybe Hero -> Coord -> ViewPort updateViewPort v Nothing _ = v updateViewPort ((x1, y1), (x2, y2)) (Just Hero{position = (c1, c2)}) (maxX, maxY) = ((x1', y1'), (x2', y2')) where viewPortX = (x1, x2) viewPortY = (y1, y2) (x1', x2') = updatePort c1 viewPortX (30, maxX) (y1', y2') = updatePort c2 viewPortY (2, maxY) updatePort :: Int -> Coord -> Coord -> Coord updatePort x (a, b) (pSize, pMax) | (x - a) <= pSize && a > 0 = (a - 1, b - 1) | (b - x) <= pSize && b <= pMax = (a + 1, b + 1) | otherwise = (a, b)
kmerz/the_sword
src/Sword/ViewPorter.hs
bsd-3-clause
862
0
12
208
445
253
192
20
1
module Main(main) where import Enterprise.FizzBuzz import System.Environment main = do putStrLn "How many numbers should I FizzBuzz?" n <- getLine putStrLn $ show $ fizzBuzzRange $ (read n :: Int)
JHawk/enterpriseFizzBuzz
src/Main.hs
bsd-3-clause
214
0
9
47
61
32
29
7
1
module Lava.MyST ( ST , STRef , newSTRef , readSTRef , writeSTRef , runST , fixST , unsafePerformST , unsafeInterleaveST , unsafeIOtoST ) where import System.IO import System.IO.Unsafe import Data.IORef newtype ST s a = ST (IO a) unST :: ST s a -> IO a unST (ST io) = io instance Functor (ST s) where fmap f (ST io) = ST (fmap f io) instance Monad (ST s) where return a = ST (return a) ST io >>= k = ST (do a <- io ; unST (k a)) newtype STRef s a = STRef (IORef a) instance Eq (STRef s a) where STRef r1 == STRef r2 = r1 == r2 newSTRef :: a -> ST s (STRef s a) newSTRef a = ST (STRef `fmap` newIORef a) readSTRef :: STRef s a -> ST s a readSTRef (STRef r) = ST (readIORef r) writeSTRef :: STRef s a -> a -> ST s () writeSTRef (STRef r) a = ST (writeIORef r a) runST :: (forall s . ST s a) -> a runST st = unsafePerformST st fixST :: (a -> ST s a) -> ST s a fixST f = ST (fixIO (unST . f)) unsafePerformST :: ST s a -> a unsafePerformST (ST io) = unsafePerformIO io unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST (ST io) = ST (unsafeInterleaveIO io) unsafeIOtoST :: IO a -> ST s a unsafeIOtoST = ST
dfordivam/lava
Lava/MyST.hs
bsd-3-clause
1,164
0
12
295
583
296
287
-1
-1
{-# LANGUAGE OverloadedStrings #-} import Network.HaskellNet.IMAP.SSL import Network.HaskellNet.SMTP.SSL as SMTP import Network.HaskellNet.Auth (AuthType(LOGIN)) import qualified Data.ByteString.Char8 as B username = "username@gmail.com" password = "password" recipient = "someone@somewhere.com" imapTest = do c <- connectIMAPSSLWithSettings "imap.gmail.com" cfg login c username password mboxes <- list c mapM_ print mboxes select c "INBOX" msgs <- search c [ALLs] let firstMsg = head msgs msgContent <- fetch c firstMsg B.putStrLn msgContent logout c where cfg = defaultSettingsIMAPSSL { sslMaxLineLength = 100000 } smtpTest = doSMTPSTARTTLS "smtp.gmail.com" $ \c -> do authSucceed <- SMTP.authenticate LOGIN username password c if authSucceed then print "Authentication error." else sendPlainTextMail recipient username subject body c where subject = "Test message" body = "This is a test message" main :: IO () main = smtpTest >> imapTest >> return ()
da-x/HaskellNet-SSL
examples/gmail.hs
bsd-3-clause
1,068
0
11
241
278
142
136
29
2
----------------------------------------------- module Board where import qualified Data.Map.Strict as Map import Color import Position ----------------------------------------------- nums = [1,2..19] -- last number defines size of board chars = ['A'..'Z'] ----------------------------------------------- newtype Board = Board(Map.Map Position Color) instance Show Board where show = showBoard instance Eq Board where Board m1 == Board m2 = m1 == m2 ----------------------------------------------- addToBoard :: Position -> Color -> Board -> Board addToBoard pos col board@(Board prevMap) | checkPos pos board = Board(Map.insert pos col prevMap) | otherwise = board getPosColor :: Position -> Board -> Maybe Color getPosColor pos (Board boardMap) = Map.lookup pos boardMap getKeys :: Board -> [Position] getKeys (Board boardMap) = Map.keys boardMap --------------- showing board ----------------- showBoard :: Board -> String showBoard board = "\n" ++ upDownLabel ++ getAllStringRows board ++ upDownLabel showDisc :: Board -> Position -> String showDisc (Board boardMap) pos |Map.member pos boardMap = show (unJust(Map.lookup pos boardMap)) ++ " " |otherwise = "- " getStringRow :: Board -> Int -> String getStringRow board row = concat [showDisc board (Position row col) | col <- nums] packRowChars :: Board -> Int -> String packRowChars board row = charToStr (chars !! (row - 1)) ++ " " ++ getStringRow board row ++ charToStr(chars !! (row - 1)) packRowNums :: Board -> Int -> String packRowNums board row = leftSideLabelPack (nums !! (row - 1)) ++ " " ++ getStringRow board row ++ show (nums !! (row - 1)) getAllStringRows :: Board -> String getAllStringRows board = concat [packRowNums board row ++ "\n" | row <- nums] leftSideLabelPack :: Int -> String leftSideLabelPack num | (num > 0) && (num < 10) = " " ++ show num | otherwise = show num upDownLabel :: String upDownLabel = " " ++ concat [charToStr c ++ " " | c <- take (last nums) chars] ++ "\n" ---------- check position within board -------- checkPosRange :: Position -> Bool checkPosRange (Position x y) | x > 0 && x < (last nums + 1) && y > 0 && y < (last nums + 1) = True | otherwise = False checkPosAvailable :: Position -> Board -> Bool checkPosAvailable pos (Board boardMap) | Map.notMember pos boardMap = True | otherwise = False checkPos :: Position -> Board -> Bool checkPos pos board = checkPosRange pos && checkPosAvailable pos board --------- check neighbors within board -------- checkPointNeighbors :: Position -> Board -> [Position] checkPointNeighbors pos board = [n | n <- getPointNeighbors pos, checkPos n board] ---------------- helpful ------------------ charToStr :: Char -> String charToStr c = [c]
irmikrys/Gomoku
src/Board.hs
bsd-3-clause
2,825
0
15
565
951
483
468
55
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} module ETA.Utils.Maybes ( module Data.Maybe, MaybeErr(..), -- Instance of Monad failME, isSuccess, orElse, firstJust, firstJusts, whenIsJust, expectJust, MaybeT(..), liftMaybeT ) where import Control.Applicative import Control.Monad import Data.Maybe infixr 4 `orElse` {- ************************************************************************ * * \subsection[Maybe type]{The @Maybe@ type} * * ************************************************************************ -} firstJust :: Maybe a -> Maybe a -> Maybe a firstJust a b = firstJusts [a, b] -- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or -- @Nothing@ otherwise. firstJusts :: [Maybe a] -> Maybe a firstJusts = msum expectJust :: String -> Maybe a -> a {-# INLINE expectJust #-} expectJust _ (Just x) = x expectJust err Nothing = error ("expectJust " ++ err) whenIsJust :: Monad m => Maybe a -> (a -> m ()) -> m () whenIsJust (Just x) f = f x whenIsJust Nothing _ = return () -- | Flipped version of @fromMaybe@, useful for chaining. orElse :: Maybe a -> a -> a orElse = flip fromMaybe {- ************************************************************************ * * \subsection[MaybeT type]{The @MaybeT@ monad transformer} * * ************************************************************************ -} newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)} instance Functor m => Functor (MaybeT m) where fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x instance (Monad m, Functor m) => Applicative (MaybeT m) where pure = return (<*>) = ap instance Monad m => Monad (MaybeT m) where return = MaybeT . return . Just x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f) fail _ = MaybeT $ return Nothing -- TODO:#if __GLASGOW_HASKELL__ < 710 -- -- Pre-AMP change -- instance (Monad m, Functor m) => Alternative (MaybeT m) where -- #else instance (Monad m) => Alternative (MaybeT m) where -- #endif empty = mzero (<|>) = mplus instance Monad m => MonadPlus (MaybeT m) where mzero = MaybeT $ return Nothing p `mplus` q = MaybeT $ do ma <- runMaybeT p case ma of Just a -> return (Just a) Nothing -> runMaybeT q liftMaybeT :: Monad m => m a -> MaybeT m a liftMaybeT act = MaybeT $ Just `liftM` act {- ************************************************************************ * * \subsection[MaybeErr type]{The @MaybeErr@ type} * * ************************************************************************ -} data MaybeErr err val = Succeeded val | Failed err instance Functor (MaybeErr err) where fmap = liftM instance Applicative (MaybeErr err) where pure = return (<*>) = ap instance Monad (MaybeErr err) where return v = Succeeded v Succeeded v >>= k = k v Failed e >>= _ = Failed e isSuccess :: MaybeErr err val -> Bool isSuccess (Succeeded {}) = True isSuccess (Failed {}) = False failME :: err -> MaybeErr err val failME e = Failed e
alexander-at-github/eta
compiler/ETA/Utils/Maybes.hs
bsd-3-clause
3,588
0
14
1,114
868
455
413
62
1
{-| Module : Data.Number.MPFR.Mutable Description : Mutable MPFR's Copyright : (c) Aleš Bizjak License : BSD3 Maintainer : ales.bizjak0@gmail.com Stability : experimental Portability : non-portable This module provides a \"mutable\" interface to the MPFR library. Functions i this module should have very little overhead over the original @C@ functions. Type signatures of functions should be self-explanatory. Order of arguments is identical to the one in @C@ functions. See MPFR manual for documentation on particular functions. All operations are performed in the 'ST' monad so safe transition between mutable and immutable interface is possible with 'runST'. For example mutable interface could be used in inner loops or in local calculations with temporary variables, helping reduce allocation overhead of the pure interface. -} {-# INCLUDE <mpfr.h> #-} {-# INCLUDE <chsmpfr.h> #-} module Data.Number.MPFR.Mutable ( MMPFR, -- * Utility functions thaw, writeMMPFR, freeze, unsafeThaw, unsafeWriteMMPFR, unsafeFreeze, -- * Basic arithmetic functions -- | For documentation on particular functions see -- <http://www.mpfr.org/mpfr-current/mpfr.html#Basic-Arithmetic-Functions> module Data.Number.MPFR.Mutable.Arithmetic, -- * Special functions -- | For documentation on particular functions see -- <http://www.mpfr.org/mpfr-current/mpfr.html#Special-Functions> module Data.Number.MPFR.Mutable.Special, -- * Miscellaneous functions -- | For documentation on particular functions see -- <http://www.mpfr.org/mpfr-current/mpfr.html#Miscellaneous functions> module Data.Number.MPFR.Mutable.Misc, -- * Integer related functions -- | For documentation on particular functions see -- <http://www.mpfr.org/mpfr-current/mpfr.html#Integer-Related-Functions> module Data.Number.MPFR.Mutable.Integer ) where import Data.Number.MPFR.Mutable.Arithmetic import Data.Number.MPFR.Mutable.Special import Data.Number.MPFR.Mutable.Misc import Data.Number.MPFR.Mutable.Integer import Data.Number.MPFR.Mutable.Internal
ekmett/hmpfr
src/Data/Number/MPFR/Mutable.hs
bsd-3-clause
2,166
0
5
388
123
95
28
13
0
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleContexts #-} -- | -- Module : Simulation.Aivika.Trans.Experiment.Types -- Copyright : Copyright (c) 2012-2017, David Sorokin <david.sorokin@gmail.com> -- License : BSD3 -- Maintainer : David Sorokin <david.sorokin@gmail.com> -- Stability : experimental -- Tested with: GHC 8.0.1 -- -- The module defines the simulation experiments. They automate -- the process of generating and analyzing the results. Moreover, -- this module is open to extensions, allowing you to define -- your own output views for the simulation results, for example, -- such views that would allow saving the results in PDF or as -- charts. To decrease the number of dependencies, such possible -- extenstions are not included in this package, although simple -- views are provided. -- module Simulation.Aivika.Trans.Experiment.Types where import Control.Monad import Control.Exception import Data.Maybe import Data.Monoid import Data.Either import GHC.Conc (getNumCapabilities) import Simulation.Aivika.Trans -- | It defines the simulation experiment with the specified rendering backend and its bound data. data Experiment m = Experiment { experimentSpecs :: Specs m, -- ^ The simulation specs for the experiment. experimentTransform :: ResultTransform m, -- ^ How the results must be transformed before rendering. experimentLocalisation :: ResultLocalisation, -- ^ Specifies a localisation applied when rendering the experiment. experimentRunCount :: Int, -- ^ How many simulation runs should be launched. experimentTitle :: String, -- ^ The experiment title. experimentDescription :: String, -- ^ The experiment description. experimentVerbose :: Bool, -- ^ Whether the process of generating the results is verbose. experimentNumCapabilities :: IO Int -- ^ The number of threads used for the Monte-Carlo simulation -- if the executable was compiled with the support of multi-threading. } -- | The default experiment. defaultExperiment :: Experiment m defaultExperiment = Experiment { experimentSpecs = Specs 0 10 0.01 RungeKutta4 SimpleGenerator, experimentTransform = id, experimentLocalisation = englishResultLocalisation, experimentRunCount = 1, experimentTitle = "Simulation Experiment", experimentDescription = "", experimentVerbose = True, experimentNumCapabilities = getNumCapabilities } -- | Allows specifying the experiment monad. class ExperimentMonadProviding r (m :: * -> *) where -- | Defines the experiment monad type. type ExperimentMonad r m :: * -> * -- | Defines the experiment computation that tries to perform the calculation. type ExperimentMonadTry r m a = ExperimentMonad r m (Either SomeException a) -- | It allows rendering the simulation results in an arbitrary way. class ExperimentMonadProviding r m => ExperimentRendering r m where -- | Defines a context used when rendering the experiment. data ExperimentContext r m :: * -- | Defines the experiment environment. type ExperimentEnvironment r m :: * -- | Prepare before rendering the experiment. prepareExperiment :: Experiment m -> r -> ExperimentMonad r m (ExperimentEnvironment r m) -- | Render the experiment after the simulation is finished, for example, -- creating the @index.html@ file in the specified directory. renderExperiment :: Experiment m -> r -> [ExperimentReporter r m] -> ExperimentEnvironment r m -> ExperimentMonad r m () -- | It is called when the experiment has been completed. onExperimentCompleted :: Experiment m -> r -> ExperimentEnvironment r m -> ExperimentMonad r m () -- | It is called when the experiment rendering has failed. onExperimentFailed :: Exception e => Experiment m -> r -> ExperimentEnvironment r m -> e -> ExperimentMonad r m () -- | This is a generator of the reporter with the specified rendering backend. data ExperimentGenerator r m = ExperimentGenerator { generateReporter :: Experiment m -> r -> ExperimentEnvironment r m -> ExperimentMonad r m (ExperimentReporter r m) -- ^ Generate a reporter. } -- | Defines a view in which the simulation results should be saved. -- You should extend this type class to define your own views such -- as the PDF document. class ExperimentRendering r m => ExperimentView v r m where -- | Create a generator of the reporter. outputView :: v m -> ExperimentGenerator r m -- | It describes the source simulation data used in the experiment. data ExperimentData m = ExperimentData { experimentResults :: Results m, -- ^ The simulation results used in the experiment. experimentPredefinedSignals :: ResultPredefinedSignals m -- ^ The predefined signals provided by every model. } -- | Defines what creates the simulation reports by the specified renderer. data ExperimentReporter r m = ExperimentReporter { reporterInitialise :: ExperimentMonad r m (), -- ^ Initialise the reporting before -- the simulation runs are started. reporterFinalise :: ExperimentMonad r m (), -- ^ Finalise the reporting after -- all simulation runs are finished. reporterSimulate :: ExperimentData m -> Composite m (), -- ^ Start the simulation run in the start time. reporterContext :: ExperimentContext r m -- ^ Return a context used by the renderer. } -- | Run the simulation experiment sequentially. runExperiment_ :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => (m () -> ExperimentMonad r m a) -- ^ the function that actually starts the simulation run -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> ExperimentMonadTry r m () {-# INLINABLE runExperiment_ #-} runExperiment_ executor0 e generators r simulation = do x <- runExperimentWithExecutor executor e generators r simulation return (x >> return ()) where executor = sequence_ . map executor0 -- | Run the simulation experiment sequentially. runExperiment :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => (m () -> ExperimentMonad r m a) -- ^ the function that actually starts the simulation run -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> ExperimentMonadTry r m [a] {-# INLINABLE runExperiment #-} runExperiment executor0 = runExperimentWithExecutor executor where executor = sequence . map executor0 -- | Run the simulation experiment with the specified executor. runExperimentWithExecutor :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => ([m ()] -> ExperimentMonad r m a) -- ^ an executor that allows parallelizing the simulation if required -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> ExperimentMonadTry r m a {-# INLINABLE runExperimentWithExecutor #-} runExperimentWithExecutor executor e generators r simulation = do let specs = experimentSpecs e runCount = experimentRunCount e env <- prepareExperiment e r let c1 = do reporters <- mapM (\x -> generateReporter x e r env) generators forM_ reporters reporterInitialise let simulate = do signals <- newResultPredefinedSignals results <- simulation let d = ExperimentData { experimentResults = experimentTransform e results, experimentPredefinedSignals = signals } ((), fs) <- runDynamicsInStartTime $ runEventWith EarlierEvents $ flip runComposite mempty $ forM_ reporters $ \reporter -> reporterSimulate reporter d let m1 = runEventInStopTime $ return () m2 = runEventInStopTime $ disposeEvent fs mh (SimulationAbort e') = return () finallySimulation (catchSimulation m1 mh) m2 a <- executor $ runSimulations simulate specs runCount forM_ reporters reporterFinalise renderExperiment e r reporters env onExperimentCompleted e r env return (Right a) ch z@(SomeException e') = do onExperimentFailed e r env e' return (Left z) catchComp c1 ch -- | Run the simulation experiment by the specified run index in series. runExperimentByIndex :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => (m () -> ExperimentMonad r m a) -- ^ the function that actually starts the simulation run -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> Int -- ^ the index of the current run (started from 1) -> ExperimentMonadTry r m a {-# INLINABLE runExperimentByIndex #-} runExperimentByIndex executor e generators r simulation runIndex = do let specs = experimentSpecs e runCount = experimentRunCount e env <- prepareExperiment e r let c1 = do reporters <- mapM (\x -> generateReporter x e r env) generators forM_ reporters reporterInitialise let simulate = do signals <- newResultPredefinedSignals results <- simulation let d = ExperimentData { experimentResults = experimentTransform e results, experimentPredefinedSignals = signals } ((), fs) <- runDynamicsInStartTime $ runEventWith EarlierEvents $ flip runComposite mempty $ forM_ reporters $ \reporter -> reporterSimulate reporter d let m1 = runEventInStopTime $ return () m2 = runEventInStopTime $ disposeEvent fs mh (SimulationAbort e') = return () finallySimulation (catchSimulation m1 mh) m2 a <- executor $ runSimulationByIndex simulate specs runCount runIndex forM_ reporters reporterFinalise renderExperiment e r reporters env onExperimentCompleted e r env return (Right a) ch z@(SomeException e') = do onExperimentFailed e r env e' return (Left z) catchComp c1 ch -- | Run the simulation experiment by the specified run index in series. runExperimentByIndex_ :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => (m () -> ExperimentMonad r m a) -- ^ the function that actually starts the simulation run -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> Int -- ^ the index of the current run (started from 1) -> ExperimentMonadTry r m () {-# INLINABLE runExperimentByIndex_ #-} runExperimentByIndex_ executor e generators r simulation runIndex = do x <- runExperimentByIndex executor e generators r simulation runIndex return (x >> return ()) -- | Run the simulation experiment by the specified run index in series -- returning the continuation of the actual computation. runExperimentContByIndex :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => (m () -> ExperimentMonad r m (a, ExperimentMonad r m b)) -- ^ the function that actually starts the simulation run -- and returns the corresponding continuation -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> Int -- ^ the index of the current run (started from 1) -> ExperimentMonadTry r m (a, ExperimentMonadTry r m b) {-# INLINABLE runExperimentContByIndex #-} runExperimentContByIndex executor e generators r simulation runIndex = do let specs = experimentSpecs e runCount = experimentRunCount e env <- prepareExperiment e r let c1 = do reporters <- mapM (\x -> generateReporter x e r env) generators forM_ reporters reporterInitialise let simulate = do signals <- newResultPredefinedSignals results <- simulation let d = ExperimentData { experimentResults = experimentTransform e results, experimentPredefinedSignals = signals } ((), fs) <- runDynamicsInStartTime $ runEventWith EarlierEvents $ flip runComposite mempty $ forM_ reporters $ \reporter -> reporterSimulate reporter d let m1 = runEventInStopTime $ return () m2 = runEventInStopTime $ disposeEvent fs mh (SimulationAbort e') = return () finallySimulation (catchSimulation m1 mh) m2 (a, m) <- executor $ runSimulationByIndex simulate specs runCount runIndex let m2 = do b <- m forM_ reporters reporterFinalise renderExperiment e r reporters env onExperimentCompleted e r env return (Right b) mh z@(SomeException e') = do onExperimentFailed e r env e' return (Left z) return (Right (a, catchComp m2 mh)) ch z@(SomeException e') = do onExperimentFailed e r env e' return (Left z) catchComp c1 ch -- | Run the simulation experiment by the specified run index in series -- returning the continuation of the actual computation. runExperimentContByIndex_ :: (MonadDES m, ExperimentRendering r m, Monad (ExperimentMonad r m), MonadException (ExperimentMonad r m)) => (m () -> ExperimentMonad r m (a, ExperimentMonad r m b)) -- ^ the function that actually starts the simulation run -- and returns the corresponding continuation -> Experiment m -- ^ the simulation experiment to run -> [ExperimentGenerator r m] -- ^ generators used for rendering -> r -- ^ the rendering backend -> Simulation m (Results m) -- ^ the simulation results received from the model -> Int -- ^ the index of the current run (started from 1) -> ExperimentMonadTry r m (a, ExperimentMonadTry r m ()) {-# INLINABLE runExperimentContByIndex_ #-} runExperimentContByIndex_ executor e generators r simulation runIndex = do x <- runExperimentContByIndex executor e generators r simulation runIndex case x of Left e -> return (Left e) Right (a, cont) -> return $ Right (a, cont >> return (Right ()))
dsorokin/aivika-experiment
Simulation/Aivika/Trans/Experiment/Types.hs
bsd-3-clause
19,767
0
22
8,087
3,110
1,583
1,527
255
2
module Superfuse.Frontend where import Data.Int import Data.Kind import Data.Word import GHC.TypeLits -- | Signed integral types data IType = I8 | I16 | I32 | I64 -- | Unsigned integral types data UType = U8 | U16 | U32 | U64 -- | Floating-point types data FType = F32 | F64 -- | Scalar types data SType = SIType IType | SUType UType | SBType | SFType FType -- | Scalar types' corresponding Haskell types type family HsSType t = h | h -> t where HsSType ('SIType 'I8) = Int8 HsSType ('SIType 'I16) = Int16 HsSType ('SIType 'I32) = Int32 HsSType ('SIType 'I64) = Int64 HsSType ('SUType 'U8) = Word8 HsSType ('SUType 'U16) = Word16 HsSType ('SUType 'U32) = Word32 HsSType ('SUType 'U64) = Word64 HsSType ('SBType) = Bool HsSType ('SFType 'F32) = Float HsSType ('SFType 'F64) = Double -- | Scalar unary operators. data SUnOp :: SType -> Type where Neg :: SUnOp t Abs :: SUnOp t -- | Scalar binary operators. The Bool indicates whether it satisfies monoid laws. data SBinOp :: SType -> Bool -> Type where Add, Mul :: SBinOp t 'True Sub, Div :: SBinOp t 'False Max, Min :: SBinOp t 'True -- | Vector expressions data VExpr :: SType -> Nat -> Type where SLift :: HsSType t -> VExpr t 0 SCopy :: VExpr t 0 -> VExpr t dim VReshape :: VExpr t dim -> VExpr t dim' VCoerce :: VExpr t dim -> VExpr t' dim VUnApp :: SUnOp t -> VExpr t dim -> VExpr t dim VBinApp :: SBinOp t f -> VExpr t dim -> VExpr t dim -> VExpr t dim VFold :: SBinOp t 'True -> VExpr t dim -> VExpr t 0 VFoldl, VFoldr :: SBinOp t f -> VExpr t 0 -> VExpr t dim -> VExpr t 0
TerrorJack/superfuse
src/Superfuse/Frontend.hs
bsd-3-clause
1,697
36
10
475
605
324
281
-1
-1
{-# LANGUAGE CPP #-} -- ----------------------------------------------------------------------------- -- -- Main.hs, part of Alex -- -- (c) Chris Dornan 1995-2000, Simon Marlow 2003 -- -- ----------------------------------------------------------------------------} module Main (main) where import AbsSyn import CharSet import DFA import DFAMin import NFA import Info import Map ( Map ) import qualified Map hiding ( Map ) import Output import ParseMonad ( runP, Warning(..) ) import Parser import Scan import Util ( hline ) import Paths_alex ( version, getDataDir ) #if __GLASGOW_HASKELL__ < 610 import Control.Exception as Exception ( block, unblock, catch, throw ) #endif #if __GLASGOW_HASKELL__ >= 610 import Control.Exception ( bracketOnError ) #endif import Control.Monad ( when, liftM ) import Data.Char ( chr ) import Data.List ( isSuffixOf, nub ) import Data.Version ( showVersion ) import System.Console.GetOpt ( getOpt, usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..) ) import System.Directory ( removeFile ) import System.Environment ( getProgName, getArgs ) import System.Exit ( ExitCode(..), exitWith ) import System.IO ( stderr, Handle, IOMode(..), openFile, hClose, hPutStr, hPutStrLn ) #if __GLASGOW_HASKELL__ >= 612 import System.IO ( hGetContents, hSetEncoding, utf8 ) #endif -- We need to force every file we open to be read in -- as UTF8 alexReadFile :: FilePath -> IO String #if __GLASGOW_HASKELL__ >= 612 alexReadFile file = do h <- alexOpenFile file ReadMode hGetContents h #else alexReadFile = readFile #endif -- We need to force every file we write to be written -- to as UTF8 alexOpenFile :: FilePath -> IOMode -> IO Handle #if __GLASGOW_HASKELL__ >= 612 alexOpenFile file mode = do h <- openFile file mode hSetEncoding h utf8 return h #else alexOpenFile = openFile #endif -- `main' decodes the command line arguments and calls `alex'. main:: IO () main = do args <- getArgs case getOpt Permute argInfo args of (cli,_,[]) | DumpHelp `elem` cli -> do prog <- getProgramName bye (usageInfo (usageHeader prog) argInfo) (cli,_,[]) | DumpVersion `elem` cli -> bye copyright (cli,[file],[]) -> runAlex cli file (_,_,errors) -> do prog <- getProgramName die (concat errors ++ usageInfo (usageHeader prog) argInfo) projectVersion :: String projectVersion = showVersion version copyright :: String copyright = "Alex version " ++ projectVersion ++ ", (c) 2003 Chris Dornan and Simon Marlow\n" usageHeader :: String -> String usageHeader prog = "Usage: " ++ prog ++ " [OPTION...] file\n" runAlex :: [CLIFlags] -> FilePath -> IO () runAlex cli file = do basename <- case (reverse file) of 'x':'.':r -> return (reverse r) _ -> die (file ++ ": filename must end in \'.x\'\n") prg <- alexReadFile file script <- parseScript file prg alex cli file basename script parseScript :: FilePath -> String -> IO (Maybe (AlexPosn,Code), [Directive], Scanner, Maybe (AlexPosn,Code)) parseScript file prg = case runP prg initialParserEnv parse of Left (Just (AlexPn _ line col),err) -> die (file ++ ":" ++ show line ++ ":" ++ show col ++ ": " ++ err ++ "\n") Left (Nothing, err) -> die (file ++ ": " ++ err ++ "\n") Right (warnings, script@(_, _, scanner, _)) -> do -- issue 46: give proper error when lexer definition is empty when (null $ scannerTokens scanner) $ dieAlex $ file ++ " contains no lexer rules\n" -- issue 71: warn about nullable regular expressions mapM_ printWarning warnings return script where printWarning (WarnNullableRExp (AlexPn _ line col) msg) = hPutStrLn stderr $ concat [ "Warning: " , file , ":", show line , ":" , show col , ": " , msg ] alex :: [CLIFlags] -> FilePath -> FilePath -> (Maybe (AlexPosn, Code), [Directive], Scanner, Maybe (AlexPosn, Code)) -> IO () alex cli file basename script = do (put_info, finish_info) <- case [ f | OptInfoFile f <- cli ] of [] -> return (\_ -> return (), return ()) [Nothing] -> infoStart file (basename ++ ".info") [Just f] -> infoStart file f _ -> dieAlex "multiple -i/--info options" o_file <- case [ f | OptOutputFile f <- cli ] of [] -> return (basename ++ ".hs") [f] -> return f _ -> dieAlex "multiple -o/--outfile options" tab_size <- case [ s | OptTabSize s <- cli ] of [] -> return (8 :: Int) [s] -> case reads s of [(n,"")] -> return n _ -> dieAlex "-s/--tab-size option is not a valid integer" _ -> dieAlex "multiple -s/--tab-size options" let target | OptGhcTarget `elem` cli = GhcTarget | otherwise = HaskellTarget let encodingsCli | OptLatin1 `elem` cli = [Latin1] | otherwise = [] template_dir <- templateDir getDataDir cli let maybe_header, maybe_footer :: Maybe (AlexPosn, Code) directives :: [Directive] scanner1 :: Scanner (maybe_header, directives, scanner1, maybe_footer) = script scheme <- getScheme directives -- open the output file; remove it if we encounter an error bracketOnError (alexOpenFile o_file WriteMode) (\h -> do hClose h; removeFile o_file) $ \out_h -> do let scanner2, scanner_final :: Scanner scs :: [StartCode] sc_hdr, actions :: ShowS encodingsScript :: [Encoding] (scanner2, scs, sc_hdr) = encodeStartCodes scanner1 (scanner_final, actions) = extractActions scheme scanner2 encodingsScript = [ e | EncodingDirective e <- directives ] encoding <- case nub (encodingsCli ++ encodingsScript) of [] -> return UTF8 -- default [e] -> return e _ | null encodingsCli -> dieAlex "conflicting %encoding directives" | otherwise -> dieAlex "--latin1 flag conflicts with %encoding directive" mapM_ (hPutStrLn out_h) (optsToInject target cli) injectCode maybe_header file out_h hPutStr out_h (importsToInject target cli) -- add the wrapper, if necessary case wrapperCppDefs scheme of Nothing -> return () Just cppDefs -> do let wrapper_name = template_dir ++ "/AlexWrappers.hs" mapM_ (hPutStrLn out_h) [ unwords ["#define", i, "1"] | i <- cppDefs ] str <- alexReadFile wrapper_name hPutStr out_h str -- Inject the tab size hPutStrLn out_h $ "alex_tab_size :: Int" hPutStrLn out_h $ "alex_tab_size = " ++ show (tab_size :: Int) let dfa = scanner2dfa encoding scanner_final scs min_dfa = minimizeDFA dfa nm = scannerName scanner_final usespreds = usesPreds min_dfa put_info "\nStart codes\n" put_info (show $ scs) put_info "\nScanner\n" put_info (show $ scanner_final) put_info "\nNFA\n" put_info (show $ scanner2nfa encoding scanner_final scs) put_info "\nDFA" put_info (infoDFA 1 nm dfa "") put_info "\nMinimized DFA" put_info (infoDFA 1 nm min_dfa "") hPutStr out_h (outputDFA target 1 nm scheme min_dfa "") injectCode maybe_footer file out_h hPutStr out_h (sc_hdr "") hPutStr out_h (actions "") -- add the template do let cppDefs = templateCppDefs target encoding usespreds cli mapM_ (hPutStrLn out_h) [ unwords ["#define", i, "1"] | i <- cppDefs ] tmplt <- alexReadFile $ template_dir ++ "/AlexTemplate.hs" hPutStr out_h tmplt hClose out_h finish_info getScheme :: [Directive] -> IO Scheme getScheme directives = do token <- case [ ty | TokenType ty <- directives ] of [] -> return Nothing [res] -> return (Just res) _ -> dieAlex "multiple %token directives" action <- case [ ty | ActionType ty <- directives ] of [] -> return Nothing [res] -> return (Just res) _ -> dieAlex "multiple %action directives" typeclass <- case [ tyclass | TypeClass tyclass <- directives ] of [] -> return Nothing [res] -> return (Just res) _ -> dieAlex "multiple %typeclass directives" case [ f | WrapperDirective f <- directives ] of [] -> case (typeclass, token, action) of (Nothing, Nothing, Nothing) -> return Default { defaultTypeInfo = Nothing } (Nothing, Nothing, Just actionty) -> return Default { defaultTypeInfo = Just (Nothing, actionty) } (Just _, Nothing, Just actionty) -> return Default { defaultTypeInfo = Just (typeclass, actionty) } (_, Just _, _) -> dieAlex "%token directive only allowed with a wrapper" (Just _, Nothing, Nothing) -> dieAlex "%typeclass directive without %token directive" [single] | single == "gscan" -> case (typeclass, token, action) of (Nothing, Nothing, Nothing) -> return GScan { gscanTypeInfo = Nothing } (Nothing, Just tokenty, Nothing) -> return GScan { gscanTypeInfo = Just (Nothing, tokenty) } (Just _, Just tokenty, Nothing) -> return GScan { gscanTypeInfo = Just (typeclass, tokenty) } (_, _, Just _) -> dieAlex "%action directive not allowed with a wrapper" (Just _, Nothing, Nothing) -> dieAlex "%typeclass directive without %token directive" | single == "basic" || single == "basic-bytestring" || single == "strict-bytestring" -> let strty = case single of "basic" -> Str "basic-bytestring" -> Lazy "strict-bytestring" -> Strict _ -> error "Impossible case" in case (typeclass, token, action) of (Nothing, Nothing, Nothing) -> return Basic { basicStrType = strty, basicTypeInfo = Nothing } (Nothing, Just tokenty, Nothing) -> return Basic { basicStrType = strty, basicTypeInfo = Just (Nothing, tokenty) } (Just _, Just tokenty, Nothing) -> return Basic { basicStrType = strty, basicTypeInfo = Just (typeclass, tokenty) } (_, _, Just _) -> dieAlex "%action directive not allowed with a wrapper" (Just _, Nothing, Nothing) -> dieAlex "%typeclass directive without %token directive" | single == "posn" || single == "posn-bytestring" -> let isByteString = single == "posn-bytestring" in case (typeclass, token, action) of (Nothing, Nothing, Nothing) -> return Posn { posnByteString = isByteString, posnTypeInfo = Nothing } (Nothing, Just tokenty, Nothing) -> return Posn { posnByteString = isByteString, posnTypeInfo = Just (Nothing, tokenty) } (Just _, Just tokenty, Nothing) -> return Posn { posnByteString = isByteString, posnTypeInfo = Just (typeclass, tokenty) } (_, _, Just _) -> dieAlex "%action directive not allowed with a wrapper" (Just _, Nothing, Nothing) -> dieAlex "%typeclass directive without %token directive" | single == "monad" || single == "monad-bytestring" || single == "monadUserState" || single == "monadUserState-bytestring" -> let isByteString = single == "monad-bytestring" || single == "monadUserState-bytestring" userState = single == "monadUserState" || single == "monadUserState-bytestring" in case (typeclass, token, action) of (Nothing, Nothing, Nothing) -> return Monad { monadByteString = isByteString, monadUserState = userState, monadTypeInfo = Nothing } (Nothing, Just tokenty, Nothing) -> return Monad { monadByteString = isByteString, monadUserState = userState, monadTypeInfo = Just (Nothing, tokenty) } (Just _, Just tokenty, Nothing) -> return Monad { monadByteString = isByteString, monadUserState = userState, monadTypeInfo = Just (typeclass, tokenty) } (_, _, Just _) -> dieAlex "%action directive not allowed with a wrapper" (Just _, Nothing, Nothing) -> dieAlex "%typeclass directive without %token directive" | otherwise -> dieAlex ("unknown wrapper type " ++ single) _many -> dieAlex "multiple %wrapper directives" -- inject some code, and add a {-# LINE #-} pragma at the top injectCode :: Maybe (AlexPosn,Code) -> FilePath -> Handle -> IO () injectCode Nothing _ _ = return () injectCode (Just (AlexPn _ ln _,code)) filename hdl = do hPutStrLn hdl ("{-# LINE " ++ show ln ++ " \"" ++ filename ++ "\" #-}") hPutStrLn hdl code optsToInject :: Target -> [CLIFlags] -> [String] optsToInject target _ = optNoWarnings : "{-# LANGUAGE CPP #-}" : case target of GhcTarget -> ["{-# LANGUAGE MagicHash #-}"] _ -> [] optNoWarnings :: String optNoWarnings = "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-missing-signatures #-}" importsToInject :: Target -> [CLIFlags] -> String importsToInject _ cli = always_imports ++ debug_imports ++ glaexts_import where glaexts_import | OptGhcTarget `elem` cli = import_glaexts | otherwise = "" debug_imports | OptDebugParser `elem` cli = import_debug | otherwise = "" -- CPP is turned on for -fglasogw-exts, so we can use conditional -- compilation. We need to #include "config.h" to get hold of -- WORDS_BIGENDIAN (see AlexTemplate.hs). always_imports :: String always_imports = "#if __GLASGOW_HASKELL__ >= 603\n" ++ "#include \"ghcconfig.h\"\n" ++ "#elif defined(__GLASGOW_HASKELL__)\n" ++ "#include \"config.h\"\n" ++ "#endif\n" ++ "#if __GLASGOW_HASKELL__ >= 503\n" ++ "import Data.Array\n" ++ "#else\n" ++ "import Array\n" ++ "#endif\n" import_glaexts :: String import_glaexts = "#if __GLASGOW_HASKELL__ >= 503\n" ++ "import Data.Array.Base (unsafeAt)\n" ++ "import GHC.Exts\n" ++ "#else\n" ++ "import GlaExts\n" ++ "#endif\n" import_debug :: String import_debug = "#if __GLASGOW_HASKELL__ >= 503\n" ++ "import System.IO\n" ++ "import System.IO.Unsafe\n" ++ "import Debug.Trace\n" ++ "#else\n" ++ "import IO\n" ++ "import IOExts\n" ++ "#endif\n" templateDir :: IO FilePath -> [CLIFlags] -> IO FilePath templateDir def cli = case [ d | OptTemplateDir d <- cli ] of [] -> def ds -> return (last ds) templateCppDefs :: Target -> Encoding -> UsesPreds -> [CLIFlags] -> [String] templateCppDefs target encoding usespreds cli = map ("ALEX_" ++) $ concat [ [ "GHC" | target == GhcTarget ] , [ "LATIN1" | encoding == Latin1 ] , [ "NOPRED" | usespreds == DoesntUsePreds ] , [ "DEBUG" | OptDebugParser `elem` cli ] ] infoStart :: FilePath -> FilePath -> IO (String -> IO (), IO ()) infoStart x_file info_file = do bracketOnError (alexOpenFile info_file WriteMode) (\h -> do hClose h; removeFile info_file) (\h -> do infoHeader h x_file return (hPutStr h, hClose h) ) infoHeader :: Handle -> FilePath -> IO () infoHeader h file = do -- hSetBuffering h NoBuffering hPutStrLn h ("Info file produced by Alex version " ++ projectVersion ++ ", from " ++ file) hPutStrLn h hline hPutStr h "\n" initialParserEnv :: (Map String CharSet, Map String RExp) initialParserEnv = (initSetEnv, initREEnv) initSetEnv :: Map String CharSet initSetEnv = Map.fromList [("white", charSet " \t\n\v\f\r"), ("printable", charSetRange (chr 32) (chr 0x10FFFF)), -- FIXME: Look it up the unicode standard (".", charSetComplement emptyCharSet `charSetMinus` charSetSingleton '\n')] initREEnv :: Map String RExp initREEnv = Map.empty -- ----------------------------------------------------------------------------- -- Command-line flags data CLIFlags = OptDebugParser | OptGhcTarget | OptOutputFile FilePath | OptInfoFile (Maybe FilePath) | OptTabSize String | OptTemplateDir FilePath | OptLatin1 | DumpHelp | DumpVersion deriving Eq argInfo :: [OptDescr CLIFlags] argInfo = [ Option ['o'] ["outfile"] (ReqArg OptOutputFile "FILE") "write the output to FILE (default: file.hs)", Option ['i'] ["info"] (OptArg OptInfoFile "FILE") "put detailed state-machine info in FILE (or file.info)", Option ['t'] ["template"] (ReqArg OptTemplateDir "DIR") "look in DIR for template files", Option ['g'] ["ghc"] (NoArg OptGhcTarget) "use GHC extensions", Option ['l'] ["latin1"] (NoArg OptLatin1) "generated lexer will use the Latin-1 encoding instead of UTF-8", Option ['s'] ["tab-size"] (ReqArg OptTabSize "NUMBER") "set tab size to be used in the generated lexer (default: 8)", Option ['d'] ["debug"] (NoArg OptDebugParser) "produce a debugging scanner", Option ['?'] ["help"] (NoArg DumpHelp) "display this help and exit", Option ['V','v'] ["version"] (NoArg DumpVersion) -- ToDo: -v is deprecated! "output version information and exit" ] -- ----------------------------------------------------------------------------- -- Utils getProgramName :: IO String getProgramName = liftM (`withoutSuffix` ".bin") getProgName where str `withoutSuffix` suff | suff `isSuffixOf` str = take (length str - length suff) str | otherwise = str bye :: String -> IO a bye s = putStr s >> exitWith ExitSuccess die :: String -> IO a die s = hPutStr stderr s >> exitWith (ExitFailure 1) dieAlex :: String -> IO a dieAlex s = getProgramName >>= \prog -> die (prog ++ ": " ++ s) #if __GLASGOW_HASKELL__ < 610 bracketOnError :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracketOnError before after thing = block (do a <- before r <- Exception.catch (unblock (thing a)) (\e -> do { after a; throw e }) return r ) #endif
simonmar/alex
src/Main.hs
bsd-3-clause
19,538
7
21
6,012
5,134
2,672
2,462
-1
-1
{-# LANGUAGE FlexibleInstances #-} module Language.Haskell.GhcMod.Types where -- | Output style. data OutputStyle = LispStyle -- ^ S expression style. | PlainStyle -- ^ Plain textstyle. -- | The type for line separator. Historically, a Null string is used. newtype LineSeparator = LineSeparator String data Options = Options { outputStyle :: OutputStyle , hlintOpts :: [String] , ghcOpts :: [String] -- | If 'True', 'browse' also returns operators. , operators :: Bool -- | If 'True', 'browse' also returns types. , detailed :: Bool -- | If 'True', 'browse' will return fully qualified name , qualified :: Bool -- | Whether or not Template Haskell should be expanded. , expandSplice :: Bool -- | Line separator string. , lineSeparator :: LineSeparator -- | Package id of module , packageId :: Maybe String } -- | A default 'Options'. defaultOptions :: Options defaultOptions = Options { outputStyle = PlainStyle , hlintOpts = [] , ghcOpts = [] , operators = False , detailed = False , qualified = False , expandSplice = False , lineSeparator = LineSeparator "\0" , packageId = Nothing } ---------------------------------------------------------------- convert :: ToString a => Options -> a -> String convert Options{ outputStyle = LispStyle } = toLisp convert Options{ outputStyle = PlainStyle } = toPlain class ToString a where toLisp :: a -> String toPlain :: a -> String instance ToString [String] where toLisp = addNewLine . toSexp True toPlain = unlines instance ToString [((Int,Int,Int,Int),String)] where toLisp = addNewLine . toSexp False . map toS where toS x = "(" ++ tupToString x ++ ")" toPlain = unlines . map tupToString toSexp :: Bool -> [String] -> String toSexp False ss = "(" ++ unwords ss ++ ")" toSexp True ss = "(" ++ unwords (map quote ss) ++ ")" tupToString :: ((Int,Int,Int,Int),String) -> String tupToString ((a,b,c,d),s) = show a ++ " " ++ show b ++ " " ++ show c ++ " " ++ show d ++ " " ++ quote s quote :: String -> String quote x = "\"" ++ x ++ "\"" addNewLine :: String -> String addNewLine = (++ "\n") ---------------------------------------------------------------- -- | The environment where this library is used. data Cradle = Cradle { -- | The directory where this library is executed. cradleCurrentDir :: FilePath -- | The directory where a cabal file is found. , cradleCabalDir :: Maybe FilePath -- | The file name of the found cabal file. , cradleCabalFile :: Maybe FilePath -- | The package db options. ([\"-no-user-package-db\",\"-package-db\",\"\/foo\/bar\/i386-osx-ghc-7.6.3-packages.conf.d\"]) , cradlePackageDbOpts :: [GHCOption] } deriving (Eq, Show) ---------------------------------------------------------------- -- | A single GHC command line option. type GHCOption = String -- | An include directory for modules. type IncludeDir = FilePath -- | A package name. type Package = String -- | Haskell expression. type Expression = String -- | Module name. type ModuleString = String data CheckSpeed = Slow | Fast -- | Option information for GHC data CompilerOptions = CompilerOptions { ghcOptions :: [GHCOption] -- ^ Command line options , includeDirs :: [IncludeDir] -- ^ Include directories for modules , depPackages :: [Package] -- ^ Dependent package names } deriving (Eq, Show)
bitemyapp/ghc-mod
Language/Haskell/GhcMod/Types.hs
bsd-3-clause
3,570
0
13
861
739
435
304
69
1
----------------------------------------------------------------------------- -- | -- Module : Language.Haskell.Exts.Pretty -- Copyright : (c) Niklas Broberg 2004-2009, -- (c) The GHC Team, Noel Winstanley 1997-2000 -- License : BSD-style (see the file LICENSE.txt) -- -- Maintainer : Niklas Broberg, d00nibro@chalmers.se -- Stability : stable -- Portability : portable -- -- Pretty printer for Haskell with extensions. -- ----------------------------------------------------------------------------- module Language.Haskell.Exts.Pretty ( -- * Pretty printing Pretty, prettyPrintStyleMode, prettyPrintWithMode, prettyPrint, -- * Pretty-printing styles (from "Text.PrettyPrint.HughesPJ") P.Style(..), P.style, P.Mode(..), -- * Haskell formatting modes PPHsMode(..), Indent, PPLayout(..), defaultMode) where import Language.Haskell.Exts.Syntax import qualified Language.Haskell.Exts.Annotated.Syntax as A import Language.Haskell.Exts.Annotated.Simplify import qualified Language.Haskell.Exts.ParseSyntax as P import Language.Haskell.Exts.SrcLoc import qualified Text.PrettyPrint as P import Data.List (intersperse) infixl 5 $$$ ----------------------------------------------------------------------------- -- | Varieties of layout we can use. data PPLayout = PPOffsideRule -- ^ classical layout | PPSemiColon -- ^ classical layout made explicit | PPInLine -- ^ inline decls, with newlines between them | PPNoLayout -- ^ everything on a single line deriving Eq type Indent = Int -- | Pretty-printing parameters. -- -- /Note:/ the 'onsideIndent' must be positive and less than all other indents. data PPHsMode = PPHsMode { -- | indentation of a class or instance classIndent :: Indent, -- | indentation of a @do@-expression doIndent :: Indent, -- | indentation of the body of a -- @case@ expression caseIndent :: Indent, -- | indentation of the declarations in a -- @let@ expression letIndent :: Indent, -- | indentation of the declarations in a -- @where@ clause whereIndent :: Indent, -- | indentation added for continuation -- lines that would otherwise be offside onsideIndent :: Indent, -- | blank lines between statements? spacing :: Bool, -- | Pretty-printing style to use layout :: PPLayout, -- | add GHC-style @LINE@ pragmas to output? linePragmas :: Bool } -- | The default mode: pretty-print using the offside rule and sensible -- defaults. defaultMode :: PPHsMode defaultMode = PPHsMode{ classIndent = 8, doIndent = 3, caseIndent = 4, letIndent = 4, whereIndent = 6, onsideIndent = 2, spacing = True, layout = PPOffsideRule, linePragmas = False } -- | Pretty printing monad newtype DocM s a = DocM (s -> a) instance Functor (DocM s) where fmap f xs = do x <- xs; return (f x) instance Monad (DocM s) where (>>=) = thenDocM (>>) = then_DocM return = retDocM {-# INLINE thenDocM #-} {-# INLINE then_DocM #-} {-# INLINE retDocM #-} {-# INLINE unDocM #-} {-# INLINE getPPEnv #-} thenDocM :: DocM s a -> (a -> DocM s b) -> DocM s b thenDocM m k = DocM $ (\s -> case unDocM m $ s of a -> unDocM (k a) $ s) then_DocM :: DocM s a -> DocM s b -> DocM s b then_DocM m k = DocM $ (\s -> case unDocM m $ s of _ -> unDocM k $ s) retDocM :: a -> DocM s a retDocM a = DocM (\_s -> a) unDocM :: DocM s a -> (s -> a) unDocM (DocM f) = f -- all this extra stuff, just for this one function. getPPEnv :: DocM s s getPPEnv = DocM id -- So that pp code still looks the same -- this means we lose some generality though -- | The document type produced by these pretty printers uses a 'PPHsMode' -- environment. type Doc = DocM PPHsMode P.Doc -- | Things that can be pretty-printed, including all the syntactic objects -- in "Language.Haskell.Exts.Syntax" and "Language.Haskell.Exts.Annotated.Syntax". class Pretty a where -- | Pretty-print something in isolation. pretty :: a -> Doc -- | Pretty-print something in a precedence context. prettyPrec :: Int -> a -> Doc pretty = prettyPrec 0 prettyPrec _ = pretty -- The pretty printing combinators empty :: Doc empty = return P.empty nest :: Int -> Doc -> Doc nest i m = m >>= return . P.nest i -- Literals text, ptext :: String -> Doc text = return . P.text ptext = return . P.text char :: Char -> Doc char = return . P.char int :: Int -> Doc int = return . P.int integer :: Integer -> Doc integer = return . P.integer float :: Float -> Doc float = return . P.float double :: Double -> Doc double = return . P.double rational :: Rational -> Doc rational = return . P.rational -- Simple Combining Forms parens, brackets, braces,quotes,doubleQuotes :: Doc -> Doc parens d = d >>= return . P.parens brackets d = d >>= return . P.brackets braces d = d >>= return . P.braces quotes d = d >>= return . P.quotes doubleQuotes d = d >>= return . P.doubleQuotes parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id -- Constants semi,comma,colon,space,equals :: Doc semi = return P.semi comma = return P.comma colon = return P.colon space = return P.space equals = return P.equals lparen,rparen,lbrack,rbrack,lbrace,rbrace :: Doc lparen = return P.lparen rparen = return P.rparen lbrack = return P.lbrack rbrack = return P.rbrack lbrace = return P.lbrace rbrace = return P.rbrace -- Combinators (<>),(<+>),($$),($+$) :: Doc -> Doc -> Doc aM <> bM = do{a<-aM;b<-bM;return (a P.<> b)} aM <+> bM = do{a<-aM;b<-bM;return (a P.<+> b)} aM $$ bM = do{a<-aM;b<-bM;return (a P.$$ b)} aM $+$ bM = do{a<-aM;b<-bM;return (a P.$+$ b)} hcat,hsep,vcat,sep,cat,fsep,fcat :: [Doc] -> Doc hcat dl = sequence dl >>= return . P.hcat hsep dl = sequence dl >>= return . P.hsep vcat dl = sequence dl >>= return . P.vcat sep dl = sequence dl >>= return . P.sep cat dl = sequence dl >>= return . P.cat fsep dl = sequence dl >>= return . P.fsep fcat dl = sequence dl >>= return . P.fcat -- Some More hang :: Doc -> Int -> Doc -> Doc hang dM i rM = do{d<-dM;r<-rM;return $ P.hang d i r} -- Yuk, had to cut-n-paste this one from Pretty.hs punctuate :: Doc -> [Doc] -> [Doc] punctuate _ [] = [] punctuate p (d1:ds) = go d1 ds where go d [] = [d] go d (e:es) = (d <> p) : go e es -- | render the document with a given style and mode. renderStyleMode :: P.Style -> PPHsMode -> Doc -> String renderStyleMode ppStyle ppMode d = P.renderStyle ppStyle . unDocM d $ ppMode -- | render the document with a given mode. renderWithMode :: PPHsMode -> Doc -> String renderWithMode = renderStyleMode P.style -- | render the document with 'defaultMode'. render :: Doc -> String render = renderWithMode defaultMode -- | pretty-print with a given style and mode. prettyPrintStyleMode :: Pretty a => P.Style -> PPHsMode -> a -> String prettyPrintStyleMode ppStyle ppMode = renderStyleMode ppStyle ppMode . pretty -- | pretty-print with the default style and a given mode. prettyPrintWithMode :: Pretty a => PPHsMode -> a -> String prettyPrintWithMode = prettyPrintStyleMode P.style -- | pretty-print with the default style and 'defaultMode'. prettyPrint :: Pretty a => a -> String prettyPrint = prettyPrintWithMode defaultMode fullRenderWithMode :: PPHsMode -> P.Mode -> Int -> Float -> (P.TextDetails -> a -> a) -> a -> Doc -> a fullRenderWithMode ppMode m i f fn e mD = P.fullRender m i f fn e $ (unDocM mD) ppMode fullRender :: P.Mode -> Int -> Float -> (P.TextDetails -> a -> a) -> a -> Doc -> a fullRender = fullRenderWithMode defaultMode ------------------------- Pretty-Print a Module -------------------- instance Pretty Module where pretty (Module pos m os mbWarn mbExports imp decls) = markLine pos $ myVcat $ map pretty os ++ (if m == ModuleName "" then id else \x -> [topLevel (ppModuleHeader m mbWarn mbExports) x]) (map pretty imp ++ map pretty decls) -------------------------- Module Header ------------------------------ ppModuleHeader :: ModuleName -> Maybe WarningText -> Maybe [ExportSpec] -> Doc ppModuleHeader m mbWarn mbExportList = mySep [ text "module", pretty m, maybePP ppWarnTxt mbWarn, maybePP (parenList . map pretty) mbExportList, text "where"] ppWarnTxt :: WarningText -> Doc ppWarnTxt (DeprText s) = mySep [text "{-# DEPRECATED", text (show s), text "#-}"] ppWarnTxt (WarnText s) = mySep [text "{-# WARNING", text (show s), text "#-}"] instance Pretty ModuleName where pretty (ModuleName modName) = text modName instance Pretty ExportSpec where pretty (EVar name) = pretty name pretty (EAbs name) = pretty name pretty (EThingAll name) = pretty name <> text "(..)" pretty (EThingWith name nameList) = pretty name <> (parenList . map pretty $ nameList) pretty (EModuleContents m) = text "module" <+> pretty m instance Pretty ImportDecl where pretty (ImportDecl pos m qual src mbPkg mbName mbSpecs) = markLine pos $ mySep [text "import", if src then text "{-# SOURCE #-}" else empty, if qual then text "qualified" else empty, maybePP (\s -> text (show s)) mbPkg, pretty m, maybePP (\m' -> text "as" <+> pretty m') mbName, maybePP exports mbSpecs] where exports (b,specList) = if b then text "hiding" <+> specs else specs where specs = parenList . map pretty $ specList instance Pretty ImportSpec where pretty (IVar name) = pretty name pretty (IAbs name) = pretty name pretty (IThingAll name) = pretty name <> text "(..)" pretty (IThingWith name nameList) = pretty name <> (parenList . map pretty $ nameList) ------------------------- Declarations ------------------------------ instance Pretty Decl where pretty (TypeDecl loc name nameList htype) = blankline $ markLine loc $ mySep ( [text "type", pretty name] ++ map pretty nameList ++ [equals, pretty htype]) pretty (DataDecl loc don context name nameList constrList derives) = blankline $ markLine loc $ mySep ( [pretty don, ppContext context, pretty name] ++ map pretty nameList) <+> (myVcat (zipWith (<+>) (equals : repeat (char '|')) (map pretty constrList)) $$$ ppDeriving derives) pretty (GDataDecl loc don context name nameList optkind gadtList derives) = blankline $ markLine loc $ mySep ( [pretty don, ppContext context, pretty name] ++ map pretty nameList ++ ppOptKind optkind ++ [text "where"]) $$$ ppBody classIndent (map pretty gadtList) $$$ ppBody letIndent [ppDeriving derives] pretty (TypeFamDecl loc name nameList optkind) = blankline $ markLine loc $ mySep ([text "type", text "family", pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (DataFamDecl loc context name nameList optkind) = blankline $ markLine loc $ mySep ( [text "data", text "family", ppContext context, pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (TypeInsDecl loc ntype htype) = blankline $ markLine loc $ mySep [text "type", text "instance", pretty ntype, equals, pretty htype] pretty (DataInsDecl loc don ntype constrList derives) = blankline $ markLine loc $ mySep [pretty don, text "instance", pretty ntype] <+> (myVcat (zipWith (<+>) (equals : repeat (char '|')) (map pretty constrList)) $$$ ppDeriving derives) pretty (GDataInsDecl loc don ntype optkind gadtList derives) = blankline $ markLine loc $ mySep ( [pretty don, text "instance", pretty ntype] ++ ppOptKind optkind ++ [text "where"]) $$$ ppBody classIndent (map pretty gadtList) $$$ ppDeriving derives --m{spacing=False} -- special case for empty class declaration pretty (ClassDecl pos context name nameList fundeps []) = blankline $ markLine pos $ mySep ( [text "class", ppContext context, pretty name] ++ map pretty nameList ++ [ppFunDeps fundeps]) pretty (ClassDecl pos context name nameList fundeps declList) = blankline $ markLine pos $ mySep ( [text "class", ppContext context, pretty name] ++ map pretty nameList ++ [ppFunDeps fundeps, text "where"]) $$$ ppBody classIndent (map pretty declList) -- m{spacing=False} -- special case for empty instance declaration pretty (InstDecl pos context name args []) = blankline $ markLine pos $ mySep ( [text "instance", ppContext context, pretty name] ++ map ppAType args) pretty (InstDecl pos context name args declList) = blankline $ markLine pos $ mySep ( [text "instance", ppContext context, pretty name] ++ map ppAType args ++ [text "where"]) $$$ ppBody classIndent (map pretty declList) pretty (DerivDecl pos context name args) = blankline $ markLine pos $ mySep ( [text "deriving", text "instance", ppContext context, pretty name] ++ map ppAType args) pretty (DefaultDecl pos htypes) = blankline $ markLine pos $ text "default" <+> parenList (map pretty htypes) pretty (SpliceDecl pos splice) = blankline $ markLine pos $ pretty splice pretty (TypeSig pos nameList qualType) = blankline $ markLine pos $ mySep ((punctuate comma . map pretty $ nameList) ++ [text "::", pretty qualType]) pretty (FunBind matches) = do e <- fmap layout getPPEnv case e of PPOffsideRule -> foldr ($$$) empty (map pretty matches) _ -> foldr (\x y -> x <> semi <> y) empty (map pretty matches) pretty (PatBind pos pat optsig rhs whereBinds) = markLine pos $ myFsep [pretty pat, maybePP ppSig optsig, pretty rhs] $$$ ppWhere whereBinds pretty (InfixDecl pos assoc prec opList) = blankline $ markLine pos $ mySep ([pretty assoc, int prec] ++ (punctuate comma . map pretty $ opList)) pretty (ForImp pos cconv saf str name typ) = blankline $ markLine pos $ mySep [text "foreign import", pretty cconv, pretty saf, text (show str), pretty name, text "::", pretty typ] pretty (ForExp pos cconv str name typ) = blankline $ markLine pos $ mySep [text "foreign export", pretty cconv, text (show str), pretty name, text "::", pretty typ] pretty (RulePragmaDecl pos rules) = blankline $ markLine pos $ myVcat $ text "{-# RULES" : map pretty rules ++ [text " #-}"] pretty (DeprPragmaDecl pos deprs) = blankline $ markLine pos $ myVcat $ text "{-# DEPRECATED" : map ppWarnDepr deprs ++ [text " #-}"] pretty (WarnPragmaDecl pos deprs) = blankline $ markLine pos $ myVcat $ text "{-# WARNING" : map ppWarnDepr deprs ++ [text " #-}"] pretty (InlineSig pos inl activ name) = blankline $ markLine pos $ mySep [text (if inl then "{-# INLINE" else "{-# NOINLINE"), pretty activ, pretty name, text "#-}"] pretty (InlineConlikeSig pos activ name) = blankline $ markLine pos $ mySep [text "{-# INLINE_CONLIKE", pretty activ, pretty name, text "#-}"] pretty (SpecSig pos activ name types) = blankline $ markLine pos $ mySep $ [text "{-# SPECIALISE", pretty activ, pretty name, text "::"] ++ punctuate comma (map pretty types) ++ [text "#-}"] pretty (SpecInlineSig pos inl activ name types) = blankline $ markLine pos $ mySep $ [text "{-# SPECIALISE", text (if inl then "INLINE" else "NOINLINE"), pretty activ, pretty name, text "::"] ++ (punctuate comma $ map pretty types) ++ [text "#-}"] pretty (InstSig pos context name args) = blankline $ markLine pos $ mySep $ [text "{-# SPECIALISE", text "instance", ppContext context, pretty name] ++ map ppAType args ++ [text "#-}"] pretty (AnnPragma pos ann) = blankline $ markLine pos $ mySep $ [text "{-# ANN", pretty ann, text "#-}"] instance Pretty Annotation where pretty (Ann n e) = myFsep [pretty n, pretty e] pretty (TypeAnn n e) = myFsep [text "type", pretty n, pretty e] pretty (ModuleAnn e) = myFsep [text "module", pretty e] instance Pretty DataOrNew where pretty DataType = text "data" pretty NewType = text "newtype" instance Pretty Assoc where pretty AssocNone = text "infix" pretty AssocLeft = text "infixl" pretty AssocRight = text "infixr" instance Pretty Match where pretty (Match pos f ps optsig rhs whereBinds) = markLine pos $ myFsep (lhs ++ [maybePP ppSig optsig, pretty rhs]) $$$ ppWhere whereBinds where lhs = case ps of l:r:ps' | isSymbolName f -> let hd = [pretty l, ppName f, pretty r] in if null ps' then hd else parens (myFsep hd) : map (prettyPrec 2) ps' _ -> pretty f : map (prettyPrec 2) ps ppWhere :: Binds -> Doc ppWhere (BDecls []) = empty ppWhere (BDecls l) = nest 2 (text "where" $$$ ppBody whereIndent (map pretty l)) ppWhere (IPBinds b) = nest 2 (text "where" $$$ ppBody whereIndent (map pretty b)) ppSig :: Type -> Doc ppSig t = text "::" <+> pretty t instance Pretty ClassDecl where pretty (ClsDecl decl) = pretty decl pretty (ClsDataFam loc context name nameList optkind) = markLine loc $ mySep ( [text "data", ppContext context, pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (ClsTyFam loc name nameList optkind) = markLine loc $ mySep ( [text "type", pretty name] ++ map pretty nameList ++ ppOptKind optkind) pretty (ClsTyDef loc ntype htype) = markLine loc $ mySep [text "type", pretty ntype, equals, pretty htype] instance Pretty InstDecl where pretty (InsDecl decl) = pretty decl pretty (InsType loc ntype htype) = markLine loc $ mySep [text "type", pretty ntype, equals, pretty htype] pretty (InsData loc don ntype constrList derives) = markLine loc $ mySep [pretty don, pretty ntype] <+> (myVcat (zipWith (<+>) (equals : repeat (char '|')) (map pretty constrList)) $$$ ppDeriving derives) pretty (InsGData loc don ntype optkind gadtList derives) = markLine loc $ mySep ( [pretty don, pretty ntype] ++ ppOptKind optkind ++ [text "where"]) $$$ ppBody classIndent (map pretty gadtList) $$$ ppDeriving derives -- pretty (InsInline loc inl activ name) = -- markLine loc $ -- mySep [text (if inl then "{-# INLINE" else "{-# NOINLINE"), pretty activ, pretty name, text "#-}"] ------------------------- FFI stuff ------------------------------------- instance Pretty Safety where pretty PlayRisky = text "unsafe" pretty (PlaySafe b) = text $ if b then "threadsafe" else "safe" pretty PlayInterruptible = text "interruptible" instance Pretty CallConv where pretty StdCall = text "stdcall" pretty CCall = text "ccall" pretty CPlusPlus = text "cplusplus" pretty DotNet = text "dotnet" pretty Jvm = text "jvm" pretty Js = text "js" ------------------------- Pragmas --------------------------------------- ppWarnDepr :: ([Name], String) -> Doc ppWarnDepr (names, txt) = mySep $ (punctuate comma $ map pretty names) ++ [text $ show txt] instance Pretty Rule where pretty (Rule tag activ rvs rhs lhs) = mySep $ [text $ show tag, pretty activ, maybePP ppRuleVars rvs, pretty rhs, char '=', pretty lhs] ppRuleVars :: [RuleVar] -> Doc ppRuleVars [] = empty ppRuleVars rvs = mySep $ text "forall" : map pretty rvs ++ [char '.'] instance Pretty Activation where pretty AlwaysActive = empty pretty (ActiveFrom i) = char '[' <> int i <> char ']' pretty (ActiveUntil i) = text "[~" <> int i <> char ']' instance Pretty RuleVar where pretty (RuleVar n) = pretty n pretty (TypedRuleVar n t) = parens $ mySep [pretty n, text "::", pretty t] instance Pretty ModulePragma where pretty (LanguagePragma _ ns) = myFsep $ text "{-# LANGUAGE" : punctuate (char ',') (map pretty ns) ++ [text "#-}"] pretty (OptionsPragma _ (Just tool) s) = myFsep $ [text "{-# OPTIONS_" <> pretty tool, text s, text "#-}"] pretty (OptionsPragma _ _ s) = myFsep $ [text "{-# OPTIONS", text s, text "#-}"] pretty (AnnModulePragma _ ann) = myFsep $ [text "{-# ANN", pretty ann, text "#-}"] instance Pretty Tool where pretty (UnknownTool s) = text s pretty t = text $ show t ------------------------- Data & Newtype Bodies ------------------------- instance Pretty QualConDecl where pretty (QualConDecl _pos tvs ctxt con) = myFsep [ppForall (Just tvs), ppContext ctxt, pretty con] instance Pretty GadtDecl where pretty (GadtDecl _pos name ty) = myFsep [pretty name, text "::", pretty ty] instance Pretty ConDecl where pretty (RecDecl name fieldList) = pretty name <> (braceList . map ppField $ fieldList) {- pretty (ConDecl name@(Symbol _) [l, r]) = myFsep [prettyPrec prec_btype l, ppName name, prettyPrec prec_btype r] -} pretty (ConDecl name typeList) = mySep $ ppName name : map (prettyPrec prec_atype) typeList pretty (InfixConDecl l name r) = myFsep [prettyPrec prec_btype l, ppNameInfix name, prettyPrec prec_btype r] ppField :: ([Name],BangType) -> Doc ppField (names, ty) = myFsepSimple $ (punctuate comma . map pretty $ names) ++ [text "::", pretty ty] instance Pretty BangType where prettyPrec _ (BangedTy ty) = char '!' <> ppAType ty prettyPrec p (UnBangedTy ty) = prettyPrec p ty prettyPrec p (UnpackedTy ty) = text "{-# UNPACK #-}" <+> char '!' <> prettyPrec p ty ppDeriving :: [Deriving] -> Doc ppDeriving [] = empty ppDeriving [(d, [])] = text "deriving" <+> ppQName d ppDeriving ds = text "deriving" <+> parenList (map ppDer ds) where ppDer :: (QName, [Type]) -> Doc ppDer (n, ts) = mySep (pretty n : map pretty ts) ------------------------- Types ------------------------- ppBType :: Type -> Doc ppBType = prettyPrec prec_btype ppAType :: Type -> Doc ppAType = prettyPrec prec_atype -- precedences for types prec_btype, prec_atype :: Int prec_btype = 1 -- left argument of ->, -- or either argument of an infix data constructor prec_atype = 2 -- argument of type or data constructor, or of a class instance Pretty Type where prettyPrec p (TyForall mtvs ctxt htype) = parensIf (p > 0) $ myFsep [ppForall mtvs, ppContext ctxt, pretty htype] prettyPrec p (TyFun a b) = parensIf (p > 0) $ myFsep [ppBType a, text "->", pretty b] prettyPrec _ (TyTuple bxd l) = let ds = map pretty l in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds prettyPrec _ (TyList t) = brackets $ pretty t prettyPrec p (TyApp a b) = {- | a == list_tycon = brackets $ pretty b -- special case | otherwise = -} parensIf (p > prec_btype) $ myFsep [pretty a, ppAType b] prettyPrec _ (TyVar name) = pretty name prettyPrec _ (TyCon name) = pretty name prettyPrec _ (TyParen t) = parens (pretty t) -- prettyPrec _ (TyPred asst) = pretty asst prettyPrec _ (TyInfix a op b) = myFsep [pretty a, ppQNameInfix op, pretty b] prettyPrec _ (TyKind t k) = parens (myFsep [pretty t, text "::", pretty k]) instance Pretty TyVarBind where pretty (KindedVar var kind) = parens $ myFsep [pretty var, text "::", pretty kind] pretty (UnkindedVar var) = pretty var ppForall :: Maybe [TyVarBind] -> Doc ppForall Nothing = empty ppForall (Just []) = empty ppForall (Just vs) = myFsep (text "forall" : map pretty vs ++ [char '.']) ---------------------------- Kinds ---------------------------- instance Pretty Kind where prettyPrec _ KindStar = text "*" prettyPrec _ KindBang = text "!" prettyPrec n (KindFn a b) = parensIf (n > 0) $ myFsep [prettyPrec 1 a, text "->", pretty b] prettyPrec _ (KindParen k) = parens $ pretty k prettyPrec _ (KindVar n) = pretty n ppOptKind :: Maybe Kind -> [Doc] ppOptKind Nothing = [] ppOptKind (Just k) = [text "::", pretty k] ------------------- Functional Dependencies ------------------- instance Pretty FunDep where pretty (FunDep from to) = myFsep $ map pretty from ++ [text "->"] ++ map pretty to ppFunDeps :: [FunDep] -> Doc ppFunDeps [] = empty ppFunDeps fds = myFsep $ (char '|':) . punctuate comma . map pretty $ fds ------------------------- Expressions ------------------------- instance Pretty Rhs where pretty (UnGuardedRhs e) = equals <+> pretty e pretty (GuardedRhss guardList) = myVcat . map pretty $ guardList instance Pretty GuardedRhs where pretty (GuardedRhs _pos guards ppBody) = myFsep $ [char '|'] ++ (punctuate comma . map pretty $ guards) ++ [equals, pretty ppBody] instance Pretty Literal where pretty (Int i) = integer i pretty (Char c) = text (show c) pretty (String s) = text (show s) pretty (Frac r) = double (fromRational r) -- GHC unboxed literals: pretty (PrimChar c) = text (show c) <> char '#' pretty (PrimString s) = text (show s) <> char '#' pretty (PrimInt i) = integer i <> char '#' pretty (PrimWord w) = integer w <> text "##" pretty (PrimFloat r) = float (fromRational r) <> char '#' pretty (PrimDouble r) = double (fromRational r) <> text "##" instance Pretty Exp where prettyPrec _ (Lit l) = pretty l -- lambda stuff prettyPrec p (InfixApp a op b) = parensIf (p > 2) $ myFsep [prettyPrec 2 a, pretty op, prettyPrec 1 b] prettyPrec p (NegApp e) = parensIf (p > 0) $ char '-' <> prettyPrec 4 e prettyPrec p (App a b) = parensIf (p > 3) $ myFsep [prettyPrec 3 a, prettyPrec 4 b] prettyPrec p (Lambda _loc patList ppBody) = parensIf (p > 1) $ myFsep $ char '\\' : map (prettyPrec 2) patList ++ [text "->", pretty ppBody] -- keywords -- two cases for lets prettyPrec p (Let (BDecls declList) letBody) = parensIf (p > 1) $ ppLetExp declList letBody prettyPrec p (Let (IPBinds bindList) letBody) = parensIf (p > 1) $ ppLetExp bindList letBody prettyPrec p (If cond thenexp elsexp) = parensIf (p > 1) $ myFsep [text "if", pretty cond, text "then", pretty thenexp, text "else", pretty elsexp] prettyPrec p (Case cond altList) = parensIf (p > 1) $ myFsep [text "case", pretty cond, text "of"] $$$ ppBody caseIndent (map pretty altList) prettyPrec p (Do stmtList) = parensIf (p > 1) $ text "do" $$$ ppBody doIndent (map pretty stmtList) prettyPrec p (MDo stmtList) = parensIf (p > 1) $ text "mdo" $$$ ppBody doIndent (map pretty stmtList) -- Constructors & Vars prettyPrec _ (Var name) = pretty name prettyPrec _ (IPVar ipname) = pretty ipname prettyPrec _ (Con name) = pretty name prettyPrec _ (Tuple bxd expList) = let ds = map pretty expList in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds prettyPrec _ (TupleSection bxd mExpList) = let ds = map (maybePP pretty) mExpList in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds -- weird stuff prettyPrec _ (Paren e) = parens . pretty $ e prettyPrec _ (LeftSection e op) = parens (pretty e <+> pretty op) prettyPrec _ (RightSection op e) = parens (pretty op <+> pretty e) prettyPrec _ (RecConstr c fieldList) = pretty c <> (braceList . map pretty $ fieldList) prettyPrec _ (RecUpdate e fieldList) = pretty e <> (braceList . map pretty $ fieldList) -- Lists prettyPrec _ (List list) = bracketList . punctuate comma . map pretty $ list prettyPrec _ (EnumFrom e) = bracketList [pretty e, text ".."] prettyPrec _ (EnumFromTo from to) = bracketList [pretty from, text "..", pretty to] prettyPrec _ (EnumFromThen from thenE) = bracketList [pretty from <> comma, pretty thenE, text ".."] prettyPrec _ (EnumFromThenTo from thenE to) = bracketList [pretty from <> comma, pretty thenE, text "..", pretty to] prettyPrec _ (ListComp e qualList) = bracketList ([pretty e, char '|'] ++ (punctuate comma . map pretty $ qualList)) prettyPrec _ (ParComp e qualLists) = bracketList (punctuate (char '|') $ pretty e : (map (hsep . punctuate comma . map pretty) $ qualLists)) prettyPrec p (ExpTypeSig _pos e ty) = parensIf (p > 0) $ myFsep [pretty e, text "::", pretty ty] -- Template Haskell prettyPrec _ (BracketExp b) = pretty b prettyPrec _ (SpliceExp s) = pretty s prettyPrec _ (TypQuote t) = text "\'\'" <> pretty t prettyPrec _ (VarQuote x) = text "\'" <> pretty x prettyPrec _ (QuasiQuote n qt) = text ("[" ++ n ++ "|" ++ qt ++ "|]") -- Hsx prettyPrec _ (XTag _ n attrs mattr cs) = let ax = maybe [] (return . pretty) mattr in hcat $ (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']): map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']] prettyPrec _ (XETag _ n attrs mattr) = let ax = maybe [] (return . pretty) mattr in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [text "/>"] prettyPrec _ (XPcdata s) = text s prettyPrec _ (XExpTag e) = myFsep $ [text "<%", pretty e, text "%>"] prettyPrec _ (XChildTag _ cs) = myFsep $ text "<%>" : map pretty cs ++ [text "</%>"] -- Pragmas prettyPrec p (CorePragma s e) = myFsep $ map text ["{-# CORE", show s, "#-}"] ++ [pretty e] prettyPrec _ (SCCPragma s e) = myFsep $ map text ["{-# SCC", show s, "#-}"] ++ [pretty e] prettyPrec _ (GenPragma s (a,b) (c,d) e) = myFsep $ [text "{-# GENERATED", text $ show s, int a, char ':', int b, char '-', int c, char ':', int d, text "#-}", pretty e] -- Arrows prettyPrec p (Proc _ pat e) = parensIf (p > 1) $ myFsep $ [text "proc", pretty pat, text "->", pretty e] prettyPrec p (LeftArrApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text "-<", pretty r] prettyPrec p (RightArrApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text ">-", pretty r] prettyPrec p (LeftArrHighApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text "-<<", pretty r] prettyPrec p (RightArrHighApp l r) = parensIf (p > 0) $ myFsep $ [pretty l, text ">>-", pretty r] instance Pretty XAttr where pretty (XAttr n v) = myFsep [pretty n, char '=', pretty v] instance Pretty XName where pretty (XName n) = text n pretty (XDomName d n) = text d <> char ':' <> text n --ppLetExp :: [Decl] -> Exp -> Doc ppLetExp l b = myFsep [text "let" <+> ppBody letIndent (map pretty l), text "in", pretty b] ppWith binds = nest 2 (text "with" $$$ ppBody withIndent (map pretty binds)) withIndent = whereIndent --------------------- Template Haskell ------------------------- instance Pretty Bracket where pretty (ExpBracket e) = ppBracket "[|" e pretty (PatBracket p) = ppBracket "[p|" p pretty (TypeBracket t) = ppBracket "[t|" t pretty (DeclBracket d) = myFsep $ text "[d|" : map pretty d ++ [text "|]"] ppBracket o x = myFsep [text o, pretty x, text "|]"] instance Pretty Splice where pretty (IdSplice s) = char '$' <> text s pretty (ParenSplice e) = myFsep [text "$(", pretty e, char ')'] ------------------------- Patterns ----------------------------- instance Pretty Pat where prettyPrec _ (PVar name) = pretty name prettyPrec _ (PLit lit) = pretty lit prettyPrec p (PNeg pat) = parensIf (p > 0) $ myFsep [char '-', pretty pat] prettyPrec p (PInfixApp a op b) = parensIf (p > 0) $ myFsep [prettyPrec 1 a, pretty (QConOp op), prettyPrec 1 b] prettyPrec p (PApp n ps) = parensIf (p > 1 && not (null ps)) $ myFsep (pretty n : map (prettyPrec 2) ps) prettyPrec _ (PTuple bxd ps) = let ds = map pretty ps in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds prettyPrec _ (PList ps) = bracketList . punctuate comma . map pretty $ ps prettyPrec _ (PParen pat) = parens . pretty $ pat prettyPrec _ (PRec c fields) = pretty c <> (braceList . map pretty $ fields) -- special case that would otherwise be buggy prettyPrec _ (PAsPat name (PIrrPat pat)) = myFsep [pretty name <> char '@', char '~' <> prettyPrec 2 pat] prettyPrec _ (PAsPat name pat) = hcat [pretty name, char '@', prettyPrec 2 pat] prettyPrec _ PWildCard = char '_' prettyPrec _ (PIrrPat pat) = char '~' <> prettyPrec 2 pat prettyPrec p (PatTypeSig _pos pat ty) = parensIf (p > 0) $ myFsep [pretty pat, text "::", pretty ty] prettyPrec p (PViewPat e pat) = parensIf (p > 0) $ myFsep [pretty e, text "->", pretty pat] prettyPrec p (PNPlusK n k) = parensIf (p > 0) $ myFsep [pretty n, text "+", text $ show k] -- HaRP prettyPrec _ (PRPat rs) = bracketList . punctuate comma . map pretty $ rs -- Hsx prettyPrec _ (PXTag _ n attrs mattr cp) = let ap = maybe [] (return . pretty) mattr in hcat $ -- TODO: should not introduce blanks (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ap ++ [char '>']): map pretty cp ++ [myFsep $ [text "</" <> pretty n, char '>']] prettyPrec _ (PXETag _ n attrs mattr) = let ap = maybe [] (return . pretty) mattr in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ap ++ [text "/>"] prettyPrec _ (PXPcdata s) = text s prettyPrec _ (PXPatTag p) = myFsep $ [text "<%", pretty p, text "%>"] prettyPrec _ (PXRPats ps) = myFsep $ text "<[" : map pretty ps ++ [text "%>"] -- Generics prettyPrec _ (PExplTypeArg qn t) = myFsep [pretty qn, text "{|", pretty t, text "|}"] -- BangPatterns prettyPrec _ (PBangPat pat) = text "!" <> prettyPrec 2 pat instance Pretty PXAttr where pretty (PXAttr n p) = myFsep [pretty n, char '=', pretty p] instance Pretty PatField where pretty (PFieldPat name pat) = myFsep [pretty name, equals, pretty pat] pretty (PFieldPun name) = pretty name pretty (PFieldWildcard) = text ".." --------------------- Regular Patterns ------------------------- instance Pretty RPat where pretty (RPOp r op) = pretty r <> pretty op pretty (RPEither r1 r2) = parens . myFsep $ [pretty r1, char '|', pretty r2] pretty (RPSeq rs) = myFsep $ text "(/" : map pretty rs ++ [text "/)"] pretty (RPGuard r gs) = myFsep $ text "(|" : pretty r : char '|' : map pretty gs ++ [text "|)"] -- special case that would otherwise be buggy pretty (RPCAs n (RPPat (PIrrPat p))) = myFsep [pretty n <> text "@:", char '~' <> pretty p] pretty (RPCAs n r) = hcat [pretty n, text "@:", pretty r] -- special case that would otherwise be buggy pretty (RPAs n (RPPat (PIrrPat p))) = myFsep [pretty n <> text "@:", char '~' <> pretty p] pretty (RPAs n r) = hcat [pretty n, char '@', pretty r] pretty (RPPat p) = pretty p pretty (RPParen rp) = parens . pretty $ rp instance Pretty RPatOp where pretty RPStar = char '*' pretty RPStarG = text "*!" pretty RPPlus = char '+' pretty RPPlusG = text "+!" pretty RPOpt = char '?' pretty RPOptG = text "?!" ------------------------- Case bodies ------------------------- instance Pretty Alt where pretty (Alt _pos e gAlts binds) = pretty e <+> pretty gAlts $$$ ppWhere binds instance Pretty GuardedAlts where pretty (UnGuardedAlt e) = text "->" <+> pretty e pretty (GuardedAlts altList) = myVcat . map pretty $ altList instance Pretty GuardedAlt where pretty (GuardedAlt _pos guards body) = myFsep $ char '|': (punctuate comma . map pretty $ guards) ++ [text "->", pretty body] ------------------------- Statements in monads, guards & list comprehensions ----- instance Pretty Stmt where pretty (Generator _loc e from) = pretty e <+> text "<-" <+> pretty from pretty (Qualifier e) = pretty e -- two cases for lets pretty (LetStmt (BDecls declList)) = ppLetStmt declList pretty (LetStmt (IPBinds bindList)) = ppLetStmt bindList pretty (RecStmt stmtList) = text "rec" $$$ ppBody letIndent (map pretty stmtList) ppLetStmt l = text "let" $$$ ppBody letIndent (map pretty l) instance Pretty QualStmt where pretty (QualStmt s) = pretty s pretty (ThenTrans f) = myFsep $ [text "then", pretty f] pretty (ThenBy f e) = myFsep $ [text "then", pretty f, text "by", pretty e] pretty (GroupBy e) = myFsep $ [text "then", text "group", text "by", pretty e] pretty (GroupUsing f) = myFsep $ [text "then", text "group", text "using", pretty f] pretty (GroupByUsing e f) = myFsep $ [text "then", text "group", text "by", pretty e, text "using", pretty f] ------------------------- Record updates instance Pretty FieldUpdate where pretty (FieldUpdate name e) = myFsep [pretty name, equals, pretty e] pretty (FieldPun name) = pretty name pretty (FieldWildcard) = text ".." ------------------------- Names ------------------------- instance Pretty QOp where pretty (QVarOp n) = ppQNameInfix n pretty (QConOp n) = ppQNameInfix n ppQNameInfix :: QName -> Doc ppQNameInfix name | isSymbolName (getName name) = ppQName name | otherwise = char '`' <> ppQName name <> char '`' instance Pretty QName where pretty name = case name of UnQual (Symbol ('#':_)) -> char '(' <+> ppQName name <+> char ')' _ -> parensIf (isSymbolName (getName name)) (ppQName name) ppQName :: QName -> Doc ppQName (UnQual name) = ppName name ppQName (Qual m name) = pretty m <> char '.' <> ppName name ppQName (Special sym) = text (specialName sym) instance Pretty Op where pretty (VarOp n) = ppNameInfix n pretty (ConOp n) = ppNameInfix n ppNameInfix :: Name -> Doc ppNameInfix name | isSymbolName name = ppName name | otherwise = char '`' <> ppName name <> char '`' instance Pretty Name where pretty name = case name of Symbol ('#':_) -> char '(' <+> ppName name <+> char ')' _ -> parensIf (isSymbolName name) (ppName name) ppName :: Name -> Doc ppName (Ident s) = text s ppName (Symbol s) = text s instance Pretty IPName where pretty (IPDup s) = char '?' <> text s pretty (IPLin s) = char '%' <> text s instance Pretty IPBind where pretty (IPBind _loc ipname exp) = myFsep [pretty ipname, equals, pretty exp] instance Pretty CName where pretty (VarName n) = pretty n pretty (ConName n) = pretty n instance Pretty SpecialCon where pretty sc = text $ specialName sc isSymbolName :: Name -> Bool isSymbolName (Symbol _) = True isSymbolName _ = False getName :: QName -> Name getName (UnQual s) = s getName (Qual _ s) = s getName (Special Cons) = Symbol ":" getName (Special FunCon) = Symbol "->" getName (Special s) = Ident (specialName s) specialName :: SpecialCon -> String specialName UnitCon = "()" specialName ListCon = "[]" specialName FunCon = "->" specialName (TupleCon b n) = "(" ++ hash ++ replicate (n-1) ',' ++ hash ++ ")" where hash = if b == Unboxed then "#" else "" specialName Cons = ":" specialName UnboxedSingleCon = "(# #)" ppContext :: Context -> Doc ppContext [] = empty ppContext context = mySep [parenList (map pretty context), text "=>"] -- hacked for multi-parameter type classes instance Pretty Asst where pretty (ClassA a ts) = myFsep $ ppQName a : map ppAType ts pretty (InfixA a op b) = myFsep $ [pretty a, ppQNameInfix op, pretty b] pretty (IParam i t) = myFsep $ [pretty i, text "::", pretty t] pretty (EqualP t1 t2) = myFsep $ [pretty t1, text "~", pretty t2] -- Pretty print a source location, useful for printing out error messages instance Pretty SrcLoc where pretty srcLoc = return $ P.hsep [ colonFollow (P.text $ srcFilename srcLoc) , colonFollow (P.int $ srcLine srcLoc) , P.int $ srcColumn srcLoc ] colonFollow p = P.hcat [ p, P.colon ] instance Pretty SrcSpan where pretty srcSpan = return $ P.hsep [ colonFollow (P.text $ srcSpanFilename srcSpan) , P.hcat [ P.text "(" , P.int $ srcSpanStartLine srcSpan , P.colon , P.int $ srcSpanStartColumn srcSpan , P.text ")" ] , P.text "-" , P.hcat [ P.text "(" , P.int $ srcSpanEndLine srcSpan , P.colon , P.int $ srcSpanEndColumn srcSpan , P.text ")" ] ] --------------------------------------------------------------------- -- Annotated version ------------------------- Pretty-Print a Module -------------------- instance SrcInfo pos => Pretty (A.Module pos) where pretty (A.Module pos mbHead os imp decls) = markLine pos $ myVcat $ map pretty os ++ (case mbHead of Nothing -> id Just h -> \x -> [topLevel (pretty h) x]) (map pretty imp ++ map pretty decls) pretty (A.XmlPage pos _mn os n attrs mattr cs) = markLine pos $ myVcat $ map pretty os ++ [let ax = maybe [] (return . pretty) mattr in hcat $ (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']): map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']]] pretty (A.XmlHybrid pos mbHead os imp decls n attrs mattr cs) = markLine pos $ myVcat $ map pretty os ++ [text "<%"] ++ (case mbHead of Nothing -> id Just h -> \x -> [topLevel (pretty h) x]) (map pretty imp ++ map pretty decls ++ [let ax = maybe [] (return . pretty) mattr in hcat $ (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']): map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']]]) -------------------------- Module Header ------------------------------ instance Pretty (A.ModuleHead l) where pretty (A.ModuleHead _ m mbWarn mbExportList) = mySep [ text "module", pretty m, maybePP pretty mbWarn, maybePP pretty mbExportList, text "where"] instance Pretty (A.WarningText l) where pretty = ppWarnTxt. sWarningText instance Pretty (A.ModuleName l) where pretty = pretty . sModuleName instance Pretty (A.ExportSpecList l) where pretty (A.ExportSpecList _ especs) = parenList $ map pretty especs instance Pretty (A.ExportSpec l) where pretty = pretty . sExportSpec instance SrcInfo pos => Pretty (A.ImportDecl pos) where pretty = pretty . sImportDecl instance Pretty (A.ImportSpecList l) where pretty (A.ImportSpecList _ b ispecs) = (if b then text "hiding" else empty) <+> parenList (map pretty ispecs) instance Pretty (A.ImportSpec l) where pretty = pretty . sImportSpec ------------------------- Declarations ------------------------------ instance SrcInfo pos => Pretty (A.Decl pos) where pretty = pretty . sDecl instance Pretty (A.DeclHead l) where pretty (A.DHead l n tvs) = mySep (pretty n : map pretty tvs) pretty (A.DHInfix l tva n tvb) = mySep [pretty tva, pretty n, pretty tvb] pretty (A.DHParen l dh) = parens (pretty dh) instance Pretty (A.InstHead l) where pretty (A.IHead l qn ts) = mySep (pretty qn : map pretty ts) pretty (A.IHInfix l ta qn tb) = mySep [pretty ta, pretty qn, pretty tb] pretty (A.IHParen l ih) = parens (pretty ih) instance Pretty (A.DataOrNew l) where pretty = pretty . sDataOrNew instance Pretty (A.Assoc l) where pretty = pretty . sAssoc instance SrcInfo pos => Pretty (A.Match pos) where pretty = pretty . sMatch instance SrcInfo loc => Pretty (A.ClassDecl loc) where pretty = pretty . sClassDecl instance SrcInfo loc => Pretty (A.InstDecl loc) where pretty = pretty . sInstDecl ------------------------- FFI stuff ------------------------------------- instance Pretty (A.Safety l) where pretty = pretty . sSafety instance Pretty (A.CallConv l) where pretty = pretty . sCallConv ------------------------- Pragmas --------------------------------------- instance SrcInfo loc => Pretty (A.Rule loc) where pretty = pretty . sRule instance Pretty (A.Activation l) where pretty = pretty . sActivation instance Pretty (A.RuleVar l) where pretty = pretty . sRuleVar instance SrcInfo loc => Pretty (A.ModulePragma loc) where pretty (A.LanguagePragma _ ns) = myFsep $ text "{-# LANGUAGE" : punctuate (char ',') (map pretty ns) ++ [text "#-}"] pretty (A.OptionsPragma _ (Just tool) s) = myFsep $ [text "{-# OPTIONS_" <> pretty tool, text s, text "#-}"] pretty (A.OptionsPragma _ _ s) = myFsep $ [text "{-# OPTIONS", text s, text "#-}"] pretty (A.AnnModulePragma _ ann) = myFsep $ [text "{-# ANN", pretty ann, text "#-}"] instance SrcInfo loc => Pretty (A.Annotation loc) where pretty = pretty . sAnnotation ------------------------- Data & Newtype Bodies ------------------------- instance Pretty (A.QualConDecl l) where pretty (A.QualConDecl _pos mtvs ctxt con) = myFsep [ppForall (fmap (map sTyVarBind) mtvs), ppContext $ maybe [] sContext ctxt, pretty con] instance Pretty (A.GadtDecl l) where pretty (A.GadtDecl _pos name ty) = myFsep [pretty name, text "::", pretty ty] instance Pretty (A.ConDecl l) where pretty = pretty . sConDecl instance Pretty (A.FieldDecl l) where pretty (A.FieldDecl _ names ty) = myFsepSimple $ (punctuate comma . map pretty $ names) ++ [text "::", pretty ty] instance Pretty (A.BangType l) where pretty = pretty . sBangType instance Pretty (A.Deriving l) where pretty (A.Deriving _ []) = text "deriving" <+> parenList [] pretty (A.Deriving _ [A.IHead _ d []]) = text "deriving" <+> pretty d pretty (A.Deriving _ ihs) = text "deriving" <+> parenList (map pretty ihs) ------------------------- Types ------------------------- instance Pretty (A.Type l) where pretty = pretty . sType instance Pretty (A.TyVarBind l) where pretty = pretty . sTyVarBind ---------------------------- Kinds ---------------------------- instance Pretty (A.Kind l) where pretty = pretty . sKind ------------------- Functional Dependencies ------------------- instance Pretty (A.FunDep l) where pretty = pretty . sFunDep ------------------------- Expressions ------------------------- instance SrcInfo loc => Pretty (A.Rhs loc) where pretty = pretty . sRhs instance SrcInfo loc => Pretty (A.GuardedRhs loc) where pretty = pretty . sGuardedRhs instance Pretty (A.Literal l) where pretty = pretty . sLiteral instance SrcInfo loc => Pretty (A.Exp loc) where pretty = pretty . sExp instance SrcInfo loc => Pretty (A.XAttr loc) where pretty = pretty . sXAttr instance Pretty (A.XName l) where pretty = pretty . sXName --------------------- Template Haskell ------------------------- instance SrcInfo loc => Pretty (A.Bracket loc) where pretty = pretty . sBracket instance SrcInfo loc => Pretty (A.Splice loc) where pretty = pretty . sSplice ------------------------- Patterns ----------------------------- instance SrcInfo loc => Pretty (A.Pat loc) where pretty = pretty . sPat instance SrcInfo loc => Pretty (A.PXAttr loc) where pretty = pretty . sPXAttr instance SrcInfo loc => Pretty (A.PatField loc) where pretty = pretty . sPatField --------------------- Regular Patterns ------------------------- instance SrcInfo loc => Pretty (A.RPat loc) where pretty = pretty . sRPat instance Pretty (A.RPatOp l) where pretty = pretty . sRPatOp ------------------------- Case bodies ------------------------- instance SrcInfo loc => Pretty (A.Alt loc) where pretty = pretty . sAlt instance SrcInfo loc => Pretty (A.GuardedAlts loc) where pretty = pretty . sGuardedAlts instance SrcInfo loc => Pretty (A.GuardedAlt loc) where pretty = pretty . sGuardedAlt ------------------------- Statements in monads, guards & list comprehensions ----- instance SrcInfo loc => Pretty (A.Stmt loc) where pretty = pretty . sStmt instance SrcInfo loc => Pretty (A.QualStmt loc) where pretty = pretty . sQualStmt ------------------------- Record updates instance SrcInfo loc => Pretty (A.FieldUpdate loc) where pretty = pretty . sFieldUpdate ------------------------- Names ------------------------- instance Pretty (A.QOp l) where pretty = pretty . sQOp instance Pretty (A.QName l) where pretty = pretty . sQName instance Pretty (A.Op l) where pretty = pretty . sOp instance Pretty (A.Name l) where pretty = pretty . sName instance Pretty (A.IPName l) where pretty = pretty . sIPName instance SrcInfo loc => Pretty (A.IPBind loc) where pretty = pretty . sIPBind instance Pretty (A.CName l) where pretty = pretty . sCName instance Pretty (A.Context l) where pretty (A.CxEmpty _) = mySep [text "()", text "=>"] pretty (A.CxSingle _ asst) = mySep [pretty asst, text "=>"] pretty (A.CxTuple _ assts) = myFsep $ [parenList (map pretty assts), text "=>"] pretty (A.CxParen _ asst) = parens (pretty asst) -- hacked for multi-parameter type classes instance Pretty (A.Asst l) where pretty = pretty . sAsst ------------------------- pp utils ------------------------- maybePP :: (a -> Doc) -> Maybe a -> Doc maybePP pp Nothing = empty maybePP pp (Just a) = pp a parenList :: [Doc] -> Doc parenList = parens . myFsepSimple . punctuate comma hashParenList :: [Doc] -> Doc hashParenList = hashParens . myFsepSimple . punctuate comma where hashParens = parens . hashes hashes = \doc -> char '#' <> doc <> char '#' braceList :: [Doc] -> Doc braceList = braces . myFsepSimple . punctuate comma bracketList :: [Doc] -> Doc bracketList = brackets . myFsepSimple -- Wrap in braces and semicolons, with an extra space at the start in -- case the first doc begins with "-", which would be scanned as {- flatBlock :: [Doc] -> Doc flatBlock = braces . (space <>) . hsep . punctuate semi -- Same, but put each thing on a separate line prettyBlock :: [Doc] -> Doc prettyBlock = braces . (space <>) . vcat . punctuate semi -- Monadic PP Combinators -- these examine the env blankline :: Doc -> Doc blankline dl = do{e<-getPPEnv;if spacing e && layout e /= PPNoLayout then space $$ dl else dl} topLevel :: Doc -> [Doc] -> Doc topLevel header dl = do e <- fmap layout getPPEnv case e of PPOffsideRule -> header $$ vcat dl PPSemiColon -> header $$ prettyBlock dl PPInLine -> header $$ prettyBlock dl PPNoLayout -> header <+> flatBlock dl ppBody :: (PPHsMode -> Int) -> [Doc] -> Doc ppBody f dl = do e <- fmap layout getPPEnv case e of PPOffsideRule -> indent PPSemiColon -> indentExplicit _ -> flatBlock dl where indent = do{i <-fmap f getPPEnv;nest i . vcat $ dl} indentExplicit = do {i <- fmap f getPPEnv; nest i . prettyBlock $ dl} ($$$) :: Doc -> Doc -> Doc a $$$ b = layoutChoice (a $$) (a <+>) b mySep :: [Doc] -> Doc mySep = layoutChoice mySep' hsep where -- ensure paragraph fills with indentation. mySep' [x] = x mySep' (x:xs) = x <+> fsep xs mySep' [] = error "Internal error: mySep" myVcat :: [Doc] -> Doc myVcat = layoutChoice vcat hsep myFsepSimple :: [Doc] -> Doc myFsepSimple = layoutChoice fsep hsep -- same, except that continuation lines are indented, -- which is necessary to avoid triggering the offside rule. myFsep :: [Doc] -> Doc myFsep = layoutChoice fsep' hsep where fsep' [] = empty fsep' (d:ds) = do e <- getPPEnv let n = onsideIndent e nest n (fsep (nest (-n) d:ds)) layoutChoice :: (a -> Doc) -> (a -> Doc) -> a -> Doc layoutChoice a b dl = do e <- getPPEnv if layout e == PPOffsideRule || layout e == PPSemiColon then a dl else b dl -- Prefix something with a LINE pragma, if requested. -- GHC's LINE pragma actually sets the current line number to n-1, so -- that the following line is line n. But if there's no newline before -- the line we're talking about, we need to compensate by adding 1. markLine :: SrcInfo s => s -> Doc -> Doc markLine loc doc = do e <- getPPEnv let y = startLine loc let line l = text ("{-# LINE " ++ show l ++ " \"" ++ fileName loc ++ "\" #-}") if linePragmas e then layoutChoice (line y $$) (line (y+1) <+>) doc else doc -------------------------------------------------------------------------------- -- Pretty-printing of internal constructs, for error messages while parsing instance SrcInfo loc => Pretty (P.PExp loc) where pretty (P.Lit _ l) = pretty l pretty (P.InfixApp _ a op b) = myFsep [pretty a, pretty op, pretty b] pretty (P.NegApp _ e) = myFsep [char '-', pretty e] pretty (P.App _ a b) = myFsep [pretty a, pretty b] pretty (P.Lambda _loc expList ppBody) = myFsep $ char '\\' : map pretty expList ++ [text "->", pretty ppBody] pretty (P.Let _ (A.BDecls _ declList) letBody) = ppLetExp declList letBody pretty (P.Let _ (A.IPBinds _ bindList) letBody) = ppLetExp bindList letBody pretty (P.If _ cond thenexp elsexp) = myFsep [text "if", pretty cond, text "then", pretty thenexp, text "else", pretty elsexp] pretty (P.Case _ cond altList) = myFsep [text "case", pretty cond, text "of"] $$$ ppBody caseIndent (map pretty altList) pretty (P.Do _ stmtList) = text "do" $$$ ppBody doIndent (map pretty stmtList) pretty (P.MDo _ stmtList) = text "mdo" $$$ ppBody doIndent (map pretty stmtList) pretty (P.Var _ name) = pretty name pretty (P.IPVar _ ipname) = pretty ipname pretty (P.Con _ name) = pretty name pretty (P.TupleSection _ bxd mExpList) = let ds = map (maybePP pretty) mExpList in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds pretty (P.Paren _ e) = parens . pretty $ e pretty (P.RecConstr _ c fieldList) = pretty c <> (braceList . map pretty $ fieldList) pretty (P.RecUpdate _ e fieldList) = pretty e <> (braceList . map pretty $ fieldList) pretty (P.List _ list) = bracketList . punctuate comma . map pretty $ list pretty (P.EnumFrom _ e) = bracketList [pretty e, text ".."] pretty (P.EnumFromTo _ from to) = bracketList [pretty from, text "..", pretty to] pretty (P.EnumFromThen _ from thenE) = bracketList [pretty from <> comma, pretty thenE, text ".."] pretty (P.EnumFromThenTo _ from thenE to) = bracketList [pretty from <> comma, pretty thenE, text "..", pretty to] pretty (P.ParComp _ e qualLists) = bracketList (intersperse (char '|') $ pretty e : (punctuate comma . concatMap (map pretty) $ qualLists)) pretty (P.ExpTypeSig _pos e ty) = myFsep [pretty e, text "::", pretty ty] pretty (P.BracketExp _ b) = pretty b pretty (P.SpliceExp _ s) = pretty s pretty (P.TypQuote _ t) = text "\'\'" <> pretty t pretty (P.VarQuote _ x) = text "\'" <> pretty x pretty (P.QuasiQuote _ n qt) = text ("[$" ++ n ++ "|" ++ qt ++ "|]") pretty (P.XTag _ n attrs mattr cs) = let ax = maybe [] (return . pretty) mattr in hcat $ (myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [char '>']): map pretty cs ++ [myFsep $ [text "</" <> pretty n, char '>']] pretty (P.XETag _ n attrs mattr) = let ax = maybe [] (return . pretty) mattr in myFsep $ (char '<' <> pretty n): map pretty attrs ++ ax ++ [text "/>"] pretty (P.XPcdata _ s) = text s pretty (P.XExpTag _ e) = myFsep $ [text "<%", pretty e, text "%>"] pretty (P.XChildTag _ es) = myFsep $ text "<%>" : map pretty es ++ [text "</%>"] pretty (P.CorePragma _ s e) = myFsep $ map text ["{-# CORE", show s, "#-}"] ++ [pretty e] pretty (P.SCCPragma _ s e) = myFsep $ map text ["{-# SCC", show s, "#-}"] ++ [pretty e] pretty (P.GenPragma _ s (a,b) (c,d) e) = myFsep $ [text "{-# GENERATED", text $ show s, int a, char ':', int b, char '-', int c, char ':', int d, text "#-}", pretty e] pretty (P.Proc _ p e) = myFsep $ [text "proc", pretty p, text "->", pretty e] pretty (P.LeftArrApp _ l r) = myFsep $ [pretty l, text "-<", pretty r] pretty (P.RightArrApp _ l r) = myFsep $ [pretty l, text ">-", pretty r] pretty (P.LeftArrHighApp _ l r) = myFsep $ [pretty l, text "-<<", pretty r] pretty (P.RightArrHighApp _ l r) = myFsep $ [pretty l, text ">>-", pretty r] pretty (P.AsPat _ name (P.IrrPat _ pat)) = myFsep [pretty name <> char '@', char '~' <> pretty pat] pretty (P.AsPat _ name pat) = hcat [pretty name, char '@', pretty pat] pretty (P.WildCard _) = char '_' pretty (P.IrrPat _ pat) = char '~' <> pretty pat pretty (P.PostOp _ e op) = pretty e <+> pretty op pretty (P.PreOp _ op e) = pretty op <+> pretty e pretty (P.ViewPat _ e p) = myFsep [pretty e, text "->", pretty p] pretty (P.SeqRP _ rs) = myFsep $ text "(/" : map pretty rs ++ [text "/)"] pretty (P.GuardRP _ r gs) = myFsep $ text "(|" : pretty r : char '|' : map pretty gs ++ [text "|)"] pretty (P.EitherRP _ r1 r2) = parens . myFsep $ [pretty r1, char '|', pretty r2] pretty (P.CAsRP _ n (P.IrrPat _ e)) = myFsep [pretty n <> text "@:", char '~' <> pretty e] pretty (P.CAsRP _ n r) = hcat [pretty n, text "@:", pretty r] pretty (P.XRPats _ ps) = myFsep $ text "<[" : map pretty ps ++ [text "%>"] pretty (P.ExplTypeArg _ qn t) = myFsep [pretty qn, text "{|", pretty t, text "|}"] pretty (P.BangPat _ e) = text "!" <> pretty e instance SrcInfo loc => Pretty (P.PFieldUpdate loc) where pretty (P.FieldUpdate _ name e) = myFsep [pretty name, equals, pretty e] pretty (P.FieldPun _ name) = pretty name pretty (P.FieldWildcard _) = text ".." instance SrcInfo loc => Pretty (P.ParseXAttr loc) where pretty (P.XAttr _ n v) = myFsep [pretty n, char '=', pretty v] instance SrcInfo loc => Pretty (P.PContext loc) where pretty (P.CxEmpty _) = mySep [text "()", text "=>"] pretty (P.CxSingle _ asst) = mySep [pretty asst, text "=>"] pretty (P.CxTuple _ assts) = myFsep $ [parenList (map pretty assts), text "=>"] pretty (P.CxParen _ asst) = parens (pretty asst) instance SrcInfo loc => Pretty (P.PAsst loc) where pretty (P.ClassA _ a ts) = myFsep $ ppQName (sQName a) : map (prettyPrec prec_atype) ts pretty (P.InfixA _ a op b) = myFsep $ [pretty a, ppQNameInfix (sQName op), pretty b] pretty (P.IParam _ i t) = myFsep $ [pretty i, text "::", pretty t] pretty (P.EqualP _ t1 t2) = myFsep $ [pretty t1, text "~", pretty t2] instance SrcInfo loc => Pretty (P.PType loc) where prettyPrec p (P.TyForall _ mtvs ctxt htype) = parensIf (p > 0) $ myFsep [ppForall (fmap (map sTyVarBind) mtvs), maybePP pretty ctxt, pretty htype] prettyPrec p (P.TyFun _ a b) = parensIf (p > 0) $ myFsep [prettyPrec prec_btype a, text "->", pretty b] prettyPrec _ (P.TyTuple _ bxd l) = let ds = map pretty l in case bxd of Boxed -> parenList ds Unboxed -> hashParenList ds prettyPrec _ (P.TyList _ t) = brackets $ pretty t prettyPrec p (P.TyApp _ a b) = {- | a == list_tycon = brackets $ pretty b -- special case | otherwise = -} parensIf (p > prec_btype) $ myFsep [pretty a, prettyPrec prec_atype b] prettyPrec _ (P.TyVar _ name) = pretty name prettyPrec _ (P.TyCon _ name) = pretty name prettyPrec _ (P.TyParen _ t) = parens (pretty t) prettyPrec _ (P.TyPred _ asst) = pretty asst prettyPrec _ (P.TyInfix _ a op b) = myFsep [pretty a, ppQNameInfix (sQName op), pretty b] prettyPrec _ (P.TyKind _ t k) = parens (myFsep [pretty t, text "::", pretty k])
rodrigogribeiro/mptc
src/Language/Haskell/Exts/Pretty.hs
bsd-3-clause
68,127
0
23
22,789
22,708
11,309
11,399
1,228
4
{-# LANGUAGE OverlappingInstances, ScopedTypeVariables, TemplateHaskell, FlexibleContexts #-} module YaLedger.Main (module YaLedger.Types, module YaLedger.Types.Reports, LedgerOptions (..), parseCmdLine, defaultParsers, defaultMain, lookupInit, initialize, runYaLedger ) where import Prelude hiding (catch) import Control.Applicative ((<$>)) import qualified Control.Exception as E import Control.Monad.State import Control.Monad.Exception import Control.Concurrent.ParallelIO import Data.Char import Data.Maybe import qualified Data.Map as M import Data.List import qualified Data.Text as T import Data.Monoid import Data.Dates import System.Environment import System.Console.GetOpt import Text.Parsec hiding (try) import System.FilePath import System.Environment.XDG.BaseDir import System.IO import System.Log.Logger import YaLedger.Types import YaLedger.Exceptions import YaLedger.Types.Reports import YaLedger.Parser import YaLedger.Parser.Common (pAttribute) import YaLedger.Parser.Currencies import YaLedger.Kernel import YaLedger.Kernel.Correspondence (buildGroupsMap) import YaLedger.Processor import YaLedger.Config import YaLedger.Logger import YaLedger.Reports.Common import YaLedger.Installer -- | Parrse NAME=VALUE attribute syntax parsePair :: String -> Either ParseError (String, AttributeValue) parsePair str = runParser pAttribute () str (T.pack str) -- | Parse PARSER=CONFIG syntax parseParserConfig :: String -> Maybe (String, FilePath) parseParserConfig str = case span (/= '=') str of (key, '=':value) -> Just (key, value) _ -> Nothing -- | Parse debug level (debug, warning etc) parseDebug :: String -> Maybe Priority parseDebug str = case reads (map toUpper str) of [(x, "")] -> Just x _ -> Nothing parseDebugPair :: String -> Maybe (String, Priority) parseDebugPair str = case break (== '=') str of (s,"") -> (\p -> ("", p)) <$> parseDebug s (name, _:s) -> (\p -> (name, p)) <$> parseDebug s -- | Apply SetOption to LedgerOptions apply :: SetOption -> LedgerOptions -> LedgerOptions apply (SetConfigPath path) opts = opts {mainConfigPath = Just path} apply (SetCoAPath path) opts = opts {chartOfAccounts = Just path} apply (SetAMapPath path) opts = opts {accountMap = Just path} apply (SetCurrenciesPath path) opts = opts {currenciesList = Just path} apply (AddFile (Just path)) opts = opts {files = path: files opts} apply (AddFile Nothing) opts = opts {files = []} apply (SetStartDate date) opts = opts {query = (query opts) {qStart = Just date}} apply (SetEndDate date) opts = opts {query = (query opts) {qEnd = Just date}} apply (SetAllAdmin) opts = opts {query = (query opts) {qAllAdmin = True}} apply (AddAttribute (n,v)) opts = let qry = query opts in opts {query = qry {qAttributes = M.insert n v (qAttributes qry)}} apply (SetReportStart date) opts = let qry = reportsQuery opts in opts {reportsQuery = qry {qStart = Just date}} apply (SetReportEnd date) opts = let qry = reportsQuery opts in opts {reportsQuery = qry {qEnd = Just date}} apply (SetGrep regex) opts = let qry = reportsQuery opts val = Regexp regex in opts {reportsQuery = qry {qAttributes = M.insert "description" val (qAttributes qry)}} apply (SetReportsInterval i) opts = opts {reportsInterval = Just i} apply (SetDebugLevel ("", lvl)) opts = opts {defaultLogSeverity = lvl} apply (SetDebugLevel (name, lvl)) opts = opts {logSeveritySetup = logSeveritySetup opts ++ [(name,lvl)] } apply (SetParserConfig (n,p)) opts = opts {parserConfigs = setParserConfig n p (parserConfigs opts)} apply (SetColorizeOutput) opts = opts {colorizeOutput = True} apply (SetOutputFile path) opts = opts {outputFile = Just path} apply SetHelp _ = Help setParserConfig :: String -> String -> [ParserSpec] -> [ParserSpec] setParserConfig name path specs = let p = case parserByName' name specs of Nothing -> case parserByName name of Nothing -> error $ "Unknown parser: " ++ name Just p -> p Just p -> p in (p {psConfigPath = path}): specs -- | Parse command line parseCmdLine :: [String] -> IO LedgerOptions parseCmdLine argv = do now <- getCurrentDateTime let attr v = case parsePair v of Right (name,value) -> (name, value) Left err -> error $ show err interval str = case runParser pDateInterval () str str of Left err -> error $ show err Right int -> int level str = case parseDebugPair str of Just value -> value Nothing -> error $ "Unknown debug level: " ++ str date str = case parseDate now str of Right date -> date Left err -> error $ show err pconfig str = case parseParserConfig str of Just (name,value) -> (name, value) Nothing -> error $ "Invalid parser config file specification: " ++ str ++ " (required: PARSER=CONFIGFILE)." let header = "Usage: yaledger [OPTIONS] [REPORT] [REPORT PARAMS]\n\ \ or: yaledger init [DIRECTORY]\n\ \Supported options are:" let options = [ Option "c" ["config"] (ReqArg SetConfigPath "FILE") "Use specified config file instead of ~/.config/yaledger/yaledger.yaml", Option "C" ["coa"] (ReqArg SetCoAPath "FILE") "Chart of accounts file to use", Option "M" ["map"] (ReqArg SetAMapPath "FILE") "Accounts map file to use", Option "r" ["currencies"] (ReqArg SetCurrenciesPath "FILE") "Currencies list file to use", Option "f" ["file"] (OptArg AddFile "FILE(s)") "Input file[s]", Option "s" ["start"] (ReqArg (SetStartDate . date) "DATE") "Process only transactions after this date", Option "e" ["end"] (ReqArg (SetEndDate . date) "DATE") "Process only transactions before this date", Option "S" ["report-from"] (ReqArg (SetReportStart . date) "DATE") "Start report from this date", Option "E" ["report-to"] (ReqArg (SetReportEnd . date) "DATE") "End report at this date", Option "g" ["grep"] (ReqArg SetGrep "REGEXP") "Show only records with description matching REGEXP", Option "A" ["all-admin"] (NoArg SetAllAdmin) "Process all admin records with any dates and attributes", Option "a" ["attribute"] (ReqArg (AddAttribute . attr) "NAME=VALUE") "Process only transactions with this attribute", Option "P" ["period"] (ReqArg (SetReportsInterval . interval) "PERIOD") "Output report by PERIOD", Option "" ["daily"] (NoArg (SetReportsInterval $ Days 1)) "Alias for --period \"1 day\"", Option "" ["weekly"] (NoArg (SetReportsInterval $ Weeks 1)) "Alias for --period \"1 week\"", Option "" ["monthly"] (NoArg (SetReportsInterval $ Months 1)) "Alias for --period \"1 month\"", Option "" ["yearly"] (NoArg (SetReportsInterval $ Years 1)) "Alias for --period \"1 year\"", Option "d" ["debug"] (ReqArg (SetDebugLevel . level) "[MODULE=]LEVEL") "Set debug level (for MODULE or for all modules) to LEVEL", Option "p" ["parser-config"] (ReqArg (SetParserConfig . pconfig) "PARSER=CONFIGFILE") "Use specified config file for this parser", Option "o" ["output"] (ReqArg SetOutputFile "FILE") "Output report to specified FILE", Option "" ["color", "colorize"] (NoArg SetColorizeOutput) "Use coloring when writing report to console", Option "h" ["help"] (NoArg SetHelp) "Show this help and exit" ] case getOpt RequireOrder options argv of (fns, params, []) -> do if SetHelp `elem` fns then do putStrLn $ usageInfo header options return Help else do configPath <- case [p | SetConfigPath p <- fns] of [] -> do configDir <- getUserConfigDir "yaledger" return (configDir </> "yaledger.yaml") (p:_) -> return p defaultOptions <- loadConfig configPath case foldr apply defaultOptions (reverse fns) of Help -> fail "Impossible: Main.parseCmdLine.Help" opts -> do let opts' = opts { mainConfigPath = Just configPath, reportsQuery = query opts `mappend` reportsQuery opts } if null params then return opts' else return $ opts' { defaultReport = head params, reportParams = tail params } (_,_,errs) -> fail $ concat errs ++ usageInfo header options -- | Lookup for items with keys starting with given prefix lookupInit :: String -> [(String, a)] -> [a] lookupInit key list = [v | (k,v) <- list, key `isPrefixOf` k] initialize :: [(String, Report)] -- ^ List of reports to support: (report name, report) -> [String] -> IO (Maybe (Report, LedgerOptions, [String])) initialize reports argv = do options <- parseCmdLine argv case options of Help -> do putStrLn $ "Supported reports are: " ++ unwords (map fst reports) return Nothing _ -> do setupLogger (defaultLogSeverity options) (logSeveritySetup options) $infoIO $ "Using chart of accounts: " ++ fromJust (chartOfAccounts options) $infoIO $ "Using accounts map: " ++ fromJust (accountMap options) $debugIO $ "Using parser configs:\n" ++ (unlines $ map show (parserConfigs options)) let report = defaultReport options params <- if null (reportParams options) then case lookupInit report (M.assocs $ defaultReportParams options) of [] -> return [] [str] -> return $ words str list -> do putStrLn $ "Ambigous report specification: " ++ report ++ "\nSupported reports are: " ++ unwords (map fst reports) return [] else return $ reportParams options case lookupInit report reports of [] -> do putStrLn $ "No such report: " ++ report ++ "\nSupported reports are: " ++ unwords (map fst reports) return Nothing [fn] -> return $ Just (fn, options, params) _ -> do putStrLn $ "Ambigous report specification: " ++ report ++ "\nSupported reports are: " ++ unwords (map fst reports) return Nothing -- | Default `main' function defaultMain :: [(String, Report)] -- ^ List of reports to support: (report name, report) -> IO () defaultMain reports = do argv <- getArgs if (not $ null argv) && (head argv == "init") then install $ tail argv else do init <- initialize reports argv case init of Nothing -> return () Just (report, options, params) -> runYaLedger options report params tryE action = (Right <$> action) `catchWithSrcLoc` (\l e -> return (Left (l, e))) fromJustM msg Nothing = fail msg fromJustM _ (Just x) = return x loadConfigs :: FilePath -> FilePath -> FilePath -> IO (Currencies, ChartOfAccounts, AccountMap) loadConfigs cpath coaPath mapPath = do currs <- loadCurrencies cpath let currsMap = M.fromList [(cSymbol c, c) | c <- currs] coa <- readCoA currsMap coaPath amap <- readAMap currsMap coa mapPath return (currsMap, coa, amap) withOutputFile :: Throws InternalError l => Ledger l a -> Ledger l a withOutputFile action = do mbPath <- gets (outputFile . lsConfig) case mbPath of Just path -> do handle <- wrapIO $ openFile path WriteMode modify $ \st -> st {lsOutput = handle} result <- action wrapIO $ hClose handle modify $ \st -> st {lsOutput = stdout} return result Nothing -> action runYaLedger :: LedgerOptions -> Report -> [String] -> IO () runYaLedger options report params = do coaPath <- fromJustM "No CoA path specified" (chartOfAccounts options) mapPath <- fromJustM "No accounts map path specified" (accountMap options) cpath <- fromJustM "No currencies list file specified" (currenciesList options) let mbInterval = reportsInterval options rules = deduplicationRules options inputPaths = files options qry = query options qryReport = reportsQuery options $debugIO $ "Deduplication rules: " ++ show rules (currsMap, coa, amap) <- loadConfigs cpath coaPath mapPath `E.catch` (\(e :: SomeException) -> do fail $ "An error occured while loading configs:\n " ++ show e ++ "\nIf you do not have any configs, just run `yaledger init' command." ) records <- parseInputFiles options currsMap coa inputPaths $debugIO $ "Records loaded." runLedger options currsMap coa amap records $ runEMT $ do -- Build full map of groups of accounts. modify $ \st -> st { lsFullGroupsMap = buildGroupsMap coa [1.. snd (agRange $ branchData coa)] } processYaLedger qry mbInterval rules (filter (checkRecord qry) records) qryReport report params stopGlobalPool processYaLedger qry mbInterval rules records qryReport report params = do now <- gets lsStartDate let endDate = fromMaybe now (qEnd qry) $info $ "Records query: " ++ show qry $info $ "Report query: " ++ show qryReport t <- tryE $ processRecords endDate rules records case t of Left (l, e :: SomeException) -> wrapIO $ putStrLn $ showExceptionWithTrace l e Right _ -> do let firstDate = minimum (map getDate records) let queries = case mbInterval of Nothing -> [qryReport] Just int -> splitQuery firstDate now qryReport int (withOutputFile $ runAReport queries params report) `catch` (\(e :: InvalidCmdLine) -> do wrapIO (putStrLn $ show e))
portnov/yaledger
YaLedger/Main.hs
bsd-3-clause
14,989
0
26
4,669
4,197
2,157
2,040
308
11
-- {-# LANGUAGE OverloadedStrings #-} -- {-# LANGUAGE RecordWildCards #-} -- {-# LANGUAGE MultiWayIf #-} import Development.Shake import Development.Shake.FilePath -- import Development.Shake.Util -- import Development.Shake.Command -- import Control.Applicative ((<$>)) import qualified Control.Monad as M -- import Data.Traversable -- import Text.Regex.Posix -- import Data.Maybe (fromMaybe) main :: IO () main = shakeArgs shakeOptions { -- shakeFiles="." shakeFiles="_build" -- , shakeProgress=progressSimple } $ do phony "clean" $ (do { -- liftIO $ removeFiles "." [...] ; removeFilesAfter "." $ tail [ undefined , "//*.html" , "//*.dbkhtml" , "//html" , "//dbkhtml" , "//*.fo", "//*.pdf" , "//pdf" , "//*.dbk", "//*.dbk+", "//*.dbkxi" , "snippets" , "_snippet_*" ] -- formerly in pire dir - but they really should go here -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords $ [ "rm -rf ./doctest-snippets" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords $ [ "rm -f *.dyn_hi" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords $ [ "rm -f *.dyn_o" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords $ [ "rm -f *.hi" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords $ [ "rm -f *.o" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords ["rm -f ./_*.hs" ] -- -- create w/ build.sh -B -V writedoctests -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords ["rm -f ./_*.hs" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords ["rm -f ./_*.hs" ] ; unit $ cmd Shell $ words $ unwords [ "rm -rf ./doctest-snippets" ] ; unit $ cmd Shell $ words $ unwords [ "rm -f *.dyn_hi" ] ; unit $ cmd Shell $ words $ unwords [ "rm -f *.dyn_o" ] ; unit $ cmd Shell $ words $ unwords [ "rm -f *.hi" ] ; unit $ cmd Shell $ words $ unwords [ "rm -f *.o" ] ; unit $ cmd Shell $ words $ unwords ["rm -f ./_*.hs" ] -- create w/ build.sh -B -V writedoctests ; unit $ cmd Shell $ words $ unwords ["rm -f ./_*.hs" ] ; unit $ cmd Shell $ words $ unwords ["rm -f ./_*.hs" ] }) -- shake clean phony "shclean" $ do { -- formerly in pire -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords [ "rm -rf _shake" ] -- ; unit $ cmd (Cwd "docs") Shell $ words $ unwords [ "rm -rf _build" ] ; unit $ cmd Shell $ words $ unwords [ "rm -rf _shake" ] ; unit $ cmd Shell $ words $ unwords [ "rm -rf _build" ] } phony "oclean" $ (do -- liftIO $ removeFiles "." [...] ; removeFilesAfter "." $ tail [ undefined , "//*.hi" , "//*.o" ] ) -- phony "sclean" $ -- (do -- ; removeFilesAfter "." $ tail [ -- undefined -- , "_snippet_*" -- ] -- ) -- "aka fonts clean" phony "fclean" $ do { -- maybe -- need ["clean"] ; removeFilesAfter "." $ tail [ undefined , "fonts/lucidatypewriter" , "fonts/palatino" , "fonts/palatinoi" , "fonts/dejavu" , "fonts/dejavui" , "fonts/dejavusansmono" -- , "urwclassico" , "fcreate" ] } "snippets" %> \c -> (do -- ; let hs = "support" </> (dropDirectory1 c) <.> ".hs" -- ; let hs = (dropDirectory1 c) <.> ".hs" ; let hs = c <.> ".hs" ; need [hs] ; () <- cmd Shell $ tail [ undefined , "ghc" , "-O2 -threaded" -- , "-outputdir=_build" -- , "-cpp" -- , "-DShakeDep" , "-o ", c , hs ] ; return () ) phony "allsnippets" $ (do ; need ["snippets"] -- ; let p = "~/website/static/pire" -- ; () <- cmd Shell [ "cp", "./pire.pdf" , p] -- ; () <- cmd Shell [ "cp", "-r", "./css" , p] ; () <- cmd Shell [ "snippets" , "--hsfile", "../src/docs.hs" , "--nicer" ] ; return () ) -- -------------------------------------------------- -- the program "doctest-snippets" %> \c -> (do -- ; let hs = "support" </> (dropDirectory1 c) <.> ".hs" -- ; let hs = (dropDirectory1 c) <.> ".hs" ; let hs = c <.> ".hs" ; need [hs] ; () <- cmd Shell $ words $ unwords $ tail [ undefined , "ghc" , "-O2 -threaded" -- , "-outputdir=_build" -- , "-cpp" -- , "-DShakeDep" , "-o ", c , hs ] ; return () ) "_*.hs" %> \hs -> (do -- ; let hs = "support" </> (dropDirectory1 c) <.> ".hs" -- ; let hs = (dropDirectory1 c) <.> ".hs" ; let adoc = (tail hs) -<.> "adoc" ; need ["doctest-snippets"] ; need [adoc] ; () <- cmd Shell $ words $ unwords $ tail [ undefined , "doctest-snippets" , "--adoc", adoc , ">", hs ] ; return () ) phony "writedoctests" $ (do ; let ch = tail [ undefined , "parsec.adoc" , "tour.adoc" , "backtracking+mimicry.adoc" , "zipperimpl.adoc" ] ; let ch' = (('_':) . (-<.> "hs")) <$> ch -- ; let chapters' = chapters ; need ch' ; M.mapM (\c -> (do ; () <- cmd Shell [ "cp" -- , c, "../tests" , c, "../src" ] ; return () ) ) ch' -- ; let chapters = ["parsec.adoc", "tour.adoc"] -- ; let chapters' = ((\ch -> '_':(ch -<.> "hs")) <$> chapters) -- ; need chapters' ; return () ) -- -------------------------------------------------- -- test w/ -- -- $ (cd ~/etc/lib-pi-forall/ && find . -iname "*" -print0 -type f | egrep -z -Z -v "^.$|\.cabal-sandbox|/dist|cabal\.sandbox\.config" | xargs -0 -L 1) -- -- $ (cd ~/etc/lib-pi-forall/ && find . -iname "*" -print0 -type f | egrep -z -Z -v "^.$|\.cabal-sandbox|/dist" | rsync -a -e ssh --delete --progress --files-from=- -0 ./ ~/website/static/lib-pi-forall) -- cf sync -- -- only by egrep -v "^.$" as well are the empty dir dist/ and cabal.sandbox.config excluded -- -- ie. normally the sneak in by . result of find phony "web-lib-pi-forall" $ do { ; () <- cmd Shell [ "(cd /home/rx/etc/lib-pi-forall && find . -iname \"*\" -print0 -type f" ,"| egrep -z -Z -v \"^\\.$|\\.cabal-sandbox|/dist|cabal\\.sandbox\\.config\"" -- ,"| xargs -0 -L 1" -- ,"| rsync -a -e ssh --delete --progress --files-from=- ./ /home/rx/website/static/lib-pi-forall/)" , -- "| rsync -a -e ssh --delete-missing-args --delete --progress --files-from=- -0 ./ /home/rx/website/static/lib-pi-forall/)" -- --exclude='*/' removes empty dirs/ at least - why is that transferred in the first place ? -- --exclude='' removes empty dirs/ at least - why is that transferred in the first place ? "| rsync -a -e ssh --delete --progress --files-from=- -0 ./ /home/rx/website/static/lib-pi-forall/)" ] -- create tgz ; () <- cmd Shell [ "(cd /home/rx/website/static && rm -rf lib-pi-forall.tgz && tar cvpzf lib-pi-forall.tgz lib-pi-forall)" ] -- provide lib-pi-forall.cabal file ; () <- cmd Shell [ "cp /home/rx/etc/lib-pi-forall/lib-pi-forall.cabal /home/rx/website/static" ] ; return () } phony "web" $ do { ; need ["pire.pdf"] ; need ["pire.html"] ; let p = "~/website/static/pire" ; () <- cmd Shell [ "cp", "./pire.pdf" , p] ; () <- cmd Shell [ "cp", "./pire.html" , p] ; () <- cmd Shell [ "cp", "-r", "./css" , p] ; need ["web-lib-pi-forall"] -- jan2016 - sync website to website_ -- as that is, what's used on web -- (backup.py -t web -web copies both: website, and website_) -- and recall: /etc/init.d/website starts the srv in /home/rx/website_ -- (ie. website_ is used on the srv) ; () <- cmd Shell [ -- "(cd /home/rx/website && sync)" -- july 2016 -- "(cd /home/rx/website && ./sync.hs -t /home/rx/website_)" "(cd /home/rx/work/servant && ./sync.hs -t /home/rx/website_)" ] ; return () } -- create link "html" %> \lnk -> do let html = "pire.html" need [html] () <- cmd Shell $ words $ unwords $ tail [ undefined , "ln -s -f "++html++" ./" ++ lnk ] return () -- create link "dbkhtml" %> \lnk -> do let dh = "pire.dbkhtml" need [dh] () <- cmd Shell $ tail [ undefined , "ln -s -f "++dh++" ./" ++ lnk ] return () -- asciidoctor html "*.html" %> \h -> do let ad = h -<.> "adoc" need [ad] () <- cmd Shell $ words $ unwords $ tail [ undefined , "asciidoctor -a linkcss -a stylesdir=css -a stylesheet=pire.css "++ad -- , "asciidoctor -b xhtml5 -a linkcss -a stylesdir=css -a stylesheet=pire.css "++ad ] return () -- w/ deps - ! should really get them automatically "pire.html" %> \h -> do let ad = h -<.> "adoc" need [ad] -- deps need ["intro.adoc" , "tour.adoc" , "changes.adoc" ] () <- cmd Shell $ words $ unwords $ tail [ undefined , "asciidoctor -a linkcss -a stylesdir=css -a stylesheet=pire.css "++ad -- , "asciidoctor -b xhtml5 -a linkcss -a stylesdir=css -a stylesheet=pire.css "++ad ] return () -- dbk html "*.dbkhtml" %> \h -> do let plus = h -<.> "dbk+" -- let dbk = dropExtension tex need [plus] () <- cmd Shell $ tail [ undefined , "xsltproc --xinclude --xincludestyle --output "++h++" --stringparam use.extensions 0 ./html.xsl "++plus ] return () -- create link pdf -> pire.pdf "pdf" %> \lnk -> do let pdf = "pire.pdf" need [pdf] () <- cmd Shell $ tail [ undefined , "ln -s -f "++pdf++" ./" ++ lnk ] return () -- need fonts as well, but rather build them by hand "*.pdf" %> \pdf -> do let fo = pdf -<.> "fo" need [fo] need ["cfg"] -- but rather do them by hand -- need ["fcreate"] () <- cmd Shell $ tail [ undefined , "fop -c cfg -fo "++fo++" -pdf "++pdf ] return () "*.fo" %> \fo -> do let p = fo -<.> "dbk+" need [p] need ["fo.xsl"] () <- cmd Shell $ tail [ undefined , "xsltproc --xinclude --xincludestyle --output "++fo++" --stringparam fop1.extensions 1 fo.xsl "++p ] return () "*.dbk" %> \d -> do -- turn off preprocessing, so that the html can be used for cut & paste -- still needed ? let ad = d -<.> "adoc" -- -- let dbk = dropExtension x need [ad] () <- cmd Shell $ tail [ undefined , "asciidoctor -b docbook5 -o "++d++" "++ad -- dbk5 should be the default for dbk later -- , "asciidoctor -b docbook "++ad ] return () "*.dbk+" %> \p -> do -- turn off preprocessing, so that the html can be used for cut & paste -- still needed ? let xi = p -<.> "dbkxi" -- let dbk = dropExtension tex need [xi] () <- cmd Shell $ tail [ undefined , "saxonb-xslt -xi -s:"++xi++" -xsl:preproc.xsl -o:"++p ] return () "*.dbkxi" %> \xi -> do let dbk = xi -<.> "dbk" -- let dbk = dropExtension tex need [dbk] () <- cmd Shell $ tail [ undefined -- want xincludes and just plain section tags... , "xmllint --xinclude "++dbk++" | saxonb-xslt -s:- -xsl:rm-xml-base-etc.xsl -o:"++xi ] return () -- phony "fonts" $ do "fcreate" %> \f -> (do ; need $ tail [ undefined , "fonts/lucidatypewriter" , "fonts/palatino" , "fonts/palatinoi" , "fonts/dejavu" , "fonts/dejavui" , "fonts/dejavusansmono" -- , "optima" -- , "urwclassico" ] -- touch a file fonts-created as an indicator that the fonts -- have been created, -- as opposed to using a phony target and creating them -- over and over again ; () <- cmd Shell $ tail [ undefined , "touch "++f ] ; return () ) "fonts/lucidatypewriter" %> \f -> (do ; () <- cmd Shell $ tail [ undefined , "fop-ttfreader ./fonts/LucidaTypewriter.ttf "++f ] ; return () ) "fonts/palatino" %> \f -> (do ; () <- cmd Shell $ tail [ undefined , "fop-ttfreader ./fonts/PalatinoLinotype.ttf "++f ] ; return () ) "fonts/palatinoi" %> \f -> (do ; () <- cmd Shell $ tail [ undefined , "fop-ttfreader ./fonts/PalatinoLinotypeItalic.ttf "++f ] ; return () ) "fonts/dejavu" %> \f -> do { ; () <- cmd Shell $ tail [ undefined , "fop-ttfreader /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf "++f ] ; return () } "fonts/dejavui" %> \f -> do { ; () <- cmd Shell $ tail [ undefined , "fop-ttfreader /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Italic.ttf "++f ] ; return () } "fonts/dejavusansmono" %> \f -> do { ; () <- cmd Shell $ tail [ undefined , "fop-ttfreader /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf "++f ] ; return () } -- "urwclassico" %> \f -> do -- () <- cmd Shell $ tail [ -- undefined -- , "./my-fop-pfmreader ./fonts/uopr8a.pfm "++f -- ] -- return () {- remark: I often write lists as tail $ [ undefined , item1 , item2 , etc ] rather than [ item1 , item2 , etc ] that way I can more easily comment out items (lines), or move them up/down, as all items start w/ a comma then, and the first item is not in any way special -} ; "_build/gitignore" %> \c -> do { -- ; let hs = "support" </> (dropDirectory1 c) <.> ".hs" -- ; hs <- return $ (dropDirectory1 c) <.> ".hs" -- -- ; hs <- return $ c <.> ".hs" ; let hs = (dropDirectory1 c) <.> ".hs" ; need [hs] ; () <- cmd Shell $ tail [ undefined , "ghc" , "-O2 -threaded" -- , "-outputdir=_build" , "-cpp" -- -- , if ShakeDep `elem` flgs then -- -- "-DShakeDep" else "" -- -- , if Min `elem` flgs then -- -- "-DMin" else "" , "-o ", c , hs ] ; return () } ; ".gitignore" %> \c -> do { -- ; need ["gitignore"] ; need ["_build/gitignore"] ; () <- do { ; cmd Shell $ tail [ undefined ,"./_build/gitignore" -- ,"./gitignore" , ">" , c ] } ; return () }
reuleaux/pire
docs/Build.hs
bsd-3-clause
17,072
44
20
7,190
2,837
1,467
1,370
273
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} -- | Type-level specification of Explorer API (via Servant). module Pos.Explorer.Web.Api ( ExplorerApi , explorerApi , ExplorerApiRecord(..) ) where import Universum import Control.Exception.Safe (try) import Data.Proxy (Proxy (Proxy)) import Servant.API ((:>), Capture, Get, JSON, Post, QueryParam, ReqBody, Summary) import Servant.API.Generic ((:-), ToServantApi) import Servant.Server (ServantErr (..)) import Pos.Core (EpochIndex) import Pos.Explorer.Web.ClientTypes (Byte, CAda, CAddress, CAddressSummary, CAddressesFilter, CBlockEntry, CBlockSummary, CGenesisAddressInfo, CGenesisSummary, CHash, CTxBrief, CTxEntry, CTxId, CTxSummary, CUtxo, CBlockRange) import Pos.Explorer.Web.Error (ExplorerError) import Pos.Util.Servant (DQueryParam, ModifiesApiRes (..), VerbMod) type PageNumber = Integer -- | API result modification mode used here. data ExplorerVerbTag -- | Wrapper for Servants 'Verb' data type, -- which allows to catch exceptions thrown by Explorer's endpoints. type ExplorerVerb verb = VerbMod ExplorerVerbTag verb -- | Shortcut for common api result types. type ExRes verbMethod a = ExplorerVerb (verbMethod '[JSON] a) instance ModifiesApiRes ExplorerVerbTag where type ApiModifiedRes ExplorerVerbTag a = Either ExplorerError a modifyApiResult :: Proxy ExplorerVerbTag -> IO (Either ServantErr a) -> IO (Either ServantErr (Either ExplorerError a)) modifyApiResult _ action = try . try $ either throwM pure =<< action -- | Servant API which provides access to explorer type ExplorerApi = "api" :> ToServantApi ExplorerApiRecord -- | Helper Proxy explorerApi :: Proxy ExplorerApi explorerApi = Proxy -- | A servant-generic record with all the methods of the API data ExplorerApiRecord route = ExplorerApiRecord { _totalAda :: route :- "supply" :> "ada" :> ExRes Get CAda , _blocksPages :: route :- Summary "Get the list of blocks, contained in pages." :> "blocks" :> "pages" :> QueryParam "page" Word :> QueryParam "pageSize" Word :> ExRes Get (PageNumber, [CBlockEntry]) , _dumpBlockRange :: route :- Summary "Dump a range of blocks, including all tx in those blocks" :> "blocks" :> "range" :> Capture "start" CHash :> Capture "stop" CHash :> ExRes Get CBlockRange , _blocksPagesTotal :: route :- Summary "Get the list of total pages." :> "blocks" :> "pages" :> "total" :> QueryParam "pageSize" Word :> ExRes Get PageNumber , _blocksSummary :: route :- Summary "Get block's summary information." :> "blocks" :> "summary" :> Capture "hash" CHash :> ExRes Get CBlockSummary , _blocksTxs :: route :- Summary "Get brief information about transactions." :> "blocks" :> "txs" :> Capture "hash" CHash :> QueryParam "limit" Word :> QueryParam "offset" Word :> ExRes Get [CTxBrief] , _txsLast :: route :- Summary "Get information about the N latest transactions." :> "txs" :> "last" :> ExRes Get [CTxEntry] , _txsSummary :: route :- Summary "Get summary information about a transaction." :> "txs" :> "summary" :> Capture "txid" CTxId :> ExRes Get CTxSummary , _addressSummary :: route :- Summary "Get summary information about an address." :> "addresses" :> "summary" :> Capture "address" CAddress :> ExRes Get CAddressSummary , _addressUtxoBulk :: route :- Summary "Get summary information about multiple addresses." :> "bulk" :> "addresses" :> "utxo" :> ReqBody '[JSON] [CAddress] :> ExRes Post [CUtxo] , _epochPages :: route :- Summary "Get epoch pages, all the paged slots in the epoch." :> "epochs" :> Capture "epoch" EpochIndex :> QueryParam "page" Int :> ExRes Get (Int, [CBlockEntry]) , _epochSlots :: route :- Summary "Get the slot information in an epoch." :> "epochs" :> Capture "epoch" EpochIndex :> Capture "slot" Word16 :> ExRes Get [CBlockEntry] , _genesisSummary :: route :- "genesis" :> "summary" :> ExRes Get CGenesisSummary , _genesisPagesTotal :: route :- "genesis" :> "address" :> "pages" :> "total" :> QueryParam "pageSize" Word :> DQueryParam "filter" CAddressesFilter :> ExRes Get PageNumber , _genesisAddressInfo :: route :- "genesis" :> "address" :> QueryParam "page" Word :> QueryParam "pageSize" Word :> DQueryParam "filter" CAddressesFilter :> ExRes Get [CGenesisAddressInfo] , _statsTxs :: route :- "stats" :> "txs" :> QueryParam "page" Word :> ExRes Get TxsStats } deriving (Generic) type TxsStats = (PageNumber, [(CTxId, Byte)])
input-output-hk/pos-haskell-prototype
explorer/src/Pos/Explorer/Web/Api.hs
mit
5,375
0
17
1,613
1,124
610
514
-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="fil-PH"> <title>Code Dx | Ekstensyon ng ZAP</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Mga Nilalaman</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Maghanap</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Mga Paborito</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_fil_PH/helpset_fil_PH.hs
apache-2.0
985
80
66
163
423
213
210
-1
-1
{-# LANGUAGE ParallelListComp #-} {-# LANGUAGE TemplateHaskell #-} module Database.DSH.SL.Opt.Rewrite.Projections where -- This module contains rewrites which aim to simplify and merge complex expressions -- which are expressed through multiple operators. import Control.Monad import Database.Algebra.Dag.Common import Database.DSH.Common.Opt import Database.DSH.Common.VectorLang import Database.DSH.SL.Lang import Database.DSH.SL.Opt.Rewrite.Common optExpressions :: SLRewrite TExpr TExpr Bool optExpressions = iteratively $ applyToAll noProps expressionRules expressionRules :: SLRuleSet TExpr TExpr () expressionRules = [ mergeProject , identityProject , pullProjectSelect , pullProjectAppKey , pullProjectAppMap , pullProjectSort , pullProjectMergeSegLeft , pullProjectMergeSegRight , pullProjectNumber , pullProjectSegment , pullProjectUnsegment , pullProjectGroupR1 , pullProjectGroupR2 , pullProjectGroupAggr , pullProjectUnboxDefaultLeft , pullProjectUnboxSngLeft , pullProjectUnboxSngRight , pullProjectNestJoinLeft , pullProjectNestJoinRight , pullProjectThetaJoinLeft , pullProjectThetaJoinRight , pullProjectFilterJoinLeft , pullProjectFilterJoinRight , pullProjectReplicateVecLeft , pullProjectReplicateVecRight , pullProjectCartProductLeft , pullProjectCartProductRight , pullProjectGroupJoinLeft , pullProjectGroupJoinRight , pullProjectReplicateScalarRight , pullProjectAlignLeft , pullProjectAlignRight , pullProjectDistLiftLeft , pullProjectDistLiftRight ] mergeProject :: SLRule TExpr TExpr () mergeProject q = $(dagPatMatch 'q "Project e2 (Project e1 (q1))" [| do return $ do logRewrite "Expr.Merge.11" q let e2' = partialEval $ mergeExpr $(v "e1") $(v "e2") void $ replaceWithNew q $ UnOp (Project e2') $(v "q1") |]) pullProjectSelect :: SLRule TExpr TExpr () pullProjectSelect q = $(dagPatMatch 'q "R1 (qs=Select p (Project e (q1)))" [| do return $ do logRewrite "Expr.Merge.Select" q let p' = partialEval $ mergeExpr $(v "e") $(v "p") selectNode <- insert $ UnOp (Select p') $(v "q1") r1Node <- insert $ UnOp R1 selectNode void $ replaceWithNew q $ UnOp (Project $(v "e")) r1Node r2Parents <- lookupR2Parents $(v "qs") -- If there are any R2 nodes linking to the original -- Restrict operator (i.e. there are inner vectors to which -- changes must be propagated), they have to be rewired to -- the new Select operator. when (not $ null r2Parents) $ do qr2' <- insert $ UnOp R2 selectNode mapM_ (\qr2 -> replace qr2 qr2') r2Parents |]) identityProject :: SLRule TExpr TExpr () identityProject q = $(dagPatMatch 'q "Project e (q1)" [| do TInput <- return $(v "e") return $ do logRewrite "Project.Identity" q replace q $(v "q1") |]) pullProjectDistLiftLeft :: SLRule TExpr TExpr () pullProjectDistLiftLeft q = $(dagPatMatch 'q "R1 ((Project e (q1)) ReplicateNest (q2))" [| do return $ do logRewrite "Redundant.ReplicateNest.Project.Left" q -- Take the projection expressions from the left and the -- shifted columns from the right. let e' = appExprFst $(v "e") distNode <- insert $ BinOp ReplicateNest $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 distNode void $ replaceWithNew q $ UnOp (Project e') r1Node |]) pullProjectDistLiftRight :: SLRule TExpr TExpr () pullProjectDistLiftRight q = $(dagPatMatch 'q "R1 ((q1) ReplicateNest (Project e (q2)))" [| do return $ do logRewrite "Redundant.ReplicateNest.Project.Right" q let e' = appExprSnd $(v "e") distNode <- insert $ BinOp ReplicateNest $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 distNode void $ replaceWithNew q $ UnOp (Project e') r1Node |]) pullProjectAlignLeft :: SLRule TExpr TExpr () pullProjectAlignLeft q = $(dagPatMatch 'q "(Project e (q1)) Align (q2)" [| do return $ do logRewrite "Redundant.Align.Project.Left" q -- Take the projection expressions from the left and the -- shifted columns from the right. let e' = appExprFst $(v "e") alignNode <- insert $ BinOp Align $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp (Project e') alignNode |]) pullProjectAlignRight :: SLRule TExpr TExpr () pullProjectAlignRight q = $(dagPatMatch 'q "(q1) Align (Project e (q2))" [| do return $ do logRewrite "Redundant.Align.Project.Right" q -- Take the projection expressions from the right and the -- shifted columns from the left. let e' = appExprSnd $(v "e") alignNode <- insert $ BinOp Align $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp (Project e') alignNode |]) pullProjectGroupJoinLeft :: SLRule TExpr TExpr () pullProjectGroupJoinLeft q = $(dagPatMatch 'q "(Project e (q1)) GroupJoin args (q2)" [| do let (p, as) = $(v "args") return $ do logRewrite "Redundant.Project.GroupJoin.Left" q let p' = partialEval <$> inlineJoinPredLeft $(v "e") p as' = fmap (fmap (partialEval . (mergeExpr $ appExprFst $(v "e")))) as e' = appExprFst $(v "e") joinNode <- insert $ BinOp (GroupJoin (p', as')) $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp (Project e') joinNode |]) pullProjectGroupJoinRight :: SLRule TExpr TExpr () pullProjectGroupJoinRight q = $(dagPatMatch 'q "(q1) GroupJoin args (Project e (q2))" [| do let (p, as) = $(v "args") return $ do logRewrite "Redundant.Project.GroupJoin.Right" q let p' = partialEval <$> inlineJoinPredRight e p as' = fmap (fmap (partialEval . (mergeExpr $ appExprSnd $(v "e")))) as void $ replaceWithNew q $ BinOp (GroupJoin (p', as')) $(v "q1") $(v "q2") |]) pullProjectReplicateVecLeft :: SLRule TExpr TExpr () pullProjectReplicateVecLeft q = $(dagPatMatch 'q "R1 ((Project proj (q1)) ReplicateVector (q2))" [| return $ do logRewrite "Redundant.Project.ReplicateVector.Left" q repNode <- insert $ BinOp ReplicateVector $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 repNode void $ replaceWithNew q $ UnOp (Project $(v "proj")) r1Node -- FIXME relink R2 parents |]) pullProjectReplicateVecRight :: SLRule TExpr TExpr () pullProjectReplicateVecRight q = $(dagPatMatch 'q "R1 ((q1) ReplicateVector (Project _ (q2)))" [| return $ do logRewrite "Redundant.Project.ReplicateVector.Right" q repNode <- insert $ BinOp ReplicateVector $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp R1 repNode -- FIXME relink R2 parents |]) pullProjectFilterJoinLeft :: SLRule TExpr TExpr () pullProjectFilterJoinLeft q = $(dagPatMatch 'q "R1 ((Project e (q1)) [SemiJoin | AntiJoin]@joinOp p (q2))" [| do return $ do logRewrite "Redundant.Project.FilterJoin.Left" q let p' = partialEval <$> inlineJoinPredLeft $(v "e") $(v "p") joinNode <- insert $ BinOp ($(v "joinOp") p') $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 joinNode void $ replaceWithNew q $ UnOp (Project $(v "e")) r1Node -- FIXME relink R2 |]) pullProjectFilterJoinRight :: SLRule TExpr TExpr () pullProjectFilterJoinRight q = $(dagPatMatch 'q "R1 ((q1) [SemiJoin | AntiJoin]@joinOp p (Project e (q2)))" [| do return $ do logRewrite "Redundant.Project.FilterJoin.Right" q let p' = partialEval <$> inlineJoinPredRight $(v "e") $(v "p") joinNode <- insert $ BinOp ($(v "joinOp") p') $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp R1 joinNode -- FIXME relink R2 |]) pullProjectNestJoinLeft :: SLRule TExpr TExpr () pullProjectNestJoinLeft q = $(dagPatMatch 'q "R1 ((Project e (q1)) NestJoin p (q2))" [| do return $ do logRewrite "Redundant.Project.NestJoin.Left" q let e' = partialEval $ appExprFst $(v "e") p' = partialEval <$> inlineJoinPredLeft $(v "e") $(v "p") joinNode <- insert $ BinOp (NestJoin p') $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 joinNode void $ replaceWithNew q $ UnOp (Project e') r1Node -- FIXME relink R2 and R3 parents |]) pullProjectNestJoinRight :: SLRule TExpr TExpr () pullProjectNestJoinRight q = $(dagPatMatch 'q "R1 ((q1) NestJoin p (Project e (q2)))" [| do return $ do logRewrite "Redundant.Project.NestJoin.Right" q let e' = partialEval $ appExprSnd $(v "e") p' = partialEval <$> inlineJoinPredRight $(v "e") $(v "p") joinNode <- insert $ BinOp (NestJoin p') $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 joinNode void $ replaceWithNew q $ UnOp (Project e') r1Node -- FIXME relink R2 and R3 parents |]) pullProjectThetaJoinLeft :: SLRule TExpr TExpr () pullProjectThetaJoinLeft q = $(dagPatMatch 'q "R1 ((Project e (q1)) ThetaJoin p (q2))" [| do return $ do logRewrite "Redundant.Project.ThetaJoin.Left" q let e' = partialEval $ appExprFst $(v "e") p' = partialEval <$> inlineJoinPredLeft $(v "e") $(v "p") joinNode <- insert $ BinOp (ThetaJoin p') $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 joinNode void $ replaceWithNew q $ UnOp (Project e') r1Node -- FIXME relink R2 and R3 parents |]) pullProjectThetaJoinRight :: SLRule TExpr TExpr () pullProjectThetaJoinRight q = $(dagPatMatch 'q "R1 ((q1) ThetaJoin p (Project e (q2)))" [| do return $ do logRewrite "Redundant.Project.ThetaJoin.Right" q let e' = partialEval $ appExprSnd $(v "e") p' = partialEval <$> inlineJoinPredRight $(v "e") $(v "p") joinNode <- insert $ BinOp (ThetaJoin p') $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 joinNode void $ replaceWithNew q $ UnOp (Project e') r1Node -- FIXME relink R2 and R3 parents |]) pullProjectCartProductLeft :: SLRule TExpr TExpr () pullProjectCartProductLeft q = $(dagPatMatch 'q "R1 ((Project e (q1)) CartProduct (q2))" [| do return $ do logRewrite "Redundant.Project.CartProduct.Left" q let e' = appExprFst $(v "e") prodNode <- insert $ BinOp CartProduct $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 prodNode void $ replaceWithNew q $ UnOp (Project e') r1Node -- FIXME relink R2 and R3 parents |]) pullProjectCartProductRight :: SLRule TExpr TExpr () pullProjectCartProductRight q = $(dagPatMatch 'q "R1 ((q1) CartProduct (Project e (q2)))" [| do return $ do logRewrite "Redundant.Project.CartProduct.Right" q let e' = appExprSnd $(v "e") prodNode <- insert $ BinOp CartProduct $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 prodNode void $ replaceWithNew q $ UnOp (Project e') r1Node -- FIXME relink R2 and R3 parents |]) pullProjectNumber :: SLRule TExpr TExpr () pullProjectNumber q = $(dagPatMatch 'q "Number (Project e (q1))" [| do return $ do logRewrite "Redundant.Project.Number" q -- We have to preserve the numbering column in the -- pulled-up projection. let e' = appExprFst $(v "e") numberNode <- insert $ UnOp Number $(v "q1") void $ replaceWithNew q $ UnOp (Project e') numberNode |]) pullProjectGroupAggr :: SLRule TExpr TExpr () pullProjectGroupAggr q = $(dagPatMatch 'q "GroupAggr args (Project e (q1))" [| do return $ do logRewrite "Redundant.Project.GroupAggr" q let (g, as) = $(v "args") g' = partialEval $ mergeExpr $(v "e") g as' = fmap ((partialEval . mergeExpr $(v "e")) <$>) as void $ replaceWithNew q $ UnOp (GroupAggr (g', as')) $(v "q1") |]) pullProjectSort :: SLRule TExpr TExpr () pullProjectSort q = $(dagPatMatch 'q "R1 (Sort se (Project e (q1)))" [| return $ do logRewrite "Redundant.Project.Sort" q let se' = partialEval $ mergeExpr $(v "e") $(v "se") sortNode <- insert $ UnOp (Sort se') $(v "q1") r1Node <- insert (UnOp R1 sortNode) void $ replaceWithNew q $ UnOp (Project $(v "e")) r1Node |]) -- Motivation: In order to eliminate or pull up sorting operations in -- SL rewrites or subsequent stages, payload columns which might -- induce sort order should be available as long as possible. We -- assume that the cost of having unrequired columns around is -- negligible (best case: column store). pullProjectAppKey :: SLRule TExpr TExpr () pullProjectAppKey q = $(dagPatMatch 'q "(qp) AppKey (Project proj (qv))" [| return $ do logRewrite "Redundant.Project.AppKey" q rekeyNode <- insert $ BinOp AppKey $(v "qp") $(v "qv") void $ replaceWithNew q $ UnOp (Project $(v "proj")) rekeyNode |]) pullProjectUnboxSngLeft :: SLRule TExpr TExpr () pullProjectUnboxSngLeft q = $(dagPatMatch 'q "R1 ((Project e (q1)) UnboxSng (q2))" [| do return $ do logRewrite "Redundant.Project.UnboxSng.Left" q -- Employ projection expressions on top of the unboxing -- operator, add right input columns. let e' = appExprFst $(v "e") unboxNode <- insert $ BinOp UnboxSng $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 unboxNode void $ replaceWithNew q $ UnOp (Project e') r1Node |]) pullProjectUnboxDefaultLeft :: SLRule TExpr TExpr () pullProjectUnboxDefaultLeft q = $(dagPatMatch 'q "(Project e (q1)) UnboxDefault d (q2)" [| do return $ do logRewrite "Redundant.Project.UnboxDefault.Left" q -- Employ projection expressions on top of the unboxing -- operator, add right input columns. let e' = partialEval $ appExprFst $(v "e") unboxNode <- insert $ BinOp (UnboxDefault $(v "d")) $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp (Project e') unboxNode |]) pullProjectUnboxSngRight :: SLRule TExpr TExpr () pullProjectUnboxSngRight q = $(dagPatMatch 'q "R1 ((q1) UnboxSng (Project e (q2)))" [| do return $ do logRewrite "Redundant.Project.UnboxSng.Right" q -- Preserve left input columns on top of the unboxing -- operator and add right input expressions with shifted -- columns. let e' = appExprSnd $(v "e") unboxNode <- insert $ BinOp UnboxSng $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 unboxNode void $ replaceWithNew q $ UnOp (Project e') r1Node |]) pullProjectReplicateScalarRight :: SLRule TExpr TExpr () pullProjectReplicateScalarRight q = $(dagPatMatch 'q "R1 ((q1) ReplicateScalar (Project e (q2)))" [| do return $ do logRewrite "Redundant.Project.ReplicateScalar" q let e' = appExprSnd $(v "e") distNode <- insert $ BinOp ReplicateScalar $(v "q1") $(v "q2") r1Node <- insert $ UnOp R1 distNode void $ replaceWithNew q $ UnOp (Project e') r1Node |]) pullProjectAppMap :: SLRule TExpr TExpr () pullProjectAppMap q = $(dagPatMatch 'q "R1 ((qp) [AppRep | AppSort | AppFilter]@op (Project proj (qv)))" [| return $ do logRewrite "Redundant.Project.AppMap" q repNode <- insert $ BinOp $(v "op") $(v "qp") $(v "qv") r1Node <- insert $ UnOp R1 repNode void $ replaceWithNew q $ UnOp (Project $(v "proj")) r1Node |]) pullProjectMergeSegLeft :: SLRule TExpr TExpr () pullProjectMergeSegLeft q = $(dagPatMatch 'q "(Project _ (q1)) MergeSeg (q2)" [| return $ do logRewrite "Redundant.Project.MergeSeg.Left" q void $ replaceWithNew q $ BinOp MergeSeg $(v "q1") $(v "q2") |]) pullProjectMergeSegRight :: SLRule TExpr TExpr () pullProjectMergeSegRight q = $(dagPatMatch 'q "(q1) MergeSeg (Project e (q2))" [| return $ do logRewrite "Redundant.Project.MergeSeg.Right" q mergeNode <- insert $ BinOp MergeSeg $(v "q1") $(v "q2") void $ replaceWithNew q $ UnOp (Project $(v "e")) mergeNode |]) pullProjectUnsegment :: SLRule TExpr TExpr () pullProjectUnsegment q = $(dagPatMatch 'q "Unsegment (Project e (q1))" [| return $ do logRewrite "Redundant.Project.Unsegment" q segNode <- insert $ UnOp Unsegment $(v "q1") void $ replaceWithNew q $ UnOp (Project $(v "e")) segNode |] ) pullProjectSegment :: SLRule TExpr TExpr () pullProjectSegment q = $(dagPatMatch 'q "Segment (Project e (q1))" [| return $ do logRewrite "Redundant.Project.Segment" q segNode <- insert $ UnOp Segment $(v "q1") void $ replaceWithNew q $ UnOp (Project $(v "e")) segNode |] ) pullProjectGroupR2 :: SLRule TExpr TExpr () pullProjectGroupR2 q = $(dagPatMatch 'q "R2 (Group g (Project e (q1)))" [| return $ do logRewrite "Redundant.Project.Group.Inner" q let g' = partialEval $ mergeExpr $(v "e") $(v "g") groupNode <- insert $ UnOp (Group g') $(v "q1") r2Node <- insert $ UnOp R2 groupNode void $ replaceWithNew q $ UnOp (Project $(v "e")) r2Node |] ) pullProjectGroupR1 :: SLRule TExpr TExpr () pullProjectGroupR1 q = $(dagPatMatch 'q "R1 (Group g (Project e (q1)))" [| return $ do logRewrite "Redundant.Project.Group.Outer" q let g' = partialEval $ mergeExpr $(v "e") $(v "g") groupNode <- insert $ UnOp (Group g') $(v "q1") void $ replaceWithNew q $ UnOp R1 groupNode |] ) ------------------------------------------------------------------------------ -- Constant expression inputs -- liftPairRight :: Monad m => (a, m b) -> m (a, b) -- liftPairRight (a, mb) = mb >>= \b -> return (a, b) -- mapPair :: (a -> c) -> (b -> d) -> (a, b) -> (c, d) -- mapPair f g (a, b) = (f a, g b) -- insertConstants :: [(DBCol, ScalarVal)] -> Expr -> Expr -- insertConstants env expr = -- case expr of -- BinApp o e1 e2 -> BinApp o (insertConstants env e1) (insertConstants env e2) -- UnApp o e1 -> UnApp o (insertConstants env e1) -- Column c -> case lookup c env of -- Just val -> Constant val -- Nothing -> Column c -- If c t e -> If (insertConstants env c) (insertConstants env t) (insertConstants env e) -- Constant _ -> expr -- constProject :: SLRule TExpr TExpr BottomUpProps -- constProject q = -- $(dagPatMatch 'q "Project projs (q1)" -- [| do -- VProp (ConstVec constCols) <- constProp <$> properties $(v "q1") -- let envEntry = liftPairRight . mapPair id (constVal id) -- let constEnv = mapMaybe envEntry $ zip [1..] constCols -- predicate $ not $ null constEnv -- let projs' = map (insertConstants constEnv) $(v "projs") -- -- To avoid rewriting loops, ensure that a change occured. -- predicate $ projs' /= $(v "projs") -- return $ do -- logRewrite "Expr.Project.Const" q -- void $ replaceWithNew q $ UnOp (Project projs') $(v "q1") |])
ulricha/dsh
src/Database/DSH/SL/Opt/Rewrite/Projections.hs
bsd-3-clause
20,558
0
7
6,277
1,496
848
648
360
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, TypeSynonymInstances, PatternGuards #-} module Idris.AbsSyntax(module Idris.AbsSyntax, module Idris.AbsSyntaxTree) where import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Typecheck import Idris.AbsSyntaxTree import Idris.Colours import Idris.Docstrings import Idris.IdeMode hiding (Opt(..)) import IRTS.CodegenCommon import Util.DynamicLinker import System.Console.Haskeline import System.IO import System.Directory (canonicalizePath, doesFileExist) import Control.Applicative import Control.Monad (liftM3) import Control.Monad.State import Data.List hiding (insert,union) import Data.Char import qualified Data.Text as T import Data.Either import qualified Data.Map as M import Data.Maybe import qualified Data.Set as S import Data.Word (Word) import Data.Generics.Uniplate.Data (descend, descendM) import Debug.Trace import System.IO.Error(isUserError, ioeGetErrorString, tryIOError) import Util.Pretty import Util.ScreenSize import Util.System getContext :: Idris Context getContext = do i <- getIState; return (tt_ctxt i) forCodegen :: Codegen -> [(Codegen, a)] -> [a] forCodegen tgt xs = [x | (tgt', x) <- xs, tgt == tgt'] getObjectFiles :: Codegen -> Idris [FilePath] getObjectFiles tgt = do i <- getIState; return (forCodegen tgt $ idris_objs i) addObjectFile :: Codegen -> FilePath -> Idris () addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = nub $ (tgt, f) : idris_objs i } getLibs :: Codegen -> Idris [String] getLibs tgt = do i <- getIState; return (forCodegen tgt $ idris_libs i) addLib :: Codegen -> String -> Idris () addLib tgt f = do i <- getIState; putIState $ i { idris_libs = nub $ (tgt, f) : idris_libs i } getFlags :: Codegen -> Idris [String] getFlags tgt = do i <- getIState; return (forCodegen tgt $ idris_cgflags i) addFlag :: Codegen -> String -> Idris () addFlag tgt f = do i <- getIState; putIState $ i { idris_cgflags = nub $ (tgt, f) : idris_cgflags i } addDyLib :: [String] -> Idris (Either DynamicLib String) addDyLib libs = do i <- getIState let ls = idris_dynamic_libs i let importdirs = opt_importdirs (idris_options i) case mapMaybe (findDyLib ls) libs of x:_ -> return (Left x) [] -> do handle <- lift . lift . mapM (\l -> catchIO (tryLoadLib importdirs l) (\_ -> return Nothing)) $ libs case msum handle of Nothing -> return (Right $ "Could not load dynamic alternatives \"" ++ concat (intersperse "," libs) ++ "\"") Just x -> do putIState $ i { idris_dynamic_libs = x:ls } return (Left x) where findDyLib :: [DynamicLib] -> String -> Maybe DynamicLib findDyLib [] l = Nothing findDyLib (lib:libs) l | l == lib_name lib = Just lib | otherwise = findDyLib libs l getAutoImports :: Idris [FilePath] getAutoImports = do i <- getIState return (opt_autoImport (idris_options i)) addAutoImport :: FilePath -> Idris () addAutoImport fp = do i <- getIState let opts = idris_options i let autoimps = opt_autoImport opts put (i { idris_options = opts { opt_autoImport = fp : opt_autoImport opts } } ) addHdr :: Codegen -> String -> Idris () addHdr tgt f = do i <- getIState; putIState $ i { idris_hdrs = nub $ (tgt, f) : idris_hdrs i } addImported :: Bool -> FilePath -> Idris () addImported pub f = do i <- getIState putIState $ i { idris_imported = nub $ (f, pub) : idris_imported i } addLangExt :: LanguageExt -> Idris () addLangExt TypeProviders = do i <- getIState putIState $ i { idris_language_extensions = TypeProviders : idris_language_extensions i } addLangExt ErrorReflection = do i <- getIState putIState $ i { idris_language_extensions = ErrorReflection : idris_language_extensions i } -- Transforms are organised by the function being applied on the lhs of the -- transform, to make looking up appropriate transforms quicker addTrans :: Name -> (Term, Term) -> Idris () addTrans basefn t = do i <- getIState let t' = case lookupCtxtExact basefn (idris_transforms i) of Just def -> (t : def) Nothing -> [t] putIState $ i { idris_transforms = addDef basefn t' (idris_transforms i) } addErrRev :: (Term, Term) -> Idris () addErrRev t = do i <- getIState putIState $ i { idris_errRev = t : idris_errRev i } addErasureUsage :: Name -> Int -> Idris () addErasureUsage n i = do ist <- getIState putIState $ ist { idris_erasureUsed = (n, i) : idris_erasureUsed ist } addExport :: Name -> Idris () addExport n = do ist <- getIState putIState $ ist { idris_exports = n : idris_exports ist } addUsedName :: FC -> Name -> Name -> Idris () addUsedName fc n arg = do ist <- getIState case lookupTyName n (tt_ctxt ist) of [(n', ty)] -> addUsage n' 0 ty [] -> throwError (At fc (NoSuchVariable n)) xs -> throwError (At fc (CantResolveAlts (map fst xs))) where addUsage n i (Bind x _ sc) | x == arg = do addIBC (IBCUsage (n, i)) addErasureUsage n i | otherwise = addUsage n (i + 1) sc addUsage _ _ _ = throwError (At fc (Msg ("No such argument name " ++ show arg))) getErasureUsage :: Idris [(Name, Int)] getErasureUsage = do ist <- getIState; return (idris_erasureUsed ist) getExports :: Idris [Name] getExports = do ist <- getIState return (idris_exports ist) totcheck :: (FC, Name) -> Idris () totcheck n = do i <- getIState; putIState $ i { idris_totcheck = idris_totcheck i ++ [n] } defer_totcheck :: (FC, Name) -> Idris () defer_totcheck n = do i <- getIState; putIState $ i { idris_defertotcheck = nub (idris_defertotcheck i ++ [n]) } clear_totcheck :: Idris () clear_totcheck = do i <- getIState; putIState $ i { idris_totcheck = [] } setFlags :: Name -> [FnOpt] -> Idris () setFlags n fs = do i <- getIState; putIState $ i { idris_flags = addDef n fs (idris_flags i) } setFnInfo :: Name -> FnInfo -> Idris () setFnInfo n fs = do i <- getIState; putIState $ i { idris_fninfo = addDef n fs (idris_fninfo i) } setAccessibility :: Name -> Accessibility -> Idris () setAccessibility n a = do i <- getIState let ctxt = setAccess n a (tt_ctxt i) putIState $ i { tt_ctxt = ctxt } setTotality :: Name -> Totality -> Idris () setTotality n a = do i <- getIState let ctxt = setTotal n a (tt_ctxt i) putIState $ i { tt_ctxt = ctxt } getTotality :: Name -> Idris Totality getTotality n = do i <- getIState case lookupTotal n (tt_ctxt i) of [t] -> return t _ -> return (Total []) -- Get coercions which might return the required type getCoercionsTo :: IState -> Type -> [Name] getCoercionsTo i ty = let cs = idris_coercions i (fn,_) = unApply (getRetTy ty) in findCoercions fn cs where findCoercions t [] = [] findCoercions t (n : ns) = let ps = case lookupTy n (tt_ctxt i) of [ty'] -> case unApply (getRetTy (normalise (tt_ctxt i) [] ty')) of (t', _) -> if t == t' then [n] else [] _ -> [] in ps ++ findCoercions t ns addToCG :: Name -> CGInfo -> Idris () addToCG n cg = do i <- getIState putIState $ i { idris_callgraph = addDef n cg (idris_callgraph i) } addTyInferred :: Name -> Idris () addTyInferred n = do i <- getIState putIState $ i { idris_tyinfodata = addDef n TIPartial (idris_tyinfodata i) } addTyInfConstraints :: FC -> [(Term, Term)] -> Idris () addTyInfConstraints fc ts = do logLvl 2 $ "TI missing: " ++ show ts mapM_ addConstraint ts return () where addConstraint (x, y) = findMVApps x y findMVApps x y = do let (fx, argsx) = unApply x let (fy, argsy) = unApply y if (not (fx == fy)) then do tryAddMV fx y tryAddMV fy x else mapM_ addConstraint (zip argsx argsy) tryAddMV (P _ mv _) y = do ist <- get case lookup mv (idris_metavars ist) of Just _ -> addConstraintRule mv y _ -> return () tryAddMV _ _ = return () addConstraintRule :: Name -> Term -> Idris () addConstraintRule n t = do ist <- get logLvl 1 $ "TI constraint: " ++ show (n, t) case lookupCtxt n (idris_tyinfodata ist) of [TISolution ts] -> do mapM_ (checkConsistent t) ts let ti' = addDef n (TISolution (t : ts)) (idris_tyinfodata ist) put $ ist { idris_tyinfodata = ti' } _ -> do let ti' = addDef n (TISolution [t]) (idris_tyinfodata ist) put $ ist { idris_tyinfodata = ti' } -- Check a solution is consistent with previous solutions -- Meaning: If heads are both data types, they had better be the -- same. checkConsistent :: Term -> Term -> Idris () checkConsistent x y = do let (fx, _) = unApply x let (fy, _) = unApply y case (fx, fy) of (P (TCon _ _) n _, P (TCon _ _) n' _) -> errWhen (n/=n) (P (TCon _ _) n _, Constant _) -> errWhen True (Constant _, P (TCon _ _) n' _) -> errWhen True (P (DCon _ _ _) n _, P (DCon _ _ _) n' _) -> errWhen (n/=n) _ -> return () where errWhen True = throwError (At fc (CantUnify False (x, Nothing) (y, Nothing) (Msg "") [] 0)) errWhen False = return () isTyInferred :: Name -> Idris Bool isTyInferred n = do i <- getIState case lookupCtxt n (idris_tyinfodata i) of [TIPartial] -> return True _ -> return False -- | Adds error handlers for a particular function and argument. If names are -- ambiguous, all matching handlers are updated. addFunctionErrorHandlers :: Name -> Name -> [Name] -> Idris () addFunctionErrorHandlers f arg hs = do i <- getIState let oldHandlers = idris_function_errorhandlers i let newHandlers = flip (addDef f) oldHandlers $ case lookupCtxtExact f oldHandlers of Nothing -> M.singleton arg (S.fromList hs) Just (oldHandlers) -> M.insertWith S.union arg (S.fromList hs) oldHandlers -- will always be one of those two, thus no extra case putIState $ i { idris_function_errorhandlers = newHandlers } getFunctionErrorHandlers :: Name -> Name -> Idris [Name] getFunctionErrorHandlers f arg = do i <- getIState return . maybe [] S.toList $ undefined --lookup arg =<< lookupCtxtExact f (idris_function_errorhandlers i) -- Trace all the names in a call graph starting at the given name getAllNames :: Name -> Idris [Name] getAllNames n = allNames [] n allNames :: [Name] -> Name -> Idris [Name] allNames ns n | n `elem` ns = return [] allNames ns n = do i <- getIState case lookupCtxtExact n (idris_callgraph i) of Just ns' -> do more <- mapM (allNames (n:ns)) (map fst (calls ns')) return (nub (n : concat more)) _ -> return [n] addCoercion :: Name -> Idris () addCoercion n = do i <- getIState putIState $ i { idris_coercions = nub $ n : idris_coercions i } addDocStr :: Name -> Docstring DocTerm -> [(Name, Docstring DocTerm)] -> Idris () addDocStr n doc args = do i <- getIState putIState $ i { idris_docstrings = addDef n (doc, args) (idris_docstrings i) } addNameHint :: Name -> Name -> Idris () addNameHint ty n = do i <- getIState ty' <- case lookupCtxtName ty (idris_implicits i) of [(tyn, _)] -> return tyn [] -> throwError (NoSuchVariable ty) tyns -> throwError (CantResolveAlts (map fst tyns)) let ns' = case lookupCtxt ty' (idris_namehints i) of [ns] -> ns ++ [n] _ -> [n] putIState $ i { idris_namehints = addDef ty' ns' (idris_namehints i) } getNameHints :: IState -> Name -> [Name] getNameHints i (UN arr) | arr == txt "->" = [sUN "f",sUN "g"] getNameHints i n = case lookupCtxt n (idris_namehints i) of [ns] -> ns _ -> [] -- Issue #1737 in the Issue Tracker. -- https://github.com/idris-lang/Idris-dev/issues/1737 addToCalledG :: Name -> [Name] -> Idris () addToCalledG n ns = return () -- TODO addDeprecated :: Name -> String -> Idris () addDeprecated n reason = do i <- getIState putIState $ i { idris_deprecated = addDef n reason (idris_deprecated i) } getDeprecated :: Name -> Idris (Maybe String) getDeprecated n = do i <- getIState return $ lookupCtxtExact n (idris_deprecated i) push_estack :: Name -> Bool -> Idris () push_estack n inst = do i <- getIState putIState (i { elab_stack = (n, inst) : elab_stack i }) pop_estack :: Idris () pop_estack = do i <- getIState putIState (i { elab_stack = ptail (elab_stack i) }) where ptail [] = [] ptail (x : xs) = xs -- | Add a class instance function. -- -- Precondition: the instance should have the correct type. -- -- Dodgy hack 1: Put integer instances first in the list so they are -- resolved by default. -- -- Dodgy hack 2: put constraint chasers (@@) last addInstance :: Bool -- ^ whether the name is an Integer instance -> Bool -- ^ whether to include the instance in instance search -> Name -- ^ the name of the class -> Name -- ^ the name of the instance -> Idris () addInstance int res n i = do ist <- getIState case lookupCtxt n (idris_classes ist) of [CI a b c d e ins fds] -> do let cs = addDef n (CI a b c d e (addI i ins) fds) (idris_classes ist) putIState $ ist { idris_classes = cs } _ -> do let cs = addDef n (CI (sMN 0 "none") [] [] [] [] [(i, res)] []) (idris_classes ist) putIState $ ist { idris_classes = cs } where addI, insI :: Name -> [(Name, Bool)] -> [(Name, Bool)] addI i ins | int = (i, res) : ins | chaser n = ins ++ [(i, res)] | otherwise = insI i ins insI i [] = [(i, res)] insI i (n : ns) | chaser (fst n) = (i, res) : n : ns | otherwise = n : insI i ns chaser (UN nm) | ('@':'@':_) <- str nm = True chaser (NS n _) = chaser n chaser _ = False addClass :: Name -> ClassInfo -> Idris () addClass n i = do ist <- getIState let i' = case lookupCtxt n (idris_classes ist) of [c] -> c { class_instances = class_instances i } _ -> i putIState $ ist { idris_classes = addDef n i' (idris_classes ist) } addRecord :: Name -> RecordInfo -> Idris () addRecord n ri = do ist <- getIState putIState $ ist { idris_records = addDef n ri (idris_records ist) } addAutoHint :: Name -> Name -> Idris () addAutoHint n hint = do ist <- getIState case lookupCtxtExact n (idris_autohints ist) of Nothing -> do let hs = addDef n [hint] (idris_autohints ist) putIState $ ist { idris_autohints = hs } Just nhints -> do let hs = addDef n (hint : nhints) (idris_autohints ist) putIState $ ist { idris_autohints = hs } getAutoHints :: Name -> Idris [Name] getAutoHints n = do ist <- getIState case lookupCtxtExact n (idris_autohints ist) of Nothing -> return [] Just ns -> return ns addIBC :: IBCWrite -> Idris () addIBC ibc@(IBCDef n) = do i <- getIState when (notDef (ibc_write i)) $ putIState $ i { ibc_write = ibc : ibc_write i } where notDef [] = True notDef (IBCDef n': is) | n == n' = False notDef (_ : is) = notDef is addIBC ibc = do i <- getIState; putIState $ i { ibc_write = ibc : ibc_write i } clearIBC :: Idris () clearIBC = do i <- getIState; putIState $ i { ibc_write = [] } resetNameIdx :: Idris () resetNameIdx = do i <- getIState put (i { idris_nameIdx = (0, emptyContext) }) -- Used to preserve sharing of names addNameIdx :: Name -> Idris (Int, Name) addNameIdx n = do i <- getIState let (i', x) = addNameIdx' i n putIState i' return x addNameIdx' :: IState -> Name -> (IState, (Int, Name)) addNameIdx' i n = let idxs = snd (idris_nameIdx i) in case lookupCtxt n idxs of [x] -> (i, x) _ -> let i' = fst (idris_nameIdx i) + 1 in (i { idris_nameIdx = (i', addDef n (i', n) idxs) }, (i', n)) getSymbol :: Name -> Idris Name getSymbol n = do i <- getIState case M.lookup n (idris_symbols i) of Just n' -> return n' Nothing -> do let sym' = M.insert n n (idris_symbols i) put (i { idris_symbols = sym' }) return n getHdrs :: Codegen -> Idris [String] getHdrs tgt = do i <- getIState; return (forCodegen tgt $ idris_hdrs i) getImported :: Idris [(FilePath, Bool)] getImported = do i <- getIState; return (idris_imported i) setErrSpan :: FC -> Idris () setErrSpan x = do i <- getIState; case (errSpan i) of Nothing -> putIState $ i { errSpan = Just x } Just _ -> return () clearErr :: Idris () clearErr = do i <- getIState putIState $ i { errSpan = Nothing } getSO :: Idris (Maybe String) getSO = do i <- getIState return (compiled_so i) setSO :: Maybe String -> Idris () setSO s = do i <- getIState putIState $ (i { compiled_so = s }) getIState :: Idris IState getIState = get putIState :: IState -> Idris () putIState = put updateIState :: (IState -> IState) -> Idris () updateIState f = do i <- getIState putIState $ f i withContext :: (IState -> Ctxt a) -> Name -> b -> (a -> Idris b) -> Idris b withContext ctx name dflt action = do ist <- getIState case lookupCtxt name (ctx ist) of [x] -> action x _ -> return dflt withContext_ :: (IState -> Ctxt a) -> Name -> (a -> Idris ()) -> Idris () withContext_ ctx name action = withContext ctx name () action -- | A version of liftIO that puts errors into the exception type of the Idris monad runIO :: IO a -> Idris a runIO x = liftIO (tryIOError x) >>= either (throwError . Msg . show) return -- TODO: create specific Idris exceptions for specific IO errors such as "openFile: does not exist" -- -- Issue #1738 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1738 getName :: Idris Int getName = do i <- getIState; let idx = idris_name i; putIState $ (i { idris_name = idx + 1 }) return idx -- InternalApp keeps track of the real function application for making case splits from, not the application the -- programmer wrote, which doesn't have the whole context in any case other than top level definitions addInternalApp :: FilePath -> Int -> PTerm -> Idris () addInternalApp fp l t = do i <- getIState -- We canonicalise the path to make "./Test/Module.idr" equal -- to "Test/Module.idr" exists <- runIO $ doesFileExist fp when exists $ do fp' <- runIO $ canonicalizePath fp putIState (i { idris_lineapps = ((fp', l), t) : idris_lineapps i }) getInternalApp :: FilePath -> Int -> Idris PTerm getInternalApp fp l = do i <- getIState -- We canonicalise the path to make -- "./Test/Module.idr" equal to -- "Test/Module.idr" exists <- runIO $ doesFileExist fp if exists then do fp' <- runIO $ canonicalizePath fp case lookup (fp', l) (idris_lineapps i) of Just n' -> return n' Nothing -> return Placeholder -- TODO: What if it's not there? else return Placeholder -- Pattern definitions are only used for coverage checking, so erase them -- when we're done clearOrigPats :: Idris () clearOrigPats = do i <- get let ps = idris_patdefs i let ps' = mapCtxt (\ (_,miss) -> ([], miss)) ps put (i { idris_patdefs = ps' }) -- Erase types from Ps in the context (basically ending up with what's in -- the .ibc, which is all we need after all the analysis is done) clearPTypes :: Idris () clearPTypes = do i <- get let ctxt = tt_ctxt i put (i { tt_ctxt = mapDefCtxt pErase ctxt }) where pErase (CaseOp c t tys orig tot cds) = CaseOp c t tys orig [] (pErase' cds) pErase x = x pErase' (CaseDefs _ (cs, c) _ rs) = let c' = (cs, fmap pEraseType c) in CaseDefs c' c' c' rs checkUndefined :: FC -> Name -> Idris () checkUndefined fc n = do i <- getContext case lookupTy n i of (_:_) -> throwError . Msg $ show fc ++ ":" ++ show n ++ " already defined" _ -> return () isUndefined :: FC -> Name -> Idris Bool isUndefined fc n = do i <- getContext case lookupTyExact n i of Just _ -> return False _ -> return True setContext :: Context -> Idris () setContext ctxt = do i <- getIState; putIState $ (i { tt_ctxt = ctxt } ) updateContext :: (Context -> Context) -> Idris () updateContext f = do i <- getIState; putIState $ (i { tt_ctxt = f (tt_ctxt i) } ) addConstraints :: FC -> (Int, [UConstraint]) -> Idris () addConstraints fc (v, cs) = do i <- getIState let ctxt = tt_ctxt i let ctxt' = ctxt { next_tvar = v } let ics = insertAll (zip cs (repeat fc)) (idris_constraints i) putIState $ i { tt_ctxt = ctxt', idris_constraints = ics } where insertAll [] c = c insertAll ((c, fc) : cs) ics = insertAll cs $ S.insert (ConstraintFC c fc) ics addDeferred = addDeferred' Ref addDeferredTyCon = addDeferred' (TCon 0 0) -- | Save information about a name that is not yet defined addDeferred' :: NameType -> [(Name, (Int, Maybe Name, Type, [Name], Bool))] -- ^ The Name is the name being made into a metavar, -- the Int is the number of vars that are part of a -- putative proof context, the Maybe Name is the -- top-level function containing the new metavariable, -- the Type is its type, and the Bool is whether :p is -- allowed -> Idris () addDeferred' nt ns = do mapM_ (\(n, (i, _, t, _, _)) -> updateContext (addTyDecl n nt (tidyNames S.empty t))) ns mapM_ (\(n, _) -> when (not (n `elem` primDefs)) $ addIBC (IBCMetavar n)) ns i <- getIState putIState $ i { idris_metavars = map (\(n, (i, top, _, ns, isTopLevel)) -> (n, (top, i, ns, isTopLevel))) ns ++ idris_metavars i } where -- 'tidyNames' is to generate user accessible names in case they are -- needed in tactic scripts tidyNames used (Bind (MN i x) b sc) = let n' = uniqueNameSet (UN x) used in Bind n' b $ tidyNames (S.insert n' used) sc tidyNames used (Bind n b sc) = let n' = uniqueNameSet n used in Bind n' b $ tidyNames (S.insert n' used) sc tidyNames used b = b solveDeferred :: Name -> Idris () solveDeferred n = do i <- getIState putIState $ i { idris_metavars = filter (\(n', _) -> n/=n') (idris_metavars i), ibc_write = filter (notMV n) (ibc_write i) } where notMV n (IBCMetavar n') = not (n == n') notMV n _ = True getUndefined :: Idris [Name] getUndefined = do i <- getIState return (map fst (idris_metavars i) \\ primDefs) isMetavarName :: Name -> IState -> Bool isMetavarName n ist = case lookupNames n (tt_ctxt ist) of (t:_) -> isJust $ lookup t (idris_metavars ist) _ -> False getWidth :: Idris ConsoleWidth getWidth = fmap idris_consolewidth getIState setWidth :: ConsoleWidth -> Idris () setWidth w = do ist <- getIState put ist { idris_consolewidth = w } setDepth :: Maybe Int -> Idris () setDepth d = do ist <- getIState put ist { idris_options = (idris_options ist) { opt_printdepth = d } } typeDescription :: String typeDescription = "The type of types" type1Doc :: Doc OutputAnnotation type1Doc = (annotate (AnnType "Type" "The type of types, one level up") $ text "Type 1") isetPrompt :: String -> Idris () isetPrompt p = do i <- getIState case idris_outputmode i of IdeMode n h -> runIO . hPutStrLn h $ convSExp "set-prompt" p n -- | Tell clients how much was parsed and loaded isetLoadedRegion :: Idris () isetLoadedRegion = do i <- getIState let span = idris_parsedSpan i case span of Just fc -> case idris_outputmode i of IdeMode n h -> runIO . hPutStrLn h $ convSExp "set-loaded-region" fc n Nothing -> return () setLogLevel :: Int -> Idris () setLogLevel l = do i <- getIState let opts = idris_options i let opt' = opts { opt_logLevel = l } putIState $ i { idris_options = opt' } setLogCats :: [LogCat] -> Idris () setLogCats cs = do i <- getIState let opts = idris_options i let opt' = opts { opt_logcats = cs } putIState $ i { idris_options = opt' } setCmdLine :: [Opt] -> Idris () setCmdLine opts = do i <- getIState let iopts = idris_options i putIState $ i { idris_options = iopts { opt_cmdline = opts } } getCmdLine :: Idris [Opt] getCmdLine = do i <- getIState return (opt_cmdline (idris_options i)) getDumpHighlighting :: Idris Bool getDumpHighlighting = do ist <- getIState return (findC (opt_cmdline (idris_options ist))) where findC = elem DumpHighlights getDumpDefun :: Idris (Maybe FilePath) getDumpDefun = do i <- getIState return $ findC (opt_cmdline (idris_options i)) where findC [] = Nothing findC (DumpDefun x : _) = Just x findC (_ : xs) = findC xs getDumpCases :: Idris (Maybe FilePath) getDumpCases = do i <- getIState return $ findC (opt_cmdline (idris_options i)) where findC [] = Nothing findC (DumpCases x : _) = Just x findC (_ : xs) = findC xs logLevel :: Idris Int logLevel = do i <- getIState return (opt_logLevel (idris_options i)) setErrContext :: Bool -> Idris () setErrContext t = do i <- getIState let opts = idris_options i let opts' = opts { opt_errContext = t } putIState $ i { idris_options = opts' } errContext :: Idris Bool errContext = do i <- getIState return (opt_errContext (idris_options i)) getOptimise :: Idris [Optimisation] getOptimise = do i <- getIState return (opt_optimise (idris_options i)) setOptimise :: [Optimisation] -> Idris () setOptimise newopts = do i <- getIState let opts = idris_options i let opts' = opts { opt_optimise = newopts } putIState $ i { idris_options = opts' } addOptimise :: Optimisation -> Idris () addOptimise opt = do opts <- getOptimise setOptimise (nub (opt : opts)) removeOptimise :: Optimisation -> Idris () removeOptimise opt = do opts <- getOptimise setOptimise ((nub opts) \\ [opt]) -- Set appropriate optimisation set for the given level. We only have -- one optimisation that is configurable at the moment, however! setOptLevel :: Int -> Idris () setOptLevel n | n <= 0 = setOptimise [] setOptLevel 1 = setOptimise [] setOptLevel 2 = setOptimise [PETransform] setOptLevel n | n >= 3 = setOptimise [PETransform] useREPL :: Idris Bool useREPL = do i <- getIState return (opt_repl (idris_options i)) setREPL :: Bool -> Idris () setREPL t = do i <- getIState let opts = idris_options i let opt' = opts { opt_repl = t } putIState $ i { idris_options = opt' } showOrigErr :: Idris Bool showOrigErr = do i <- getIState return (opt_origerr (idris_options i)) setShowOrigErr :: Bool -> Idris () setShowOrigErr b = do i <- getIState let opts = idris_options i let opt' = opts { opt_origerr = b } putIState $ i { idris_options = opt' } setAutoSolve :: Bool -> Idris () setAutoSolve b = do i <- getIState let opts = idris_options i let opt' = opts { opt_autoSolve = b } putIState $ i { idris_options = opt' } setNoBanner :: Bool -> Idris () setNoBanner n = do i <- getIState let opts = idris_options i let opt' = opts { opt_nobanner = n } putIState $ i { idris_options = opt' } getNoBanner :: Idris Bool getNoBanner = do i <- getIState let opts = idris_options i return (opt_nobanner opts) setEvalTypes :: Bool -> Idris () setEvalTypes n = do i <- getIState let opts = idris_options i let opt' = opts { opt_evaltypes = n } putIState $ i { idris_options = opt' } getDesugarNats :: Idris Bool getDesugarNats = do i <- getIState let opts = idris_options i return (opt_desugarnats opts) setDesugarNats :: Bool -> Idris () setDesugarNats n = do i <- getIState let opts = idris_options i let opt' = opts { opt_desugarnats = n } putIState $ i { idris_options = opt' } setQuiet :: Bool -> Idris () setQuiet q = do i <- getIState let opts = idris_options i let opt' = opts { opt_quiet = q } putIState $ i { idris_options = opt' } getQuiet :: Idris Bool getQuiet = do i <- getIState let opts = idris_options i return (opt_quiet opts) setCodegen :: Codegen -> Idris () setCodegen t = do i <- getIState let opts = idris_options i let opt' = opts { opt_codegen = t } putIState $ i { idris_options = opt' } codegen :: Idris Codegen codegen = do i <- getIState return (opt_codegen (idris_options i)) setOutputTy :: OutputType -> Idris () setOutputTy t = do i <- getIState let opts = idris_options i let opt' = opts { opt_outputTy = t } putIState $ i { idris_options = opt' } outputTy :: Idris OutputType outputTy = do i <- getIState return $ opt_outputTy $ idris_options i setIdeMode :: Bool -> Handle -> Idris () setIdeMode True h = do i <- getIState putIState $ i { idris_outputmode = IdeMode 0 h , idris_colourRepl = False } setIdeMode False _ = return () setTargetTriple :: String -> Idris () setTargetTriple t = do i <- getIState let opts = idris_options i opt' = opts { opt_triple = t } putIState $ i { idris_options = opt' } targetTriple :: Idris String targetTriple = do i <- getIState return (opt_triple (idris_options i)) setTargetCPU :: String -> Idris () setTargetCPU t = do i <- getIState let opts = idris_options i opt' = opts { opt_cpu = t } putIState $ i { idris_options = opt' } targetCPU :: Idris String targetCPU = do i <- getIState return (opt_cpu (idris_options i)) verbose :: Idris Bool verbose = do i <- getIState -- Quietness overrides verbosity return (not (opt_quiet (idris_options i)) && opt_verbose (idris_options i)) setVerbose :: Bool -> Idris () setVerbose t = do i <- getIState let opts = idris_options i let opt' = opts { opt_verbose = t } putIState $ i { idris_options = opt' } typeInType :: Idris Bool typeInType = do i <- getIState return (opt_typeintype (idris_options i)) setTypeInType :: Bool -> Idris () setTypeInType t = do i <- getIState let opts = idris_options i let opt' = opts { opt_typeintype = t } putIState $ i { idris_options = opt' } coverage :: Idris Bool coverage = do i <- getIState return (opt_coverage (idris_options i)) setCoverage :: Bool -> Idris () setCoverage t = do i <- getIState let opts = idris_options i let opt' = opts { opt_coverage = t } putIState $ i { idris_options = opt' } setIBCSubDir :: FilePath -> Idris () setIBCSubDir fp = do i <- getIState let opts = idris_options i let opt' = opts { opt_ibcsubdir = fp } putIState $ i { idris_options = opt' } valIBCSubDir :: IState -> Idris FilePath valIBCSubDir i = return (opt_ibcsubdir (idris_options i)) addImportDir :: FilePath -> Idris () addImportDir fp = do i <- getIState let opts = idris_options i let opt' = opts { opt_importdirs = nub $ fp : opt_importdirs opts } putIState $ i { idris_options = opt' } setImportDirs :: [FilePath] -> Idris () setImportDirs fps = do i <- getIState let opts = idris_options i let opt' = opts { opt_importdirs = fps } putIState $ i { idris_options = opt' } allImportDirs :: Idris [FilePath] allImportDirs = do i <- getIState let optdirs = opt_importdirs (idris_options i) return ("." : reverse optdirs) colourise :: Idris Bool colourise = do i <- getIState return $ idris_colourRepl i setColourise :: Bool -> Idris () setColourise b = do i <- getIState putIState $ i { idris_colourRepl = b } impShow :: Idris Bool impShow = do i <- getIState return (opt_showimp (idris_options i)) setImpShow :: Bool -> Idris () setImpShow t = do i <- getIState let opts = idris_options i let opt' = opts { opt_showimp = t } putIState $ i { idris_options = opt' } setColour :: ColourType -> IdrisColour -> Idris () setColour ct c = do i <- getIState let newTheme = setColour' ct c (idris_colourTheme i) putIState $ i { idris_colourTheme = newTheme } where setColour' KeywordColour c t = t { keywordColour = c } setColour' BoundVarColour c t = t { boundVarColour = c } setColour' ImplicitColour c t = t { implicitColour = c } setColour' FunctionColour c t = t { functionColour = c } setColour' TypeColour c t = t { typeColour = c } setColour' DataColour c t = t { dataColour = c } setColour' PromptColour c t = t { promptColour = c } setColour' PostulateColour c t = t { postulateColour = c } logLvl :: Int -> String -> Idris () logLvl = logLvlCats [] logCoverage :: Int -> String -> Idris () logCoverage = logLvlCats [ICoverage] logErasure :: Int -> String -> Idris () logErasure = logLvlCats [IErasure] -- | Log an action of the parser logParser :: Int -> String -> Idris () logParser = logLvlCats parserCats -- | Log an action of the elaborator. logElab :: Int -> String -> Idris () logElab = logLvlCats elabCats -- | Log an action of the compiler. logCodeGen :: Int -> String -> Idris () logCodeGen = logLvlCats codegenCats logIBC :: Int -> String -> Idris () logIBC = logLvlCats [IIBC] -- | Log aspect of Idris execution -- -- An empty set of logging levels is used to denote all categories. -- -- @TODO update IDE protocol logLvlCats :: [LogCat] -- ^ The categories that the message should appear under. -> Int -- ^ The Logging level the message should appear. -> String -- ^ The message to show the developer. -> Idris () logLvlCats cs l str = do i <- getIState let lvl = opt_logLevel (idris_options i) let cats = opt_logcats (idris_options i) when (lvl >= l) $ when (inCat cs cats || null cats) $ case idris_outputmode i of RawOutput h -> do runIO $ hPutStrLn h str IdeMode n h -> do let good = SexpList [IntegerAtom (toInteger l), toSExp str] runIO . hPutStrLn h $ convSExp "log" good n where inCat :: [LogCat] -> [LogCat] -> Bool inCat cs cats = or $ map (\x -> elem x cats) cs cmdOptType :: Opt -> Idris Bool cmdOptType x = do i <- getIState return $ x `elem` opt_cmdline (idris_options i) noErrors :: Idris Bool noErrors = do i <- getIState case errSpan i of Nothing -> return True _ -> return False setTypeCase :: Bool -> Idris () setTypeCase t = do i <- getIState let opts = idris_options i let opt' = opts { opt_typecase = t } putIState $ i { idris_options = opt' } -- Dealing with parameters expandParams :: (Name -> Name) -> [(Name, PTerm)] -> [Name] -> -- all names [Name] -> -- names with no declaration PTerm -> PTerm expandParams dec ps ns infs tm = en 0 tm where -- if we shadow a name (say in a lambda binding) that is used in a call to -- a lifted function, we need access to both names - once in the scope of the -- binding and once to call the lifted functions. So we'll explicitly shadow -- it. (Yes, it's a hack. The alternative would be to resolve names earlier -- but we didn't...) mkShadow (UN n) = MN 0 n mkShadow (MN i n) = MN (i+1) n mkShadow (NS x s) = NS (mkShadow x) s en :: Int -- ^ The quotation level - only transform terms that are used, not terms -- that are merely mentioned. -> PTerm -> PTerm en 0 (PLam fc n nfc t s) | n `elem` (map fst ps ++ ns) = let n' = mkShadow n in PLam fc n' nfc (en 0 t) (en 0 (shadow n n' s)) | otherwise = PLam fc n nfc (en 0 t) (en 0 s) en 0 (PPi p n nfc t s) | n `elem` (map fst ps ++ ns) = let n' = mkShadow n in -- TODO THINK SHADOWING TacImp? PPi (enTacImp 0 p) n' nfc (en 0 t) (en 0 (shadow n n' s)) | otherwise = PPi (enTacImp 0 p) n nfc (en 0 t) (en 0 s) en 0 (PLet fc n nfc ty v s) | n `elem` (map fst ps ++ ns) = let n' = mkShadow n in PLet fc n' nfc (en 0 ty) (en 0 v) (en 0 (shadow n n' s)) | otherwise = PLet fc n nfc (en 0 ty) (en 0 v) (en 0 s) -- FIXME: Should only do this in a type signature! en 0 (PDPair f hls p (PRef f' fcs n) t r) | n `elem` (map fst ps ++ ns) && t /= Placeholder = let n' = mkShadow n in PDPair f hls p (PRef f' fcs n') (en 0 t) (en 0 (shadow n n' r)) en 0 (PRewrite f l r g) = PRewrite f (en 0 l) (en 0 r) (fmap (en 0) g) en 0 (PTyped l r) = PTyped (en 0 l) (en 0 r) en 0 (PPair f hls p l r) = PPair f hls p (en 0 l) (en 0 r) en 0 (PDPair f hls p l t r) = PDPair f hls p (en 0 l) (en 0 t) (en 0 r) en 0 (PAlternative ns a as) = PAlternative ns a (map (en 0) as) en 0 (PHidden t) = PHidden (en 0 t) en 0 (PUnifyLog t) = PUnifyLog (en 0 t) en 0 (PDisamb ds t) = PDisamb ds (en 0 t) en 0 (PNoImplicits t) = PNoImplicits (en 0 t) en 0 (PDoBlock ds) = PDoBlock (map (fmap (en 0)) ds) en 0 (PProof ts) = PProof (map (fmap (en 0)) ts) en 0 (PTactics ts) = PTactics (map (fmap (en 0)) ts) en 0 (PQuote (Var n)) | n `nselem` ns = PQuote (Var (dec n)) en 0 (PApp fc (PInferRef fc' hl n) as) | n `nselem` ns = PApp fc (PInferRef fc' hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps) ++ (map (fmap (en 0)) as)) en 0 (PApp fc (PRef fc' hl n) as) | n `elem` infs = PApp fc (PInferRef fc' hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps) ++ (map (fmap (en 0)) as)) | n `nselem` ns = PApp fc (PRef fc' hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps) ++ (map (fmap (en 0)) as)) en 0 (PAppBind fc (PRef fc' hl n) as) | n `elem` infs = PAppBind fc (PInferRef fc' hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps) ++ (map (fmap (en 0)) as)) | n `nselem` ns = PAppBind fc (PRef fc' hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps) ++ (map (fmap (en 0)) as)) en 0 (PRef fc hl n) | n `elem` infs = PApp fc (PInferRef fc hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps)) | n `nselem` ns = PApp fc (PRef fc hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps)) en 0 (PInferRef fc hl n) | n `nselem` ns = PApp fc (PInferRef fc hl (dec n)) (map (pexp . (PRef fc hl)) (map fst ps)) en 0 (PApp fc f as) = PApp fc (en 0 f) (map (fmap (en 0)) as) en 0 (PAppBind fc f as) = PAppBind fc (en 0 f) (map (fmap (en 0)) as) en 0 (PCase fc c os) = PCase fc (en 0 c) (map (pmap (en 0)) os) en 0 (PIfThenElse fc c t f) = PIfThenElse fc (en 0 c) (en 0 t) (en 0 f) en 0 (PRunElab fc tm ns) = PRunElab fc (en 0 tm) ns en 0 (PConstSugar fc tm) = PConstSugar fc (en 0 tm) en ql (PQuasiquote tm ty) = PQuasiquote (en (ql + 1) tm) (fmap (en ql) ty) en ql (PUnquote tm) = PUnquote (en (ql - 1) tm) en ql t = descend (en ql) t nselem x [] = False nselem x (y : xs) | nseq x y = True | otherwise = nselem x xs nseq x y = nsroot x == nsroot y enTacImp ql (TacImp aos st scr) = TacImp aos st (en ql scr) enTacImp ql other = other expandParamsD :: Bool -> -- True = RHS only IState -> (Name -> Name) -> [(Name, PTerm)] -> [Name] -> PDecl -> PDecl expandParamsD rhsonly ist dec ps ns (PTy doc argdocs syn fc o n nfc ty) = if n `elem` ns && (not rhsonly) then -- trace (show (n, expandParams dec ps ns ty)) $ PTy doc argdocs syn fc o (dec n) nfc (piBindp expl_param ps (expandParams dec ps ns [] ty)) else --trace (show (n, expandParams dec ps ns ty)) $ PTy doc argdocs syn fc o n nfc (expandParams dec ps ns [] ty) expandParamsD rhsonly ist dec ps ns (PPostulate e doc syn fc nfc o n ty) = if n `elem` ns && (not rhsonly) then -- trace (show (n, expandParams dec ps ns ty)) $ PPostulate e doc syn fc nfc o (dec n) (piBind ps (expandParams dec ps ns [] ty)) else --trace (show (n, expandParams dec ps ns ty)) $ PPostulate e doc syn fc nfc o n (expandParams dec ps ns [] ty) expandParamsD rhsonly ist dec ps ns (PClauses fc opts n cs) = let n' = if n `elem` ns then dec n else n in PClauses fc opts n' (map expandParamsC cs) where expandParamsC (PClause fc n lhs ws rhs ds) = let -- ps' = updateps True (namesIn ist rhs) (zip ps [0..]) ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..]) lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs) n' = if n `elem` ns then dec n else n -- names bound on the lhs should not be expanded on the rhs ns' = removeBound lhs ns in PClause fc n' lhs' (map (expandParams dec ps'' ns' []) ws) (expandParams dec ps'' ns' [] rhs) (map (expandParamsD True ist dec ps'' ns') ds) expandParamsC (PWith fc n lhs ws wval pn ds) = let -- ps' = updateps True (namesIn ist wval) (zip ps [0..]) ps'' = updateps False (namesIn [] ist lhs) (zip ps [0..]) lhs' = if rhsonly then lhs else (expandParams dec ps'' ns [] lhs) n' = if n `elem` ns then dec n else n ns' = removeBound lhs ns in PWith fc n' lhs' (map (expandParams dec ps'' ns' []) ws) (expandParams dec ps'' ns' [] wval) pn (map (expandParamsD rhsonly ist dec ps'' ns') ds) updateps yn nm [] = [] updateps yn nm (((a, t), i):as) | (a `elem` nm) == yn = (a, t) : updateps yn nm as | otherwise = (sMN i ('_' : show n ++ "_u"), t) : updateps yn nm as removeBound lhs ns = ns \\ nub (bnames lhs) bnames (PRef _ _ n) = [n] bnames (PApp _ _ args) = concatMap bnames (map getTm args) bnames (PPair _ _ _ l r) = bnames l ++ bnames r bnames (PDPair _ _ _ l Placeholder r) = bnames l ++ bnames r bnames _ = [] -- | Expands parameters defined in parameter and where blocks inside of declarations expandParamsD rhs ist dec ps ns (PData doc argDocs syn fc co pd) = PData doc argDocs syn fc co (expandPData pd) where -- just do the type decl, leave constructors alone (parameters will be -- added implicitly) expandPData (PDatadecl n nfc ty cons) = if n `elem` ns then PDatadecl (dec n) nfc (piBind ps (expandParams dec ps ns [] ty)) (map econ cons) else PDatadecl n nfc (expandParams dec ps ns [] ty) (map econ cons) econ (doc, argDocs, n, nfc, t, fc, fs) = (doc, argDocs, dec n, nfc, piBindp expl ps (expandParams dec ps ns [] t), fc, fs) expandParamsD rhs ist dec ps ns d@(PRecord doc rsyn fc opts name nfc prs pdocs fls cn cdoc csyn) = d expandParamsD rhs ist dec ps ns (PParams f params pds) = PParams f (ps ++ map (mapsnd (expandParams dec ps ns [])) params) (map (expandParamsD True ist dec ps ns) pds) -- (map (expandParamsD ist dec ps ns) pds) expandParamsD rhs ist dec ps ns (PMutual f pds) = PMutual f (map (expandParamsD rhs ist dec ps ns) pds) expandParamsD rhs ist dec ps ns (PClass doc info f cs n nfc params pDocs fds decls cn cd) = PClass doc info f (map (\ (n, t) -> (n, expandParams dec ps ns [] t)) cs) n nfc (map (\(n, fc, t) -> (n, fc, expandParams dec ps ns [] t)) params) pDocs fds (map (expandParamsD rhs ist dec ps ns) decls) cn cd expandParamsD rhs ist dec ps ns (PInstance doc argDocs info f cs n nfc params ty cn decls) = PInstance doc argDocs info f (map (\ (n, t) -> (n, expandParams dec ps ns [] t)) cs) n nfc (map (expandParams dec ps ns []) params) (expandParams dec ps ns [] ty) cn (map (expandParamsD rhs ist dec ps ns) decls) expandParamsD rhs ist dec ps ns d = d mapsnd f (x, t) = (x, f t) -- Calculate a priority for a type, for deciding elaboration order -- * if it's just a type variable or concrete type, do it early (0) -- * if there's only type variables and injective constructors, do it next (1) -- * if there's a function type, next (2) -- * finally, everything else (3) getPriority :: IState -> PTerm -> Int getPriority i tm = 1 -- pri tm where pri (PRef _ _ n) = case lookupP n (tt_ctxt i) of ((P (DCon _ _ _) _ _):_) -> 1 ((P (TCon _ _) _ _):_) -> 1 ((P Ref _ _):_) -> 1 [] -> 0 -- must be locally bound, if it's not an error... pri (PPi _ _ _ x y) = max 5 (max (pri x) (pri y)) pri (PTrue _ _) = 0 pri (PRewrite _ l r _) = max 1 (max (pri l) (pri r)) pri (PApp _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as))) pri (PAppBind _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.getTm) as))) pri (PCase _ f as) = max 1 (max (pri f) (foldr max 0 (map (pri.snd) as))) pri (PTyped l r) = pri l pri (PPair _ _ _ l r) = max 1 (max (pri l) (pri r)) pri (PDPair _ _ _ l t r) = max 1 (max (pri l) (max (pri t) (pri r))) pri (PAlternative _ a as) = maximum (map pri as) pri (PConstant _ _) = 0 pri Placeholder = 1 pri _ = 3 addStatics :: Name -> Term -> PTerm -> Idris () addStatics n tm ptm = do let (statics, dynamics) = initStatics tm ptm ist <- getIState let paramnames = nub $ case lookupCtxtExact n (idris_fninfo ist) of Just p -> getNamesFrom 0 (fn_params p) tm ++ concatMap (getParamNames ist) (map snd statics) _ -> concatMap (getParamNames ist) (map snd statics) let stnames = nub $ concatMap freeArgNames (map snd statics) let dnames = (nub $ concatMap freeArgNames (map snd dynamics)) \\ paramnames -- also get the arguments which are 'uniquely inferrable' from -- statics (see sec 4.2 of "Scrapping Your Inefficient Engine") -- or parameters to the type of a static let statics' = nub $ map fst statics ++ filter (\x -> not (elem x dnames)) stnames let stpos = staticList statics' tm i <- getIState when (not (null statics)) $ logLvl 3 $ "Statics for " ++ show n ++ " " ++ show tm ++ "\n" ++ showTmImpls ptm ++ "\n" ++ show statics ++ "\n" ++ show dynamics ++ "\n" ++ show paramnames ++ "\n" ++ show stpos putIState $ i { idris_statics = addDef n stpos (idris_statics i) } addIBC (IBCStatic n) where initStatics (Bind n (Pi _ ty _) sc) (PPi p n' fc t s) | n /= n' = let (static, dynamic) = initStatics sc (PPi p n' fc t s) in (static, (n, ty) : dynamic) initStatics (Bind n (Pi _ ty _) sc) (PPi p n' fc _ s) = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in if pstatic p == Static then ((n, ty) : static, dynamic) else if (not (searchArg p)) then (static, (n, ty) : dynamic) else (static, dynamic) initStatics t pt = ([], []) getParamNames ist tm | (P _ n _ , args) <- unApply tm = case lookupCtxtExact n (idris_datatypes ist) of Just ti -> getNamePos 0 (param_pos ti) args Nothing -> [] where getNamePos i ps [] = [] getNamePos i ps (P _ n _ : as) | i `elem` ps = n : getNamePos (i + 1) ps as getNamePos i ps (_ : as) = getNamePos (i + 1) ps as getParamNames ist (Bind t (Pi _ (P _ n _) _) sc) = n : getParamNames ist sc getParamNames ist _ = [] getNamesFrom i ps (Bind n (Pi _ _ _) sc) | i `elem` ps = n : getNamesFrom (i + 1) ps sc | otherwise = getNamesFrom (i + 1) ps sc getNamesFrom i ps sc = [] freeArgNames (Bind n (Pi _ ty _) sc) = nub $ freeNames ty ++ freeNames sc -- treat '->' as fn here freeArgNames tm = let (_, args) = unApply tm in concatMap freeNames args -- if a name appears in a type class or tactic implicit index, it doesn't -- affect its 'uniquely inferrable' from a static status since these are -- resolved by searching. searchArg (Constraint _ _) = True searchArg (TacImp _ _ _) = True searchArg _ = False staticList sts (Bind n (Pi _ _ _) sc) = (n `elem` sts) : staticList sts sc staticList _ _ = [] -- Dealing with implicit arguments -- Add some bound implicits to the using block if they aren't there already addToUsing :: [Using] -> [(Name, PTerm)] -> [Using] addToUsing us [] = us addToUsing us ((n, t) : ns) | n `notElem` mapMaybe impName us = addToUsing (us ++ [UImplicit n t]) ns | otherwise = addToUsing us ns where impName (UImplicit n _) = Just n impName _ = Nothing -- Add constraint bindings from using block addUsingConstraints :: SyntaxInfo -> FC -> PTerm -> Idris PTerm addUsingConstraints syn fc t = do ist <- get let ns = namesIn [] ist t let cs = getConstraints t -- check declared constraints let addconsts = uconsts \\ cs return (doAdd addconsts ns t) where uconsts = filter uconst (using syn) uconst (UConstraint _ _) = True uconst _ = False doAdd [] _ t = t -- if all of args in ns, then add it doAdd (UConstraint c args : cs) ns t | all (\n -> elem n ns) args = PPi (Constraint [] Dynamic) (sMN 0 "cu") NoFC (mkConst c args) (doAdd cs ns t) | otherwise = doAdd cs ns t mkConst c args = PApp fc (PRef fc [] c) (map (\n -> PExp 0 [] (sMN 0 "carg") (PRef fc [] n)) args) getConstraints (PPi (Constraint _ _) _ _ c sc) = getcapp c ++ getConstraints sc getConstraints (PPi _ _ _ c sc) = getConstraints sc getConstraints _ = [] getcapp (PApp _ (PRef _ _ c) args) = do ns <- mapM getName args return (UConstraint c ns) getcapp _ = [] getName (PExp _ _ _ (PRef _ _ n)) = return n getName _ = [] -- Add implicit bindings from using block, and bind any missing names addUsingImpls :: SyntaxInfo -> Name -> FC -> PTerm -> Idris PTerm addUsingImpls syn n fc t = do ist <- getIState let ns = implicitNamesIn (map iname uimpls) ist t let badnames = filter (\n -> not (implicitable n) && n `notElem` (map iname uimpls)) ns when (not (null badnames)) $ throwError (At fc (Elaborating "type of " n Nothing (NoSuchVariable (head badnames)))) let cs = getArgnames t -- get already bound names let addimpls = filter (\n -> iname n `notElem` cs) uimpls -- if all names in the arguments of addconsts appear in ns, -- add the constraint implicitly return (bindFree ns (doAdd addimpls ns t)) where uimpls = filter uimpl (using syn) uimpl (UImplicit _ _) = True uimpl _ = False iname (UImplicit n _) = n iname (UConstraint _ _) = error "Can't happen addUsingImpls" doAdd [] _ t = t -- if all of args in ns, then add it doAdd (UImplicit n ty : cs) ns t | elem n ns = PPi (Imp [] Dynamic False Nothing) n NoFC ty (doAdd cs ns t) | otherwise = doAdd cs ns t -- bind the free names which weren't in the using block bindFree [] tm = tm bindFree (n:ns) tm | elem n (map iname uimpls) = bindFree ns tm | otherwise = PPi (Imp [InaccessibleArg] Dynamic False Nothing) n NoFC Placeholder (bindFree ns tm) getArgnames (PPi _ n _ c sc) = n : getArgnames sc getArgnames _ = [] -- Given the original type and the elaborated type, return the implicitness -- status of each pi-bound argument, and whether it's inaccessible (True) or not. getUnboundImplicits :: IState -> Type -> PTerm -> [(Bool, PArg)] getUnboundImplicits i t tm = getImps t (collectImps tm) where collectImps (PPi p n _ t sc) = (n, (p, t)) : collectImps sc collectImps _ = [] scopedimpl (Just i) = not (toplevel_imp i) scopedimpl _ = False getImps (Bind n (Pi i _ _) sc) imps | scopedimpl i = getImps sc imps getImps (Bind n (Pi _ t _) sc) imps | Just (p, t') <- lookup n imps = argInfo n p t' : getImps sc imps where argInfo n (Imp opt _ _ _) Placeholder = (True, PImp 0 True opt n Placeholder) argInfo n (Imp opt _ _ _) t' = (False, PImp (getPriority i t') True opt n t') argInfo n (Exp opt _ _) t' = (InaccessibleArg `elem` opt, PExp (getPriority i t') opt n t') argInfo n (Constraint opt _) t' = (InaccessibleArg `elem` opt, PConstraint 10 opt n t') argInfo n (TacImp opt _ scr) t' = (InaccessibleArg `elem` opt, PTacImplicit 10 opt n scr t') getImps (Bind n (Pi _ t _) sc) imps = impBind n t : getImps sc imps where impBind n t = (True, PImp 1 True [] n Placeholder) getImps sc tm = [] -- Add implicit Pi bindings for any names in the term which appear in an -- argument position. -- This has become a right mess already. Better redo it some time... -- TODO: This is obsoleted by the new way of elaborating types, (which -- calls addUsingImpls) but there's still a couple of places which use -- it. Clean them up! -- -- Issue 1739 in the issue tracker -- https://github.com/idris-lang/Idris-dev/issues/1739 implicit :: ElabInfo -> SyntaxInfo -> Name -> PTerm -> Idris PTerm implicit info syn n ptm = implicit' info syn [] n ptm implicit' :: ElabInfo -> SyntaxInfo -> [Name] -> Name -> PTerm -> Idris PTerm implicit' info syn ignore n ptm = do i <- getIState let (tm', impdata) = implicitise syn ignore i ptm defaultArgCheck (eInfoNames info ++ M.keys (idris_implicits i)) impdata -- let (tm'', spos) = findStatics i tm' putIState $ i { idris_implicits = addDef n impdata (idris_implicits i) } addIBC (IBCImp n) logLvl 5 ("Implicit " ++ show n ++ " " ++ show impdata) -- i <- get -- putIState $ i { idris_statics = addDef n spos (idris_statics i) } return tm' where -- Detect unknown names in default arguments and throw error if found. defaultArgCheck :: [Name] -> [PArg] -> Idris () defaultArgCheck knowns params = foldM_ notFoundInDefault knowns params notFoundInDefault :: [Name] -> PArg -> Idris [Name] notFoundInDefault kns (PTacImplicit _ _ n script _) = do i <- getIState case notFound kns (namesIn [] i script) of Nothing -> return (n:kns) Just name -> throwError (NoSuchVariable name) notFoundInDefault kns p = return ((pname p):kns) notFound :: [Name] -> [Name] -> Maybe Name notFound kns [] = Nothing notFound kns (SN (WhereN _ _ _) : ns) = notFound kns ns -- Known already notFound kns (n:ns) = if elem n kns then notFound kns ns else Just n implicitise :: SyntaxInfo -> [Name] -> IState -> PTerm -> (PTerm, [PArg]) implicitise syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $ let (declimps, ns') = execState (imps True [] tm) ([], []) ns = filter (\n -> implicitable n || elem n (map fst uvars)) $ ns' \\ (map fst pvars ++ no_imp syn ++ ignore) nsOrder = filter (not . inUsing) ns ++ filter inUsing ns in if null ns then (tm, reverse declimps) else implicitise syn ignore ist (pibind uvars nsOrder tm) where uvars = map ipair (filter uimplicit (using syn)) pvars = syn_params syn inUsing n = n `elem` map fst uvars ipair (UImplicit x y) = (x, y) uimplicit (UImplicit _ _) = True uimplicit _ = False dropAll (x:xs) ys | x `elem` ys = dropAll xs ys | otherwise = x : dropAll xs ys dropAll [] ys = [] -- Find names in argument position in a type, suitable for implicit -- binding -- Not the function position, but do everything else... implNamesIn uv (PApp fc f args) = concatMap (implNamesIn uv) (map getTm args) implNamesIn uv t = namesIn uv ist t imps top env (PApp _ f as) = do (decls, ns) <- get let isn = concatMap (namesIn uvars ist) (map getTm as) put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps top env (PPi (Imp l _ _ _) n _ ty sc) = do let isn = nub (implNamesIn uvars ty) `dropAll` [n] (decls , ns) <- get put (PImp (getPriority ist ty) True l n Placeholder : decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps True (n:env) sc imps top env (PPi (Exp l _ _) n _ ty sc) = do let isn = nub (implNamesIn uvars ty ++ case sc of (PRef _ _ x) -> namesIn uvars ist sc `dropAll` [n] _ -> []) (decls, ns) <- get -- ignore decls in HO types put (PExp (getPriority ist ty) l n Placeholder : decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps True (n:env) sc imps top env (PPi (Constraint l _) n _ ty sc) = do let isn = nub (implNamesIn uvars ty ++ case sc of (PRef _ _ x) -> namesIn uvars ist sc `dropAll` [n] _ -> []) (decls, ns) <- get -- ignore decls in HO types put (PConstraint 10 l n Placeholder : decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps True (n:env) sc imps top env (PPi (TacImp l _ scr) n _ ty sc) = do let isn = nub (implNamesIn uvars ty ++ case sc of (PRef _ _ x) -> namesIn uvars ist sc `dropAll` [n] _ -> []) (decls, ns) <- get -- ignore decls in HO types put (PTacImplicit 10 l n scr Placeholder : decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps True (n:env) sc imps top env (PRewrite _ l r _) = do (decls, ns) <- get let isn = namesIn uvars ist l ++ namesIn uvars ist r put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps top env (PTyped l r) = imps top env l imps top env (PPair _ _ _ l r) = do (decls, ns) <- get let isn = namesIn uvars ist l ++ namesIn uvars ist r put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps top env (PDPair _ _ _ (PRef _ _ n) t r) = do (decls, ns) <- get let isn = nub (namesIn uvars ist t ++ namesIn uvars ist r) \\ [n] put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls))))) imps top env (PDPair _ _ _ l t r) = do (decls, ns) <- get let isn = namesIn uvars ist l ++ namesIn uvars ist t ++ namesIn uvars ist r put (decls, nub (ns ++ (isn \\ (env ++ map fst (getImps decls))))) imps top env (PAlternative ms a as) = do (decls, ns) <- get let isn = concatMap (namesIn uvars ist) as put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls))))) imps top env (PLam fc n _ ty sc) = do imps False env ty imps False (n:env) sc imps top env (PHidden tm) = imps False env tm imps top env (PUnifyLog tm) = imps False env tm imps top env (PNoImplicits tm) = imps False env tm imps top env (PRunElab fc tm ns) = imps False env tm imps top env (PConstSugar fc tm) = imps top env tm -- ignore PConstSugar - it's for highlighting only! imps top env _ = return () pibind using [] sc = sc pibind using (n:ns) sc = case lookup n using of Just ty -> PPi (Imp [] Dynamic False (Just (Impl False True))) n NoFC ty (pibind using ns sc) Nothing -> PPi (Imp [InaccessibleArg] Dynamic False (Just (Impl False True))) n NoFC Placeholder (pibind using ns sc) -- Add implicit arguments in function calls addImplPat :: IState -> PTerm -> PTerm addImplPat = addImpl' True [] [] [] addImplBound :: IState -> [Name] -> PTerm -> PTerm addImplBound ist ns = addImpl' False ns [] [] ist addImplBoundInf :: IState -> [Name] -> [Name] -> PTerm -> PTerm addImplBoundInf ist ns inf = addImpl' False ns inf [] ist -- | Add the implicit arguments to applications in the term -- [Name] gives the names to always expend, even when under a binder of -- that name (this is to expand methods with implicit arguments in dependent -- type classes). addImpl :: [Name] -> IState -> PTerm -> PTerm addImpl = addImpl' False [] [] -- TODO: in patterns, don't add implicits to function names guarded by constructors -- and *not* inside a PHidden addImpl' :: Bool -> [Name] -> [Name] -> [Name] -> IState -> PTerm -> PTerm addImpl' inpat env infns imp_meths ist ptm = mkUniqueNames env [] (ai inpat False (zip env (repeat Nothing)) [] ptm) where topname = case ptm of PRef _ _ n -> n PApp _ (PRef _ _ n) _ -> n _ -> sUN "" -- doesn't matter then ai :: Bool -> Bool -> [(Name, Maybe PTerm)] -> [[T.Text]] -> PTerm -> PTerm ai inpat qq env ds (PRef fc fcs f) | f `elem` infns = PInferRef fc fcs f | not (f `elem` map fst env) = handleErr $ aiFn topname inpat inpat qq imp_meths ist fc f fc ds [] [] ai inpat qq env ds (PHidden (PRef fc hl f)) | not (f `elem` map fst env) = PHidden (handleErr $ aiFn topname inpat False qq imp_meths ist fc f fc ds [] []) ai inpat qq env ds (PRewrite fc l r g) = let l' = ai inpat qq env ds l r' = ai inpat qq env ds r g' = fmap (ai inpat qq env ds) g in PRewrite fc l' r' g' ai inpat qq env ds (PTyped l r) = let l' = ai inpat qq env ds l r' = ai inpat qq env ds r in PTyped l' r' ai inpat qq env ds (PPair fc hls p l r) = let l' = ai inpat qq env ds l r' = ai inpat qq env ds r in PPair fc hls p l' r' ai inpat qq env ds (PDPair fc hls p l t r) = let l' = ai inpat qq env ds l t' = ai inpat qq env ds t r' = ai inpat qq env ds r in PDPair fc hls p l' t' r' ai inpat qq env ds (PAlternative ms a as) = let as' = map (ai inpat qq env ds) as in PAlternative ms a as' ai inpat qq env _ (PDisamb ds' as) = ai inpat qq env ds' as ai inpat qq env ds (PApp fc (PInferRef ffc hl f) as) = let as' = map (fmap (ai inpat qq env ds)) as in PApp fc (PInferRef ffc hl f) as' ai inpat qq env ds (PApp fc ftm@(PRef ffc hl f) as) | f `elem` infns = ai inpat qq env ds (PApp fc (PInferRef ffc hl f) as) | not (f `elem` map fst env) = let as' = map (fmap (ai inpat qq env ds)) as asdotted' = map (fmap (ai False qq env ds)) as in handleErr $ aiFn topname inpat False qq imp_meths ist fc f ffc ds as' asdotted' | Just (Just ty) <- lookup f env = let as' = map (fmap (ai inpat qq env ds)) as arity = getPArity ty in mkPApp fc arity ftm as' ai inpat qq env ds (PApp fc f as) = let f' = ai inpat qq env ds f as' = map (fmap (ai inpat qq env ds)) as in mkPApp fc 1 f' as' ai inpat qq env ds (PCase fc c os) = let c' = ai inpat qq env ds c in -- leave os alone, because they get lifted into a new pattern match -- definition which is passed through addImpl agai inpatn with more scope -- information PCase fc c' os ai inpat qq env ds (PIfThenElse fc c t f) = PIfThenElse fc (ai inpat qq env ds c) (ai inpat qq env ds t) (ai inpat qq env ds f) -- If the name in a lambda is a constructor name, do this as a 'case' -- instead (it is harmless to do so, especially since the lambda will -- be lifted anyway!) ai inpat qq env ds (PLam fc n nfc ty sc) = case lookupDef n (tt_ctxt ist) of [] -> let ty' = ai inpat qq env ds ty sc' = ai inpat qq ((n, Just ty):env) ds sc in PLam fc n nfc ty' sc' _ -> ai inpat qq env ds (PLam fc (sMN 0 "lamp") NoFC ty (PCase fc (PRef fc [] (sMN 0 "lamp") ) [(PRef fc [] n, sc)])) ai inpat qq env ds (PLet fc n nfc ty val sc) = case lookupDef n (tt_ctxt ist) of [] -> let ty' = ai inpat qq env ds ty val' = ai inpat qq env ds val sc' = ai inpat qq ((n, Just ty):env) ds sc in PLet fc n nfc ty' val' sc' defs -> ai inpat qq env ds (PCase fc val [(PRef fc [] n, sc)]) ai inpat qq env ds (PPi p n nfc ty sc) = let ty' = ai inpat qq env ds ty env' = if n `elem` imp_meths then env else ((n, Just ty) : env) sc' = ai inpat qq env' ds sc in PPi p n nfc ty' sc' ai inpat qq env ds (PGoal fc r n sc) = let r' = ai inpat qq env ds r sc' = ai inpat qq ((n, Nothing):env) ds sc in PGoal fc r' n sc' ai inpat qq env ds (PHidden tm) = PHidden (ai inpat qq env ds tm) -- Don't do PProof or PTactics since implicits get added when scope is -- properly known in ElabTerm.runTac ai inpat qq env ds (PUnifyLog tm) = PUnifyLog (ai inpat qq env ds tm) ai inpat qq env ds (PNoImplicits tm) = PNoImplicits (ai inpat qq env ds tm) ai inpat qq env ds (PQuasiquote tm g) = PQuasiquote (ai inpat True env ds tm) (fmap (ai inpat True env ds) g) ai inpat qq env ds (PUnquote tm) = PUnquote (ai inpat False env ds tm) ai inpat qq env ds (PRunElab fc tm ns) = PRunElab fc (ai inpat False env ds tm) ns ai inpat qq env ds (PConstSugar fc tm) = PConstSugar fc (ai inpat qq env ds tm) ai inpat qq env ds tm = tm handleErr (Left err) = PElabError err handleErr (Right x) = x -- if in a pattern, and there are no arguments, and there's no possible -- names with zero explicit arguments, don't add implicits. aiFn :: Name -> Bool -> Bool -> Bool -> [Name] -> IState -> FC -> Name -- ^ function being applied -> FC -> [[T.Text]] -> [PArg] -- ^ initial arguments (if in a pattern) -> [PArg] -- ^ initial arguments (if in an expression) -> Either Err PTerm aiFn topname inpat True qq imp_meths ist fc f ffc ds [] _ | inpat && implicitable f && unqualified f = Right $ PPatvar ffc f | otherwise = case lookupDef f (tt_ctxt ist) of [] -> Right $ PPatvar ffc f alts -> let ialts = lookupCtxtName f (idris_implicits ist) in -- trace (show f ++ " " ++ show (fc, any (all imp) ialts, ialts, any constructor alts)) $ if (not (vname f) || tcname f || any (conCaf (tt_ctxt ist)) ialts) -- any constructor alts || any allImp ialts)) then aiFn topname inpat False qq imp_meths ist fc f ffc ds [] [] -- use it as a constructor else Right $ PPatvar ffc f where imp (PExp _ _ _ _) = False imp _ = True -- allImp [] = False allImp xs = all imp xs unqualified (NS _ _) = False unqualified _ = True constructor (TyDecl (DCon _ _ _) _) = True constructor _ = False conCaf ctxt (n, cia) = (isDConName n ctxt || (qq && isTConName n ctxt)) && allImp cia vname (UN n) = True -- non qualified vname _ = False aiFn topname inpat expat qq imp_meths ist fc f ffc ds as asexp | f `elem` primNames = Right $ PApp fc (PRef ffc [ffc] f) as aiFn topname inpat expat qq imp_meths ist fc f ffc ds as asexp -- This is where namespaces get resolved by adding PAlternative = do let ns = lookupCtxtName f (idris_implicits ist) let nh = filter (\(n, _) -> notHidden n) ns let ns' = case trimAlts ds nh of [] -> nh x -> x case ns' of [(f',ns)] -> Right $ mkPApp fc (length ns) (PRef ffc [ffc] (isImpName f f')) (insertImpl ns (chooseArgs f' as asexp)) [] -> if f `elem` (map fst (idris_metavars ist)) then Right $ PApp fc (PRef ffc [ffc] f) as else Right $ mkPApp fc (length as) (PRef ffc [ffc] f) as alts -> Right $ PAlternative [] (ExactlyOne True) $ map (\(f', ns) -> mkPApp fc (length ns) (PRef ffc [ffc] (isImpName f f')) (insertImpl ns (chooseArgs f' as asexp))) alts where -- choose whether to treat the arguments as patterns or expressions -- if 'f' is a defined function, treat as expression, otherwise do the default. -- This is so any names which later go under a PHidden are treated -- as function names rather than bound pattern variables chooseArgs f as asexp | isConName f (tt_ctxt ist) = as | f == topname = as | Nothing <- lookupDefExact f (tt_ctxt ist) = as | otherwise = asexp -- if the name is in imp_meths, we should actually refer to the bound -- name rather than the global one after expanding implicits isImpName f f' | f `elem` imp_meths = f | otherwise = f' trimAlts [] alts = alts trimAlts ns alts = filter (\(x, _) -> any (\d -> d `isPrefixOf` nspace x) ns) alts nspace (NS _ s) = s nspace _ = [] notHidden n = case getAccessibility n of Hidden -> False _ -> True getAccessibility n = case lookupDefAccExact n False (tt_ctxt ist) of Just (n,t) -> t _ -> Public insertImpl :: [PArg] -- ^ expected argument types (from idris_implicits) -> [PArg] -- ^ given arguments -> [PArg] insertImpl ps as = let (as', badimpls) = partition (impIn ps) as in map addUnknownImp badimpls ++ insImpAcc M.empty ps (filter expArg as') (filter (not . expArg) as') insImpAcc :: M.Map Name PTerm -- accumulated param names & arg terms -> [PArg] -- parameters -> [PArg] -- explicit arguments -> [PArg] -- implicits given -> [PArg] insImpAcc pnas (PExp p l n ty : ps) (PExp _ _ _ tm : given) imps = PExp p l n tm : insImpAcc (M.insert n tm pnas) ps given imps insImpAcc pnas (PConstraint p l n ty : ps) (PConstraint _ _ _ tm : given) imps = PConstraint p l n tm : insImpAcc (M.insert n tm pnas) ps given imps insImpAcc pnas (PConstraint p l n ty : ps) given imps = let rtc = PResolveTC fc in PConstraint p l n rtc : insImpAcc (M.insert n rtc pnas) ps given imps insImpAcc pnas (PImp p _ l n ty : ps) given imps = case find n imps [] of Just (tm, imps') -> PImp p False l n tm : insImpAcc (M.insert n tm pnas) ps given imps' Nothing -> let ph = if f `elem` imp_meths then PRef fc [] n else Placeholder in PImp p True l n ph : insImpAcc (M.insert n ph pnas) ps given imps insImpAcc pnas (PTacImplicit p l n sc' ty : ps) given imps = let sc = addImpl imp_meths ist (substMatches (M.toList pnas) sc') in case find n imps [] of Just (tm, imps') -> PTacImplicit p l n sc tm : insImpAcc (M.insert n tm pnas) ps given imps' Nothing -> if inpat then PTacImplicit p l n sc Placeholder : insImpAcc (M.insert n Placeholder pnas) ps given imps else PTacImplicit p l n sc sc : insImpAcc (M.insert n sc pnas) ps given imps insImpAcc _ expected [] imps = map addUnknownImp imps -- so that unused implicits give error insImpAcc _ _ given imps = given ++ imps addUnknownImp arg = arg { argopts = UnknownImp : argopts arg } find n [] acc = Nothing find n (PImp _ _ _ n' t : gs) acc | n == n' = Just (t, reverse acc ++ gs) find n (PTacImplicit _ _ n' _ t : gs) acc | n == n' = Just (t, reverse acc ++ gs) find n (g : gs) acc = find n gs (g : acc) -- return True if the second argument is an implicit argument which is -- expected in the implicits, or if it's not an implicit impIn :: [PArg] -> PArg -> Bool impIn ps (PExp _ _ _ _) = True impIn ps (PConstraint _ _ _ _) = True impIn ps arg = any (\p -> not (expArg arg) && pname arg == pname p) ps expArg (PExp _ _ _ _) = True expArg (PConstraint _ _ _ _) = True expArg _ = False -- replace non-linear occurrences with _ stripLinear :: IState -> PTerm -> PTerm stripLinear i tm = evalState (sl tm) [] where sl :: PTerm -> State [Name] PTerm sl (PRef fc hl f) | (_:_) <- lookupTy f (tt_ctxt i) = return $ PRef fc hl f | otherwise = do ns <- get if (f `elem` ns) then return $ PHidden (PRef fc hl f) -- Placeholder else do put (f : ns) return (PRef fc hl f) sl (PPatvar fc f) = do ns <- get if (f `elem` ns) then return $ PHidden (PPatvar fc f) -- Placeholder else do put (f : ns) return (PPatvar fc f) -- Assumption is that variables are all the same in each alternative sl t@(PAlternative ms b as) = do ns <- get as' <- slAlts ns as return (PAlternative ms b as') where slAlts ns (a : as) = do put ns a' <- sl a as' <- slAlts ns as return (a' : as') slAlts ns [] = return [] sl (PPair fc hls p l r) = do l' <- sl l; r' <- sl r; return (PPair fc hls p l' r') sl (PDPair fc hls p l t r) = do l' <- sl l t' <- sl t r' <- sl r return (PDPair fc hls p l' t' r') sl (PApp fc fn args) = do fn' <- case fn of -- Just the args, fn isn't matchable as a var PRef _ _ _ -> return fn t -> sl t args' <- mapM slA args return $ PApp fc fn' args' where slA (PImp p m l n t) = do t' <- sl t return $ PImp p m l n t' slA (PExp p l n t) = do t' <- sl t return $ PExp p l n t' slA (PConstraint p l n t) = do t' <- sl t return $ PConstraint p l n t' slA (PTacImplicit p l n sc t) = do t' <- sl t return $ PTacImplicit p l n sc t' sl x = return x -- | Remove functions which aren't applied to anything, which must then -- be resolved by unification. Assume names resolved and alternatives -- filled in (so no ambiguity). stripUnmatchable :: IState -> PTerm -> PTerm stripUnmatchable i (PApp fc fn args) = PApp fc fn (fmap (fmap su) args) where su :: PTerm -> PTerm su tm@(PRef fc hl f) | (Bind n (Pi _ t _) sc :_) <- lookupTy f (tt_ctxt i) = Placeholder | (TType _ : _) <- lookupTy f (tt_ctxt i), not (implicitable f) = PHidden tm | (UType _ : _) <- lookupTy f (tt_ctxt i), not (implicitable f) = PHidden tm su (PApp fc f@(PRef _ _ fn) args) -- here we use canBeDConName because the impossible pattern -- check will not necessarily fully resolve constructor names, -- and these bare names will otherwise get in the way of -- impossbility checking. | canBeDConName fn ctxt = PApp fc f (fmap (fmap su) args) su (PApp fc f args) = PHidden (PApp fc f args) su (PAlternative ms b alts) = let alts' = filter (/= Placeholder) (map su alts) in if null alts' then Placeholder else PAlternative ms b alts' su (PPair fc hls p l r) = PPair fc hls p (su l) (su r) su (PDPair fc hls p l t r) = PDPair fc hls p (su l) (su t) (su r) su t@(PLam fc _ _ _ _) = PHidden t su t@(PPi _ _ _ _ _) = PHidden t su t@(PConstant _ c) | isTypeConst c = PHidden t su t = t ctxt = tt_ctxt i stripUnmatchable i tm = tm mkPApp fc a f [] = f mkPApp fc a f as = let rest = drop a as in if a == 0 then appRest fc f rest else appRest fc (PApp fc f (take a as)) rest where appRest fc f [] = f appRest fc f (a : as) = appRest fc (PApp fc f [a]) as -- Find 'static' argument positions -- (the declared ones, plus any names in argument position in the declared -- statics) -- FIXME: It's possible that this really has to happen after elaboration findStatics :: IState -> PTerm -> (PTerm, [Bool]) findStatics ist tm = let (ns, ss) = fs tm in runState (pos ns ss tm) [] where fs (PPi p n fc t sc) | Static <- pstatic p = let (ns, ss) = fs sc in (namesIn [] ist t : ns, n : ss) | otherwise = let (ns, ss) = fs sc in (ns, ss) fs _ = ([], []) inOne n ns = length (filter id (map (elem n) ns)) == 1 pos ns ss (PPi p n fc t sc) | elem n ss = do sc' <- pos ns ss sc spos <- get put (True : spos) return (PPi (p { pstatic = Static }) n fc t sc') | otherwise = do sc' <- pos ns ss sc spos <- get put (False : spos) return (PPi p n fc t sc') pos ns ss t = return t -- for 6.12/7 compatibility data EitherErr a b = LeftErr a | RightOK b deriving ( Functor ) instance Applicative (EitherErr a) where pure = return (<*>) = ap instance Monad (EitherErr a) where return = RightOK (LeftErr e) >>= k = LeftErr e RightOK v >>= k = k v toEither (LeftErr e) = Left e toEither (RightOK ho) = Right ho -- | Syntactic match of a against b, returning pair of variables in a -- and what they match. Returns the pair that failed if not a match. matchClause :: IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)] matchClause = matchClause' False matchClause' :: Bool -> IState -> PTerm -> PTerm -> Either (PTerm, PTerm) [(Name, PTerm)] matchClause' names i x y = checkRpts $ match (fullApp x) (fullApp y) where matchArg x y = match (fullApp (getTm x)) (fullApp (getTm y)) fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs)) fullApp x = x match' x y = match (fullApp x) (fullApp y) match (PApp _ (PRef _ _ (NS (UN fi) [b])) [_,_,x]) x' | fi == txt "fromInteger" && b == txt "builtins", PConstant _ (I _) <- getTm x = match (getTm x) x' match x' (PApp _ (PRef _ _ (NS (UN fi) [b])) [_,_,x]) | fi == txt "fromInteger" && b == txt "builtins", PConstant _ (I _) <- getTm x = match (getTm x) x' match (PApp _ (PRef _ _ (UN l)) [_,x]) x' | l == txt "lazy" = match (getTm x) x' match x (PApp _ (PRef _ _ (UN l)) [_,x']) | l == txt "lazy" = match x (getTm x') match (PApp _ f args) (PApp _ f' args') | length args == length args' = do mf <- match' f f' ms <- zipWithM matchArg args args' return (mf ++ concat ms) match (PRef f hl n) (PApp _ x []) = match (PRef f hl n) x match (PPatvar f n) xr = match (PRef f [f] n) xr match xr (PPatvar f n) = match xr (PRef f [f] n) match (PApp _ x []) (PRef f hl n) = match x (PRef f hl n) match (PRef _ _ n) tm@(PRef _ _ n') | n == n' && not names && (not (isConName n (tt_ctxt i) || isFnName n (tt_ctxt i)) || tm == Placeholder) = return [(n, tm)] -- if one namespace is missing, drop the other | n == n' || n == dropNS n' || dropNS n == n' = return [] where dropNS (NS n _) = n dropNS n = n match (PRef _ _ n) tm | not names && (not (isConName n (tt_ctxt i) || isFnName n (tt_ctxt i)) || tm == Placeholder) = return [(n, tm)] match (PRewrite _ l r _) (PRewrite _ l' r' _) = do ml <- match' l l' mr <- match' r r' return (ml ++ mr) match (PTyped l r) (PTyped l' r') = do ml <- match l l' mr <- match r r' return (ml ++ mr) match (PTyped l r) x = match l x match x (PTyped l r) = match x l match (PPair _ _ _ l r) (PPair _ _ _ l' r') = do ml <- match' l l' mr <- match' r r' return (ml ++ mr) match (PDPair _ _ _ l t r) (PDPair _ _ _ l' t' r') = do ml <- match' l l' mt <- match' t t' mr <- match' r r' return (ml ++ mt ++ mr) match (PAlternative _ a as) (PAlternative _ a' as') = do ms <- zipWithM match' as as' return (concat ms) match a@(PAlternative _ _ as) b = do let ms = zipWith match' as (repeat b) case (rights (map toEither ms)) of (x: _) -> return x _ -> LeftErr (a, b) match (PCase _ _ _) _ = return [] -- lifted out match (PMetavar _ _) _ = return [] -- modified match (PInferRef _ _ _) _ = return [] -- modified match (PQuote _) _ = return [] match (PProof _) _ = return [] match (PTactics _) _ = return [] match (PResolveTC _) (PResolveTC _) = return [] match (PTrue _ _) (PTrue _ _) = return [] match (PReturn _) (PReturn _) = return [] match (PPi _ _ _ t s) (PPi _ _ _ t' s') = do mt <- match' t t' ms <- match' s s' return (mt ++ ms) match (PLam _ _ _ t s) (PLam _ _ _ t' s') = do mt <- match' t t' ms <- match' s s' return (mt ++ ms) match (PLet _ _ _ t ty s) (PLet _ _ _ t' ty' s') = do mt <- match' t t' mty <- match' ty ty' ms <- match' s s' return (mt ++ mty ++ ms) match (PHidden x) (PHidden y) | RightOK xs <- match x y = return xs -- to collect variables | otherwise = return [] -- Otherwise hidden things are unmatchable match (PHidden x) y | RightOK xs <- match x y = return xs | otherwise = return [] match x (PHidden y) | RightOK xs <- match x y = return xs | otherwise = return [] match (PUnifyLog x) y = match' x y match x (PUnifyLog y) = match' x y match (PNoImplicits x) y = match' x y match x (PNoImplicits y) = match' x y match Placeholder _ = return [] match _ Placeholder = return [] match (PResolveTC _) _ = return [] match a b | a == b = return [] | otherwise = LeftErr (a, b) checkRpts (RightOK ms) = check ms where check ((n,t):xs) | Just t' <- lookup n xs = if t/=t' && t/=Placeholder && t'/=Placeholder then Left (t, t') else check xs check (_:xs) = check xs check [] = Right ms checkRpts (LeftErr x) = Left x substMatches :: [(Name, PTerm)] -> PTerm -> PTerm substMatches ms = substMatchesShadow ms [] substMatchesShadow :: [(Name, PTerm)] -> [Name] -> PTerm -> PTerm substMatchesShadow [] shs t = t substMatchesShadow ((n,tm):ns) shs t = substMatchShadow n shs tm (substMatchesShadow ns shs t) substMatch :: Name -> PTerm -> PTerm -> PTerm substMatch n = substMatchShadow n [] substMatchShadow :: Name -> [Name] -> PTerm -> PTerm -> PTerm substMatchShadow n shs tm t = sm shs t where sm xs (PRef _ _ n') | n == n' = tm sm xs (PLam fc x xfc t sc) = PLam fc x xfc (sm xs t) (sm xs sc) sm xs (PPi p x fc t sc) | x `elem` xs = let x' = nextName x in PPi p x' fc (sm (x':xs) (substMatch x (PRef emptyFC [] x') t)) (sm (x':xs) (substMatch x (PRef emptyFC [] x') sc)) | otherwise = PPi p x fc (sm xs t) (sm (x : xs) sc) sm xs (PApp f x as) = fullApp $ PApp f (sm xs x) (map (fmap (sm xs)) as) sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as) sm xs (PIfThenElse fc c t f) = PIfThenElse fc (sm xs c) (sm xs t) (sm xs f) sm xs (PRewrite f x y tm) = PRewrite f (sm xs x) (sm xs y) (fmap (sm xs) tm) sm xs (PTyped x y) = PTyped (sm xs x) (sm xs y) sm xs (PPair f hls p x y) = PPair f hls p (sm xs x) (sm xs y) sm xs (PDPair f hls p x t y) = PDPair f hls p (sm xs x) (sm xs t) (sm xs y) sm xs (PAlternative ms a as) = PAlternative ms a (map (sm xs) as) sm xs (PHidden x) = PHidden (sm xs x) sm xs (PUnifyLog x) = PUnifyLog (sm xs x) sm xs (PNoImplicits x) = PNoImplicits (sm xs x) sm xs (PRunElab fc script ns) = PRunElab fc (sm xs script) ns sm xs (PConstSugar fc tm) = PConstSugar fc (sm xs tm) sm xs x = x fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs)) fullApp x = x shadow :: Name -> Name -> PTerm -> PTerm shadow n n' t = sm 0 t where sm 0 (PRef fc hl x) | n == x = PRef fc hl n' sm 0 (PLam fc x xfc t sc) | n /= x = PLam fc x xfc (sm 0 t) (sm 0 sc) | otherwise = PLam fc x xfc (sm 0 t) sc sm 0 (PPi p x fc t sc) | n /= x = PPi p x fc (sm 0 t) (sm 0 sc) | otherwise = PPi p x fc (sm 0 t) sc sm 0 (PLet fc x xfc t v sc) | n /= x = PLet fc x xfc (sm 0 t) (sm 0 v) (sm 0 sc) | otherwise = PLet fc x xfc (sm 0 t) (sm 0 v) sc sm 0 (PApp f x as) = PApp f (sm 0 x) (map (fmap (sm 0)) as) sm 0 (PAppBind f x as) = PAppBind f (sm 0 x) (map (fmap (sm 0)) as) sm 0 (PCase f x as) = PCase f (sm 0 x) (map (pmap (sm 0)) as) sm 0 (PIfThenElse fc c t f) = PIfThenElse fc (sm 0 c) (sm 0 t) (sm 0 f) sm 0 (PRewrite f x y tm) = PRewrite f (sm 0 x) (sm 0 y) (fmap (sm 0) tm) sm 0 (PTyped x y) = PTyped (sm 0 x) (sm 0 y) sm 0 (PPair f hls p x y) = PPair f hls p (sm 0 x) (sm 0 y) sm 0 (PDPair f hls p x t y) = PDPair f hls p (sm 0 x) (sm 0 t) (sm 0 y) sm 0 (PAlternative ms a as) = PAlternative ms a (map (sm 0) as) sm 0 (PTactics ts) = PTactics (map (fmap (sm 0)) ts) sm 0 (PProof ts) = PProof (map (fmap (sm 0)) ts) sm 0 (PHidden x) = PHidden (sm 0 x) sm 0 (PUnifyLog x) = PUnifyLog (sm 0 x) sm 0 (PNoImplicits x) = PNoImplicits (sm 0 x) sm 0 (PCoerced t) = PCoerced (sm 0 t) sm ql (PQuasiquote tm ty) = PQuasiquote (sm (ql + 1) tm) (fmap (sm ql) ty) sm ql (PUnquote tm) = PUnquote (sm (ql - 1) tm) sm ql x = descend (sm ql) x -- | Rename any binders which are repeated (so that we don't have to mess -- about with shadowing anywhere else). mkUniqueNames :: [Name] -> [(Name, Name)] -> PTerm -> PTerm mkUniqueNames env shadows tm = evalState (mkUniq 0 initMap tm) (S.fromList env) where initMap = M.fromList shadows inScope :: S.Set Name inScope = S.fromList $ boundNamesIn tm mkUniqA ql nmap arg = do t' <- mkUniq ql nmap (getTm arg) return (arg { getTm = t' }) -- Initialise the unique name with the environment length (so we're not -- looking for too long...) initN (UN n) l = UN $ txt (str n ++ show l) initN (MN i s) l = MN (i+l) s initN n l = n -- FIXME: Probably ought to do this for completeness! It's fine as -- long as there are no bindings inside tactics though. mkUniqT _ nmap tac = return tac mkUniq :: Int -- ^ The number of quotations that we're under -> M.Map Name Name -> PTerm -> State (S.Set Name) PTerm mkUniq 0 nmap (PLam fc n nfc ty sc) = do env <- get (n', sc') <- if n `S.member` env then do let n' = uniqueNameSet (initN n (S.size env)) (S.union env inScope) return (n', sc) -- shadow n n' sc) else return (n, sc) put (S.insert n' env) let nmap' = M.insert n n' nmap ty' <- mkUniq 0 nmap ty sc'' <- mkUniq 0 nmap' sc' return $! PLam fc n' nfc ty' sc'' mkUniq 0 nmap (PPi p n fc ty sc) = do env <- get (n', sc') <- if n `S.member` env then do let n' = uniqueNameSet (initN n (S.size env)) (S.union env inScope) return (n', sc) -- shadow n n' sc) else return (n, sc) put (S.insert n' env) let nmap' = M.insert n n' nmap ty' <- mkUniq 0 nmap ty sc'' <- mkUniq 0 nmap' sc' return $! PPi p n' fc ty' sc'' mkUniq 0 nmap (PLet fc n nfc ty val sc) = do env <- get (n', sc') <- if n `S.member` env then do let n' = uniqueNameSet (initN n (S.size env)) (S.union env inScope) return (n', sc) -- shadow n n' sc) else return (n, sc) put (S.insert n' env) let nmap' = M.insert n n' nmap ty' <- mkUniq 0 nmap ty; val' <- mkUniq 0 nmap val sc'' <- mkUniq 0 nmap' sc' return $! PLet fc n' nfc ty' val' sc'' mkUniq 0 nmap (PApp fc t args) = do t' <- mkUniq 0 nmap t args' <- mapM (mkUniqA 0 nmap) args return $! PApp fc t' args' mkUniq 0 nmap (PAppBind fc t args) = do t' <- mkUniq 0 nmap t args' <- mapM (mkUniqA 0 nmap) args return $! PAppBind fc t' args' mkUniq 0 nmap (PCase fc t alts) = do t' <- mkUniq 0 nmap t alts' <- mapM (\(x,y)-> do x' <- mkUniq 0 nmap x; y' <- mkUniq 0 nmap y return (x', y')) alts return $! PCase fc t' alts' mkUniq 0 nmap (PIfThenElse fc c t f) = liftM3 (PIfThenElse fc) (mkUniq 0 nmap c) (mkUniq 0 nmap t) (mkUniq 0 nmap f) mkUniq 0 nmap (PPair fc hls p l r) = do l' <- mkUniq 0 nmap l; r' <- mkUniq 0 nmap r return $! PPair fc hls p l' r' mkUniq 0 nmap (PDPair fc hls p (PRef fc' hls' n) t sc) | t /= Placeholder = do env <- get (n', sc') <- if n `S.member` env then do let n' = uniqueNameSet n (S.union env inScope) return (n', sc) -- shadow n n' sc) else return (n, sc) put (S.insert n' env) let nmap' = M.insert n n' nmap t' <- mkUniq 0 nmap t sc'' <- mkUniq 0 nmap' sc' return $! PDPair fc hls p (PRef fc' hls' n') t' sc'' mkUniq 0 nmap (PDPair fc hls p l t r) = do l' <- mkUniq 0 nmap l; t' <- mkUniq 0 nmap t; r' <- mkUniq 0 nmap r return $! PDPair fc hls p l' t' r' mkUniq 0 nmap (PAlternative ns b as) -- store the nmap and defer the rest until we've pruned the set -- during elaboration = return $ PAlternative (M.toList nmap ++ ns) b as mkUniq 0 nmap (PHidden t) = liftM PHidden (mkUniq 0 nmap t) mkUniq 0 nmap (PUnifyLog t) = liftM PUnifyLog (mkUniq 0 nmap t) mkUniq 0 nmap (PDisamb n t) = liftM (PDisamb n) (mkUniq 0 nmap t) mkUniq 0 nmap (PNoImplicits t) = liftM PNoImplicits (mkUniq 0 nmap t) mkUniq 0 nmap (PProof ts) = liftM PProof (mapM (mkUniqT 0 nmap) ts) mkUniq 0 nmap (PTactics ts) = liftM PTactics (mapM (mkUniqT 0 nmap) ts) mkUniq 0 nmap (PRunElab fc ts ns) = liftM (\tm -> PRunElab fc tm ns) (mkUniq 0 nmap ts) mkUniq 0 nmap (PConstSugar fc tm) = liftM (PConstSugar fc) (mkUniq 0 nmap tm) mkUniq 0 nmap (PCoerced tm) = liftM PCoerced (mkUniq 0 nmap tm) mkUniq 0 nmap t = return $ shadowAll (M.toList nmap) t where shadowAll [] t = t shadowAll ((n, n') : ns) t = shadow n n' (shadowAll ns t) mkUniq ql nmap (PQuasiquote tm ty) = do tm' <- mkUniq (ql + 1) nmap tm ty' <- case ty of Nothing -> return Nothing Just t -> fmap Just $ mkUniq ql nmap t return $! PQuasiquote tm' ty' mkUniq ql nmap (PUnquote tm) = fmap PUnquote (mkUniq (ql - 1) nmap tm) mkUniq ql nmap tm = descendM (mkUniq ql nmap) tm
aaronc/Idris-dev
src/Idris/AbsSyntax.hs
bsd-3-clause
100,715
8
29
37,107
38,111
18,917
19,194
1,861
49
module Get_top_scores where import Split_output import qualified Data.List as DL import qualified Data.Maybe as DM import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as CH import Numeric as NU get_top_scores :: Int -> [BS.ByteString] -> [BS.ByteString] get_top_scores num instrs = take num sort_array where sort_array = DL.sortBy (\x y -> compare (ext_str y) (ext_str x)) instrs rstr :: BS.ByteString -> Maybe BS.ByteString rstr inv = extract_single_data (CH.pack "score:") inv ext_str :: BS.ByteString -> Float ext_str instr = read (CH.unpack (DM.fromMaybe (CH.pack "-1") mstr)) where mstr = rstr instr get_top_nums :: Int -> [BS.ByteString] -> [Float] get_top_nums num instrs = --take num (DL.sortBy (\x y -> compare (NU.readDec (ext_str y)) (NU.readDec (ext_str x))) instrs) take num sort_array where sort_array = DL.sortBy (\x y -> compare y x) (map ext_str instrs) rstr :: BS.ByteString -> Maybe BS.ByteString rstr inv = extract_single_data (CH.pack "score:") inv ext_str :: BS.ByteString -> Float ext_str instr = read (CH.unpack (DM.fromMaybe (CH.pack "-1") mstr)) where mstr = rstr instr
schets/LILAC
src/scripts/haskell/get_top_scores.hs
bsd-3-clause
1,397
0
14
436
388
208
180
27
1
{- | Module : $Header$ Description : derived functions for signatures with symbol sets Copyright : (c) Till Mossakowski, and Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : till@informatik.uni-bremen.de Stability : provisional Portability : non-portable (imports Logic.Logic) Functions from the class Logic that operate over signatures are extended to work over signatures with symbol sets. -} module Logic.ExtSign where import qualified Data.Set as Set import qualified Data.Map as Map import Control.Monad import Common.Result import Common.DocUtils import Common.ExtSign import Logic.Logic ext_sym_of :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> ExtSign sign symbol -> Set.Set symbol ext_sym_of l = symset_of l . plainSign -- | simply put all symbols into the symbol set makeExtSign :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> sign -> ExtSign sign symbol makeExtSign l s = ExtSign s $ symset_of l s ext_ide :: (Ord symbol, Category sign morphism) => ExtSign sign symbol -> morphism ext_ide = ide . plainSign ext_empty_signature :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> ExtSign sign symbol ext_empty_signature = mkExtSign . empty_signature checkExtSign :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> String -> ExtSign sign symbol -> Result () checkExtSign l msg e@(ExtSign s sy) = let sys = symset_of l s in unless (Set.isSubsetOf sy sys) $ error $ "inconsistent symbol set in extended signature: " ++ msg ++ "\n" ++ showDoc e "\rwith unknown symbols\n" ++ showDoc (Set.difference sy sys) "" ext_signature_union :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> ExtSign sign symbol -> ExtSign sign symbol -> Result (ExtSign sign symbol) ext_signature_union l e1@(ExtSign s1 _) e2@(ExtSign s2 _) = do checkExtSign l "u1" e1 checkExtSign l "u2" e2 s <- signature_union l s1 s2 return $ makeExtSign l s ext_is_subsig :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> ExtSign sign symbol -> ExtSign sign symbol -> Bool ext_is_subsig l (ExtSign sig1 _) (ExtSign sig2 _) = is_subsig l sig1 sig2 ext_final_union :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> ExtSign sign symbol -> ExtSign sign symbol -> Result (ExtSign sign symbol) ext_final_union l e1@(ExtSign s1 _) e2@(ExtSign s2 _) = do checkExtSign l "f1" e1 checkExtSign l "f2" e2 s <- final_union l s1 s2 return $ makeExtSign l s ext_inclusion :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> ExtSign sign symbol -> ExtSign sign symbol -> Result morphism ext_inclusion l (ExtSign s1 _) (ExtSign s2 _) = inclusion l s1 s2 ext_generated_sign :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> Set.Set symbol -> ExtSign sign symbol -> Result morphism ext_generated_sign l s (ExtSign sig _) = generated_sign l s sig ext_cogenerated_sign :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> Set.Set symbol -> ExtSign sign symbol -> Result morphism ext_cogenerated_sign l s (ExtSign sig _) = cogenerated_sign l s sig ext_induced_from_morphism :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> EndoMap raw_symbol -> ExtSign sign symbol -> Result morphism ext_induced_from_morphism l rmap (ExtSign sigma _) = do -- first check: do all source raw symbols match with source signature? checkRawMap l rmap sigma mor <- induced_from_morphism l rmap sigma legal_mor mor return mor checkRawMap :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> EndoMap raw_symbol -> sign -> Result () checkRawMap l rmap = checkRawSyms l (Map.keys rmap) . symset_of l checkRawSyms :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> [raw_symbol] -> Set.Set symbol -> Result () checkRawSyms l rsyms syms = do let unknownSyms = filter ( \ rsy -> Set.null $ Set.filter (flip (matches l) rsy) syms) rsyms unless (null unknownSyms) $ Result [mkDiag Error "unknown symbols" unknownSyms] $ Just () ext_induced_from_to_morphism :: Logic lid sublogics basic_spec sentence symb_items symb_map_items sign morphism symbol raw_symbol proof_tree => lid -> EndoMap raw_symbol -> ExtSign sign symbol -> ExtSign sign symbol -> Result morphism ext_induced_from_to_morphism l r s@(ExtSign p sy) t = do checkExtSign l "from" s checkExtSign l "to" t checkRawMap l r p checkRawSyms l (Map.elems r) $ nonImportedSymbols t mor <- induced_from_to_morphism l r s t let sysI = Set.toList $ Set.difference (symset_of l p) sy morM = symmap_of l mor msysI = map (\ sym -> Map.findWithDefault sym sym morM) sysI unless (sysI == msysI) $ fail $ "imported symbols are mapped differently.\n" ++ showDoc (filter (uncurry (/=)) $ zip sysI msysI) "" legal_mor mor return mor
keithodulaigh/Hets
Logic/ExtSign.hs
gpl-2.0
6,085
0
18
1,448
1,700
817
883
123
1
{-| Module : Unicorn Description : The Unicorn CPU emulator. Copyright : (c) Adrian Herrera, 2016 License : GPL-2 Unicorn is a lightweight, multi-platform, multi-architecture CPU emulator framework based on QEMU. Further information is available at <http://www.unicorn-engine.org>. -} module Unicorn ( -- * Emulator control Emulator , Engine , Architecture(..) , Mode(..) , QueryType(..) , runEmulator , open , query , start , stop -- * Register operations , regWrite , regRead , regWriteBatch , regReadBatch -- * Memory operations , MemoryPermission(..) , MemoryRegion(..) , memWrite , memRead , memMap , memUnmap , memProtect , memRegions -- * Context operations , Context , contextAllocate , contextSave , contextRestore -- * Error handling , Error(..) , errno , strerror -- * Misc. , version ) where import Control.Monad (liftM) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Either (hoistEither, left, right, runEitherT) import Data.ByteString (ByteString, pack) import Foreign import Prelude hiding (until) import Unicorn.Internal.Core import Unicorn.Internal.Unicorn ------------------------------------------------------------------------------- -- Emulator control ------------------------------------------------------------------------------- -- | Run the Unicorn emulator and return a result on success, or an 'Error' on -- failure. runEmulator :: Emulator a -- ^ The emulation code to execute -> IO (Either Error a) -- ^ A result on success, or an 'Error' on -- failure runEmulator = runEitherT -- | Create a new instance of the Unicorn engine. open :: Architecture -- ^ CPU architecture -> [Mode] -- ^ CPU hardware mode -> Emulator Engine -- ^ A 'Unicorn' engine on success, or an 'Error' on -- failure open arch mode = do (err, ucPtr) <- lift $ ucOpen arch mode if err == ErrOk then -- Return a pointer to the Unicorn engine if ucOpen completed -- successfully lift $ mkEngine ucPtr else -- Otherwise return the error left err -- | Query internal status of the Unicorn engine. query :: Engine -- ^ 'Unicorn' engine handle -> QueryType -- ^ Query type -> Emulator Int -- ^ The result of the query query uc queryType = do (err, result) <- lift $ ucQuery uc queryType if err == ErrOk then right result else left err -- | Emulate machine code for a specific duration of time. start :: Engine -- ^ 'Unicorn' engine handle -> Word64 -- ^ Address where emulation starts -> Word64 -- ^ Address where emulation stops (i.e. when this -- address is hit) -> Maybe Int -- ^ Optional duration to emulate code (in -- microseconds). -- If 'Nothing' is provided, continue to emulate -- until the code is finished -> Maybe Int -- ^ Optional number of instructions to emulate. If -- 'Nothing' is provided, emulate all the code -- available, until the code is finished -> Emulator () -- ^ An 'Error' on failure start uc begin until timeout count = do err <- lift $ ucEmuStart uc begin until (maybeZ timeout) (maybeZ count) if err == ErrOk then right () else left err where maybeZ = maybe 0 id -- | Stop emulation (which was started by 'start'). -- This is typically called from callback functions registered by tracing APIs. -- -- NOTE: For now, this will stop execution only after the current block. stop :: Engine -- ^ 'Unicorn' engine handle -> Emulator () -- ^ An 'Error' on failure stop uc = do err <- lift $ ucEmuStop uc if err == ErrOk then right () else left err ------------------------------------------------------------------------------- -- Register operations ------------------------------------------------------------------------------- -- | Write to register. regWrite :: Reg r => Engine -- ^ 'Unicorn' engine handle -> r -- ^ Register to write to -> Int64 -- ^ Value to write to register -> Emulator () -- ^ An 'Error' on failure regWrite uc reg value = do err <- lift $ ucRegWrite uc reg value if err == ErrOk then right () else left err -- | Read register value. regRead :: Reg r => Engine -- ^ 'Unicorn' engine handle -> r -- ^ Register to read from -> Emulator Int64 -- ^ The value read from the register on success, -- or an 'Error' on failure regRead uc reg = do (err, val) <- lift $ ucRegRead uc reg if err == ErrOk then right val else left err -- | Write multiple register values. regWriteBatch :: Reg r => Engine -- ^ 'Unicorn' engine handle -> [r] -- ^ List of registers to write to -> [Int64] -- ^ List of values to write to the registers -> Emulator () -- ^ An 'Error' on failure regWriteBatch uc regs vals = do err <- lift $ ucRegWriteBatch uc regs vals (length regs) if err == ErrOk then right () else left err -- | Read multiple register values. regReadBatch :: Reg r => Engine -- ^ 'Unicorn' engine handle -> [r] -- ^ List of registers to read from -> Emulator [Int64] -- ^ A list of register values on success, -- or an 'Error' on failure regReadBatch uc regs = do -- Allocate an array of the given size let size = length regs result <- lift . allocaArray size $ \array -> do err <- ucRegReadBatch uc regs array size if err == ErrOk then -- If ucRegReadBatch completed successfully, pack the contents of -- the array into a list and return it liftM Right (peekArray size array) else -- Otherwise return the error return $ Left err hoistEither result ------------------------------------------------------------------------------- -- Memory operations ------------------------------------------------------------------------------- -- | Write to memory. memWrite :: Engine -- ^ 'Unicorn' engine handle -> Word64 -- ^ Starting memory address of bytes to write -> ByteString -- ^ The data to write -> Emulator () -- ^ An 'Error' on failure memWrite uc address bytes = do err <- lift $ ucMemWrite uc address bytes if err == ErrOk then right () else left err -- | Read memory contents. memRead :: Engine -- ^ 'Unicorn' engine handle -> Word64 -- ^ Starting memory address to read -- from -> Int -- ^ Size of memory to read (in bytes) -> Emulator ByteString -- ^ The memory contents on success, or -- an 'Error' on failure memRead uc address size = do -- Allocate an array of the given size result <- lift . allocaArray size $ \array -> do err <- ucMemRead uc address array size if err == ErrOk then -- If ucMemRead completed successfully, pack the contents of the -- array into a ByteString and return it liftM (Right . pack) (peekArray size array) else -- Otherwise return the error return $ Left err hoistEither result -- | Map a range of memory. memMap :: Engine -- ^ 'Unicorn' engine handle -> Word64 -- ^ Start address of the new memory region to -- be mapped in. This address must be -- aligned to 4KB, or this will return with -- 'ErrArg' error -> Int -- ^ Size of the new memory region to be mapped -- in. This size must be a multiple of 4KB, or -- this will return with an 'ErrArg' error -> [MemoryPermission] -- ^ Permissions for the newly mapped region -> Emulator () -- ^ An 'Error' on failure memMap uc address size perms = do err <- lift $ ucMemMap uc address size perms if err == ErrOk then right () else left err -- | Unmap a range of memory. memUnmap :: Engine -- ^ 'Unicorn' engine handle -> Word64 -- ^ Start addres of the memory region to be unmapped. -- This address must be aligned to 4KB or this will -- return with an 'ErrArg' error -> Int -- ^ Size of the memory region to be modified. This -- must be a multiple of 4KB, or this will return with -- an 'ErrArg' error -> Emulator () -- ^ An 'Error' on failure memUnmap uc address size = do err <- lift $ ucMemUnmap uc address size if err == ErrOk then right () else left err -- | Change permissions on a range of memory. memProtect :: Engine -- ^ 'Unicorn' engine handle -> Word64 -- ^ Start address of the memory region to -- modify. This address must be aligned to -- 4KB, or this will return with an -- 'ErrArg' error -> Int -- ^ Size of the memory region to be -- modified. This size must be a multiple -- of 4KB, or this will return with an -- 'ErrArg' error -> [MemoryPermission] -- ^ New permissions for the mapped region -> Emulator () -- ^ An 'Error' on failure memProtect uc address size perms = do err <- lift $ ucMemProtect uc address size perms if err == ErrOk then right () else left err -- | Retrieve all memory regions mapped by 'memMap'. memRegions :: Engine -- ^ 'Unicorn' engine handle -> Emulator [MemoryRegion] -- ^ A list of memory regions memRegions uc = do (err, regionPtr, count) <- lift $ ucMemRegions uc if err == ErrOk then do regions <- lift $ peekArray count regionPtr right regions else left err ------------------------------------------------------------------------------- -- Context operations ------------------------------------------------------------------------------- -- | Allocate a region that can be used to perform quick save/rollback of the -- CPU context, which includes registers and some internal metadata. Contexts -- may not be shared across engine instances with differing architectures or -- modes. contextAllocate :: Engine -- ^ 'Unicon' engine handle -> Emulator Context -- ^ A CPU context contextAllocate uc = do (err, contextPtr) <- lift $ ucContextAlloc uc if err == ErrOk then -- Return a CPU context if ucContextAlloc completed successfully lift $ mkContext contextPtr else left err -- | Save a copy of the internal CPU context. contextSave :: Engine -- ^ 'Unicorn' engine handle -> Context -- ^ A CPU context -> Emulator () -- ^ An error on failure contextSave uc context = do err <- lift $ ucContextSave uc context if err == ErrOk then right () else left err -- | Restore the current CPU context from a saved copy. contextRestore :: Engine -- ^ 'Unicorn' engine handle -> Context -- ^ A CPU context -> Emulator () -- ^ An error on failure contextRestore uc context = do err <- lift $ ucContextRestore uc context if err == ErrOk then right () else left err ------------------------------------------------------------------------------- -- Misc. ------------------------------------------------------------------------------- -- | Combined API version & major and minor version numbers. Returns a -- hexadecimal number as (major << 8 | minor), which encodes both major and -- minor versions. version :: Int version = ucVersion nullPtr nullPtr -- | Report the 'Error' of the last failed API call. errno :: Engine -- ^ 'Unicorn' engine handle -> Emulator Error -- ^ The last 'Error' code errno = lift . ucErrno -- | Return a string describing the given 'Error'. strerror :: Error -- ^ The 'Error' code -> String -- ^ Description of the error code strerror = ucStrerror
alekhin0w/unicorn
bindings/haskell/src/Unicorn.hs
gpl-2.0
13,109
0
15
4,464
1,871
1,026
845
211
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Redshift.ModifyClusterParameterGroup -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Modifies the parameters of a parameter group. -- -- For more information about managing parameter groups, go to <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html Amazon RedshiftParameter Groups> in the /Amazon Redshift Cluster Management Guide/. -- -- <http://docs.aws.amazon.com/redshift/latest/APIReference/API_ModifyClusterParameterGroup.html> module Network.AWS.Redshift.ModifyClusterParameterGroup ( -- * Request ModifyClusterParameterGroup -- ** Request constructor , modifyClusterParameterGroup -- ** Request lenses , mcpgParameterGroupName , mcpgParameters -- * Response , ModifyClusterParameterGroupResponse -- ** Response constructor , modifyClusterParameterGroupResponse -- ** Response lenses , mcpgrParameterGroupName , mcpgrParameterGroupStatus ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.Redshift.Types import qualified GHC.Exts data ModifyClusterParameterGroup = ModifyClusterParameterGroup { _mcpgParameterGroupName :: Text , _mcpgParameters :: List "member" Parameter } deriving (Eq, Read, Show) -- | 'ModifyClusterParameterGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'mcpgParameterGroupName' @::@ 'Text' -- -- * 'mcpgParameters' @::@ ['Parameter'] -- modifyClusterParameterGroup :: Text -- ^ 'mcpgParameterGroupName' -> ModifyClusterParameterGroup modifyClusterParameterGroup p1 = ModifyClusterParameterGroup { _mcpgParameterGroupName = p1 , _mcpgParameters = mempty } -- | The name of the parameter group to be modified. mcpgParameterGroupName :: Lens' ModifyClusterParameterGroup Text mcpgParameterGroupName = lens _mcpgParameterGroupName (\s a -> s { _mcpgParameterGroupName = a }) -- | An array of parameters to be modified. A maximum of 20 parameters can be -- modified in a single request. -- -- For each parameter to be modified, you must supply at least the parameter -- name and parameter value; other name-value pairs of the parameter are -- optional. -- -- For the workload management (WLM) configuration, you must supply all the -- name-value pairs in the wlm_json_configuration parameter. mcpgParameters :: Lens' ModifyClusterParameterGroup [Parameter] mcpgParameters = lens _mcpgParameters (\s a -> s { _mcpgParameters = a }) . _List data ModifyClusterParameterGroupResponse = ModifyClusterParameterGroupResponse { _mcpgrParameterGroupName :: Maybe Text , _mcpgrParameterGroupStatus :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'ModifyClusterParameterGroupResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'mcpgrParameterGroupName' @::@ 'Maybe' 'Text' -- -- * 'mcpgrParameterGroupStatus' @::@ 'Maybe' 'Text' -- modifyClusterParameterGroupResponse :: ModifyClusterParameterGroupResponse modifyClusterParameterGroupResponse = ModifyClusterParameterGroupResponse { _mcpgrParameterGroupName = Nothing , _mcpgrParameterGroupStatus = Nothing } -- | The name of the cluster parameter group. mcpgrParameterGroupName :: Lens' ModifyClusterParameterGroupResponse (Maybe Text) mcpgrParameterGroupName = lens _mcpgrParameterGroupName (\s a -> s { _mcpgrParameterGroupName = a }) -- | The status of the parameter group. For example, if you made a change to a -- parameter group name-value pair, then the change could be pending a reboot of -- an associated cluster. mcpgrParameterGroupStatus :: Lens' ModifyClusterParameterGroupResponse (Maybe Text) mcpgrParameterGroupStatus = lens _mcpgrParameterGroupStatus (\s a -> s { _mcpgrParameterGroupStatus = a }) instance ToPath ModifyClusterParameterGroup where toPath = const "/" instance ToQuery ModifyClusterParameterGroup where toQuery ModifyClusterParameterGroup{..} = mconcat [ "ParameterGroupName" =? _mcpgParameterGroupName , "Parameters" =? _mcpgParameters ] instance ToHeaders ModifyClusterParameterGroup instance AWSRequest ModifyClusterParameterGroup where type Sv ModifyClusterParameterGroup = Redshift type Rs ModifyClusterParameterGroup = ModifyClusterParameterGroupResponse request = post "ModifyClusterParameterGroup" response = xmlResponse instance FromXML ModifyClusterParameterGroupResponse where parseXML = withElement "ModifyClusterParameterGroupResult" $ \x -> ModifyClusterParameterGroupResponse <$> x .@? "ParameterGroupName" <*> x .@? "ParameterGroupStatus"
romanb/amazonka
amazonka-redshift/gen/Network/AWS/Redshift/ModifyClusterParameterGroup.hs
mpl-2.0
5,650
0
11
1,046
578
352
226
69
1
{-# LANGUAGE CPP, GADTs #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} -- ---------------------------------------------------------------------------- -- | Handle conversion of CmmProc to LLVM code. -- module LlvmCodeGen.CodeGen ( genLlvmProc ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import LlvmCodeGen.Regs import BlockId import CodeGen.Platform ( activeStgRegs, callerSaves ) import CLabel import Cmm import CPrim import PprCmm import CmmUtils import CmmSwitch import Hoopl import DynFlags import FastString import ForeignCall import Outputable import Platform import OrdList import UniqSupply import Unique import Data.List ( nub ) import Data.Maybe ( catMaybes ) type Atomic = Bool type LlvmStatements = OrdList LlvmStatement -- ----------------------------------------------------------------------------- -- | Top-level of the LLVM proc Code generator -- genLlvmProc :: RawCmmDecl -> LlvmM [LlvmCmmDecl] genLlvmProc (CmmProc infos lbl live graph) = do let blocks = toBlockListEntryFirstFalseFallthrough graph (lmblocks, lmdata) <- basicBlocksCodeGen live blocks let info = mapLookup (g_entry graph) infos proc = CmmProc info lbl live (ListGraph lmblocks) return (proc:lmdata) genLlvmProc _ = panic "genLlvmProc: case that shouldn't reach here!" -- ----------------------------------------------------------------------------- -- * Block code generation -- -- | Generate code for a list of blocks that make up a complete -- procedure. The first block in the list is exepected to be the entry -- point and will get the prologue. basicBlocksCodeGen :: LiveGlobalRegs -> [CmmBlock] -> LlvmM ([LlvmBasicBlock], [LlvmCmmDecl]) basicBlocksCodeGen _ [] = panic "no entry block!" basicBlocksCodeGen live (entryBlock:cmmBlocks) = do (prologue, prologueTops) <- funPrologue live (entryBlock:cmmBlocks) -- Generate code (BasicBlock bid entry, entryTops) <- basicBlockCodeGen entryBlock (blocks, topss) <- fmap unzip $ mapM basicBlockCodeGen cmmBlocks -- Compose let entryBlock = BasicBlock bid (fromOL prologue ++ entry) return (entryBlock : blocks, prologueTops ++ entryTops ++ concat topss) -- | Generate code for one block basicBlockCodeGen :: CmmBlock -> LlvmM ( LlvmBasicBlock, [LlvmCmmDecl] ) basicBlockCodeGen block = do let (_, nodes, tail) = blockSplit block id = entryLabel block (mid_instrs, top) <- stmtsToInstrs $ blockToList nodes (tail_instrs, top') <- stmtToInstrs tail let instrs = fromOL (mid_instrs `appOL` tail_instrs) return (BasicBlock id instrs, top' ++ top) -- ----------------------------------------------------------------------------- -- * CmmNode code generation -- -- A statement conversion return data. -- * LlvmStatements: The compiled LLVM statements. -- * LlvmCmmDecl: Any global data needed. type StmtData = (LlvmStatements, [LlvmCmmDecl]) -- | Convert a list of CmmNode's to LlvmStatement's stmtsToInstrs :: [CmmNode e x] -> LlvmM StmtData stmtsToInstrs stmts = do (instrss, topss) <- fmap unzip $ mapM stmtToInstrs stmts return (concatOL instrss, concat topss) -- | Convert a CmmStmt to a list of LlvmStatement's stmtToInstrs :: CmmNode e x -> LlvmM StmtData stmtToInstrs stmt = case stmt of CmmComment _ -> return (nilOL, []) -- nuke comments CmmTick _ -> return (nilOL, []) CmmUnwind {} -> return (nilOL, []) CmmAssign reg src -> genAssign reg src CmmStore addr src -> genStore addr src CmmBranch id -> genBranch id CmmCondBranch arg true false -> genCondBranch arg true false CmmSwitch arg ids -> genSwitch arg ids -- Foreign Call CmmUnsafeForeignCall target res args -> genCall target res args -- Tail call CmmCall { cml_target = arg, cml_args_regs = live } -> genJump arg live _ -> panic "Llvm.CodeGen.stmtToInstrs" -- | Wrapper function to declare an instrinct function by function type getInstrinct2 :: LMString -> LlvmType -> LlvmM ExprData getInstrinct2 fname fty@(LMFunction funSig) = do let fv = LMGlobalVar fname fty (funcLinkage funSig) Nothing Nothing Constant fn <- funLookup fname tops <- case fn of Just _ -> return [] Nothing -> do funInsert fname fty return [CmmData Data [([],[fty])]] return (fv, nilOL, tops) getInstrinct2 _ _ = error "getInstrinct2: Non-function type!" -- | Declares an instrinct function by return and parameter types getInstrinct :: LMString -> LlvmType -> [LlvmType] -> LlvmM ExprData getInstrinct fname retTy parTys = let funSig = LlvmFunctionDecl fname ExternallyVisible CC_Ccc retTy FixedArgs (tysToParams parTys) Nothing fty = LMFunction funSig in getInstrinct2 fname fty -- | Memory barrier instruction for LLVM >= 3.0 barrier :: LlvmM StmtData barrier = do let s = Fence False SyncSeqCst return (unitOL s, []) -- | Foreign Calls genCall :: ForeignTarget -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData -- Write barrier needs to be handled specially as it is implemented as an LLVM -- intrinsic function. genCall (PrimTarget MO_WriteBarrier) _ _ = do platform <- getLlvmPlatform if platformArch platform `elem` [ArchX86, ArchX86_64, ArchSPARC] then return (nilOL, []) else barrier genCall (PrimTarget MO_Touch) _ _ = return (nilOL, []) genCall (PrimTarget (MO_UF_Conv w)) [dst] [e] = do dstV <- getCmmReg (CmmLocal dst) let ty = cmmToLlvmType $ localRegType dst width = widthToLlvmFloat w castV <- mkLocalVar ty (ve, stmts, top) <- exprToVar e let stmt3 = Assignment castV $ Cast LM_Uitofp ve width stmt4 = Store castV dstV return (stmts `snocOL` stmt3 `snocOL` stmt4, top) genCall (PrimTarget (MO_UF_Conv _)) [_] args = panic $ "genCall: Too many arguments to MO_UF_Conv. " ++ "Can only handle 1, given" ++ show (length args) ++ "." -- Handle prefetching data genCall t@(PrimTarget (MO_Prefetch_Data localityInt)) [] args | 0 <= localityInt && localityInt <= 3 = do let argTy = [i8Ptr, i32, i32, i32] funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing let (_, arg_hints) = foreignTargetHints t let args_hints' = zip args arg_hints (argVars, stmts1, top1) <- arg_vars args_hints' ([], nilOL, []) (fptr, stmts2, top2) <- getFunPtr funTy t (argVars', stmts3) <- castVars $ zip argVars argTy trash <- getTrashStmts let argSuffix = [mkIntLit i32 0, mkIntLit i32 localityInt, mkIntLit i32 1] call = Expr $ Call StdCall fptr (argVars' ++ argSuffix) [] stmts = stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` trash `snocOL` call return (stmts, top1 ++ top2) | otherwise = panic $ "prefetch locality level integer must be between 0 and 3, given: " ++ (show localityInt) -- Handle PopCnt, Clz, Ctz, and BSwap that need to only convert arg -- and return types genCall t@(PrimTarget (MO_PopCnt w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_Clz w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_Ctz w)) dsts args = genCallSimpleCast w t dsts args genCall t@(PrimTarget (MO_BSwap w)) dsts args = genCallSimpleCast w t dsts args genCall (PrimTarget (MO_AtomicRead _)) [dst] [addr] = do dstV <- getCmmReg (CmmLocal dst) (v1, stmts, top) <- genLoad True addr (localRegType dst) let stmt1 = Store v1 dstV return (stmts `snocOL` stmt1, top) -- TODO: implement these properly rather than calling to RTS functions. -- genCall t@(PrimTarget (MO_AtomicWrite width)) [] [addr, val] = undefined -- genCall t@(PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = undefined -- genCall t@(PrimTarget (MO_Cmpxchg width)) [dst] [addr, old, new] = undefined -- Handle memcpy function specifically since llvm's intrinsic version takes -- some extra parameters. genCall t@(PrimTarget op) [] args' | op == MO_Memcpy || op == MO_Memset || op == MO_Memmove = do dflags <- getDynFlags let (args, alignVal) = splitAlignVal args' isVolTy = [i1] isVolVal = [mkIntLit i1 0] argTy | op == MO_Memset = [i8Ptr, i8, llvmWord dflags, i32] ++ isVolTy | otherwise = [i8Ptr, i8Ptr, llvmWord dflags, i32] ++ isVolTy funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible CC_Ccc LMVoid FixedArgs (tysToParams argTy) Nothing let (_, arg_hints) = foreignTargetHints t let args_hints = zip args arg_hints (argVars, stmts1, top1) <- arg_vars args_hints ([], nilOL, []) (fptr, stmts2, top2) <- getFunPtr funTy t (argVars', stmts3) <- castVars $ zip argVars argTy stmts4 <- getTrashStmts let arguments = argVars' ++ (alignVal:isVolVal) call = Expr $ Call StdCall fptr arguments [] stmts = stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` stmts4 `snocOL` call return (stmts, top1 ++ top2) where splitAlignVal xs = (init xs, extractLit $ last xs) -- Fix for trac #6158. Since LLVM 3.1, opt fails when given anything other -- than a direct constant (i.e. 'i32 8') as the alignment argument for the -- memcpy & co llvm intrinsic functions. So we handle this directly now. extractLit (CmmLit (CmmInt i _)) = mkIntLit i32 i extractLit _other = trace ("WARNING: Non constant alignment value given" ++ " for memcpy! Please report to GHC developers") mkIntLit i32 0 -- Handle all other foreign calls and prim ops. genCall target res args = do dflags <- getDynFlags -- parameter types let arg_type (_, AddrHint) = i8Ptr -- cast pointers to i8*. Llvm equivalent of void* arg_type (expr, _) = cmmToLlvmType $ cmmExprType dflags expr -- ret type let ret_type [] = LMVoid ret_type [(_, AddrHint)] = i8Ptr ret_type [(reg, _)] = cmmToLlvmType $ localRegType reg ret_type t = panic $ "genCall: Too many return values! Can only handle" ++ " 0 or 1, given " ++ show (length t) ++ "." -- extract Cmm call convention, and translate to LLVM call convention platform <- getLlvmPlatform let lmconv = case target of ForeignTarget _ (ForeignConvention conv _ _ _) -> case conv of StdCallConv -> case platformArch platform of ArchX86 -> CC_X86_Stdcc ArchX86_64 -> CC_X86_Stdcc _ -> CC_Ccc CCallConv -> CC_Ccc CApiConv -> CC_Ccc PrimCallConv -> panic "LlvmCodeGen.CodeGen.genCall: PrimCallConv" JavaScriptCallConv -> panic "LlvmCodeGen.CodeGen.genCall: JavaScriptCallConv" PrimTarget _ -> CC_Ccc {- CC_Ccc of the possibilities here are a worry with the use of a custom calling convention for passing STG args. In practice the more dangerous combinations (e.g StdCall + llvmGhcCC) don't occur. The native code generator only handles StdCall and CCallConv. -} -- call attributes let fnAttrs | never_returns = NoReturn : llvmStdFunAttrs | otherwise = llvmStdFunAttrs never_returns = case target of ForeignTarget _ (ForeignConvention _ _ _ CmmNeverReturns) -> True _ -> False -- fun type let (res_hints, arg_hints) = foreignTargetHints target let args_hints = zip args arg_hints let ress_hints = zip res res_hints let ccTy = StdCall -- tail calls should be done through CmmJump let retTy = ret_type ress_hints let argTy = tysToParams $ map arg_type args_hints let funTy = \name -> LMFunction $ LlvmFunctionDecl name ExternallyVisible lmconv retTy FixedArgs argTy (llvmFunAlign dflags) (argVars, stmts1, top1) <- arg_vars args_hints ([], nilOL, []) (fptr, stmts2, top2) <- getFunPtr funTy target let retStmt | ccTy == TailCall = unitOL $ Return Nothing | never_returns = unitOL $ Unreachable | otherwise = nilOL stmts3 <- getTrashStmts let stmts = stmts1 `appOL` stmts2 `appOL` stmts3 -- make the actual call case retTy of LMVoid -> do let s1 = Expr $ Call ccTy fptr argVars fnAttrs let allStmts = stmts `snocOL` s1 `appOL` retStmt return (allStmts, top1 ++ top2) _ -> do (v1, s1) <- doExpr retTy $ Call ccTy fptr argVars fnAttrs -- get the return register let ret_reg [reg] = reg ret_reg t = panic $ "genCall: Bad number of registers! Can only handle" ++ " 1, given " ++ show (length t) ++ "." let creg = ret_reg res vreg <- getCmmReg (CmmLocal creg) let allStmts = stmts `snocOL` s1 if retTy == pLower (getVarType vreg) then do let s2 = Store v1 vreg return (allStmts `snocOL` s2 `appOL` retStmt, top1 ++ top2) else do let ty = pLower $ getVarType vreg let op = case ty of vt | isPointer vt -> LM_Bitcast | isInt vt -> LM_Ptrtoint | otherwise -> panic $ "genCall: CmmReg bad match for" ++ " returned type!" (v2, s2) <- doExpr ty $ Cast op v1 ty let s3 = Store v2 vreg return (allStmts `snocOL` s2 `snocOL` s3 `appOL` retStmt, top1 ++ top2) -- Handle simple function call that only need simple type casting, of the form: -- truncate arg >>= \a -> call(a) >>= zext -- -- since GHC only really has i32 and i64 types and things like Word8 are backed -- by an i32 and just present a logical i8 range. So we must handle conversions -- from i32 to i8 explicitly as LLVM is strict about types. genCallSimpleCast :: Width -> ForeignTarget -> [CmmFormal] -> [CmmActual] -> LlvmM StmtData genCallSimpleCast w t@(PrimTarget op) [dst] args = do let width = widthToLlvmInt w dstTy = cmmToLlvmType $ localRegType dst fname <- cmmPrimOpFunctions op (fptr, _, top3) <- getInstrinct fname width [width] dstV <- getCmmReg (CmmLocal dst) let (_, arg_hints) = foreignTargetHints t let args_hints = zip args arg_hints (argsV, stmts2, top2) <- arg_vars args_hints ([], nilOL, []) (argsV', stmts4) <- castVars $ zip argsV [width] (retV, s1) <- doExpr width $ Call StdCall fptr argsV' [] ([retV'], stmts5) <- castVars [(retV,dstTy)] let s2 = Store retV' dstV let stmts = stmts2 `appOL` stmts4 `snocOL` s1 `appOL` stmts5 `snocOL` s2 return (stmts, top2 ++ top3) genCallSimpleCast _ _ dsts _ = panic ("genCallSimpleCast: " ++ show (length dsts) ++ " dsts") -- | Create a function pointer from a target. getFunPtr :: (LMString -> LlvmType) -> ForeignTarget -> LlvmM ExprData getFunPtr funTy targ = case targ of ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do name <- strCLabel_llvm lbl getHsFunc' name (funTy name) ForeignTarget expr _ -> do (v1, stmts, top) <- exprToVar expr dflags <- getDynFlags let fty = funTy $ fsLit "dynamic" cast = case getVarType v1 of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr ty -> panic $ "genCall: Expr is of bad type for function" ++ " call! (" ++ showSDoc dflags (ppr ty) ++ ")" (v2,s1) <- doExpr (pLift fty) $ Cast cast v1 (pLift fty) return (v2, stmts `snocOL` s1, top) PrimTarget mop -> do name <- cmmPrimOpFunctions mop let fty = funTy name getInstrinct2 name fty -- | Conversion of call arguments. arg_vars :: [(CmmActual, ForeignHint)] -> ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) -> LlvmM ([LlvmVar], LlvmStatements, [LlvmCmmDecl]) arg_vars [] (vars, stmts, tops) = return (vars, stmts, tops) arg_vars ((e, AddrHint):rest) (vars, stmts, tops) = do (v1, stmts', top') <- exprToVar e dflags <- getDynFlags let op = case getVarType v1 of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr a -> panic $ "genCall: Can't cast llvmType to i8*! (" ++ showSDoc dflags (ppr a) ++ ")" (v2, s1) <- doExpr i8Ptr $ Cast op v1 i8Ptr arg_vars rest (vars ++ [v2], stmts `appOL` stmts' `snocOL` s1, tops ++ top') arg_vars ((e, _):rest) (vars, stmts, tops) = do (v1, stmts', top') <- exprToVar e arg_vars rest (vars ++ [v1], stmts `appOL` stmts', tops ++ top') -- | Cast a collection of LLVM variables to specific types. castVars :: [(LlvmVar, LlvmType)] -> LlvmM ([LlvmVar], LlvmStatements) castVars vars = do done <- mapM (uncurry castVar) vars let (vars', stmts) = unzip done return (vars', toOL stmts) -- | Cast an LLVM variable to a specific type, panicing if it can't be done. castVar :: LlvmVar -> LlvmType -> LlvmM (LlvmVar, LlvmStatement) castVar v t | getVarType v == t = return (v, Nop) | otherwise = do dflags <- getDynFlags let op = case (getVarType v, t) of (LMInt n, LMInt m) -> if n < m then LM_Sext else LM_Trunc (vt, _) | isFloat vt && isFloat t -> if llvmWidthInBits dflags vt < llvmWidthInBits dflags t then LM_Fpext else LM_Fptrunc (vt, _) | isInt vt && isFloat t -> LM_Sitofp (vt, _) | isFloat vt && isInt t -> LM_Fptosi (vt, _) | isInt vt && isPointer t -> LM_Inttoptr (vt, _) | isPointer vt && isInt t -> LM_Ptrtoint (vt, _) | isPointer vt && isPointer t -> LM_Bitcast (vt, _) | isVector vt && isVector t -> LM_Bitcast (vt, _) -> panic $ "castVars: Can't cast this type (" ++ showSDoc dflags (ppr vt) ++ ") to (" ++ showSDoc dflags (ppr t) ++ ")" doExpr t $ Cast op v t -- | Decide what C function to use to implement a CallishMachOp cmmPrimOpFunctions :: CallishMachOp -> LlvmM LMString cmmPrimOpFunctions mop = do dflags <- getDynFlags let intrinTy1 = "p0i8.p0i8." ++ showSDoc dflags (ppr $ llvmWord dflags) intrinTy2 = "p0i8." ++ showSDoc dflags (ppr $ llvmWord dflags) unsupported = panic ("cmmPrimOpFunctions: " ++ show mop ++ " not supported here") return $ case mop of MO_F32_Exp -> fsLit "expf" MO_F32_Log -> fsLit "logf" MO_F32_Sqrt -> fsLit "llvm.sqrt.f32" MO_F32_Pwr -> fsLit "llvm.pow.f32" MO_F32_Sin -> fsLit "llvm.sin.f32" MO_F32_Cos -> fsLit "llvm.cos.f32" MO_F32_Tan -> fsLit "tanf" MO_F32_Asin -> fsLit "asinf" MO_F32_Acos -> fsLit "acosf" MO_F32_Atan -> fsLit "atanf" MO_F32_Sinh -> fsLit "sinhf" MO_F32_Cosh -> fsLit "coshf" MO_F32_Tanh -> fsLit "tanhf" MO_F64_Exp -> fsLit "exp" MO_F64_Log -> fsLit "log" MO_F64_Sqrt -> fsLit "llvm.sqrt.f64" MO_F64_Pwr -> fsLit "llvm.pow.f64" MO_F64_Sin -> fsLit "llvm.sin.f64" MO_F64_Cos -> fsLit "llvm.cos.f64" MO_F64_Tan -> fsLit "tan" MO_F64_Asin -> fsLit "asin" MO_F64_Acos -> fsLit "acos" MO_F64_Atan -> fsLit "atan" MO_F64_Sinh -> fsLit "sinh" MO_F64_Cosh -> fsLit "cosh" MO_F64_Tanh -> fsLit "tanh" MO_Memcpy -> fsLit $ "llvm.memcpy." ++ intrinTy1 MO_Memmove -> fsLit $ "llvm.memmove." ++ intrinTy1 MO_Memset -> fsLit $ "llvm.memset." ++ intrinTy2 (MO_PopCnt w) -> fsLit $ "llvm.ctpop." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_BSwap w) -> fsLit $ "llvm.bswap." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Clz w) -> fsLit $ "llvm.ctlz." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Ctz w) -> fsLit $ "llvm.cttz." ++ showSDoc dflags (ppr $ widthToLlvmInt w) (MO_Prefetch_Data _ )-> fsLit "llvm.prefetch" MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_AddIntC {} -> unsupported MO_SubIntC {} -> unsupported MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported MO_UF_Conv _ -> unsupported MO_AtomicRead _ -> unsupported MO_AtomicRMW w amop -> fsLit $ atomicRMWLabel w amop MO_Cmpxchg w -> fsLit $ cmpxchgLabel w MO_AtomicWrite w -> fsLit $ atomicWriteLabel w -- | Tail function calls genJump :: CmmExpr -> [GlobalReg] -> LlvmM StmtData -- Call to known function genJump (CmmLit (CmmLabel lbl)) live = do (vf, stmts, top) <- getHsFunc live lbl (stgRegs, stgStmts) <- funEpilogue live let s1 = Expr $ Call TailCall vf stgRegs llvmStdFunAttrs let s2 = Return Nothing return (stmts `appOL` stgStmts `snocOL` s1 `snocOL` s2, top) -- Call to unknown function / address genJump expr live = do fty <- llvmFunTy live (vf, stmts, top) <- exprToVar expr dflags <- getDynFlags let cast = case getVarType vf of ty | isPointer ty -> LM_Bitcast ty | isInt ty -> LM_Inttoptr ty -> panic $ "genJump: Expr is of bad type for function call! (" ++ showSDoc dflags (ppr ty) ++ ")" (v1, s1) <- doExpr (pLift fty) $ Cast cast vf (pLift fty) (stgRegs, stgStmts) <- funEpilogue live let s2 = Expr $ Call TailCall v1 stgRegs llvmStdFunAttrs let s3 = Return Nothing return (stmts `snocOL` s1 `appOL` stgStmts `snocOL` s2 `snocOL` s3, top) -- | CmmAssign operation -- -- We use stack allocated variables for CmmReg. The optimiser will replace -- these with registers when possible. genAssign :: CmmReg -> CmmExpr -> LlvmM StmtData genAssign reg val = do vreg <- getCmmReg reg (vval, stmts2, top2) <- exprToVar val let stmts = stmts2 let ty = (pLower . getVarType) vreg dflags <- getDynFlags case ty of -- Some registers are pointer types, so need to cast value to pointer LMPointer _ | getVarType vval == llvmWord dflags -> do (v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty let s2 = Store v vreg return (stmts `snocOL` s1 `snocOL` s2, top2) LMVector _ _ -> do (v, s1) <- doExpr ty $ Cast LM_Bitcast vval ty let s2 = Store v vreg return (stmts `snocOL` s1 `snocOL` s2, top2) _ -> do let s1 = Store vval vreg return (stmts `snocOL` s1, top2) -- | CmmStore operation genStore :: CmmExpr -> CmmExpr -> LlvmM StmtData -- First we try to detect a few common cases and produce better code for -- these then the default case. We are mostly trying to detect Cmm code -- like I32[Sp + n] and use 'getelementptr' operations instead of the -- generic case that uses casts and pointer arithmetic genStore addr@(CmmReg (CmmGlobal r)) val = genStore_fast addr r 0 val genStore addr@(CmmRegOff (CmmGlobal r) n) val = genStore_fast addr r n val genStore addr@(CmmMachOp (MO_Add _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) val = genStore_fast addr r (fromInteger n) val genStore addr@(CmmMachOp (MO_Sub _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) val = genStore_fast addr r (negate $ fromInteger n) val -- generic case genStore addr val = do other <- getTBAAMeta otherN genStore_slow addr val other -- | CmmStore operation -- This is a special case for storing to a global register pointer -- offset such as I32[Sp+8]. genStore_fast :: CmmExpr -> GlobalReg -> Int -> CmmExpr -> LlvmM StmtData genStore_fast addr r n val = do dflags <- getDynFlags (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) meta <- getTBAARegMeta r let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (vval, stmts, top) <- exprToVar val (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] -- We might need a different pointer type, so check case pLower grt == getVarType vval of -- were fine True -> do let s3 = MetaStmt meta $ Store vval ptr return (stmts `appOL` s1 `snocOL` s2 `snocOL` s3, top) -- cast to pointer type needed False -> do let ty = (pLift . getVarType) vval (ptr', s3) <- doExpr ty $ Cast LM_Bitcast ptr ty let s4 = MetaStmt meta $ Store vval ptr' return (stmts `appOL` s1 `snocOL` s2 `snocOL` s3 `snocOL` s4, top) -- If its a bit type then we use the slow method since -- we can't avoid casting anyway. False -> genStore_slow addr val meta -- | CmmStore operation -- Generic case. Uses casts and pointer arithmetic if needed. genStore_slow :: CmmExpr -> CmmExpr -> [MetaAnnot] -> LlvmM StmtData genStore_slow addr val meta = do (vaddr, stmts1, top1) <- exprToVar addr (vval, stmts2, top2) <- exprToVar val let stmts = stmts1 `appOL` stmts2 dflags <- getDynFlags case getVarType vaddr of -- sometimes we need to cast an int to a pointer before storing LMPointer ty@(LMPointer _) | getVarType vval == llvmWord dflags -> do (v, s1) <- doExpr ty $ Cast LM_Inttoptr vval ty let s2 = MetaStmt meta $ Store v vaddr return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2) LMPointer _ -> do let s1 = MetaStmt meta $ Store vval vaddr return (stmts `snocOL` s1, top1 ++ top2) i@(LMInt _) | i == llvmWord dflags -> do let vty = pLift $ getVarType vval (vptr, s1) <- doExpr vty $ Cast LM_Inttoptr vaddr vty let s2 = MetaStmt meta $ Store vval vptr return (stmts `snocOL` s1 `snocOL` s2, top1 ++ top2) other -> pprPanic "genStore: ptr not right type!" (PprCmm.pprExpr addr <+> text ( "Size of Ptr: " ++ show (llvmPtrBits dflags) ++ ", Size of var: " ++ show (llvmWidthInBits dflags other) ++ ", Var: " ++ showSDoc dflags (ppr vaddr))) -- | Unconditional branch genBranch :: BlockId -> LlvmM StmtData genBranch id = let label = blockIdToLlvm id in return (unitOL $ Branch label, []) -- | Conditional branch genCondBranch :: CmmExpr -> BlockId -> BlockId -> LlvmM StmtData genCondBranch cond idT idF = do let labelT = blockIdToLlvm idT let labelF = blockIdToLlvm idF -- See Note [Literals and branch conditions]. (vc, stmts, top) <- exprToVarOpt i1Option cond if getVarType vc == i1 then do let s1 = BranchIf vc labelT labelF return (stmts `snocOL` s1, top) else do dflags <- getDynFlags panic $ "genCondBranch: Cond expr not bool! (" ++ showSDoc dflags (ppr vc) ++ ")" {- Note [Literals and branch conditions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is important that whenever we generate branch conditions for literals like '1', they are properly narrowed to an LLVM expression of type 'i1' (for bools.) Otherwise, nobody is happy. So when we convert a CmmExpr to an LLVM expression for a branch conditional, exprToVarOpt must be certain to return a properly narrowed type. genLit is responsible for this, in the case of literal integers. Often, we won't see direct statements like: if(1) { ... } else { ... } at this point in the pipeline, because the Glorious Code Generator will do trivial branch elimination in the sinking pass (among others,) which will eliminate the expression entirely. However, it's certainly possible and reasonable for this to occur in hand-written C-- code. Consider something like: #ifndef SOME_CONDITIONAL #define CHECK_THING(x) 1 #else #define CHECK_THING(x) some_operation((x)) #endif f() { if (CHECK_THING(xyz)) { ... } else { ... } } In such an instance, CHECK_THING might result in an *expression* in one case, and a *literal* in the other, depending on what in particular was #define'd. So we must be sure to properly narrow the literal in this case to i1 as it won't be eliminated beforehand. For a real example of this, see ./rts/StgStdThunks.cmm -} -- | Switch branch genSwitch :: CmmExpr -> SwitchTargets -> LlvmM StmtData genSwitch cond ids = do (vc, stmts, top) <- exprToVar cond let ty = getVarType vc let labels = [ (mkIntLit ty ix, blockIdToLlvm b) | (ix, b) <- switchTargetsCases ids ] -- out of range is undefined, so let's just branch to first label let defLbl | Just l <- switchTargetsDefault ids = blockIdToLlvm l | otherwise = snd (head labels) let s1 = Switch vc defLbl labels return $ (stmts `snocOL` s1, top) -- ----------------------------------------------------------------------------- -- * CmmExpr code generation -- -- | An expression conversion return data: -- * LlvmVar: The var holding the result of the expression -- * LlvmStatements: Any statements needed to evaluate the expression -- * LlvmCmmDecl: Any global data needed for this expression type ExprData = (LlvmVar, LlvmStatements, [LlvmCmmDecl]) -- | Values which can be passed to 'exprToVar' to configure its -- behaviour in certain circumstances. -- -- Currently just used for determining if a comparison should return -- a boolean (i1) or a word. See Note [Literals and branch conditions]. newtype EOption = EOption { i1Expected :: Bool } -- XXX: EOption is an ugly and inefficient solution to this problem. -- | i1 type expected (condition scrutinee). i1Option :: EOption i1Option = EOption True -- | Word type expected (usual). wordOption :: EOption wordOption = EOption False -- | Convert a CmmExpr to a list of LlvmStatements with the result of the -- expression being stored in the returned LlvmVar. exprToVar :: CmmExpr -> LlvmM ExprData exprToVar = exprToVarOpt wordOption exprToVarOpt :: EOption -> CmmExpr -> LlvmM ExprData exprToVarOpt opt e = case e of CmmLit lit -> genLit opt lit CmmLoad e' ty -> genLoad False e' ty -- Cmmreg in expression is the value, so must load. If you want actual -- reg pointer, call getCmmReg directly. CmmReg r -> do (v1, ty, s1) <- getCmmRegVal r case isPointer ty of True -> do -- Cmm wants the value, so pointer types must be cast to ints dflags <- getDynFlags (v2, s2) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint v1 (llvmWord dflags) return (v2, s1 `snocOL` s2, []) False -> return (v1, s1, []) CmmMachOp op exprs -> genMachOp opt op exprs CmmRegOff r i -> do dflags <- getDynFlags exprToVar $ expandCmmReg dflags (r, i) CmmStackSlot _ _ -> panic "exprToVar: CmmStackSlot not supported!" -- | Handle CmmMachOp expressions genMachOp :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData -- Unary Machop genMachOp _ op [x] = case op of MO_Not w -> let all1 = mkIntLit (widthToLlvmInt w) (-1) in negate (widthToLlvmInt w) all1 LM_MO_Xor MO_S_Neg w -> let all0 = mkIntLit (widthToLlvmInt w) 0 in negate (widthToLlvmInt w) all0 LM_MO_Sub MO_F_Neg w -> let all0 = LMLitVar $ LMFloatLit (-0) (widthToLlvmFloat w) in negate (widthToLlvmFloat w) all0 LM_MO_FSub MO_SF_Conv _ w -> fiConv (widthToLlvmFloat w) LM_Sitofp MO_FS_Conv _ w -> fiConv (widthToLlvmInt w) LM_Fptosi MO_SS_Conv from to -> sameConv from (widthToLlvmInt to) LM_Trunc LM_Sext MO_UU_Conv from to -> sameConv from (widthToLlvmInt to) LM_Trunc LM_Zext MO_FF_Conv from to -> sameConv from (widthToLlvmFloat to) LM_Fptrunc LM_Fpext MO_VS_Neg len w -> let ty = widthToLlvmInt w vecty = LMVector len ty all0 = LMIntLit (-0) ty all0s = LMLitVar $ LMVectorLit (replicate len all0) in negateVec vecty all0s LM_MO_Sub MO_VF_Neg len w -> let ty = widthToLlvmFloat w vecty = LMVector len ty all0 = LMFloatLit (-0) ty all0s = LMLitVar $ LMVectorLit (replicate len all0) in negateVec vecty all0s LM_MO_FSub -- Handle unsupported cases explicitly so we get a warning -- of missing case when new MachOps added MO_Add _ -> panicOp MO_Mul _ -> panicOp MO_Sub _ -> panicOp MO_S_MulMayOflo _ -> panicOp MO_S_Quot _ -> panicOp MO_S_Rem _ -> panicOp MO_U_MulMayOflo _ -> panicOp MO_U_Quot _ -> panicOp MO_U_Rem _ -> panicOp MO_Eq _ -> panicOp MO_Ne _ -> panicOp MO_S_Ge _ -> panicOp MO_S_Gt _ -> panicOp MO_S_Le _ -> panicOp MO_S_Lt _ -> panicOp MO_U_Ge _ -> panicOp MO_U_Gt _ -> panicOp MO_U_Le _ -> panicOp MO_U_Lt _ -> panicOp MO_F_Add _ -> panicOp MO_F_Sub _ -> panicOp MO_F_Mul _ -> panicOp MO_F_Quot _ -> panicOp MO_F_Eq _ -> panicOp MO_F_Ne _ -> panicOp MO_F_Ge _ -> panicOp MO_F_Gt _ -> panicOp MO_F_Le _ -> panicOp MO_F_Lt _ -> panicOp MO_And _ -> panicOp MO_Or _ -> panicOp MO_Xor _ -> panicOp MO_Shl _ -> panicOp MO_U_Shr _ -> panicOp MO_S_Shr _ -> panicOp MO_V_Insert _ _ -> panicOp MO_V_Extract _ _ -> panicOp MO_V_Add _ _ -> panicOp MO_V_Sub _ _ -> panicOp MO_V_Mul _ _ -> panicOp MO_VS_Quot _ _ -> panicOp MO_VS_Rem _ _ -> panicOp MO_VU_Quot _ _ -> panicOp MO_VU_Rem _ _ -> panicOp MO_VF_Insert _ _ -> panicOp MO_VF_Extract _ _ -> panicOp MO_VF_Add _ _ -> panicOp MO_VF_Sub _ _ -> panicOp MO_VF_Mul _ _ -> panicOp MO_VF_Quot _ _ -> panicOp where negate ty v2 negOp = do (vx, stmts, top) <- exprToVar x (v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx return (v1, stmts `snocOL` s1, top) negateVec ty v2 negOp = do (vx, stmts1, top) <- exprToVar x ([vx'], stmts2) <- castVars [(vx, ty)] (v1, s1) <- doExpr ty $ LlvmOp negOp v2 vx' return (v1, stmts1 `appOL` stmts2 `snocOL` s1, top) fiConv ty convOp = do (vx, stmts, top) <- exprToVar x (v1, s1) <- doExpr ty $ Cast convOp vx ty return (v1, stmts `snocOL` s1, top) sameConv from ty reduce expand = do x'@(vx, stmts, top) <- exprToVar x let sameConv' op = do (v1, s1) <- doExpr ty $ Cast op vx ty return (v1, stmts `snocOL` s1, top) dflags <- getDynFlags let toWidth = llvmWidthInBits dflags ty -- LLVM doesn't like trying to convert to same width, so -- need to check for that as we do get Cmm code doing it. case widthInBits from of w | w < toWidth -> sameConv' expand w | w > toWidth -> sameConv' reduce _w -> return x' panicOp = panic $ "LLVM.CodeGen.genMachOp: non unary op encountered" ++ "with one argument! (" ++ show op ++ ")" -- Handle GlobalRegs pointers genMachOp opt o@(MO_Add _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))] = genMachOp_fast opt o r (fromInteger n) e genMachOp opt o@(MO_Sub _) e@[(CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))] = genMachOp_fast opt o r (negate . fromInteger $ n) e -- Generic case genMachOp opt op e = genMachOp_slow opt op e -- | Handle CmmMachOp expressions -- This is a specialised method that handles Global register manipulations like -- 'Sp - 16', using the getelementptr instruction. genMachOp_fast :: EOption -> MachOp -> GlobalReg -> Int -> [CmmExpr] -> LlvmM ExprData genMachOp_fast opt op r n e = do (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) dflags <- getDynFlags let (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] (var, s3) <- doExpr (llvmWord dflags) $ Cast LM_Ptrtoint ptr (llvmWord dflags) return (var, s1 `snocOL` s2 `snocOL` s3, []) False -> genMachOp_slow opt op e -- | Handle CmmMachOp expressions -- This handles all the cases not handle by the specialised genMachOp_fast. genMachOp_slow :: EOption -> MachOp -> [CmmExpr] -> LlvmM ExprData -- Element extraction genMachOp_slow _ (MO_V_Extract l w) [val, idx] = do (vval, stmts1, top1) <- exprToVar val (vidx, stmts2, top2) <- exprToVar idx ([vval'], stmts3) <- castVars [(vval, LMVector l ty)] (v1, s1) <- doExpr ty $ Extract vval' vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `snocOL` s1, top1 ++ top2) where ty = widthToLlvmInt w genMachOp_slow _ (MO_VF_Extract l w) [val, idx] = do (vval, stmts1, top1) <- exprToVar val (vidx, stmts2, top2) <- exprToVar idx ([vval'], stmts3) <- castVars [(vval, LMVector l ty)] (v1, s1) <- doExpr ty $ Extract vval' vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `snocOL` s1, top1 ++ top2) where ty = widthToLlvmFloat w -- Element insertion genMachOp_slow _ (MO_V_Insert l w) [val, elt, idx] = do (vval, stmts1, top1) <- exprToVar val (velt, stmts2, top2) <- exprToVar elt (vidx, stmts3, top3) <- exprToVar idx ([vval'], stmts4) <- castVars [(vval, ty)] (v1, s1) <- doExpr ty $ Insert vval' velt vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` stmts4 `snocOL` s1, top1 ++ top2 ++ top3) where ty = LMVector l (widthToLlvmInt w) genMachOp_slow _ (MO_VF_Insert l w) [val, elt, idx] = do (vval, stmts1, top1) <- exprToVar val (velt, stmts2, top2) <- exprToVar elt (vidx, stmts3, top3) <- exprToVar idx ([vval'], stmts4) <- castVars [(vval, ty)] (v1, s1) <- doExpr ty $ Insert vval' velt vidx return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `appOL` stmts4 `snocOL` s1, top1 ++ top2 ++ top3) where ty = LMVector l (widthToLlvmFloat w) -- Binary MachOp genMachOp_slow opt op [x, y] = case op of MO_Eq _ -> genBinComp opt LM_CMP_Eq MO_Ne _ -> genBinComp opt LM_CMP_Ne MO_S_Gt _ -> genBinComp opt LM_CMP_Sgt MO_S_Ge _ -> genBinComp opt LM_CMP_Sge MO_S_Lt _ -> genBinComp opt LM_CMP_Slt MO_S_Le _ -> genBinComp opt LM_CMP_Sle MO_U_Gt _ -> genBinComp opt LM_CMP_Ugt MO_U_Ge _ -> genBinComp opt LM_CMP_Uge MO_U_Lt _ -> genBinComp opt LM_CMP_Ult MO_U_Le _ -> genBinComp opt LM_CMP_Ule MO_Add _ -> genBinMach LM_MO_Add MO_Sub _ -> genBinMach LM_MO_Sub MO_Mul _ -> genBinMach LM_MO_Mul MO_U_MulMayOflo _ -> panic "genMachOp: MO_U_MulMayOflo unsupported!" MO_S_MulMayOflo w -> isSMulOK w x y MO_S_Quot _ -> genBinMach LM_MO_SDiv MO_S_Rem _ -> genBinMach LM_MO_SRem MO_U_Quot _ -> genBinMach LM_MO_UDiv MO_U_Rem _ -> genBinMach LM_MO_URem MO_F_Eq _ -> genBinComp opt LM_CMP_Feq MO_F_Ne _ -> genBinComp opt LM_CMP_Fne MO_F_Gt _ -> genBinComp opt LM_CMP_Fgt MO_F_Ge _ -> genBinComp opt LM_CMP_Fge MO_F_Lt _ -> genBinComp opt LM_CMP_Flt MO_F_Le _ -> genBinComp opt LM_CMP_Fle MO_F_Add _ -> genBinMach LM_MO_FAdd MO_F_Sub _ -> genBinMach LM_MO_FSub MO_F_Mul _ -> genBinMach LM_MO_FMul MO_F_Quot _ -> genBinMach LM_MO_FDiv MO_And _ -> genBinMach LM_MO_And MO_Or _ -> genBinMach LM_MO_Or MO_Xor _ -> genBinMach LM_MO_Xor MO_Shl _ -> genBinMach LM_MO_Shl MO_U_Shr _ -> genBinMach LM_MO_LShr MO_S_Shr _ -> genBinMach LM_MO_AShr MO_V_Add l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Add MO_V_Sub l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Sub MO_V_Mul l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_Mul MO_VS_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SDiv MO_VS_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_SRem MO_VU_Quot l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_UDiv MO_VU_Rem l w -> genCastBinMach (LMVector l (widthToLlvmInt w)) LM_MO_URem MO_VF_Add l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FAdd MO_VF_Sub l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FSub MO_VF_Mul l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FMul MO_VF_Quot l w -> genCastBinMach (LMVector l (widthToLlvmFloat w)) LM_MO_FDiv MO_Not _ -> panicOp MO_S_Neg _ -> panicOp MO_F_Neg _ -> panicOp MO_SF_Conv _ _ -> panicOp MO_FS_Conv _ _ -> panicOp MO_SS_Conv _ _ -> panicOp MO_UU_Conv _ _ -> panicOp MO_FF_Conv _ _ -> panicOp MO_V_Insert {} -> panicOp MO_V_Extract {} -> panicOp MO_VS_Neg {} -> panicOp MO_VF_Insert {} -> panicOp MO_VF_Extract {} -> panicOp MO_VF_Neg {} -> panicOp where binLlvmOp ty binOp = do (vx, stmts1, top1) <- exprToVar x (vy, stmts2, top2) <- exprToVar y if getVarType vx == getVarType vy then do (v1, s1) <- doExpr (ty vx) $ binOp vx vy return (v1, stmts1 `appOL` stmts2 `snocOL` s1, top1 ++ top2) else do -- Error. Continue anyway so we can debug the generated ll file. dflags <- getDynFlags let style = mkCodeStyle CStyle toString doc = renderWithStyle dflags doc style cmmToStr = (lines . toString . PprCmm.pprExpr) let dx = Comment $ map fsLit $ cmmToStr x let dy = Comment $ map fsLit $ cmmToStr y (v1, s1) <- doExpr (ty vx) $ binOp vx vy let allStmts = stmts1 `appOL` stmts2 `snocOL` dx `snocOL` dy `snocOL` s1 return (v1, allStmts, top1 ++ top2) binCastLlvmOp ty binOp = do (vx, stmts1, top1) <- exprToVar x (vy, stmts2, top2) <- exprToVar y ([vx', vy'], stmts3) <- castVars [(vx, ty), (vy, ty)] (v1, s1) <- doExpr ty $ binOp vx' vy' return (v1, stmts1 `appOL` stmts2 `appOL` stmts3 `snocOL` s1, top1 ++ top2) -- | Need to use EOption here as Cmm expects word size results from -- comparisons while LLVM return i1. Need to extend to llvmWord type -- if expected. See Note [Literals and branch conditions]. genBinComp opt cmp = do ed@(v1, stmts, top) <- binLlvmOp (\_ -> i1) (Compare cmp) dflags <- getDynFlags if getVarType v1 == i1 then case i1Expected opt of True -> return ed False -> do let w_ = llvmWord dflags (v2, s1) <- doExpr w_ $ Cast LM_Zext v1 w_ return (v2, stmts `snocOL` s1, top) else panic $ "genBinComp: Compare returned type other then i1! " ++ (showSDoc dflags $ ppr $ getVarType v1) genBinMach op = binLlvmOp getVarType (LlvmOp op) genCastBinMach ty op = binCastLlvmOp ty (LlvmOp op) -- | Detect if overflow will occur in signed multiply of the two -- CmmExpr's. This is the LLVM assembly equivalent of the NCG -- implementation. Its much longer due to type information/safety. -- This should actually compile to only about 3 asm instructions. isSMulOK :: Width -> CmmExpr -> CmmExpr -> LlvmM ExprData isSMulOK _ x y = do (vx, stmts1, top1) <- exprToVar x (vy, stmts2, top2) <- exprToVar y dflags <- getDynFlags let word = getVarType vx let word2 = LMInt $ 2 * (llvmWidthInBits dflags $ getVarType vx) let shift = llvmWidthInBits dflags word let shift1 = toIWord dflags (shift - 1) let shift2 = toIWord dflags shift if isInt word then do (x1, s1) <- doExpr word2 $ Cast LM_Sext vx word2 (y1, s2) <- doExpr word2 $ Cast LM_Sext vy word2 (r1, s3) <- doExpr word2 $ LlvmOp LM_MO_Mul x1 y1 (rlow1, s4) <- doExpr word $ Cast LM_Trunc r1 word (rlow2, s5) <- doExpr word $ LlvmOp LM_MO_AShr rlow1 shift1 (rhigh1, s6) <- doExpr word2 $ LlvmOp LM_MO_AShr r1 shift2 (rhigh2, s7) <- doExpr word $ Cast LM_Trunc rhigh1 word (dst, s8) <- doExpr word $ LlvmOp LM_MO_Sub rlow2 rhigh2 let stmts = (unitOL s1) `snocOL` s2 `snocOL` s3 `snocOL` s4 `snocOL` s5 `snocOL` s6 `snocOL` s7 `snocOL` s8 return (dst, stmts1 `appOL` stmts2 `appOL` stmts, top1 ++ top2) else panic $ "isSMulOK: Not bit type! (" ++ showSDoc dflags (ppr word) ++ ")" panicOp = panic $ "LLVM.CodeGen.genMachOp_slow: unary op encountered" ++ "with two arguments! (" ++ show op ++ ")" -- More then two expression, invalid! genMachOp_slow _ _ _ = panic "genMachOp: More then 2 expressions in MachOp!" -- | Handle CmmLoad expression. genLoad :: Atomic -> CmmExpr -> CmmType -> LlvmM ExprData -- First we try to detect a few common cases and produce better code for -- these then the default case. We are mostly trying to detect Cmm code -- like I32[Sp + n] and use 'getelementptr' operations instead of the -- generic case that uses casts and pointer arithmetic genLoad atomic e@(CmmReg (CmmGlobal r)) ty = genLoad_fast atomic e r 0 ty genLoad atomic e@(CmmRegOff (CmmGlobal r) n) ty = genLoad_fast atomic e r n ty genLoad atomic e@(CmmMachOp (MO_Add _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) ty = genLoad_fast atomic e r (fromInteger n) ty genLoad atomic e@(CmmMachOp (MO_Sub _) [ (CmmReg (CmmGlobal r)), (CmmLit (CmmInt n _))]) ty = genLoad_fast atomic e r (negate $ fromInteger n) ty -- generic case genLoad atomic e ty = do other <- getTBAAMeta otherN genLoad_slow atomic e ty other -- | Handle CmmLoad expression. -- This is a special case for loading from a global register pointer -- offset such as I32[Sp+8]. genLoad_fast :: Atomic -> CmmExpr -> GlobalReg -> Int -> CmmType -> LlvmM ExprData genLoad_fast atomic e r n ty = do dflags <- getDynFlags (gv, grt, s1) <- getCmmRegVal (CmmGlobal r) meta <- getTBAARegMeta r let ty' = cmmToLlvmType ty (ix,rem) = n `divMod` ((llvmWidthInBits dflags . pLower) grt `div` 8) case isPointer grt && rem == 0 of True -> do (ptr, s2) <- doExpr grt $ GetElemPtr True gv [toI32 ix] -- We might need a different pointer type, so check case grt == ty' of -- were fine True -> do (var, s3) <- doExpr ty' (MExpr meta $ loadInstr ptr) return (var, s1 `snocOL` s2 `snocOL` s3, []) -- cast to pointer type needed False -> do let pty = pLift ty' (ptr', s3) <- doExpr pty $ Cast LM_Bitcast ptr pty (var, s4) <- doExpr ty' (MExpr meta $ loadInstr ptr') return (var, s1 `snocOL` s2 `snocOL` s3 `snocOL` s4, []) -- If its a bit type then we use the slow method since -- we can't avoid casting anyway. False -> genLoad_slow atomic e ty meta where loadInstr ptr | atomic = ALoad SyncSeqCst False ptr | otherwise = Load ptr -- | Handle Cmm load expression. -- Generic case. Uses casts and pointer arithmetic if needed. genLoad_slow :: Atomic -> CmmExpr -> CmmType -> [MetaAnnot] -> LlvmM ExprData genLoad_slow atomic e ty meta = do (iptr, stmts, tops) <- exprToVar e dflags <- getDynFlags case getVarType iptr of LMPointer _ -> do (dvar, load) <- doExpr (cmmToLlvmType ty) (MExpr meta $ loadInstr iptr) return (dvar, stmts `snocOL` load, tops) i@(LMInt _) | i == llvmWord dflags -> do let pty = LMPointer $ cmmToLlvmType ty (ptr, cast) <- doExpr pty $ Cast LM_Inttoptr iptr pty (dvar, load) <- doExpr (cmmToLlvmType ty) (MExpr meta $ loadInstr ptr) return (dvar, stmts `snocOL` cast `snocOL` load, tops) other -> do dflags <- getDynFlags pprPanic "exprToVar: CmmLoad expression is not right type!" (PprCmm.pprExpr e <+> text ( "Size of Ptr: " ++ show (llvmPtrBits dflags) ++ ", Size of var: " ++ show (llvmWidthInBits dflags other) ++ ", Var: " ++ showSDoc dflags (ppr iptr))) where loadInstr ptr | atomic = ALoad SyncSeqCst False ptr | otherwise = Load ptr -- | Handle CmmReg expression. This will return a pointer to the stack -- location of the register. Throws an error if it isn't allocated on -- the stack. getCmmReg :: CmmReg -> LlvmM LlvmVar getCmmReg (CmmLocal (LocalReg un _)) = do exists <- varLookup un dflags <- getDynFlags case exists of Just ety -> return (LMLocalVar un $ pLift ety) Nothing -> fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr un) ++ " was not allocated!" -- This should never happen, as every local variable should -- have been assigned a value at some point, triggering -- "funPrologue" to allocate it on the stack. getCmmReg (CmmGlobal g) = do onStack <- checkStackReg g dflags <- getDynFlags if onStack then return (lmGlobalRegVar dflags g) else fail $ "getCmmReg: Cmm register " ++ showSDoc dflags (ppr g) ++ " not stack-allocated!" -- | Return the value of a given register, as well as its type. Might -- need to be load from stack. getCmmRegVal :: CmmReg -> LlvmM (LlvmVar, LlvmType, LlvmStatements) getCmmRegVal reg = case reg of CmmGlobal g -> do onStack <- checkStackReg g dflags <- getDynFlags if onStack then loadFromStack else do let r = lmGlobalRegArg dflags g return (r, getVarType r, nilOL) _ -> loadFromStack where loadFromStack = do ptr <- getCmmReg reg let ty = pLower $ getVarType ptr (v, s) <- doExpr ty (Load ptr) return (v, ty, unitOL s) -- | Allocate a local CmmReg on the stack allocReg :: CmmReg -> (LlvmVar, LlvmStatements) allocReg (CmmLocal (LocalReg un ty)) = let ty' = cmmToLlvmType ty var = LMLocalVar un (LMPointer ty') alc = Alloca ty' 1 in (var, unitOL $ Assignment var alc) allocReg _ = panic $ "allocReg: Global reg encountered! Global registers should" ++ " have been handled elsewhere!" -- | Generate code for a literal genLit :: EOption -> CmmLit -> LlvmM ExprData genLit opt (CmmInt i w) -- See Note [Literals and branch conditions]. = let width | i1Expected opt = i1 | otherwise = LMInt (widthInBits w) -- comm = Comment [ fsLit $ "EOption: " ++ show opt -- , fsLit $ "Width : " ++ show w -- , fsLit $ "Width' : " ++ show (widthInBits w) -- ] in return (mkIntLit width i, nilOL, []) genLit _ (CmmFloat r w) = return (LMLitVar $ LMFloatLit (fromRational r) (widthToLlvmFloat w), nilOL, []) genLit opt (CmmVec ls) = do llvmLits <- mapM toLlvmLit ls return (LMLitVar $ LMVectorLit llvmLits, nilOL, []) where toLlvmLit :: CmmLit -> LlvmM LlvmLit toLlvmLit lit = do (llvmLitVar, _, _) <- genLit opt lit case llvmLitVar of LMLitVar llvmLit -> return llvmLit _ -> panic "genLit" genLit _ cmm@(CmmLabel l) = do var <- getGlobalPtr =<< strCLabel_llvm l dflags <- getDynFlags let lmty = cmmToLlvmType $ cmmLitType dflags cmm (v1, s1) <- doExpr lmty $ Cast LM_Ptrtoint var (llvmWord dflags) return (v1, unitOL s1, []) genLit opt (CmmLabelOff label off) = do dflags <- getDynFlags (vlbl, stmts, stat) <- genLit opt (CmmLabel label) let voff = toIWord dflags off (v1, s1) <- doExpr (getVarType vlbl) $ LlvmOp LM_MO_Add vlbl voff return (v1, stmts `snocOL` s1, stat) genLit opt (CmmLabelDiffOff l1 l2 off) = do dflags <- getDynFlags (vl1, stmts1, stat1) <- genLit opt (CmmLabel l1) (vl2, stmts2, stat2) <- genLit opt (CmmLabel l2) let voff = toIWord dflags off let ty1 = getVarType vl1 let ty2 = getVarType vl2 if (isInt ty1) && (isInt ty2) && (llvmWidthInBits dflags ty1 == llvmWidthInBits dflags ty2) then do (v1, s1) <- doExpr (getVarType vl1) $ LlvmOp LM_MO_Sub vl1 vl2 (v2, s2) <- doExpr (getVarType v1 ) $ LlvmOp LM_MO_Add v1 voff return (v2, stmts1 `appOL` stmts2 `snocOL` s1 `snocOL` s2, stat1 ++ stat2) else panic "genLit: CmmLabelDiffOff encountered with different label ty!" genLit opt (CmmBlock b) = genLit opt (CmmLabel $ infoTblLbl b) genLit _ CmmHighStackMark = panic "genStaticLit - CmmHighStackMark unsupported!" -- ----------------------------------------------------------------------------- -- * Misc -- -- | Find CmmRegs that get assigned and allocate them on the stack -- -- Any register that gets written needs to be allcoated on the -- stack. This avoids having to map a CmmReg to an equivalent SSA form -- and avoids having to deal with Phi node insertion. This is also -- the approach recommended by LLVM developers. -- -- On the other hand, this is unecessarily verbose if the register in -- question is never written. Therefore we skip it where we can to -- save a few lines in the output and hopefully speed compilation up a -- bit. funPrologue :: LiveGlobalRegs -> [CmmBlock] -> LlvmM StmtData funPrologue live cmmBlocks = do trash <- getTrashRegs let getAssignedRegs :: CmmNode O O -> [CmmReg] getAssignedRegs (CmmAssign reg _) = [reg] -- Calls will trash all registers. Unfortunately, this needs them to -- be stack-allocated in the first place. getAssignedRegs (CmmUnsafeForeignCall _ rs _) = map CmmGlobal trash ++ map CmmLocal rs getAssignedRegs _ = [] getRegsBlock (_, body, _) = concatMap getAssignedRegs $ blockToList body assignedRegs = nub $ concatMap (getRegsBlock . blockSplit) cmmBlocks isLive r = r `elem` alwaysLive || r `elem` live dflags <- getDynFlags stmtss <- flip mapM assignedRegs $ \reg -> case reg of CmmLocal (LocalReg un _) -> do let (newv, stmts) = allocReg reg varInsert un (pLower $ getVarType newv) return stmts CmmGlobal r -> do let reg = lmGlobalRegVar dflags r arg = lmGlobalRegArg dflags r ty = (pLower . getVarType) reg trash = LMLitVar $ LMUndefLit ty rval = if isLive r then arg else trash alloc = Assignment reg $ Alloca (pLower $ getVarType reg) 1 markStackReg r return $ toOL [alloc, Store rval reg] return (concatOL stmtss, []) -- | Function epilogue. Load STG variables to use as argument for call. -- STG Liveness optimisation done here. funEpilogue :: LiveGlobalRegs -> LlvmM ([LlvmVar], LlvmStatements) funEpilogue live = do -- Have information and liveness optimisation is enabled? let liveRegs = alwaysLive ++ live isSSE (FloatReg _) = True isSSE (DoubleReg _) = True isSSE (XmmReg _) = True isSSE (YmmReg _) = True isSSE (ZmmReg _) = True isSSE _ = False -- Set to value or "undef" depending on whether the register is -- actually live dflags <- getDynFlags let loadExpr r = do (v, _, s) <- getCmmRegVal (CmmGlobal r) return (Just $ v, s) loadUndef r = do let ty = (pLower . getVarType $ lmGlobalRegVar dflags r) return (Just $ LMLitVar $ LMUndefLit ty, nilOL) platform <- getDynFlag targetPlatform loads <- flip mapM (activeStgRegs platform) $ \r -> case () of _ | r `elem` liveRegs -> loadExpr r | not (isSSE r) -> loadUndef r | otherwise -> return (Nothing, nilOL) let (vars, stmts) = unzip loads return (catMaybes vars, concatOL stmts) -- | A series of statements to trash all the STG registers. -- -- In LLVM we pass the STG registers around everywhere in function calls. -- So this means LLVM considers them live across the entire function, when -- in reality they usually aren't. For Caller save registers across C calls -- the saving and restoring of them is done by the Cmm code generator, -- using Cmm local vars. So to stop LLVM saving them as well (and saving -- all of them since it thinks they're always live, we trash them just -- before the call by assigning the 'undef' value to them. The ones we -- need are restored from the Cmm local var and the ones we don't need -- are fine to be trashed. getTrashStmts :: LlvmM LlvmStatements getTrashStmts = do regs <- getTrashRegs stmts <- flip mapM regs $ \ r -> do reg <- getCmmReg (CmmGlobal r) let ty = (pLower . getVarType) reg return $ Store (LMLitVar $ LMUndefLit ty) reg return $ toOL stmts getTrashRegs :: LlvmM [GlobalReg] getTrashRegs = do plat <- getLlvmPlatform return $ filter (callerSaves plat) (activeStgRegs plat) -- | Get a function pointer to the CLabel specified. -- -- This is for Haskell functions, function type is assumed, so doesn't work -- with foreign functions. getHsFunc :: LiveGlobalRegs -> CLabel -> LlvmM ExprData getHsFunc live lbl = do fty <- llvmFunTy live name <- strCLabel_llvm lbl getHsFunc' name fty getHsFunc' :: LMString -> LlvmType -> LlvmM ExprData getHsFunc' name fty = do fun <- getGlobalPtr name if getVarType fun == fty then return (fun, nilOL, []) else do (v1, s1) <- doExpr (pLift fty) $ Cast LM_Bitcast fun (pLift fty) return (v1, unitOL s1, []) -- | Create a new local var mkLocalVar :: LlvmType -> LlvmM LlvmVar mkLocalVar ty = do un <- runUs getUniqueM return $ LMLocalVar un ty -- | Execute an expression, assigning result to a var doExpr :: LlvmType -> LlvmExpression -> LlvmM (LlvmVar, LlvmStatement) doExpr ty expr = do v <- mkLocalVar ty return (v, Assignment v expr) -- | Expand CmmRegOff expandCmmReg :: DynFlags -> (CmmReg, Int) -> CmmExpr expandCmmReg dflags (reg, off) = let width = typeWidth (cmmRegType dflags reg) voff = CmmLit $ CmmInt (fromIntegral off) width in CmmMachOp (MO_Add width) [CmmReg reg, voff] -- | Convert a block id into a appropriate Llvm label blockIdToLlvm :: BlockId -> LlvmVar blockIdToLlvm bid = LMLocalVar (getUnique bid) LMLabel -- | Create Llvm int Literal mkIntLit :: Integral a => LlvmType -> a -> LlvmVar mkIntLit ty i = LMLitVar $ LMIntLit (toInteger i) ty -- | Convert int type to a LLvmVar of word or i32 size toI32 :: Integral a => a -> LlvmVar toI32 = mkIntLit i32 toIWord :: Integral a => DynFlags -> a -> LlvmVar toIWord dflags = mkIntLit (llvmWord dflags) -- | Returns TBAA meta data by unique getTBAAMeta :: Unique -> LlvmM [MetaAnnot] getTBAAMeta u = do mi <- getUniqMeta u return [MetaAnnot tbaa (MetaNode i) | let Just i = mi] -- | Returns TBAA meta data for given register getTBAARegMeta :: GlobalReg -> LlvmM [MetaAnnot] getTBAARegMeta = getTBAAMeta . getTBAA
fmthoma/ghc
compiler/llvmGen/LlvmCodeGen/CodeGen.hs
bsd-3-clause
62,423
1,208
18
19,321
16,183
8,613
7,570
1,087
64
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeSynonymInstances #-} -- | Karma module Plugin.Karma (theModule) where import Plugin import qualified Message as Msg (nick, Nick, Message, showNick, readNick, lambdabotName, nName) import qualified NickEq as E import qualified Data.Map as M import Text.Printf $(plugin "Karma") type KarmaState = M.Map Msg.Nick Integer type Karma m a = ModuleT KarmaState m a instance Module KarmaModule KarmaState where moduleCmds _ = ["karma", "karma+", "karma-", "karma-all"] moduleHelp _ "karma" = "karma <polynick>. Return a person's karma value" moduleHelp _ "karma+" = "karma+ <nick>. Increment someone's karma" moduleHelp _ "karma-" = "karma- <nick>. Decrement someone's karma" moduleHelp _ "karma-all" = "karma-all. List all karma" moduleDefState _ = return $ M.empty moduleSerialize _ = Just mapSerial process _ _ _ "karma-all" _ = listKarma process _ msg _ "karma" rest = tellKarma msg sender nick' where sender = Msg.nick msg nick' = case words rest of [] -> E.mononickToPolynick sender (nick:_) -> E.readPolynick msg nick process _ msg _ cmd rest = case words rest of [] -> return [ "usage @karma(+|-) nick" ] (nick:_) -> do let nick' = Msg.readNick msg nick case cmd of "karma+" -> changeKarma msg 1 sender nick' "karma-" -> changeKarma msg (-1) sender nick' _ -> error "KarmaModule: can't happen" where sender = Msg.nick msg -- ^nick++($| ) contextual _ msg _ text = do mapM_ (changeKarma msg (-1) sender) decs mapM_ (changeKarma msg 1 sender) incs return [] where sender = Msg.nick msg ws = words text decs = match "--" incs = match "++" match m = map (Msg.readNick msg) . filter okay . map (reverse . drop 2) . filter (isPrefixOf m) . map reverse $ ws okay x = not (elem x badNicks || any (`isPrefixOf` x) badPrefixes) -- Special cases. Ignore the null nick. C must also be ignored -- because C++ and C-- are languages. badNicks = ["", "C", "c", "notepad"] -- More special cases, to ignore Perl code. badPrefixes = ["$", "@", "%"] ------------------------------------------------------------------------ tellKarma :: Msg.Message m => m -> Msg.Nick -> E.Polynick -> Karma LB [String] tellKarma msg sender nick = do lookup' <- lift E.lookupMononickMap karma <- (sum . map snd . lookup' nick) `fmap` readMS return [concat [if E.mononickToPolynick sender == nick then "You have" else E.showPolynick msg nick ++ " has" ," a karma of " ,show karma]] listKarma :: Karma LB [String] listKarma = do ks <- M.toList `fmap` readMS let ks' = sortBy (\(_,e) (_,e') -> e' `compare` e) ks return $ (:[]) . unlines $ map (\(k,e) -> printf " %-20s %4d" (show k) e :: String) ks' changeKarma :: Msg.Message m => m -> Integer -> Msg.Nick -> Msg.Nick -> Karma LB [String] changeKarma msg km sender nick | map toLower (Msg.nName nick) == "java" && km == 1 = changeKarma msg (-km) (Msg.lambdabotName msg) sender | sender == nick = return ["You can't change your own karma, silly."] | otherwise = withMS $ \fm write -> do let fm' = M.insertWith (+) nick km fm let karma = fromMaybe 0 $ M.lookup nick fm' write fm' return [fmt (Msg.showNick msg nick) km (show karma)] where fmt n v k | v < 0 = n ++ "'s karma lowered to " ++ k ++ "." | otherwise = n ++ "'s karma raised to " ++ k ++ "."
jwiegley/lambdabot
Plugin/Karma.hs
mit
3,839
0
18
1,173
1,224
625
599
70
2
import Control.Concurrent.STM main = do c <- newTChanIO atomically $ writeTChan c 'a' c1 <- atomically $ cloneTChan c atomically (readTChan c) >>= print atomically (readTChan c1) >>= print atomically (writeTChan c 'b') atomically (readTChan c) >>= print atomically (readTChan c1) >>= print
gridaphobe/packages-stm
tests/cloneTChan001.hs
bsd-3-clause
307
0
10
60
123
55
68
10
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1999 -} module TcTypeable( mkTypeableBinds, mkModIdBindings ) where import TcBinds( addTypecheckedBinds ) import IfaceEnv( newGlobalBinder ) import TcEnv import TcRnMonad import PrelNames( gHC_TYPES, trModuleDataConName, trTyConDataConName, trNameSDataConName ) import Id import IdInfo( IdDetails(..) ) import Type import TyCon import DataCon import Name( getOccName ) import OccName import Module import HsSyn import DynFlags import Bag import Fingerprint(Fingerprint(..), fingerprintString) import Outputable import Data.Word( Word64 ) import FastString ( FastString, mkFastString ) {- Note [Grand plan for Typeable] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The overall plan is this: 1. Generate a binding for each module p:M (done in TcTypeable by mkModIdBindings) M.$trModule :: GHC.Types.Module M.$trModule = Module "p" "M" ("tr" is short for "type representation"; see GHC.Types) We might want to add the filename too. This can be used for the lightweight stack-tracing stuff too Record the Name M.$trModule in the tcg_tr_module field of TcGblEnv 2. Generate a binding for every data type declaration T in module M, M.$tcT :: GHC.Types.TyCon M.$tcT = TyCon ...fingerprint info... $trModule "T" We define (in TyCon) type TyConRepName = Name to use for these M.$tcT "tycon rep names". 3. Record the TyConRepName in T's TyCon, including for promoted data and type constructors, and kinds like * and #. The TyConRepNaem is not an "implicit Id". It's more like a record selector: the TyCon knows its name but you have to go to the interface file to find its type, value, etc 4. Solve Typeable costraints. This is done by a custom Typeable solver, currently in TcInteract, that use M.$tcT so solve (Typeable T). There are many wrinkles: * Since we generate $tcT for every data type T, the types TyCon and Module must be available right from the start; so they are defined in ghc-prim:GHC.Types * To save space and reduce dependencies, we need use quite low-level representations for TyCon and Module. See GHC.Types Note [Runtime representation of modules and tycons] * It's hard to generate the TyCon/Module bindings when the types TyCon and Module aren't yet available; i.e. when compiling GHC.Types itself. So we *don't* generate them for types in GHC.Types. Instead we write them by hand in base:GHC.Typeable.Internal. * To be able to define them by hand, they need to have user-writable names, thus tcBool not $tcBool for the type-rep TyCon for Bool Hence PrelNames.tyConRepModOcc * Moreover for type constructors with special syntax, they need to have completely hand-crafted names lists tcList not $tc[] for the type-rep TyCon for [] kinds tcLiftedKind not $tc* for the type-rep TyCon for * Hence PrelNames.mkSpecialTyConRepName, which takes an extra FastString to use for the TyConRepName * Since listTyCon, boolTyCon etd are wired in, their TyConRepNames must be wired in as well. For these wired-in TyCons we generate the TyConRepName's unique from that of the TyCon; see Unique.tyConRepNameUnique, dataConRepNameUnique. -} {- ********************************************************************* * * Building top-level binding for $trModule * * ********************************************************************* -} mkModIdBindings :: TcM TcGblEnv mkModIdBindings = do { mod <- getModule ; if mod == gHC_TYPES then getGblEnv -- Do not generate bindings for modules in GHC.Types else do { loc <- getSrcSpanM ; tr_mod_dc <- tcLookupDataCon trModuleDataConName ; tr_name_dc <- tcLookupDataCon trNameSDataConName ; mod_nm <- newGlobalBinder mod (mkVarOcc "$trModule") loc ; let mod_id = mkExportedLocalId ReflectionId mod_nm (mkTyConApp (dataConTyCon tr_mod_dc) []) mod_bind = mkVarBind mod_id mod_rhs mod_rhs = nlHsApps (dataConWrapId tr_mod_dc) [ trNameLit tr_name_dc (unitIdFS (moduleUnitId mod)) , trNameLit tr_name_dc (moduleNameFS (moduleName mod)) ] ; tcg_env <- tcExtendGlobalValEnv [mod_id] getGblEnv ; return (tcg_env { tcg_tr_module = Just mod_id } `addTypecheckedBinds` [unitBag mod_bind]) } } {- ********************************************************************* * * Building type-representation bindings * * ********************************************************************* -} mkTypeableBinds :: [TyCon] -> TcM ([Id], [LHsBinds Id]) mkTypeableBinds tycons = do { dflags <- getDynFlags ; gbl_env <- getGblEnv ; mod <- getModule ; if mod == gHC_TYPES then return ([], []) -- Do not generate bindings for modules in GHC.Types else do { tr_datacon <- tcLookupDataCon trTyConDataConName ; trn_datacon <- tcLookupDataCon trNameSDataConName ; let pkg_str = unitIdString (moduleUnitId mod) mod_str = moduleNameString (moduleName mod) mod_expr = case tcg_tr_module gbl_env of -- Should be set by now Just mod_id -> nlHsVar mod_id Nothing -> pprPanic "tcMkTypeableBinds" (ppr tycons) stuff = (dflags, mod_expr, pkg_str, mod_str, tr_datacon, trn_datacon) tc_binds = map (mk_typeable_binds stuff) tycons tycon_rep_ids = foldr ((++) . collectHsBindsBinders) [] tc_binds ; return (tycon_rep_ids, tc_binds) } } trNameLit :: DataCon -> FastString -> LHsExpr Id trNameLit tr_name_dc fs = nlHsApps (dataConWrapId tr_name_dc) [nlHsLit (mkHsStringPrimLit fs)] type TypeableStuff = ( DynFlags , LHsExpr Id -- Of type GHC.Types.Module , String -- Package name , String -- Module name , DataCon -- Data constructor GHC.Types.TyCon , DataCon ) -- Data constructor GHC.Types.TrNameS mk_typeable_binds :: TypeableStuff -> TyCon -> LHsBinds Id mk_typeable_binds stuff tycon = mkTyConRepBinds stuff tycon `unionBags` unionManyBags (map (mkTypeableDataConBinds stuff) (tyConDataCons tycon)) mkTyConRepBinds :: TypeableStuff -> TyCon -> LHsBinds Id mkTyConRepBinds (dflags, mod_expr, pkg_str, mod_str, tr_datacon, trn_datacon) tycon = case tyConRepName_maybe tycon of Just rep_name -> unitBag (mkVarBind rep_id rep_rhs) where rep_id = mkExportedLocalId ReflectionId rep_name (mkTyConApp tr_tycon []) _ -> emptyBag where tr_tycon = dataConTyCon tr_datacon rep_rhs = nlHsApps (dataConWrapId tr_datacon) [ nlHsLit (word64 high), nlHsLit (word64 low) , mod_expr , trNameLit trn_datacon (mkFastString tycon_str) ] tycon_str = add_tick (occNameString (getOccName tycon)) add_tick s | isPromotedDataCon tycon = '\'' : s | isPromotedTyCon tycon = '\'' : s | otherwise = s hashThis :: String hashThis = unwords [pkg_str, mod_str, tycon_str] Fingerprint high low | gopt Opt_SuppressUniques dflags = Fingerprint 0 0 | otherwise = fingerprintString hashThis word64 :: Word64 -> HsLit word64 | wORD_SIZE dflags == 4 = \n -> HsWord64Prim (show n) (toInteger n) | otherwise = \n -> HsWordPrim (show n) (toInteger n) mkTypeableDataConBinds :: TypeableStuff -> DataCon -> LHsBinds Id mkTypeableDataConBinds stuff dc = case promoteDataCon_maybe dc of Promoted tc -> mkTyConRepBinds stuff tc NotPromoted -> emptyBag
AlexanderPankiv/ghc
compiler/typecheck/TcTypeable.hs
bsd-3-clause
8,150
0
19
2,230
1,215
641
574
101
3
{-# LANGUAGE DeriveGeneric #-} module Distribution.Client.Dependency.Types ( PreSolver(..), Solver(..), PackagesPreferenceDefault(..), ) where import Data.Char ( isAlpha, toLower ) import qualified Distribution.Compat.ReadP as Parse ( pfail, munch1 ) import Distribution.Text ( Text(..) ) import Text.PrettyPrint ( text ) import GHC.Generics (Generic) import Distribution.Compat.Binary (Binary(..)) -- | All the solvers that can be selected. data PreSolver = AlwaysTopDown | AlwaysModular | Choose deriving (Eq, Ord, Show, Bounded, Enum, Generic) -- | All the solvers that can be used. data Solver = TopDown | Modular deriving (Eq, Ord, Show, Bounded, Enum, Generic) instance Binary PreSolver instance Binary Solver instance Text PreSolver where disp AlwaysTopDown = text "topdown" disp AlwaysModular = text "modular" disp Choose = text "choose" parse = do name <- Parse.munch1 isAlpha case map toLower name of "topdown" -> return AlwaysTopDown "modular" -> return AlwaysModular "choose" -> return Choose _ -> Parse.pfail -- | Global policy for all packages to say if we prefer package versions that -- are already installed locally or if we just prefer the latest available. -- data PackagesPreferenceDefault = -- | Always prefer the latest version irrespective of any existing -- installed version. -- -- * This is the standard policy for upgrade. -- PreferAllLatest -- | Always prefer the installed versions over ones that would need to be -- installed. Secondarily, prefer latest versions (eg the latest installed -- version or if there are none then the latest source version). | PreferAllInstalled -- | Prefer the latest version for packages that are explicitly requested -- but prefers the installed version for any other packages. -- -- * This is the standard policy for install. -- | PreferLatestForSelected deriving Show
headprogrammingczar/cabal
cabal-install/Distribution/Client/Dependency/Types.hs
bsd-3-clause
2,033
0
11
476
342
199
143
37
0
-- | examine all uses of types in a program to determine which ones are -- actually needed in the method generation module E.TypeAnalysis(typeAnalyze, Typ(),expandPlaceholder) where import Control.Monad.Error import Control.Monad.Identity import Control.Monad.State import Data.Maybe import Data.Monoid import qualified Data.Foldable as T import qualified Data.Map as Map import qualified Data.Set as Set import DataConstructors import Doc.PPrint import E.Annotate import E.E hiding(isBottom) import E.Eta import E.Program import E.Rules import E.Subst import E.Traverse(emapE',emapE_,emapE) import E.TypeCheck import E.Values import Fixer.Fixer import Fixer.Supply import Fixer.VMap import Info.Types import Name.Id import Name.Name import Name.Names import Support.CanType import Util.Gen import Util.SetLike hiding(Value) import qualified Info.Info as Info import qualified Stats type Typ = VMap () Name data Env = Env { envRuleSupply :: Supply (Module,Int) Bool, envValSupply :: Supply TVr Bool, envEnv :: IdMap [Value Typ] } extractValMap :: [(TVr,E)] -> IdMap [Value Typ] extractValMap ds = fromList [ (tvrIdent t,f e []) | (t,e) <- ds] where f (ELam tvr e) rs | sortKindLike (getType tvr) = f e (runIdentity (Info.lookup $ tvrInfo tvr):rs) f _ rs = reverse rs -- all variables _must_ be unique before running this {-# NOINLINE typeAnalyze #-} typeAnalyze :: Bool -> Program -> IO Program typeAnalyze doSpecialize prog = do fixer <- newFixer ur <- newSupply fixer uv <- newSupply fixer let lambind _ nfo = do x <- newValue fixer ( bottom :: Typ) return $ Info.insert x (Info.delete (undefined :: Typ) nfo) prog <- annotateProgram mempty lambind (\_ -> return . deleteArity) (\_ -> return) prog let ds = programDs prog env = Env { envRuleSupply = ur, envValSupply = uv, envEnv = extractValMap ds } entries = progEntryPoints prog calcCombs env $ progCombinators prog forM_ entries $ \tvr -> do vv <- supplyValue uv tvr addRule $ assert vv mapM_ (sillyEntry env) entries findFixpoint Nothing fixer let lamread _ nfo | Just v <- Info.lookup nfo = do rv <- readValue v return (Info.insert (rv :: Typ) $ Info.delete (undefined :: Value Typ) nfo) lamread _ nfo = return nfo prog <- annotateProgram mempty lamread (\_ -> return) (\_ -> return) prog unusedRules <- supplyReadValues ur >>= return . fsts . filter (not . snd) unusedValues <- supplyReadValues uv >>= return . fsts . filter (not . snd) let (prog',stats) = Stats.runStatM $ specializeProgram doSpecialize (fromList unusedRules) (fromList unusedValues) prog let lamdel _ nfo = return (Info.delete (undefined :: Value Typ) nfo) prog <- annotateProgram mempty lamdel (\_ -> return) (\_ -> return) prog' return prog { progStats = progStats prog `mappend` stats } sillyEntry :: Env -> TVr -> IO () sillyEntry env t = mapM_ (addRule . (`isSuperSetOf` value (vmapPlaceholder ()))) args where args = lookupArgs t env lookupArgs t Env { envEnv = tm } = maybe [] id (mlookup (tvrIdent t) tm) toLit (EPi TVr { tvrType = a } b) = return (tc_Arrow,[a,b]) toLit (ELit LitCons { litName = n, litArgs = ts }) = return (n,ts) toLit _ = fail "not convertable to literal" assert :: Value Bool -> Fixer.Fixer.Rule assert v = v `isSuperSetOf` value True calcComb :: Env -> Comb -> IO () calcComb env@Env { envRuleSupply = ur, envValSupply = uv } comb = do let (_,ls) = fromLam $ combBody comb tls = takeWhile (sortKindLike . getType) ls rs = combRules comb t = combHead comb hr r = do ruleUsed <- supplyValue ur (ruleUniq r) addRule $ conditionalRule id ruleUsed (ioToRule $ calcE env (ruleBody r)) let hrg r (t,EVar a) | a `elem` ruleBinds r = do let (t'::Value Typ) = Info.fetch (tvrInfo t) let (a'::Value Typ) = Info.fetch (tvrInfo a) addRule $ conditionalRule id ruleUsed $ ioToRule $ do addRule $ a' `isSuperSetOf` t' return True hrg r (t,e) | Just (n,as) <- toLit e = do let (t'::Value Typ) = Info.fetch (tvrInfo t) as' <- mapM getValue as addRule $ conditionalRule id ruleUsed $ ioToRule $ do forMn_ ((zip as as')) $ \ ((a',a''),i) -> do when (isEVar a') $ addRule $ modifiedSuperSetOf a'' t' (vmapArg n i) addRule $ conditionalRule (n `vmapMember`) t' (assert ruleUsed) return False hrg x y = error $ "TypeAnalyis.hrg: " ++ show (x,y) rr <- mapM (hrg r) (zip tls (ruleArgs r)) when (and rr) $ addRule (assert ruleUsed) valUsed <- supplyValue uv t addRule $ conditionalRule id valUsed $ ioToRule $ do mapM_ hr rs calcE env $ combBody comb calcDef :: Env -> (TVr,E) -> IO () calcDef env@Env { envValSupply = uv } (t,e) = do valUsed <- supplyValue uv t addRule $ conditionalRule id valUsed $ ioToRule $ do calcE env e calcCombs :: Env -> [Comb] -> IO () calcCombs env@Env { envRuleSupply = ur, envValSupply = uv } ds = do mapM_ (calcTE env) [ (combHead c,combBody c) | c <- ds ] mapM_ (calcComb env) ds calcTE :: Env -> (TVr,E) -> IO () calcTE env@Env { envRuleSupply = ur, envValSupply = uv } ds = d ds where d (t,e) | not (sortKindLike (getType t)) = return () d (t,e) | Just v <- getValue e = do let Just t' = Info.lookup (tvrInfo t) addRule $ t' `isSuperSetOf` v d (t,e) | Just (n,xs) <- toLit e = do let Just t' = Info.lookup (tvrInfo t) v = vmapSingleton n addRule $ t' `isSuperSetOf` (value v) xs' <- mapM getValue xs forMn_ xs' $ \ (v,i) -> do addRule $ modifiedSuperSetOf t' v (vmapArgSingleton n i) d (t,e) | (EVar v,as) <- fromAp e = do let Just t' = Info.lookup (tvrInfo t) Just v' = Info.lookup (tvrInfo v) as' <- mapM getValue as addRule $ dynamicRule v' $ \ v -> mconcat $ (t' `isSuperSetOf` value (vmapDropArgs v)):case vmapHeads v of Just vs -> concat $ flip map vs $ \h -> (flip map (zip as' [0.. ]) $ \ (a,i) -> modifiedSuperSetOf t' a $ \ v -> vmapArgSingleton h i v) Nothing -> flip map (zip as' [0.. ]) $ \ (_,i) -> isSuperSetOf t' (value $ vmapProxyIndirect i v) d (t,e) = fail $ "calcDs: " ++ show (t,e) calcDs :: Env -> [(TVr,E)] -> IO () calcDs env@Env { envRuleSupply = ur, envValSupply = uv } ds = do mapM_ (calcTE env) ds forM_ ds $ \ (v,e) -> do calcDef env (v,e) -- TODO - make default case conditional calcAlt env v (Alt ~LitCons { litName = n, litArgs = xs } e) = do addRule $ conditionalRule (n `vmapMember`) v $ ioToRule $ do calcE env e forMn_ xs $ \ (t,i) -> do let Just t' = Info.lookup (tvrInfo t) addRule $ modifiedSuperSetOf t' v (vmapArg n i) calcE :: Env -> E -> IO () calcE env (ELetRec ds e) = calcDs nenv ds >> calcE nenv e where nenv = env { envEnv = extractValMap ds `union` envEnv env } calcE env ec@ECase {} | sortKindLike (getType $ eCaseScrutinee ec) = do calcE env (eCaseScrutinee ec) T.mapM_ (calcE env) (eCaseDefault ec) v <- getValue (eCaseScrutinee ec) mapM_ (calcAlt env v) (eCaseAlts ec) calcE env e | (e',(_:_)) <- fromLam e = calcE env e' calcE env ec@ECase {} = do calcE env (eCaseScrutinee ec) mapM_ (calcE env) (caseBodies ec) calcE env e@ELit {} = tagE env e calcE env e@EPrim {} = tagE env e calcE _ EError {} = return () calcE _ ESort {} = return () calcE _ Unknown = return () calcE env e | (EVar v,as@(_:_)) <- fromAp e = do let ts = lookupArgs v env tagE env e when (length as < length ts) $ fail ("calcE: unsaturated call to function: " ++ pprint e) forM_ (zip as ts) $ \ (a,t) -> do when (sortKindLike (getType a)) $ do a' <- getValue a addRule $ t `isSuperSetOf` a' calcE env e@EVar {} = tagE env e calcE env e@EAp {} = tagE env e calcE env e@EPi {} = tagE env e calcE _ e = fail $ "odd calcE: " ++ show e tagE Env { envValSupply = uv } (EVar v) | not $ getProperty prop_RULEBINDER v = do v <- supplyValue uv v addRule $ assert v tagE env e = emapE_ (tagE env) e getValue (EVar v) | Just x <- Info.lookup (tvrInfo v) = return x | otherwise = return $ value (vmapPlaceholder ()) -- | otherwise = fail $ "getValue: no varinfo: " ++ show v getValue e | Just c <- typConstant e = return $ value c getValue e = return $ value $ fuzzyConstant e -- TODO - make more accurate fuzzyConstant :: E -> Typ fuzzyConstant e | Just (n,as) <- toLit e = vmapValue n (map fuzzyConstant as) fuzzyConstant _ = vmapPlaceholder () typConstant :: Monad m => E -> m Typ typConstant e | Just (n,as) <- toLit e = return (vmapValue n) `ap` mapM typConstant as typConstant e = fail $ "typConstant: " ++ show e data SpecEnv = SpecEnv { senvUnusedRules :: Set.Set (Module,Int), senvUnusedVars :: Set.Set TVr, senvDataTable :: DataTable, senvArgs :: Map.Map TVr [Int] } getTyp :: Monad m => E -> DataTable -> Typ -> m E getTyp kind dataTable vm = f (10::Int) kind vm where f n _ _ | n <= 0 = fail "getTyp: too deep" f n kind vm | Just [] <- vmapHeads vm = return $ tAbsurd kind f n kind vm | Just [h] <- vmapHeads vm = do let ss = slotTypes dataTable h kind as = [ (s,vmapArg h i vm) | (s,i) <- zip ss [0..]] as'@(~[fa,fb]) <- mapM (uncurry (f (n - 1))) as if h == tc_Arrow then return $ EPi tvr { tvrType = fa } fb else return $ ELit (updateLit dataTable litCons { litName = h, litArgs = as', litType = kind }) f _ _ _ = fail "getTyp: not constant type" specializeProgram :: (Stats.MonadStats m) => Bool -- ^ do specialization -> (Set.Set (Module,Int)) -- ^ unused rules -> (Set.Set TVr) -- ^ unused values -> Program -> m Program specializeProgram doSpecialize unusedRules unusedValues prog = do (nds,_) <- specializeCombs doSpecialize SpecEnv { senvUnusedRules = unusedRules , senvUnusedVars = unusedValues , senvDataTable = progDataTable prog , senvArgs = mempty } (progCombinators prog) return $ progCombinators_s nds prog repi (ELit LitCons { litName = n, litArgs = [a,b] }) | n == tc_Arrow = EPi tvr { tvrIdent = emptyId, tvrType = repi a } (repi b) repi e = runIdentity $ emapE (return . repi ) e specializeComb _ env comb | isUnused env (combHead comb) = let tvr = combHead comb in return (combRules_s [] . combBody_s (EError ("Unused Def: " ++ tvrShowName tvr) (tvrType tvr)) $ comb , mempty) specializeComb _ _ comb | getProperty prop_PLACEHOLDER comb = return (comb, mempty) specializeComb True SpecEnv { senvDataTable = dataTable } comb | needsSpec = ans where tvr = combHead comb e = combBody comb sub = substMap' $ fromList [ (tvrIdent t,v) | (t,Just v) <- sts ] sts = map spec ts spec t | Just nt <- Info.lookup (tvrInfo t) >>= getTyp (getType t) dataTable, sortKindLike (getType t) = (t,Just (repi nt)) spec t = (t,Nothing) (fe,ts) = fromLam e ne = sub $ foldr ELam fe [ t | (t,Nothing) <- sts] vs = [ (n,v) | ((_,Just v),n) <- zip sts naturals ] needsSpec = not $ null vs ans = do sequence_ [ Stats.mtick ("Specialize.body.{" ++ pprint tvr ++ "}.{" ++ pprint t ++ "}.{" ++ pprint v) | (t,Just v) <- sts ] let nc = combHead_s tvr { tvrType = infertype dataTable ne } . combBody_s ne . combRules_u (dropArguments vs) $ comb return (nc,msingleton tvr (fsts vs)) specializeComb _ _ comb = return (comb,mempty) instance Error () where noMsg = () strMsg _ = () evalErrorT :: Monad m => a -> ErrorT () m a -> m a evalErrorT err action = liftM f (runErrorT action) where f (Left _) = err f (Right x) = x eToPatM :: Monad m => (E -> m TVr) -> E -> m (Lit TVr E) eToPatM cv e = f e where f (ELit LitCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }) = do ts <- mapM cv ts return litCons { litAliasFor = af, litName = x, litArgs = ts, litType = t } f (ELit (LitInt e t)) = return (LitInt e t) f (EPi (TVr { tvrType = a}) b) = do a <- cv a b <- cv b return litCons { litName = tc_Arrow, litArgs = [a,b], litType = eStar } f x = fail $ "E.Values.eToPatM: " ++ show x caseCast :: TVr -> E -> E -> E caseCast t ty e = evalState (f t ty e) (newIds (freeIds e),[]) where -- f t ty e | isFullyConst ty = return $ -- prim_unsafeCoerce (subst t ty e) (getType e) f t ty e = do p <- eToPatM cv ty (ns,es) <- get put (ns,[]) let rs = map (uncurry caseCast) es return (eCase (EVar t) [Alt p (foldr (.) id rs e)] Unknown) cv (EVar v) = return v cv e = do ((n:ns),es) <- get let t = tvr { tvrIdent = n, tvrType = getType e } put (ns,(t,e):es) return t specAlt :: Stats.MonadStats m => SpecEnv -> Alt E -> m (Alt E) specAlt env@SpecEnv { senvDataTable = dataTable } (Alt ~lc@LitCons { litArgs = ts } e) = ans where f xs = do ws <- forM xs $ \t -> evalErrorT id $ do False <- return $ isUnused env t Just nt <- return $ Info.lookup (tvrInfo t) Just tt <- return $ getTyp (getType t) dataTable nt Stats.mtick $ "Specialize.alt.{" ++ pprint (show nt,tt) ++ "}" return $ caseCast t tt return $ foldr (.) id ws ans = do ws <- f ts return (Alt lc (ws e)) isUnused SpecEnv { senvUnusedVars = unusedVars } v = v `member` unusedVars && isJust (Info.lookup $ tvrInfo v :: Maybe Typ) specBody :: Stats.MonadStats m => Bool -> SpecEnv -> E -> m E --specBody _ env e | (EVar h,as) <- fromAp e, isUnused env h = do -- Stats.mtick $ "Specialize.delete.{" ++ pprint h ++ "}" -- return $ foldl EAp (EError ("Unused: " ++ pprint h) (getType h)) as specBody True env@SpecEnv { senvArgs = dmap } e | (EVar h,as) <- fromAp e, Just os <- mlookup h dmap = do Stats.mtick $ "Specialize.use.{" ++ pprint h ++ "}" as' <- mapM (specBody True env) as return $ foldl EAp (EVar h) [ a | (a,i) <- zip as' naturals, i `notElem` os ] specBody True env ec@ECase { eCaseScrutinee = EVar v } | sortKindLike (getType v) = do alts <- mapM (specAlt env) (eCaseAlts ec) emapE' (specBody True env) ec { eCaseAlts = alts } specBody doSpecialize env (ELetRec ds e) = do (nds,nenv) <- specializeDs doSpecialize env ds e <- specBody doSpecialize nenv e return $ ELetRec nds e specBody doSpecialize env e = emapE' (specBody doSpecialize env) e --specializeDs :: MonadStats m => DataTable -> Map.Map TVr [Int] -> [(TVr,E)] -> m ([(TVr,E)] specializeDs doSpecialize env@SpecEnv { senvUnusedRules = unusedRules, senvDataTable = dataTable } ds = do (ds,nenv) <- mapAndUnzipM (specializeComb doSpecialize env) (map bindComb ds) ds <- return $ map combBind ds let tenv = env { senvArgs = unions nenv `union` senvArgs env } sb = specBody doSpecialize tenv let f (t,e) = do e <- sb e return (t,e) ds <- mapM f ds return (ds,tenv) --specializeDs :: MonadStats m => DataTable -> Map.Map TVr [Int] -> [(TVr,E)] -> m ([(TVr,E)] specializeCombs doSpecialize env@SpecEnv { senvUnusedRules = unusedRules, senvDataTable = dataTable } ds = do (ds,nenv) <- mapAndUnzipM (specializeComb doSpecialize env) ds let tenv = env { senvArgs = unions nenv `union` senvArgs env } sb = specBody doSpecialize tenv let f comb = do e <- sb (combBody comb) rs <- mapM (mapRBodyArgs sb) (combRules comb) let rs' = filter ( not . (`member` unusedRules) . ruleUniq) rs return . combBody_s e . combRules_s rs' $ comb ds <- mapM f ds return (ds,tenv) expandPlaceholder :: Monad m => Comb -> m Comb expandPlaceholder comb | getProperty prop_PLACEHOLDER (combHead comb) = do let rules = filter isBodyRule $ combRules comb tvr = combHead comb isBodyRule Rule { ruleType = RuleSpecialization } = True isBodyRule _ = False let mcomb nb = (combBody_s nb . combHead_u (unsetProperty prop_PLACEHOLDER) $ comb) if null rules then return (mcomb $ EError ("Placeholder, no bodies: " ++ tvrShowName tvr) (getType tvr)) else do let (oe',as) = fromLam $ combBody comb rule1:_ = rules ct = getType $ foldr ELam oe' (drop (length $ ruleArgs rule1) as) as'@(a:ras) | (a:ras) <- take (length $ ruleArgs rule1) as = (a:ras) | otherwise = error $ pprint (tvr,(combBody comb,show rule1)) ne = emptyCase { eCaseScrutinee = EVar a, eCaseAlts = map calt rules, eCaseBind = a { tvrIdent = emptyId }, eCaseType = ct } calt rule@Rule { ruleArgs = ~(arg:rs) } = Alt vp (substMap (fromList [ (tvrIdent v,EVar r) | ~(EVar v) <- rs | r <- ras ]) $ ruleBody rule) where Just vp = eToPat arg return (mcomb (foldr ELam ne as')) expandPlaceholder _x = fail "not placeholder"
m-alvarez/jhc
src/E/TypeAnalysis.hs
mit
17,383
1
29
4,816
7,419
3,697
3,722
-1
-1
module Avg where {-@ LIQUID "--real" @-} {-@ measure sumD :: [Double] -> Double sumD([]) = 0.0 sumD(x:xs) = x + (sumD xs) @-} {-@ measure lenD :: [Double] -> Double lenD([]) = 0.0 lenD(x:xs) = (1.0) + (lenD xs) @-} {-@ expression Avg Xs = ((sumD Xs) / (lenD Xs)) @-} {-@ meansD :: xs:{v:[Double] | ((lenD v) > 0.0)} -> {v:Double | v = Avg xs} @-} meansD :: [Double] -> Double meansD xs = sumD xs / lenD xs {-@ lenD :: xs:[Double] -> {v:Double | v = (lenD xs)} @-} lenD :: [Double] -> Double lenD [] = 0.0 lenD (x:xs) = 1.0 + lenD xs {-@ sumD :: xs:[Double] -> {v:Double | v = (sumD xs)} @-} sumD :: [Double] -> Double sumD [] = 0.0 sumD (x:xs) = x + sumD xs
mightymoose/liquidhaskell
tests/pos/Avg.hs
bsd-3-clause
699
0
7
179
129
71
58
9
1
{-# LANGUAGE CPP, MagicHash #-} -- -- (c) The University of Glasgow 2002-2006 -- -- | ByteCodeGen: Generate bytecode from Core module ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where #include "HsVersions.h" import ByteCodeInstr import ByteCodeItbls import ByteCodeAsm import ByteCodeLink import LibFFI import DynFlags import Outputable import Platform import Name import MkId import Id import ForeignCall import HscTypes import CoreUtils import CoreSyn import PprCore import Literal import PrimOp import CoreFVs import Type import DataCon import TyCon import Util import VarSet import TysPrim import ErrUtils import Unique import FastString import Panic import StgCmmLayout ( ArgRep(..), toArgRep, argRepSizeW ) import SMRep import Bitmap import OrdList import Data.List import Foreign import Foreign.C #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif import Control.Monad import Data.Char import UniqSupply import BreakArray import Data.Maybe import Module import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import Data.Map (Map) import qualified Data.Map as Map import qualified FiniteMap as Map import Data.Ord -- ----------------------------------------------------------------------------- -- Generating byte code for a complete module byteCodeGen :: DynFlags -> Module -> CoreProgram -> [TyCon] -> ModBreaks -> IO CompiledByteCode byteCodeGen dflags this_mod binds tycs modBreaks = do showPass dflags "ByteCodeGen" let flatBinds = [ (bndr, freeVars rhs) | (bndr, rhs) <- flattenBinds binds] us <- mkSplitUniqSupply 'y' (BcM_State _dflags _us _this_mod _final_ctr mallocd _, proto_bcos) <- runBc dflags us this_mod modBreaks (mapM schemeTopBind flatBinds) when (notNull mallocd) (panic "ByteCodeGen.byteCodeGen: missing final emitBc?") dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos))) assembleBCOs dflags proto_bcos tycs -- ----------------------------------------------------------------------------- -- Generating byte code for an expression -- Returns: (the root BCO for this expression, -- a list of auxilary BCOs resulting from compiling closures) coreExprToBCOs :: DynFlags -> Module -> CoreExpr -> IO UnlinkedBCO coreExprToBCOs dflags this_mod expr = do showPass dflags "ByteCodeGen" -- create a totally bogus name for the top-level BCO; this -- should be harmless, since it's never used for anything let invented_name = mkSystemVarName (mkPseudoUniqueE 0) (fsLit "ExprTopLevel") invented_id = Id.mkLocalId invented_name (panic "invented_id's type") -- the uniques are needed to generate fresh variables when we introduce new -- let bindings for ticked expressions us <- mkSplitUniqSupply 'y' (BcM_State _dflags _us _this_mod _final_ctr mallocd _ , proto_bco) <- runBc dflags us this_mod emptyModBreaks $ schemeTopBind (invented_id, freeVars expr) when (notNull mallocd) (panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?") dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco) assembleBCO dflags proto_bco -- ----------------------------------------------------------------------------- -- Compilation schema for the bytecode generator type BCInstrList = OrdList BCInstr type Sequel = Word -- back off to this depth before ENTER -- Maps Ids to the offset from the stack _base_ so we don't have -- to mess with it after each push/pop. type BCEnv = Map Id Word -- To find vars on the stack {- ppBCEnv :: BCEnv -> SDoc ppBCEnv p = text "begin-env" $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (Map.toList p)))) $$ text "end-env" where pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (bcIdArgRep var) cmp_snd x y = compare (snd x) (snd y) -} -- Create a BCO and do a spot of peephole optimisation on the insns -- at the same time. mkProtoBCO :: DynFlags -> name -> BCInstrList -> Either [AnnAlt Id VarSet] (AnnExpr Id VarSet) -> Int -> Word16 -> [StgWord] -> Bool -- True <=> is a return point, rather than a function -> [BcPtr] -> ProtoBCO name mkProtoBCO dflags nm instrs_ordlist origin arity bitmap_size bitmap is_ret mallocd_blocks = ProtoBCO { protoBCOName = nm, protoBCOInstrs = maybe_with_stack_check, protoBCOBitmap = bitmap, protoBCOBitmapSize = bitmap_size, protoBCOArity = arity, protoBCOExpr = origin, protoBCOPtrs = mallocd_blocks } where -- Overestimate the stack usage (in words) of this BCO, -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit -- stack check. (The interpreter always does a stack check -- for iNTERP_STACK_CHECK_THRESH words at the start of each -- BCO anyway, so we only need to add an explicit one in the -- (hopefully rare) cases when the (overestimated) stack use -- exceeds iNTERP_STACK_CHECK_THRESH. maybe_with_stack_check | is_ret && stack_usage < fromIntegral (aP_STACK_SPLIM dflags) = peep_d -- don't do stack checks at return points, -- everything is aggregated up to the top BCO -- (which must be a function). -- That is, unless the stack usage is >= AP_STACK_SPLIM, -- see bug #1466. | stack_usage >= fromIntegral iNTERP_STACK_CHECK_THRESH = STKCHECK stack_usage : peep_d | otherwise = peep_d -- the supposedly common case -- We assume that this sum doesn't wrap stack_usage = sum (map bciStackUse peep_d) -- Merge local pushes peep_d = peep (fromOL instrs_ordlist) peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest) = PUSH_LLL off1 (off2-1) (off3-2) : peep rest peep (PUSH_L off1 : PUSH_L off2 : rest) = PUSH_LL off1 (off2-1) : peep rest peep (i:rest) = i : peep rest peep [] = [] argBits :: DynFlags -> [ArgRep] -> [Bool] argBits _ [] = [] argBits dflags (rep : args) | isFollowableArg rep = False : argBits dflags args | otherwise = take (argRepSizeW dflags rep) (repeat True) ++ argBits dflags args -- ----------------------------------------------------------------------------- -- schemeTopBind -- Compile code for the right-hand side of a top-level binding schemeTopBind :: (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name) schemeTopBind (id, rhs) | Just data_con <- isDataConWorkId_maybe id, isNullaryRepDataCon data_con = do dflags <- getDynFlags -- Special case for the worker of a nullary data con. -- It'll look like this: Nil = /\a -> Nil a -- If we feed it into schemeR, we'll get -- Nil = Nil -- because mkConAppCode treats nullary constructor applications -- by just re-using the single top-level definition. So -- for the worker itself, we must allocate it directly. -- ioToBc (putStrLn $ "top level BCO") emitBc (mkProtoBCO dflags (getName id) (toOL [PACK data_con 0, ENTER]) (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-}) | otherwise = schemeR [{- No free variables -}] (id, rhs) -- ----------------------------------------------------------------------------- -- schemeR -- Compile code for a right-hand side, to give a BCO that, -- when executed with the free variables and arguments on top of the stack, -- will return with a pointer to the result on top of the stack, after -- removing the free variables and arguments. -- -- Park the resulting BCO in the monad. Also requires the -- variable to which this value was bound, so as to give the -- resulting BCO a name. schemeR :: [Id] -- Free vars of the RHS, ordered as they -- will appear in the thunk. Empty for -- top-level things, which have no free vars. -> (Id, AnnExpr Id VarSet) -> BcM (ProtoBCO Name) schemeR fvs (nm, rhs) {- | trace (showSDoc ( (char ' ' $$ (ppr.filter (not.isTyVar).varSetElems.fst) rhs $$ pprCoreExpr (deAnnotate rhs) $$ char ' ' ))) False = undefined | otherwise -} = schemeR_wrk fvs nm rhs (collect rhs) collect :: AnnExpr Id VarSet -> ([Var], AnnExpr' Id VarSet) collect (_, e) = go [] e where go xs e | Just e' <- bcView e = go xs e' go xs (AnnLam x (_,e)) | UbxTupleRep _ <- repType (idType x) = unboxedTupleException | otherwise = go (x:xs) e go xs not_lambda = (reverse xs, not_lambda) schemeR_wrk :: [Id] -> Id -> AnnExpr Id VarSet -> ([Var], AnnExpr' Var VarSet) -> BcM (ProtoBCO Name) schemeR_wrk fvs nm original_body (args, body) = do dflags <- getDynFlags let all_args = reverse args ++ fvs arity = length all_args -- all_args are the args in reverse order. We're compiling a function -- \fv1..fvn x1..xn -> e -- i.e. the fvs come first szsw_args = map (fromIntegral . idSizeW dflags) all_args szw_args = sum szsw_args p_init = Map.fromList (zip all_args (mkStackOffsets 0 szsw_args)) -- make the arg bitmap bits = argBits dflags (reverse (map bcIdArgRep all_args)) bitmap_size = genericLength bits bitmap = mkBitmap dflags bits body_code <- schemeER_wrk szw_args p_init body emitBc (mkProtoBCO dflags (getName nm) body_code (Right original_body) arity bitmap_size bitmap False{-not alts-}) -- introduce break instructions for ticked expressions schemeER_wrk :: Word -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList schemeER_wrk d p rhs | AnnTick (Breakpoint tick_no fvs) (_annot, newRhs) <- rhs = do code <- schemeE (fromIntegral d) 0 p newRhs arr <- getBreakArray this_mod <- getCurrentModule let idOffSets = getVarOffSets d p fvs let breakInfo = BreakInfo { breakInfo_module = this_mod , breakInfo_number = tick_no , breakInfo_vars = idOffSets , breakInfo_resty = exprType (deAnnotate' newRhs) } let breakInstr = case arr of BA arr# -> BRK_FUN arr# (fromIntegral tick_no) breakInfo return $ breakInstr `consOL` code | otherwise = schemeE (fromIntegral d) 0 p rhs getVarOffSets :: Word -> BCEnv -> [Id] -> [(Id, Word16)] getVarOffSets d p = catMaybes . map (getOffSet d p) getOffSet :: Word -> BCEnv -> Id -> Maybe (Id, Word16) getOffSet d env id = case lookupBCEnv_maybe id env of Nothing -> Nothing Just offset -> Just (id, trunc16 $ d - offset) trunc16 :: Word -> Word16 trunc16 w | w > fromIntegral (maxBound :: Word16) = panic "stack depth overflow" | otherwise = fromIntegral w fvsToEnv :: BCEnv -> VarSet -> [Id] -- Takes the free variables of a right-hand side, and -- delivers an ordered list of the local variables that will -- be captured in the thunk for the RHS -- The BCEnv argument tells which variables are in the local -- environment: these are the ones that should be captured -- -- The code that constructs the thunk, and the code that executes -- it, have to agree about this layout fvsToEnv p fvs = [v | v <- varSetElems fvs, isId v, -- Could be a type variable v `Map.member` p] -- ----------------------------------------------------------------------------- -- schemeE returnUnboxedAtom :: Word -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> ArgRep -> BcM BCInstrList -- Returning an unlifted value. -- Heave it on the stack, SLIDE, and RETURN. returnUnboxedAtom d s p e e_rep = do (push, szw) <- pushAtom d p e return (push -- value onto stack `appOL` mkSLIDE szw (d-s) -- clear to sequel `snocOL` RETURN_UBX e_rep) -- go -- Compile code to apply the given expression to the remaining args -- on the stack, returning a HNF. schemeE :: Word -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList schemeE d s p e | Just e' <- bcView e = schemeE d s p e' -- Delegate tail-calls to schemeT. schemeE d s p e@(AnnApp _ _) = schemeT d s p e schemeE d s p e@(AnnLit lit) = returnUnboxedAtom d s p e (typeArgRep (literalType lit)) schemeE d s p e@(AnnCoercion {}) = returnUnboxedAtom d s p e V schemeE d s p e@(AnnVar v) | isUnLiftedType (idType v) = returnUnboxedAtom d s p e (bcIdArgRep v) | otherwise = schemeT d s p e schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body)) | (AnnVar v, args_r_to_l) <- splitApp rhs, Just data_con <- isDataConWorkId_maybe v, dataConRepArity data_con == length args_r_to_l = do -- Special case for a non-recursive let whose RHS is a -- saturatred constructor application. -- Just allocate the constructor and carry on alloc_code <- mkConAppCode d s p data_con args_r_to_l body_code <- schemeE (d+1) s (Map.insert x d p) body return (alloc_code `appOL` body_code) -- General case for let. Generates correct, if inefficient, code in -- all situations. schemeE d s p (AnnLet binds (_,body)) = do dflags <- getDynFlags let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs]) AnnRec xs_n_rhss -> unzip xs_n_rhss n_binds = genericLength xs fvss = map (fvsToEnv p' . fst) rhss -- Sizes of free vars sizes = map (\rhs_fvs -> sum (map (fromIntegral . idSizeW dflags) rhs_fvs)) fvss -- the arity of each rhs arities = map (genericLength . fst . collect) rhss -- This p', d' defn is safe because all the items being pushed -- are ptrs, so all have size 1. d' and p' reflect the stack -- after the closures have been allocated in the heap (but not -- filled in), and pointers to them parked on the stack. p' = Map.insertList (zipE xs (mkStackOffsets d (genericReplicate n_binds 1))) p d' = d + fromIntegral n_binds zipE = zipEqual "schemeE" -- ToDo: don't build thunks for things with no free variables build_thunk _ [] size bco off arity = return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size)) where mkap | arity == 0 = MKAP | otherwise = MKPAP build_thunk dd (fv:fvs) size bco off arity = do (push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv) more_push_code <- build_thunk (dd + fromIntegral pushed_szw) fvs size bco off arity return (push_code `appOL` more_push_code) alloc_code = toOL (zipWith mkAlloc sizes arities) where mkAlloc sz 0 | is_tick = ALLOC_AP_NOUPD sz | otherwise = ALLOC_AP sz mkAlloc sz arity = ALLOC_PAP arity sz is_tick = case binds of AnnNonRec id _ -> occNameFS (getOccName id) == tickFS _other -> False compile_bind d' fvs x rhs size arity off = do bco <- schemeR fvs (x,rhs) build_thunk d' fvs size bco off arity compile_binds = [ compile_bind d' fvs x rhs size arity n | (fvs, x, rhs, size, arity, n) <- zip6 fvss xs rhss sizes arities [n_binds, n_binds-1 .. 1] ] body_code <- schemeE d' s p' body thunk_codes <- sequence compile_binds return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code) -- introduce a let binding for a ticked case expression. This rule -- *should* only fire when the expression was not already let-bound -- (the code gen for let bindings should take care of that). Todo: we -- call exprFreeVars on a deAnnotated expression, this may not be the -- best way to calculate the free vars but it seemed like the least -- intrusive thing to do schemeE d s p exp@(AnnTick (Breakpoint _id _fvs) _rhs) = if isUnLiftedType ty then do -- If the result type is unlifted, then we must generate -- let f = \s . tick<n> e -- in f realWorld# -- When we stop at the breakpoint, _result will have an unlifted -- type and hence won't be bound in the environment, but the -- breakpoint will otherwise work fine. id <- newId (mkFunTy realWorldStatePrimTy ty) st <- newId realWorldStatePrimTy let letExp = AnnLet (AnnNonRec id (fvs, AnnLam st (emptyVarSet, exp))) (emptyVarSet, (AnnApp (emptyVarSet, AnnVar id) (emptyVarSet, AnnVar realWorldPrimId))) schemeE d s p letExp else do id <- newId ty -- Todo: is emptyVarSet correct on the next line? let letExp = AnnLet (AnnNonRec id (fvs, exp)) (emptyVarSet, AnnVar id) schemeE d s p letExp where exp' = deAnnotate' exp fvs = exprFreeVars exp' ty = exprType exp' -- ignore other kinds of tick schemeE d s p (AnnTick _ (_, rhs)) = schemeE d s p rhs schemeE d s p (AnnCase (_,scrut) _ _ []) = schemeE d s p scrut -- no alts: scrut is guaranteed to diverge schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1, bind2], rhs)]) | isUnboxedTupleCon dc , UnaryRep rep_ty1 <- repType (idType bind1), UnaryRep rep_ty2 <- repType (idType bind2) -- Convert -- case .... of x { (# V'd-thing, a #) -> ... } -- to -- case .... of a { DEFAULT -> ... } -- becuse the return convention for both are identical. -- -- Note that it does not matter losing the void-rep thing from the -- envt (it won't be bound now) because we never look such things up. , Just res <- case () of _ | VoidRep <- typePrimRep rep_ty1 -> Just $ doCase d s p scrut bind2 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} | VoidRep <- typePrimRep rep_ty2 -> Just $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} | otherwise -> Nothing = res schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1], rhs)]) | isUnboxedTupleCon dc, UnaryRep _ <- repType (idType bind1) -- Similarly, convert -- case .... of x { (# a #) -> ... } -- to -- case .... of a { DEFAULT -> ... } = --trace "automagic mashing of case alts (# a #)" $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} schemeE d s p (AnnCase scrut bndr _ [(DEFAULT, [], rhs)]) | Just (tc, tys) <- splitTyConApp_maybe (idType bndr) , isUnboxedTupleTyCon tc , Just res <- case tys of [ty] | UnaryRep _ <- repType ty , let bind = bndr `setIdType` ty -> Just $ doCase d s p scrut bind [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} [ty1, ty2] | UnaryRep rep_ty1 <- repType ty1 , UnaryRep rep_ty2 <- repType ty2 -> case () of _ | VoidRep <- typePrimRep rep_ty1 , let bind2 = bndr `setIdType` ty2 -> Just $ doCase d s p scrut bind2 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} | VoidRep <- typePrimRep rep_ty2 , let bind1 = bndr `setIdType` ty1 -> Just $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-} | otherwise -> Nothing _ -> Nothing = res schemeE d s p (AnnCase scrut bndr _ alts) = doCase d s p scrut bndr alts Nothing{-not an unboxed tuple-} schemeE _ _ _ expr = pprPanic "ByteCodeGen.schemeE: unhandled case" (pprCoreExpr (deAnnotate' expr)) {- Ticked Expressions ------------------ The idea is that the "breakpoint<n,fvs> E" is really just an annotation on the code. When we find such a thing, we pull out the useful information, and then compile the code as if it was just the expression E. -} -- Compile code to do a tail call. Specifically, push the fn, -- slide the on-stack app back down to the sequel depth, -- and enter. Four cases: -- -- 0. (Nasty hack). -- An application "GHC.Prim.tagToEnum# <type> unboxed-int". -- The int will be on the stack. Generate a code sequence -- to convert it to the relevant constructor, SLIDE and ENTER. -- -- 1. The fn denotes a ccall. Defer to generateCCall. -- -- 2. (Another nasty hack). Spot (# a::V, b #) and treat -- it simply as b -- since the representations are identical -- (the V takes up zero stack space). Also, spot -- (# b #) and treat it as b. -- -- 3. Application of a constructor, by defn saturated. -- Split the args into ptrs and non-ptrs, and push the nonptrs, -- then the ptrs, and then do PACK and RETURN. -- -- 4. Otherwise, it must be a function call. Push the args -- right to left, SLIDE and ENTER. schemeT :: Word -- Stack depth -> Sequel -- Sequel depth -> BCEnv -- stack env -> AnnExpr' Id VarSet -> BcM BCInstrList schemeT d s p app -- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False -- = panic "schemeT ?!?!" -- | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False -- = error "?!?!" -- Case 0 | Just (arg, constr_names) <- maybe_is_tagToEnum_call app = implement_tagToId d s p arg constr_names -- Case 1 | Just (CCall ccall_spec) <- isFCallId_maybe fn = generateCCall d s p ccall_spec fn args_r_to_l -- Case 2: Constructor application | Just con <- maybe_saturated_dcon, isUnboxedTupleCon con = case args_r_to_l of [arg1,arg2] | isVAtom arg1 -> unboxedTupleReturn d s p arg2 [arg1,arg2] | isVAtom arg2 -> unboxedTupleReturn d s p arg1 _other -> unboxedTupleException -- Case 3: Ordinary data constructor | Just con <- maybe_saturated_dcon = do alloc_con <- mkConAppCode d s p con args_r_to_l return (alloc_con `appOL` mkSLIDE 1 (d - s) `snocOL` ENTER) -- Case 4: Tail call of function | otherwise = doTailCall d s p fn args_r_to_l where -- Extract the args (R->L) and fn -- The function will necessarily be a variable, -- because we are compiling a tail call (AnnVar fn, args_r_to_l) = splitApp app -- Only consider this to be a constructor application iff it is -- saturated. Otherwise, we'll call the constructor wrapper. n_args = length args_r_to_l maybe_saturated_dcon = case isDataConWorkId_maybe fn of Just con | dataConRepArity con == n_args -> Just con _ -> Nothing -- ----------------------------------------------------------------------------- -- Generate code to build a constructor application, -- leaving it on top of the stack mkConAppCode :: Word -> Sequel -> BCEnv -> DataCon -- The data constructor -> [AnnExpr' Id VarSet] -- Args, in *reverse* order -> BcM BCInstrList mkConAppCode _ _ _ con [] -- Nullary constructor = ASSERT( isNullaryRepDataCon con ) return (unitOL (PUSH_G (getName (dataConWorkId con)))) -- Instead of doing a PACK, which would allocate a fresh -- copy of this constructor, use the single shared version. mkConAppCode orig_d _ p con args_r_to_l = ASSERT( dataConRepArity con == length args_r_to_l ) do_pushery orig_d (non_ptr_args ++ ptr_args) where -- The args are already in reverse order, which is the way PACK -- expects them to be. We must push the non-ptrs after the ptrs. (ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l do_pushery d (arg:args) = do (push, arg_words) <- pushAtom d p arg more_push_code <- do_pushery (d + fromIntegral arg_words) args return (push `appOL` more_push_code) do_pushery d [] = return (unitOL (PACK con n_arg_words)) where n_arg_words = trunc16 $ d - orig_d -- ----------------------------------------------------------------------------- -- Returning an unboxed tuple with one non-void component (the only -- case we can handle). -- -- Remember, we don't want to *evaluate* the component that is being -- returned, even if it is a pointed type. We always just return. unboxedTupleReturn :: Word -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList unboxedTupleReturn d s p arg = returnUnboxedAtom d s p arg (atomRep arg) -- ----------------------------------------------------------------------------- -- Generate code for a tail-call doTailCall :: Word -> Sequel -> BCEnv -> Id -> [AnnExpr' Id VarSet] -> BcM BCInstrList doTailCall init_d s p fn args = do_pushes init_d args (map atomRep args) where do_pushes d [] reps = do ASSERT( null reps ) return () (push_fn, sz) <- pushAtom d p (AnnVar fn) ASSERT( sz == 1 ) return () return (push_fn `appOL` ( mkSLIDE (trunc16 $ d - init_d + 1) (init_d - s) `appOL` unitOL ENTER)) do_pushes d args reps = do let (push_apply, n, rest_of_reps) = findPushSeq reps (these_args, rest_of_args) = splitAt n args (next_d, push_code) <- push_seq d these_args instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps -- ^^^ for the PUSH_APPLY_ instruction return (push_code `appOL` (push_apply `consOL` instrs)) push_seq d [] = return (d, nilOL) push_seq d (arg:args) = do (push_code, sz) <- pushAtom d p arg (final_d, more_push_code) <- push_seq (d + fromIntegral sz) args return (final_d, push_code `appOL` more_push_code) -- v. similar to CgStackery.findMatch, ToDo: merge findPushSeq :: [ArgRep] -> (BCInstr, Int, [ArgRep]) findPushSeq (P: P: P: P: P: P: rest) = (PUSH_APPLY_PPPPPP, 6, rest) findPushSeq (P: P: P: P: P: rest) = (PUSH_APPLY_PPPPP, 5, rest) findPushSeq (P: P: P: P: rest) = (PUSH_APPLY_PPPP, 4, rest) findPushSeq (P: P: P: rest) = (PUSH_APPLY_PPP, 3, rest) findPushSeq (P: P: rest) = (PUSH_APPLY_PP, 2, rest) findPushSeq (P: rest) = (PUSH_APPLY_P, 1, rest) findPushSeq (V: rest) = (PUSH_APPLY_V, 1, rest) findPushSeq (N: rest) = (PUSH_APPLY_N, 1, rest) findPushSeq (F: rest) = (PUSH_APPLY_F, 1, rest) findPushSeq (D: rest) = (PUSH_APPLY_D, 1, rest) findPushSeq (L: rest) = (PUSH_APPLY_L, 1, rest) findPushSeq _ = panic "ByteCodeGen.findPushSeq" -- ----------------------------------------------------------------------------- -- Case expressions doCase :: Word -> Sequel -> BCEnv -> AnnExpr Id VarSet -> Id -> [AnnAlt Id VarSet] -> Maybe Id -- Just x <=> is an unboxed tuple case with scrut binder, don't enter the result -> BcM BCInstrList doCase d s p (_,scrut) bndr alts is_unboxed_tuple | UbxTupleRep _ <- repType (idType bndr) = unboxedTupleException | otherwise = do dflags <- getDynFlags let -- Top of stack is the return itbl, as usual. -- underneath it is the pointer to the alt_code BCO. -- When an alt is entered, it assumes the returned value is -- on top of the itbl. ret_frame_sizeW :: Word ret_frame_sizeW = 2 -- An unlifted value gets an extra info table pushed on top -- when it is returned. unlifted_itbl_sizeW :: Word unlifted_itbl_sizeW | isAlgCase = 0 | otherwise = 1 -- depth of stack after the return value has been pushed d_bndr = d + ret_frame_sizeW + fromIntegral (idSizeW dflags bndr) -- depth of stack after the extra info table for an unboxed return -- has been pushed, if any. This is the stack depth at the -- continuation. d_alts = d_bndr + unlifted_itbl_sizeW -- Env in which to compile the alts, not including -- any vars bound by the alts themselves d_bndr' = fromIntegral d_bndr - 1 p_alts0 = Map.insert bndr d_bndr' p p_alts = case is_unboxed_tuple of Just ubx_bndr -> Map.insert ubx_bndr d_bndr' p_alts0 Nothing -> p_alts0 bndr_ty = idType bndr isAlgCase = not (isUnLiftedType bndr_ty) && isNothing is_unboxed_tuple -- given an alt, return a discr and code for it. codeAlt (DEFAULT, _, (_,rhs)) = do rhs_code <- schemeE d_alts s p_alts rhs return (NoDiscr, rhs_code) codeAlt alt@(_, bndrs, (_,rhs)) -- primitive or nullary constructor alt: no need to UNPACK | null real_bndrs = do rhs_code <- schemeE d_alts s p_alts rhs return (my_discr alt, rhs_code) | any (\bndr -> case repType (idType bndr) of UbxTupleRep _ -> True; _ -> False) bndrs = unboxedTupleException -- algebraic alt with some binders | otherwise = let (ptrs,nptrs) = partition (isFollowableArg.bcIdArgRep) real_bndrs ptr_sizes = map (fromIntegral . idSizeW dflags) ptrs nptrs_sizes = map (fromIntegral . idSizeW dflags) nptrs bind_sizes = ptr_sizes ++ nptrs_sizes size = sum ptr_sizes + sum nptrs_sizes -- the UNPACK instruction unpacks in reverse order... p' = Map.insertList (zip (reverse (ptrs ++ nptrs)) (mkStackOffsets d_alts (reverse bind_sizes))) p_alts in do MASSERT(isAlgCase) rhs_code <- schemeE (d_alts + size) s p' rhs return (my_discr alt, unitOL (UNPACK (trunc16 size)) `appOL` rhs_code) where real_bndrs = filterOut isTyVar bndrs my_discr (DEFAULT, _, _) = NoDiscr {-shouldn't really happen-} my_discr (DataAlt dc, _, _) | isUnboxedTupleCon dc = unboxedTupleException | otherwise = DiscrP (fromIntegral (dataConTag dc - fIRST_TAG)) my_discr (LitAlt l, _, _) = case l of MachInt i -> DiscrI (fromInteger i) MachWord w -> DiscrW (fromInteger w) MachFloat r -> DiscrF (fromRational r) MachDouble r -> DiscrD (fromRational r) MachChar i -> DiscrI (ord i) _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l) maybe_ncons | not isAlgCase = Nothing | otherwise = case [dc | (DataAlt dc, _, _) <- alts] of [] -> Nothing (dc:_) -> Just (tyConFamilySize (dataConTyCon dc)) -- the bitmap is relative to stack depth d, i.e. before the -- BCO, info table and return value are pushed on. -- This bit of code is v. similar to buildLivenessMask in CgBindery, -- except that here we build the bitmap from the known bindings of -- things that are pointers, whereas in CgBindery the code builds the -- bitmap from the free slots and unboxed bindings. -- (ToDo: merge?) -- -- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002. -- The bitmap must cover the portion of the stack up to the sequel only. -- Previously we were building a bitmap for the whole depth (d), but we -- really want a bitmap up to depth (d-s). This affects compilation of -- case-of-case expressions, which is the only time we can be compiling a -- case expression with s /= 0. bitmap_size = trunc16 $ d-s bitmap_size' :: Int bitmap_size' = fromIntegral bitmap_size bitmap = intsToReverseBitmap dflags bitmap_size'{-size-} (sort (filter (< bitmap_size') rel_slots)) where binds = Map.toList p -- NB: unboxed tuple cases bind the scrut binder to the same offset -- as one of the alt binders, so we have to remove any duplicates here: rel_slots = nub $ map fromIntegral $ concat (map spread binds) spread (id, offset) | isFollowableArg (bcIdArgRep id) = [ rel_offset ] | otherwise = [] where rel_offset = trunc16 $ d - fromIntegral offset - 1 alt_stuff <- mapM codeAlt alts alt_final <- mkMultiBranch maybe_ncons alt_stuff let alt_bco_name = getName bndr alt_bco = mkProtoBCO dflags alt_bco_name alt_final (Left alts) 0{-no arity-} bitmap_size bitmap True{-is alts-} -- trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++ -- "\n bitmap = " ++ show bitmap) $ do scrut_code <- schemeE (d + ret_frame_sizeW) (d + ret_frame_sizeW) p scrut alt_bco' <- emitBc alt_bco let push_alts | isAlgCase = PUSH_ALTS alt_bco' | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeArgRep bndr_ty) return (push_alts `consOL` scrut_code) -- ----------------------------------------------------------------------------- -- Deal with a CCall. -- Taggedly push the args onto the stack R->L, -- deferencing ForeignObj#s and adjusting addrs to point to -- payloads in Ptr/Byte arrays. Then, generate the marshalling -- (machine) code for the ccall, and create bytecodes to call that and -- then return in the right way. generateCCall :: Word -> Sequel -- stack and sequel depths -> BCEnv -> CCallSpec -- where to call -> Id -- of target, for type info -> [AnnExpr' Id VarSet] -- args (atoms) -> BcM BCInstrList generateCCall d0 s p (CCallSpec target cconv safety) fn args_r_to_l = do dflags <- getDynFlags let -- useful constants addr_sizeW :: Word16 addr_sizeW = fromIntegral (argRepSizeW dflags N) -- Get the args on the stack, with tags and suitably -- dereferenced for the CCall. For each arg, return the -- depth to the first word of the bits for that arg, and the -- ArgRep of what was actually pushed. pargs _ [] = return [] pargs d (a:az) = let UnaryRep arg_ty = repType (exprType (deAnnotate' a)) in case tyConAppTyCon_maybe arg_ty of -- Don't push the FO; instead push the Addr# it -- contains. Just t | t == arrayPrimTyCon || t == mutableArrayPrimTyCon -> do rest <- pargs (d + fromIntegral addr_sizeW) az code <- parg_ArrayishRep (fromIntegral (arrPtrsHdrSize dflags)) d p a return ((code,AddrRep):rest) | t == smallArrayPrimTyCon || t == smallMutableArrayPrimTyCon -> do rest <- pargs (d + fromIntegral addr_sizeW) az code <- parg_ArrayishRep (fromIntegral (smallArrPtrsHdrSize dflags)) d p a return ((code,AddrRep):rest) | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon -> do rest <- pargs (d + fromIntegral addr_sizeW) az code <- parg_ArrayishRep (fromIntegral (arrWordsHdrSize dflags)) d p a return ((code,AddrRep):rest) -- Default case: push taggedly, but otherwise intact. _ -> do (code_a, sz_a) <- pushAtom d p a rest <- pargs (d + fromIntegral sz_a) az return ((code_a, atomPrimRep a) : rest) -- Do magic for Ptr/Byte arrays. Push a ptr to the array on -- the stack but then advance it over the headers, so as to -- point to the payload. parg_ArrayishRep :: Word16 -> Word -> BCEnv -> AnnExpr' Id VarSet -> BcM BCInstrList parg_ArrayishRep hdrSize d p a = do (push_fo, _) <- pushAtom d p a -- The ptr points at the header. Advance it over the -- header and then pretend this is an Addr#. return (push_fo `snocOL` SWIZZLE 0 hdrSize) code_n_reps <- pargs d0 args_r_to_l let (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps a_reps_sizeW = fromIntegral (sum (map (primRepSizeW dflags) a_reps_pushed_r_to_l)) push_args = concatOL pushs_arg d_after_args = d0 + a_reps_sizeW a_reps_pushed_RAW | null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidRep = panic "ByteCodeGen.generateCCall: missing or invalid World token?" | otherwise = reverse (tail a_reps_pushed_r_to_l) -- Now: a_reps_pushed_RAW are the reps which are actually on the stack. -- push_args is the code to do that. -- d_after_args is the stack depth once the args are on. -- Get the result rep. (returns_void, r_rep) = case maybe_getCCallReturnRep (idType fn) of Nothing -> (True, VoidRep) Just rr -> (False, rr) {- Because the Haskell stack grows down, the a_reps refer to lowest to highest addresses in that order. The args for the call are on the stack. Now push an unboxed Addr# indicating the C function to call. Then push a dummy placeholder for the result. Finally, emit a CCALL insn with an offset pointing to the Addr# just pushed, and a literal field holding the mallocville address of the piece of marshalling code we generate. So, just prior to the CCALL insn, the stack looks like this (growing down, as usual): <arg_n> ... <arg_1> Addr# address_of_C_fn <placeholder-for-result#> (must be an unboxed type) The interpreter then calls the marshall code mentioned in the CCALL insn, passing it (& <placeholder-for-result#>), that is, the addr of the topmost word in the stack. When this returns, the placeholder will have been filled in. The placeholder is slid down to the sequel depth, and we RETURN. This arrangement makes it simple to do f-i-dynamic since the Addr# value is the first arg anyway. The marshalling code is generated specifically for this call site, and so knows exactly the (Haskell) stack offsets of the args, fn address and placeholder. It copies the args to the C stack, calls the stacked addr, and parks the result back in the placeholder. The interpreter calls it as a normal C call, assuming it has a signature void marshall_code ( StgWord* ptr_to_top_of_stack ) -} -- resolve static address get_target_info = do case target of DynamicTarget -> return (False, panic "ByteCodeGen.generateCCall(dyn)") StaticTarget _ _ _ False -> panic "generateCCall: unexpected FFI value import" StaticTarget _ target _ True -> do res <- ioToBc (lookupStaticPtr stdcall_adj_target) return (True, res) where stdcall_adj_target | OSMinGW32 <- platformOS (targetPlatform dflags) , StdCallConv <- cconv = let size = fromIntegral a_reps_sizeW * wORD_SIZE dflags in mkFastString (unpackFS target ++ '@':show size) | otherwise = target (is_static, static_target_addr) <- get_target_info let -- Get the arg reps, zapping the leading Addr# in the dynamic case a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???" | is_static = a_reps_pushed_RAW | otherwise = if null a_reps_pushed_RAW then panic "ByteCodeGen.generateCCall: dyn with no args" else tail a_reps_pushed_RAW -- push the Addr# (push_Addr, d_after_Addr) | is_static = (toOL [PUSH_UBX (Right static_target_addr) addr_sizeW], d_after_args + fromIntegral addr_sizeW) | otherwise -- is already on the stack = (nilOL, d_after_args) -- Push the return placeholder. For a call returning nothing, -- this is a V (tag). r_sizeW = fromIntegral (primRepSizeW dflags r_rep) d_after_r = d_after_Addr + fromIntegral r_sizeW r_lit = mkDummyLiteral r_rep push_r = (if returns_void then nilOL else unitOL (PUSH_UBX (Left r_lit) r_sizeW)) -- generate the marshalling code we're going to call -- Offset of the next stack frame down the stack. The CCALL -- instruction needs to describe the chunk of stack containing -- the ccall args to the GC, so it needs to know how large it -- is. See comment in Interpreter.c with the CCALL instruction. stk_offset = trunc16 $ d_after_r - s -- the only difference in libffi mode is that we prepare a cif -- describing the call type by calling libffi, and we attach the -- address of this to the CCALL instruction. token <- ioToBc $ prepForeignCall dflags cconv a_reps r_rep let addr_of_marshaller = castPtrToFunPtr token recordItblMallocBc (ItblPtr (castFunPtrToPtr addr_of_marshaller)) let -- do the call do_call = unitOL (CCALL stk_offset (castFunPtrToPtr addr_of_marshaller) (fromIntegral (fromEnum (playInterruptible safety)))) -- slide and return wrapup = mkSLIDE r_sizeW (d_after_r - fromIntegral r_sizeW - s) `snocOL` RETURN_UBX (toArgRep r_rep) --trace (show (arg1_offW, args_offW , (map argRepSizeW a_reps) )) $ return ( push_args `appOL` push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup ) -- Make a dummy literal, to be used as a placeholder for FFI return -- values on the stack. mkDummyLiteral :: PrimRep -> Literal mkDummyLiteral pr = case pr of IntRep -> MachInt 0 WordRep -> MachWord 0 AddrRep -> MachNullAddr DoubleRep -> MachDouble 0 FloatRep -> MachFloat 0 Int64Rep -> MachInt64 0 Word64Rep -> MachWord64 0 _ -> panic "mkDummyLiteral" -- Convert (eg) -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld -- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #) -- -- to Just IntRep -- and check that an unboxed pair is returned wherein the first arg is V'd. -- -- Alternatively, for call-targets returning nothing, convert -- -- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld -- -> (# GHC.Prim.State# GHC.Prim.RealWorld #) -- -- to Nothing maybe_getCCallReturnRep :: Type -> Maybe PrimRep maybe_getCCallReturnRep fn_ty = let (_a_tys, r_ty) = splitFunTys (dropForAlls fn_ty) maybe_r_rep_to_go = if isSingleton r_reps then Nothing else Just (r_reps !! 1) r_reps = case repType r_ty of UbxTupleRep reps -> map typePrimRep reps UnaryRep _ -> blargh ok = ( ( r_reps `lengthIs` 2 && VoidRep == head r_reps) || r_reps == [VoidRep] ) && case maybe_r_rep_to_go of Nothing -> True Just r_rep -> r_rep /= PtrRep -- if it was, it would be impossible -- to create a valid return value -- placeholder on the stack blargh :: a -- Used at more than one type blargh = pprPanic "maybe_getCCallReturn: can't handle:" (pprType fn_ty) in --trace (showSDoc (ppr (a_reps, r_reps))) $ if ok then maybe_r_rep_to_go else blargh maybe_is_tagToEnum_call :: AnnExpr' Id VarSet -> Maybe (AnnExpr' Id VarSet, [Name]) -- Detect and extract relevant info for the tagToEnum kludge. maybe_is_tagToEnum_call app | AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg <- app , Just TagToEnumOp <- isPrimOpId_maybe v = Just (snd arg, extract_constr_Names t) | otherwise = Nothing where extract_constr_Names ty | UnaryRep rep_ty <- repType ty , Just tyc <- tyConAppTyCon_maybe rep_ty, isDataTyCon tyc = map (getName . dataConWorkId) (tyConDataCons tyc) -- NOTE: use the worker name, not the source name of -- the DataCon. See DataCon.hs for details. | otherwise = pprPanic "maybe_is_tagToEnum_call.extract_constr_Ids" (ppr ty) {- ----------------------------------------------------------------------------- Note [Implementing tagToEnum#] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (implement_tagToId arg names) compiles code which takes an argument 'arg', (call it i), and enters the i'th closure in the supplied list as a consequence. The [Name] is a list of the constructors of this (enumeration) type. The code we generate is this: push arg push bogus-word TESTEQ_I 0 L1 PUSH_G <lbl for first data con> JMP L_Exit L1: TESTEQ_I 1 L2 PUSH_G <lbl for second data con> JMP L_Exit ...etc... Ln: TESTEQ_I n L_fail PUSH_G <lbl for last data con> JMP L_Exit L_fail: CASEFAIL L_exit: SLIDE 1 n ENTER The 'bogus-word' push is because TESTEQ_I expects the top of the stack to have an info-table, and the next word to have the value to be tested. This is very weird, but it's the way it is right now. See Interpreter.c. We don't acutally need an info-table here; we just need to have the argument to be one-from-top on the stack, hence pushing a 1-word null. See Trac #8383. -} implement_tagToId :: Word -> Sequel -> BCEnv -> AnnExpr' Id VarSet -> [Name] -> BcM BCInstrList -- See Note [Implementing tagToEnum#] implement_tagToId d s p arg names = ASSERT( notNull names ) do (push_arg, arg_words) <- pushAtom d p arg labels <- getLabelsBc (genericLength names) label_fail <- getLabelBc label_exit <- getLabelBc let infos = zip4 labels (tail labels ++ [label_fail]) [0 ..] names steps = map (mkStep label_exit) infos return (push_arg `appOL` unitOL (PUSH_UBX (Left MachNullAddr) 1) -- Push bogus word (see Note [Implementing tagToEnum#]) `appOL` concatOL steps `appOL` toOL [ LABEL label_fail, CASEFAIL, LABEL label_exit ] `appOL` mkSLIDE 1 (d - s + fromIntegral arg_words + 1) -- "+1" to account for bogus word -- (see Note [Implementing tagToEnum#]) `appOL` unitOL ENTER) where mkStep l_exit (my_label, next_label, n, name_for_n) = toOL [LABEL my_label, TESTEQ_I n next_label, PUSH_G name_for_n, JMP l_exit] -- ----------------------------------------------------------------------------- -- pushAtom -- Push an atom onto the stack, returning suitable code & number of -- stack words used. -- -- The env p must map each variable to the highest- numbered stack -- slot for it. For example, if the stack has depth 4 and we -- tagged-ly push (v :: Int#) on it, the value will be in stack[4], -- the tag in stack[5], the stack will have depth 6, and p must map v -- to 5 and not to 4. Stack locations are numbered from zero, so a -- depth 6 stack has valid words 0 .. 5. pushAtom :: Word -> BCEnv -> AnnExpr' Id VarSet -> BcM (BCInstrList, Word16) pushAtom d p e | Just e' <- bcView e = pushAtom d p e' pushAtom _ _ (AnnCoercion {}) -- Coercions are zero-width things, = return (nilOL, 0) -- treated just like a variable V pushAtom d p (AnnVar v) | UnaryRep rep_ty <- repType (idType v) , V <- typeArgRep rep_ty = return (nilOL, 0) | isFCallId v = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v) | Just primop <- isPrimOpId_maybe v = return (unitOL (PUSH_PRIMOP primop), 1) | Just d_v <- lookupBCEnv_maybe v p -- v is a local variable = do dflags <- getDynFlags let sz :: Word16 sz = fromIntegral (idSizeW dflags v) l = trunc16 $ d - d_v + fromIntegral sz - 2 return (toOL (genericReplicate sz (PUSH_L l)), sz) -- d - d_v the number of words between the TOS -- and the 1st slot of the object -- -- d - d_v - 1 the offset from the TOS of the 1st slot -- -- d - d_v - 1 + sz - 1 the offset from the TOS of the last slot -- of the object. -- -- Having found the last slot, we proceed to copy the right number of -- slots on to the top of the stack. | otherwise -- v must be a global variable = do dflags <- getDynFlags let sz :: Word16 sz = fromIntegral (idSizeW dflags v) MASSERT(sz == 1) return (unitOL (PUSH_G (getName v)), sz) pushAtom _ _ (AnnLit lit) = do dflags <- getDynFlags let code rep = let size_host_words = fromIntegral (argRepSizeW dflags rep) in return (unitOL (PUSH_UBX (Left lit) size_host_words), size_host_words) case lit of MachLabel _ _ _ -> code N MachWord _ -> code N MachInt _ -> code N MachWord64 _ -> code L MachInt64 _ -> code L MachFloat _ -> code F MachDouble _ -> code D MachChar _ -> code N MachNullAddr -> code N MachStr s -> pushStr s -- No LitInteger's should be left by the time this is called. -- CorePrep should have converted them all to a real core -- representation. LitInteger {} -> panic "pushAtom: LitInteger" where pushStr s = let getMallocvilleAddr = -- we could grab the Ptr from the ForeignPtr, -- but then we have no way to control its lifetime. -- In reality it'll probably stay alive long enoungh -- by virtue of the global FastString table, but -- to be on the safe side we copy the string into -- a malloc'd area of memory. do let n = BS.length s ptr <- ioToBc (mallocBytes (n+1)) recordMallocBc ptr ioToBc ( BS.unsafeUseAsCString s $ \p -> do memcpy ptr p (fromIntegral n) pokeByteOff ptr n (fromIntegral (ord '\0') :: Word8) return ptr ) in do addr <- getMallocvilleAddr -- Get the addr on the stack, untaggedly return (unitOL (PUSH_UBX (Right addr) 1), 1) pushAtom _ _ expr = pprPanic "ByteCodeGen.pushAtom" (pprCoreExpr (deAnnotate (undefined, expr))) foreign import ccall unsafe "memcpy" memcpy :: Ptr a -> Ptr b -> CSize -> IO () -- ----------------------------------------------------------------------------- -- Given a bunch of alts code and their discrs, do the donkey work -- of making a multiway branch using a switch tree. -- What a load of hassle! mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt -- a hint; generates better code -- Nothing is always safe -> [(Discr, BCInstrList)] -> BcM BCInstrList mkMultiBranch maybe_ncons raw_ways = do lbl_default <- getLabelBc let mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList mkTree [] _range_lo _range_hi = return (unitOL (JMP lbl_default)) -- shouldn't happen? mkTree [val] range_lo range_hi | range_lo == range_hi = return (snd val) | null defaults -- Note [CASEFAIL] = do lbl <- getLabelBc return (testEQ (fst val) lbl `consOL` (snd val `appOL` (LABEL lbl `consOL` unitOL CASEFAIL))) | otherwise = return (testEQ (fst val) lbl_default `consOL` snd val) -- Note [CASEFAIL] It may be that this case has no default -- branch, but the alternatives are not exhaustive - this -- happens for GADT cases for example, where the types -- prove that certain branches are impossible. We could -- just assume that the other cases won't occur, but if -- this assumption was wrong (because of a bug in GHC) -- then the result would be a segfault. So instead we -- emit an explicit test and a CASEFAIL instruction that -- causes the interpreter to barf() if it is ever -- executed. mkTree vals range_lo range_hi = let n = length vals `div` 2 vals_lo = take n vals vals_hi = drop n vals v_mid = fst (head vals_hi) in do label_geq <- getLabelBc code_lo <- mkTree vals_lo range_lo (dec v_mid) code_hi <- mkTree vals_hi v_mid range_hi return (testLT v_mid label_geq `consOL` (code_lo `appOL` unitOL (LABEL label_geq) `appOL` code_hi)) the_default = case defaults of [] -> nilOL [(_, def)] -> LABEL lbl_default `consOL` def _ -> panic "mkMultiBranch/the_default" instrs <- mkTree notd_ways init_lo init_hi return (instrs `appOL` the_default) where (defaults, not_defaults) = partition (isNoDiscr.fst) raw_ways notd_ways = sortBy (comparing fst) not_defaults testLT (DiscrI i) fail_label = TESTLT_I i fail_label testLT (DiscrW i) fail_label = TESTLT_W i fail_label testLT (DiscrF i) fail_label = TESTLT_F i fail_label testLT (DiscrD i) fail_label = TESTLT_D i fail_label testLT (DiscrP i) fail_label = TESTLT_P i fail_label testLT NoDiscr _ = panic "mkMultiBranch NoDiscr" testEQ (DiscrI i) fail_label = TESTEQ_I i fail_label testEQ (DiscrW i) fail_label = TESTEQ_W i fail_label testEQ (DiscrF i) fail_label = TESTEQ_F i fail_label testEQ (DiscrD i) fail_label = TESTEQ_D i fail_label testEQ (DiscrP i) fail_label = TESTEQ_P i fail_label testEQ NoDiscr _ = panic "mkMultiBranch NoDiscr" -- None of these will be needed if there are no non-default alts (init_lo, init_hi) | null notd_ways = panic "mkMultiBranch: awesome foursome" | otherwise = case fst (head notd_ways) of DiscrI _ -> ( DiscrI minBound, DiscrI maxBound ) DiscrW _ -> ( DiscrW minBound, DiscrW maxBound ) DiscrF _ -> ( DiscrF minF, DiscrF maxF ) DiscrD _ -> ( DiscrD minD, DiscrD maxD ) DiscrP _ -> ( DiscrP algMinBound, DiscrP algMaxBound ) NoDiscr -> panic "mkMultiBranch NoDiscr" (algMinBound, algMaxBound) = case maybe_ncons of -- XXX What happens when n == 0? Just n -> (0, fromIntegral n - 1) Nothing -> (minBound, maxBound) isNoDiscr NoDiscr = True isNoDiscr _ = False dec (DiscrI i) = DiscrI (i-1) dec (DiscrW w) = DiscrW (w-1) dec (DiscrP i) = DiscrP (i-1) dec other = other -- not really right, but if you -- do cases on floating values, you'll get what you deserve -- same snotty comment applies to the following minF, maxF :: Float minD, maxD :: Double minF = -1.0e37 maxF = 1.0e37 minD = -1.0e308 maxD = 1.0e308 -- ----------------------------------------------------------------------------- -- Supporting junk for the compilation schemes -- Describes case alts data Discr = DiscrI Int | DiscrW Word | DiscrF Float | DiscrD Double | DiscrP Word16 | NoDiscr deriving (Eq, Ord) instance Outputable Discr where ppr (DiscrI i) = int i ppr (DiscrW w) = text (show w) ppr (DiscrF f) = text (show f) ppr (DiscrD d) = text (show d) ppr (DiscrP i) = ppr i ppr NoDiscr = text "DEF" lookupBCEnv_maybe :: Id -> BCEnv -> Maybe Word lookupBCEnv_maybe = Map.lookup idSizeW :: DynFlags -> Id -> Int idSizeW dflags = argRepSizeW dflags . bcIdArgRep bcIdArgRep :: Id -> ArgRep bcIdArgRep = toArgRep . bcIdPrimRep bcIdPrimRep :: Id -> PrimRep bcIdPrimRep = typePrimRep . bcIdUnaryType isFollowableArg :: ArgRep -> Bool isFollowableArg P = True isFollowableArg _ = False isVoidArg :: ArgRep -> Bool isVoidArg V = True isVoidArg _ = False bcIdUnaryType :: Id -> UnaryType bcIdUnaryType x = case repType (idType x) of UnaryRep rep_ty -> rep_ty UbxTupleRep [rep_ty] -> rep_ty UbxTupleRep [rep_ty1, rep_ty2] | VoidRep <- typePrimRep rep_ty1 -> rep_ty2 | VoidRep <- typePrimRep rep_ty2 -> rep_ty1 _ -> pprPanic "bcIdUnaryType" (ppr x $$ ppr (idType x)) -- See bug #1257 unboxedTupleException :: a unboxedTupleException = throwGhcException (ProgramError ("Error: bytecode compiler can't handle unboxed tuples.\n"++ " Possibly due to foreign import/export decls in source.\n"++ " Workaround: use -fobject-code, or compile this module to .o separately.")) mkSLIDE :: Word16 -> Word -> OrdList BCInstr mkSLIDE n d -- if the amount to slide doesn't fit in a word, -- generate multiple slide instructions | d > fromIntegral limit = SLIDE n limit `consOL` mkSLIDE n (d - fromIntegral limit) | d == 0 = nilOL | otherwise = if d == 0 then nilOL else unitOL (SLIDE n $ fromIntegral d) where limit :: Word16 limit = maxBound splitApp :: AnnExpr' Var ann -> (AnnExpr' Var ann, [AnnExpr' Var ann]) -- The arguments are returned in *right-to-left* order splitApp e | Just e' <- bcView e = splitApp e' splitApp (AnnApp (_,f) (_,a)) = case splitApp f of (f', as) -> (f', a:as) splitApp e = (e, []) bcView :: AnnExpr' Var ann -> Maybe (AnnExpr' Var ann) -- The "bytecode view" of a term discards -- a) type abstractions -- b) type applications -- c) casts -- d) ticks (but not breakpoints) -- Type lambdas *can* occur in random expressions, -- whereas value lambdas cannot; that is why they are nuked here bcView (AnnCast (_,e) _) = Just e bcView (AnnLam v (_,e)) | isTyVar v = Just e bcView (AnnApp (_,e) (_, AnnType _)) = Just e bcView (AnnTick Breakpoint{} _) = Nothing bcView (AnnTick _other_tick (_,e)) = Just e bcView _ = Nothing isVAtom :: AnnExpr' Var ann -> Bool isVAtom e | Just e' <- bcView e = isVAtom e' isVAtom (AnnVar v) = isVoidArg (bcIdArgRep v) isVAtom (AnnCoercion {}) = True isVAtom _ = False atomPrimRep :: AnnExpr' Id ann -> PrimRep atomPrimRep e | Just e' <- bcView e = atomPrimRep e' atomPrimRep (AnnVar v) = bcIdPrimRep v atomPrimRep (AnnLit l) = typePrimRep (literalType l) atomPrimRep (AnnCoercion {}) = VoidRep atomPrimRep other = pprPanic "atomPrimRep" (ppr (deAnnotate (undefined,other))) atomRep :: AnnExpr' Id ann -> ArgRep atomRep e = toArgRep (atomPrimRep e) isPtrAtom :: AnnExpr' Id ann -> Bool isPtrAtom e = isFollowableArg (atomRep e) -- Let szsw be the sizes in words of some items pushed onto the stack, -- which has initial depth d'. Return the values which the stack environment -- should map these items to. mkStackOffsets :: Word -> [Word] -> [Word] mkStackOffsets original_depth szsw = map (subtract 1) (tail (scanl (+) original_depth szsw)) typeArgRep :: Type -> ArgRep typeArgRep = toArgRep . typePrimRep -- ----------------------------------------------------------------------------- -- The bytecode generator's monad type BcPtr = Either ItblPtr (Ptr ()) data BcM_State = BcM_State { bcm_dflags :: DynFlags , uniqSupply :: UniqSupply -- for generating fresh variable names , thisModule :: Module -- current module (for breakpoints) , nextlabel :: Word16 -- for generating local labels , malloced :: [BcPtr] -- thunks malloced for current BCO -- Should be free()d when it is GCd , breakArray :: BreakArray -- array of breakpoint flags } newtype BcM r = BcM (BcM_State -> IO (BcM_State, r)) ioToBc :: IO a -> BcM a ioToBc io = BcM $ \st -> do x <- io return (st, x) runBc :: DynFlags -> UniqSupply -> Module -> ModBreaks -> BcM r -> IO (BcM_State, r) runBc dflags us this_mod modBreaks (BcM m) = m (BcM_State dflags us this_mod 0 [] breakArray) where breakArray = modBreaks_flags modBreaks thenBc :: BcM a -> (a -> BcM b) -> BcM b thenBc (BcM expr) cont = BcM $ \st0 -> do (st1, q) <- expr st0 let BcM k = cont q (st2, r) <- k st1 return (st2, r) thenBc_ :: BcM a -> BcM b -> BcM b thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do (st1, _) <- expr st0 (st2, r) <- cont st1 return (st2, r) returnBc :: a -> BcM a returnBc result = BcM $ \st -> (return (st, result)) instance Functor BcM where fmap = liftM instance Applicative BcM where pure = return (<*>) = ap instance Monad BcM where (>>=) = thenBc (>>) = thenBc_ return = returnBc instance HasDynFlags BcM where getDynFlags = BcM $ \st -> return (st, bcm_dflags st) emitBc :: ([BcPtr] -> ProtoBCO Name) -> BcM (ProtoBCO Name) emitBc bco = BcM $ \st -> return (st{malloced=[]}, bco (malloced st)) recordMallocBc :: Ptr a -> BcM () recordMallocBc a = BcM $ \st -> return (st{malloced = Right (castPtr a) : malloced st}, ()) recordItblMallocBc :: ItblPtr -> BcM () recordItblMallocBc a = BcM $ \st -> return (st{malloced = Left a : malloced st}, ()) getLabelBc :: BcM Word16 getLabelBc = BcM $ \st -> do let nl = nextlabel st when (nl == maxBound) $ panic "getLabelBc: Ran out of labels" return (st{nextlabel = nl + 1}, nl) getLabelsBc :: Word16 -> BcM [Word16] getLabelsBc n = BcM $ \st -> let ctr = nextlabel st in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1]) getBreakArray :: BcM BreakArray getBreakArray = BcM $ \st -> return (st, breakArray st) newUnique :: BcM Unique newUnique = BcM $ \st -> case takeUniqFromSupply (uniqSupply st) of (uniq, us) -> let newState = st { uniqSupply = us } in return (newState, uniq) getCurrentModule :: BcM Module getCurrentModule = BcM $ \st -> return (st, thisModule st) newId :: Type -> BcM Id newId ty = do uniq <- newUnique return $ mkSysLocal tickFS uniq ty tickFS :: FastString tickFS = fsLit "ticked"
ghc-android/ghc
compiler/ghci/ByteCodeGen.hs
bsd-3-clause
65,519
0
24
21,137
14,217
7,297
6,920
-1
-1
module PatBindIn3 where sumSquares x = (sq x pow) + (sq x pow) where pow = 2 sq = x ^ pow anotherFun 0 y = sq y where sq x = x ^ 2
kmate/HaRe
old/testing/liftToToplevel/PatBindIn3AST.hs
bsd-3-clause
136
0
7
40
75
39
36
4
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , MagicHash , UnboxedTuples #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Conc.IO -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Basic concurrency stuff. -- ----------------------------------------------------------------------------- -- No: #hide, because bits of this module are exposed by the stm package. -- However, we don't want this module to be the home location for the -- bits it exports, we'd rather have Control.Concurrent and the other -- higher level modules be the home. Hence: #not-home module GHC.Conc.IO ( ensureIOManagerIsRunning , ioManagerCapabilitiesChanged -- * Waiting , threadDelay , registerDelay , threadWaitRead , threadWaitWrite , threadWaitReadSTM , threadWaitWriteSTM , closeFdWith #ifdef mingw32_HOST_OS , asyncRead , asyncWrite , asyncDoProc , asyncReadBA , asyncWriteBA , ConsoleEvent(..) , win32ConsoleHandler , toWin32ConsoleEvent #endif ) where import Foreign import GHC.Base import GHC.Conc.Sync as Sync import GHC.Real ( fromIntegral ) import System.Posix.Types #ifdef mingw32_HOST_OS import qualified GHC.Conc.Windows as Windows import GHC.Conc.Windows (asyncRead, asyncWrite, asyncDoProc, asyncReadBA, asyncWriteBA, ConsoleEvent(..), win32ConsoleHandler, toWin32ConsoleEvent) #else import qualified GHC.Event.Thread as Event #endif ensureIOManagerIsRunning :: IO () #ifndef mingw32_HOST_OS ensureIOManagerIsRunning = Event.ensureIOManagerIsRunning #else ensureIOManagerIsRunning = Windows.ensureIOManagerIsRunning #endif ioManagerCapabilitiesChanged :: IO () #ifndef mingw32_HOST_OS ioManagerCapabilitiesChanged = Event.ioManagerCapabilitiesChanged #else ioManagerCapabilitiesChanged = return () #endif -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use 'closeFdWith'. threadWaitRead :: Fd -> IO () threadWaitRead fd #ifndef mingw32_HOST_OS | threaded = Event.threadWaitRead fd #endif | otherwise = IO $ \s -> case fromIntegral fd of { I# fd# -> case waitRead# fd# s of { s' -> (# s', () #) }} -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use 'closeFdWith'. threadWaitWrite :: Fd -> IO () threadWaitWrite fd #ifndef mingw32_HOST_OS | threaded = Event.threadWaitWrite fd #endif | otherwise = IO $ \s -> case fromIntegral fd of { I# fd# -> case waitWrite# fd# s of { s' -> (# s', () #) }} -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. threadWaitReadSTM :: Fd -> IO (Sync.STM (), IO ()) threadWaitReadSTM fd #ifndef mingw32_HOST_OS | threaded = Event.threadWaitReadSTM fd #endif | otherwise = do m <- Sync.newTVarIO False _ <- Sync.forkIO $ do threadWaitRead fd Sync.atomically $ Sync.writeTVar m True let waitAction = do b <- Sync.readTVar m if b then return () else retry let killAction = return () return (waitAction, killAction) -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. threadWaitWriteSTM :: Fd -> IO (Sync.STM (), IO ()) threadWaitWriteSTM fd #ifndef mingw32_HOST_OS | threaded = Event.threadWaitWriteSTM fd #endif | otherwise = do m <- Sync.newTVarIO False _ <- Sync.forkIO $ do threadWaitWrite fd Sync.atomically $ Sync.writeTVar m True let waitAction = do b <- Sync.readTVar m if b then return () else retry let killAction = return () return (waitAction, killAction) -- | Close a file descriptor in a concurrency-safe way (GHC only). If -- you are using 'threadWaitRead' or 'threadWaitWrite' to perform -- blocking I\/O, you /must/ use this function to close file -- descriptors, or blocked threads may not be woken. -- -- Any threads that are blocked on the file descriptor via -- 'threadWaitRead' or 'threadWaitWrite' will be unblocked by having -- IO exceptions thrown. closeFdWith :: (Fd -> IO ()) -- ^ Low-level action that performs the real close. -> Fd -- ^ File descriptor to close. -> IO () closeFdWith close fd #ifndef mingw32_HOST_OS | threaded = Event.closeFdWith close fd #endif | otherwise = close fd -- | Suspends the current thread for a given number of microseconds -- (GHC only). -- -- There is no guarantee that the thread will be rescheduled promptly -- when the delay has expired, but the thread will never continue to -- run /earlier/ than specified. -- threadDelay :: Int -> IO () threadDelay time #ifdef mingw32_HOST_OS | threaded = Windows.threadDelay time #else | threaded = Event.threadDelay time #endif | otherwise = IO $ \s -> case time of { I# time# -> case delay# time# s of { s' -> (# s', () #) }} -- | Set the value of returned TVar to True after a given number of -- microseconds. The caveats associated with threadDelay also apply. -- registerDelay :: Int -> IO (TVar Bool) registerDelay usecs #ifdef mingw32_HOST_OS | threaded = Windows.registerDelay usecs #else | threaded = Event.registerDelay usecs #endif | otherwise = error "registerDelay: requires -threaded" foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
jtojnar/haste-compiler
libraries/ghc-7.10/base/GHC/Conc/IO.hs
bsd-3-clause
6,475
0
15
1,470
1,004
551
453
80
2
module T10185 where import Data.Coerce import Data.Proxy foo :: (Coercible (a b) (c d), Coercible (c d) (e f)) => Proxy (c d) -> a b -> e f foo _ = coerce
urbanslug/ghc
testsuite/tests/typecheck/should_compile/T10185.hs
bsd-3-clause
157
0
9
35
93
48
45
5
1
module TypeStructure.TH where import TypeStructure.Prelude.Basic import TypeStructure.Prelude.Transformers import TypeStructure.Prelude.Data import TypeStructure.Prelude.TH import qualified TypeStructure.Class as Class import qualified TypeStructure.TH.Model as M import qualified TypeStructure.TH.Template as Template -- | -- Automatically derive the instance of 'Class.TypeStructure' using Template Haskell. derive :: Name -> Q [Dec] derive name = do typeCon <- deriveTypeCon name info <- reify name let declaration = infoToDeclaration info vars = case declaration of M.Primitive arity -> arity |> take |> ($ [0..]) |> map (show >>> ('_':)) M.ADT vars _ -> vars M.Synonym vars _ -> vars (typesWithoutDictionaries, typesWithDictionaries) <- partitionEithers <$> execStateT (analyzeReferredTypes name) [] inlinedRecords <- forM typesWithoutDictionaries $ \n -> do typeCon <- deriveTypeCon n declaration <- infoToDeclaration <$> reify n return (typeCon, declaration) return $ (:[]) $ Template.renderInstance name vars typeCon (nub $ (typeCon, declaration) : inlinedRecords) typesWithDictionaries where deriveTypeCon name = do ns <- maybe (fail "Name without namespace") return $ nameModule name return (ns, nameBase name) analyzeReferredTypes :: Name -> StateT [Either Name Type] Q () analyzeReferredTypes name = do info <- lift $ reify $ name forM_ (referredTypes info) analyzeType where analyzeType t = do (lift $ isProperInstance' ''Class.TypeStructure [t]) >>= \case True -> void $ insert $ Right $ t False -> case t of AppT l r -> analyzeType l >> analyzeType r ConT n -> do inserted <- insert $ Left $ n when inserted $ analyzeReferredTypes n _ -> return () insert a = state $ \list -> if elem a list then (False, list) else (True, a : list) referredTypes :: Info -> [Type] referredTypes = \case TyConI d -> case d of DataD _ _ _ cons _ -> conTypes =<< cons NewtypeD _ _ _ con _ -> conTypes $ con TySynD _ _ t -> [t] d -> $bug $ "Unsupported dec: " <> show d PrimTyConI n arity _ -> [] i -> $bug $ "Unsupported info: " <> show i conTypes :: Con -> [Type] conTypes = \case NormalC n ts -> map snd ts RecC n ts -> map (\(_, _, t) -> t) ts InfixC (_, l) n (_, r) -> [l, r] c -> $bug $ "Unexpected constructor: " <> show c adaptType :: Type -> M.Type adaptType = \case AppT l r -> M.App (adaptType l) (adaptType r) VarT n -> M.Var $ nameBase $ n ConT n -> fromName n TupleT a -> fromName $ tupleTypeName a UnboxedTupleT a -> fromName $ unboxedTupleTypeName a ArrowT -> fromName ''(->) ListT -> fromName ''[] t -> $bug $ "Unsupported type: " <> show t where fromName n = M.Con $ adaptTypeConName n ?: ($bug $ "Name has no namespace: " <> show n) adaptTypeConName :: Name -> Maybe M.TypeCon adaptTypeConName n = do ns <- nameModule n return (ns, nameBase n) infoToDeclaration :: Info -> M.Declaration infoToDeclaration = \case TyConI d -> case d of DataD _ _ vars cons _ -> M.ADT (map adaptVar vars) (map adaptCon cons) NewtypeD _ _ vars con _ -> M.ADT (map adaptVar vars) [adaptCon con] TySynD _ vars t -> M.Synonym (map adaptVar vars) (adaptType t) d -> $bug $ "Unsupported dec: " <> show d PrimTyConI _ arity _ -> M.Primitive arity i -> $bug $ "Unsupported info: " <> show i adaptVar :: TyVarBndr -> M.TypeVar adaptVar = \case PlainTV n -> nameBase n KindedTV n k -> nameBase n adaptCon :: Con -> M.Constructor adaptCon = \case NormalC n ts -> (nameBase n, map (\(_, t) -> adaptType t) ts) RecC n ts -> (nameBase n, map (\(_, _, t) -> adaptType t) ts) InfixC (_, a) n (_, b) -> (nameBase n, [adaptType a, adaptType b]) c -> $bug $ "Unexpected constructor: " <> show c
nikita-volkov/type-structure
src/TypeStructure/TH.hs
mit
3,897
0
20
947
1,527
761
766
-1
-1
-- Some math helpers module MathHelpers where import Linear rotationMatrix :: Double -> M22 Double rotationMatrix a = V2 (V2 (cos a) (- sin a)) (V2 (sin a) (cos a)) rotatedUnit :: Double -> V2 Double rotatedUnit a = V2 (cos a) (sin a) data MovingPosition = MovingPosition { position :: V2 Double, velocity :: V2 Double, mass :: Double } deriving (Show, Eq) stepPosition :: Double -> MovingPosition -> MovingPosition stepPosition dt mpos = mpos { position = dt *^ v ^+^ r } where v = velocity mpos r = position mpos momentum :: MovingPosition -> V2 Double momentum mpos = mass mpos *^ velocity mpos class HasMovingPosition a where movingPosition :: a -> MovingPosition setPosition :: a -> MovingPosition -> a updatePosition :: a -> (MovingPosition -> MovingPosition) -> a updatePosition x f = setPosition x $ f $ movingPosition x instance HasMovingPosition MovingPosition where movingPosition = id setPosition = const id changeFrame :: V2 Double -> V2 Double -> Double -> MovingPosition -> MovingPosition changeFrame dr dv a pos = let rotmat = rotationMatrix a in pos { position = rotmat !* position pos ^+^ dr, velocity = rotmat !* velocity pos ^+^ dv } changeFrameR :: V2 Double -> MovingPosition -> MovingPosition changeFrameR dr = changeFrame dr zero 0 changeFrameV :: V2 Double -> MovingPosition -> MovingPosition changeFrameV dv = changeFrame zero dv 0 -- fold a real number into [0,1] by chaining homomorphisms foldToUnitInterval :: Double -> Double foldToUnitInterval x = let ex = exp x in ex / (ex + 1) cartesianProduct :: [a] -> [b] -> [(a, b)] cartesianProduct xs ys = [(x, y) | x <- xs, y <- ys] liftF :: (Float -> a) -> (Double -> a) liftF = (double2Float .) liftF2 :: (Float -> Float -> a) -> (Double -> Double -> a) liftF2 f x1 x2 = f (double2Float x1) (double2Float x2) liftF3 :: (Float -> Float -> Float -> a) -> (Double -> Double -> Double -> a) liftF3 f x1 x2 x3 = f (double2Float x1) (double2Float x2) (double2Float x3)
Solonarv/Asteroids
MathHelpers.hs
mit
2,035
1
11
441
766
398
368
44
1
module Network.TCP.Proxy.Socks5 where {- TODO: implement main RFC https://www.ietf.org/rfc/rfc1928.txt GSS API authentication https://tools.ietf.org/html/rfc1961 UserName/Password auth https://tools.ietf.org/html/rfc1929 -} protocol = undefined
danoctavian/tcp-proxy
src/Network/TCP/Proxy/Socks5.hs
mit
269
0
4
44
14
10
4
2
1
-- File : Helper.hs -- Author : Martin Valentino -- Purpose : A helper function use for list operations module Helper where -- Sort list in descending order quicksort :: Ord t => [t] -> [t] quicksort [] = [] quicksort (x:xs) = quicksort large ++ (x : quicksort small) where small = [y | y <- xs, y <= x] large = [y | y <- xs, y > x] -- remove duplicate element from two list of type a removeDuplicates :: Eq a => [a] -> [a] removeDuplicates [] = [] removeDuplicates (x:xs) = x : removeDuplicates (filter (/= x) xs) -- check whether element in position n -- is similar in both list of type a eqNthElem :: Eq a => Int -> [a] -> [a] -> Bool eqNthElem n l1 l2 = (l1 !! n) == (l2 !! n) -- Return similar element from two list of type t filterSimilar :: Eq t => [t] -> [t] -> [t] filterSimilar xs ys = [ x | x <- xs , y <- ys, x == y]
martindavid/code-sandbox
comp90048/assignments/project1/Helper.hs
mit
860
0
9
211
322
175
147
13
1
module Render.Raytracer where import Geometry.Object import Geometry.Vector import Math.SceneParams import Math.Intersect import Math.Shader computePixelPairColor :: Scene -> (Scalar, Scalar) -> Color computePixelPairColor scene (i, j) = computePixelColor scene i j computePixelColor :: Scene -> Scalar -> Scalar -> Color computePixelColor scene i j = gammaCorrect color gamma where color = colorPoint depth intersection scene intersection = rayIntersectScene (computeRay i j) scene -- generates the viewing ray for a given pixel coord computeRay :: Scalar -> Scalar -> Ray computeRay i j = Ray e (s <-> e) where s = e <+> (mult u uCoord) <+> (mult v vCoord) <-> (mult w d) uCoord = l + (r-l) * (i+0.5)/(fromIntegral width) vCoord = b + (t-b) * (j+0.5)/(fromIntegral height) getReflectedColor :: Int -> Maybe PosIntersection -> Scene -> Color getReflectedColor = colorPoint -- gets intersection color with reflection colorPoint :: Int -> Maybe PosIntersection -> Scene -> Color colorPoint (-1) _ _ = (0.0, 0.0, 0.0) colorPoint _ Nothing _ = (0.0, 0.0, 0.0) colorPoint depth (Just (Ray e d, s, surf)) scene = addColor reflectColor phongColor where surfPoint = computeSurfPoint (Ray e d) s surfNorm = normalise $ computeSurfNorm surf surfPoint fixedSurfPoint = surfPoint <+> (mult surfNorm epsilon) reflectDir = computeReflection d surfNorm reflectRay = Ray fixedSurfPoint reflectDir reflectIntersection = rayIntersectScene reflectRay scene alpha = getAlpha surf reflectColor = scaleColor (getReflectedColor (depth-1) reflectIntersection scene) alpha phongColor = getShadeColor (Ray e d, s, surf) fixedSurfPoint alpha scene getShadeColor :: PosIntersection -> Vector -> Scalar -> Scene -> Color getShadeColor (ray, s, surf) surfPoint alpha scene | isBlocked surf scene ray s = ambientShade surf | otherwise = scaleColor (computeShading surf (computeSurfPoint ray s)) (1-alpha) -- returns intersection color for a possible intersection getIntersectColor :: Maybe PosIntersection -> Scene -> Color getIntersectColor m scene = case m of Nothing -> (0.0, 0.0, 0.0) Just (Ray origin direction, s, surf) -> if (isBlocked surf scene (Ray origin direction) s) then ambientShade surf else computeShading surf (computeSurfPoint (Ray origin direction) s) -- returns true if ray is blocked by an object in the scene isBlocked :: Surface -> Scene -> Ray -> Scalar -> Bool isBlocked surf scene (Ray origin direction) scalar = rayBlocked (Ray fixedSurfPoint shadowDirection) scene where surfPoint = origin <+> (mult direction scalar) shadowDirection = lightSource <-> surfPoint normVec = computeSurfNorm surf surfPoint fixedSurfPoint = surfPoint <+> (mult normVec epsilon) rayBlocked :: Ray -> Scene -> Bool rayBlocked ray scene = case minIntersect of Nothing -> False _ -> True where minIntersect = rayIntersectScene ray scene -- returns the closest intersection rayIntersectScene :: Ray -> Scene -> Maybe PosIntersection rayIntersectScene ray scene = getMinIntersect [rayIntersect ray surf | surf <- scene] -- returns the minimum intersection getMinIntersect :: [Intersection] -> Maybe PosIntersection getMinIntersect [] = Nothing getMinIntersect xs = toPosIntersection $ foldl1 min' xs -- returns min of two maybe values min' :: Intersection -> Intersection -> Intersection min' (_, Nothing, _) b@(_, Nothing, _) = b min' (_, Nothing, _) b@(_, _, _) = b min' a@(_, _, _) (_, Nothing, _) = a min' a@(_, Just x, _) b@(_, Just y, _) | x < y = a | otherwise = b -- computes gamma corrected color gammaCorrect :: Color -> Scalar -> Color gammaCorrect (x, y, z) g = (x', y', z') where x' = x ** (1/g) y' = y ** (1/g) z' = z ** (1/g)
dongy7/raytracer
src/Render/Raytracer.hs
mit
3,964
0
13
912
1,296
690
606
70
3
module CommandContent ( CommandContent(..) , findContent404 , contentHeader , contentBody ) where import Import import Archive import Network.AWS import Network.AWS.S3 (_NoSuchKey) import qualified Data.ByteString.Lazy as BL data CommandContent = Live Token Command | Archived BL.ByteString findContent404 :: Token -> YesodDB App CommandContent findContent404 token = do mcommand <- getBy $ UniqueCommand token case mcommand of Just (Entity _ command) -> return $ Live token command _ -> lift $ Archived <$> catching _NoSuchKey (archivedOutput token) (\_ -> notFound) contentHeader :: CommandContent -> Widget contentHeader (Live _ command) = [whamlet| <span .right> #{show $ commandCreatedAt command} $maybe desc <- commandDescription command #{desc} $nothing No description |] contentHeader (Archived _) = [whamlet| Archived output |] contentBody :: CommandContent -> Widget contentBody (Live token _) = [whamlet| <code #output data-stream-url=@{OutputR token}> |] contentBody (Archived content) = [whamlet| <code>#{decodeUtf8 content} |]
pbrisbin/tee-io
src/CommandContent.hs
mit
1,163
0
13
259
269
152
117
-1
-1
--------------- -- Aufgabe 1 -- --------------- data GeladenerGast = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T deriving (Eq,Ord,Enum,Show) type Schickeria = [GeladenerGast] -- Aufsteigend geordnet type Adabeis = [GeladenerGast] -- Aufsteigend geordnet type Nidabeis = [GeladenerGast] -- Aufsteigend geordnet type NimmtTeil = GeladenerGast -> Bool -- Total definiert type Kennt = GeladenerGast -> GeladenerGast -> Bool -- Total definiert istSchickeriaEvent :: NimmtTeil -> Kennt -> Bool istSchickeriaEvent f g = length [t | t <- gaeste, elem t list && (f t)] /= 0 where list = schickeria f g istSuperSchick :: NimmtTeil -> Kennt -> Bool istSuperSchick f g = length [t | t <- gaeste, (elem t list) && (f t)] == 0 where list = adabeis f g istVollProllig :: NimmtTeil -> Kennt -> Bool istVollProllig f g = length [t | t <- gaeste, elem t list && (f t)] == 0 where list = schickeria f g schickeria :: NimmtTeil -> Kennt -> Schickeria schickeria f g = [v | v <- slebstGekannt, (gastKenntGaeste g v slebstGekannt []) == (gaesteKennenGast g slebstGekannt v [])] where slebstGekannt = [t | t <- gaeste, (elem t (slebstKenenn g)) && not (elem t (nidabeis f g))] adabeis :: NimmtTeil -> Kennt -> Adabeis adabeis f g = [v | v <- gaeste, length (gastKenntGaeste g v schick []) == length schick] where schick = schickeria f g nidabeis :: NimmtTeil -> Kennt -> Nidabeis nidabeis f g = [t | t <- gaeste, not (f t)] gaeste = [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T] slebstKenenn :: Kennt -> [GeladenerGast] slebstKenenn g = [t | t <- gaeste, g t t] gastKenntGaeste :: Kennt -> GeladenerGast -> [GeladenerGast] -> [GeladenerGast] -> [GeladenerGast] gastKenntGaeste kennt gast gaeste list | length gaeste == 0 = list | kennt gast curr = gastKenntGaeste kennt gast (drop 1 gaeste) (list ++ [curr]) | otherwise = gastKenntGaeste kennt gast (drop 1 gaeste) list where curr = (head gaeste) gaesteKennenGast :: Kennt -> [GeladenerGast] -> GeladenerGast -> [GeladenerGast] -> [GeladenerGast] gaesteKennenGast kennt gaeste gast list | length gaeste == 0 = list | kennt curr gast = gaesteKennenGast kennt (drop 1 gaeste) gast (list ++ [curr]) | otherwise = gaesteKennenGast kennt (drop 1 gaeste) gast list where curr = (head gaeste) --------------- -- Aufgabe 2 -- --------------- stream :: [Integer] stream = 1 : stream' (map (2*) stream) (stream' (map (3*) stream) (map (5*) stream)) stream' :: [Integer] -> [Integer] -> [Integer] stream' a@(x:xs) b@(y:ys) = case compare x y of LT -> x : stream' xs b EQ -> x : stream' xs ys GT -> y : stream' a ys --------------- -- Aufgabe 3 -- --------------- type Quadrupel = (Integer,Integer,Integer,Integer) quadrupel :: Integer -> [Quadrupel] quadrupel n | n <= 0 = [] | otherwise = (fil (gen n)) gen :: Integer -> [Quadrupel] gen n = [(a,b,c,d) | a <- [1..n], b <- [1..n], c <- [1..n], d <- [1..n], a <= b && a < c && c <= d] fil :: [Quadrupel] -> [Quadrupel] fil q = [t | t <- q, fil' t] fil' :: Quadrupel -> Bool fil' (a,b,c,d) = (a^3+b^3) == (c^3+d^3) sel :: Int -> [Quadrupel] -> Quadrupel sel n q = q !! (abs n)
Batev/Vienna-University-of-Technology
Functional Programming/Complex functions/ComplexFunctions8.hs
mit
3,393
0
14
889
1,491
802
689
58
3
module System.Logging.Facade.HsLogger (hsLoggerSink) where import qualified System.Log.Logger as HsLogger import System.Logging.Facade.Types hsLoggerSink :: String -> LogRecord -> IO () hsLoggerSink defaultChannel record = HsLogger.logM channel level (message "") where mLocation = logRecordLocation record channel = maybe defaultChannel channelFromLocation mLocation level = case logRecordLevel record of TRACE -> HsLogger.DEBUG DEBUG -> HsLogger.DEBUG INFO -> HsLogger.INFO WARN -> HsLogger.WARNING ERROR -> HsLogger.ERROR message = location . showString " - " . showString (logRecordMessage record) location = maybe (showString "") ((showString " " .) . formatLocation) mLocation formatLocation :: Location -> ShowS formatLocation loc = showString (locationFile loc) . colon . shows (locationLine loc) . colon . shows (locationColumn loc) where colon = showString ":" channelFromLocation :: Location -> String channelFromLocation loc = package ++ "." ++ locationModule loc where package = stripVersion (locationPackage loc) -- | Strip version string from given package name. -- -- The package name @main@ is returned verbatim. If the package name is not -- @main@, we assume that there is always a version string, delimited with a -- @\'-\'@ from the package name. Behavior is unspecified for package names -- that are neither @main@ nor have a version string. -- -- Examples: -- -- >>> stripVersion "main" -- "main" -- -- >>> stripVersion "foo-0.0.0" -- "foo" -- -- >>> stripVersion "foo-bar-0.0.0" -- "foo-bar" stripVersion :: String -> String stripVersion p = case p of "main" -> p _ -> reverse $ tail $ dropWhile (/= '-') $ reverse p
beni55/logging-facade
logging-facade-hslogger/src/System/Logging/Facade/HsLogger.hs
mit
1,726
0
11
327
389
209
180
25
5