code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE CPP #-} module API.Question.GetQuestion.Url (url) where url :: String url = "/api/getQuestion"
DataStewardshipPortal/ds-wizard
DSServer/app/API/Question/GetQuestion/Url.hs
Haskell
apache-2.0
111
module Common where import Test.QuickCheck import SIL.TypeChecker import SIL class TestableIExpr a where getIExpr :: a -> IExpr data TestIExpr = TestIExpr IExpr data ValidTestIExpr = ValidTestIExpr TestIExpr data ZeroTypedTestIExpr = ZeroTypedTestIExpr TestIExpr data ArrowTypedTestIExpr = ArrowTypedTestIExpr TestIExpr instance TestableIExpr TestIExpr where getIExpr (TestIExpr x) = x instance Show TestIExpr where show (TestIExpr t) = show t instance TestableIExpr ValidTestIExpr where getIExpr (ValidTestIExpr x) = getIExpr x instance Show ValidTestIExpr where show (ValidTestIExpr v) = show v instance TestableIExpr ZeroTypedTestIExpr where getIExpr (ZeroTypedTestIExpr x) = getIExpr x instance Show ZeroTypedTestIExpr where show (ZeroTypedTestIExpr v) = show v instance TestableIExpr ArrowTypedTestIExpr where getIExpr (ArrowTypedTestIExpr x) = getIExpr x instance Show ArrowTypedTestIExpr where show (ArrowTypedTestIExpr x) = show x lift1Texpr :: (IExpr -> IExpr) -> TestIExpr -> TestIExpr lift1Texpr f (TestIExpr x) = TestIExpr $ f x lift2Texpr :: (IExpr -> IExpr -> IExpr) -> TestIExpr -> TestIExpr -> TestIExpr lift2Texpr f (TestIExpr a) (TestIExpr b) = TestIExpr $ f a b instance Arbitrary TestIExpr where arbitrary = sized tree where tree i = let half = div i 2 pure2 = pure . TestIExpr in case i of 0 -> oneof $ map pure2 [zero, var] x -> oneof [ pure2 zero , pure2 var , lift2Texpr pair <$> tree half <*> tree half , lift1Texpr SetEnv <$> tree (i - 1) , lift1Texpr Defer <$> tree (i - 1) , lift2Texpr check <$> tree half <*> tree half , lift1Texpr gate <$> tree (i - 1) , lift1Texpr pleft <$> tree (i - 1) , lift1Texpr pright <$> tree (i - 1) , lift1Texpr Trace <$> tree (i - 1) ] shrink (TestIExpr x) = case x of Zero -> [] Env -> [] (Gate x) -> TestIExpr x : (map (lift1Texpr gate) . shrink $ TestIExpr x) (PLeft x) -> TestIExpr x : (map (lift1Texpr pleft) . shrink $ TestIExpr x) (PRight x) -> TestIExpr x : (map (lift1Texpr pright) . shrink $ TestIExpr x) (Trace x) -> TestIExpr x : (map (lift1Texpr Trace) . shrink $ TestIExpr x) (SetEnv x) -> TestIExpr x : (map (lift1Texpr SetEnv) . shrink $ TestIExpr x) (Defer x) -> TestIExpr x : (map (lift1Texpr Defer) . shrink $ TestIExpr x) (Abort x) -> TestIExpr x : (map (lift1Texpr Abort) . shrink $ TestIExpr x) (Pair a b) -> TestIExpr a : TestIExpr b : [lift2Texpr pair a' b' | (a', b') <- shrink (TestIExpr a, TestIExpr b)] typeable x = case inferType (getIExpr x) of Left _ -> False _ -> True instance Arbitrary ValidTestIExpr where arbitrary = ValidTestIExpr <$> suchThat arbitrary typeable shrink (ValidTestIExpr te) = map ValidTestIExpr . filter typeable $ shrink te zeroTyped x = inferType (getIExpr x) == Right ZeroTypeP instance Arbitrary ZeroTypedTestIExpr where arbitrary = ZeroTypedTestIExpr <$> suchThat arbitrary zeroTyped shrink (ZeroTypedTestIExpr ztte) = map ZeroTypedTestIExpr . filter zeroTyped $ shrink ztte simpleArrowTyped x = inferType (getIExpr x) == Right (ArrTypeP ZeroTypeP ZeroTypeP) instance Arbitrary ArrowTypedTestIExpr where arbitrary = ArrowTypedTestIExpr <$> suchThat arbitrary simpleArrowTyped shrink (ArrowTypedTestIExpr atte) = map ArrowTypedTestIExpr . filter simpleArrowTyped $ shrink atte
sfultong/stand-in-language
test/Common.hs
Haskell
apache-2.0
3,591
{-# LANGUAGE PackageImports #-} import "fun-w-yesod" 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
tomasherman/fun-w-yesod
devel.hs
Haskell
bsd-2-clause
705
{- path manipulation - - Copyright 2010-2014 Joey Hess <id@joeyh.name> - - License: BSD-2-clause -} {-# LANGUAGE PackageImports, CPP #-} {-# OPTIONS_GHC -fno-warn-tabs #-} module Utility.Path where import Data.String.Utils import System.FilePath import Data.List import Data.Maybe import Data.Char import Control.Applicative import Prelude #ifdef mingw32_HOST_OS import qualified System.FilePath.Posix as Posix #else import System.Posix.Files import Utility.Exception #endif import qualified "MissingH" System.Path as MissingH import Utility.Monad import Utility.UserInfo import Utility.Directory {- Simplifies a path, removing any "." component, collapsing "dir/..", - and removing the trailing path separator. - - On Windows, preserves whichever style of path separator might be used in - the input FilePaths. This is done because some programs in Windows - demand a particular path separator -- and which one actually varies! - - This does not guarantee that two paths that refer to the same location, - and are both relative to the same location (or both absolute) will - yeild the same result. Run both through normalise from System.FilePath - to ensure that. -} simplifyPath :: FilePath -> FilePath simplifyPath path = dropTrailingPathSeparator $ joinDrive drive $ joinPath $ norm [] $ splitPath path' where (drive, path') = splitDrive path norm c [] = reverse c norm c (p:ps) | p' == ".." && not (null c) && dropTrailingPathSeparator (c !! 0) /= ".." = norm (drop 1 c) ps | p' == "." = norm c ps | otherwise = norm (p:c) ps where p' = dropTrailingPathSeparator p {- Makes a path absolute. - - The first parameter is a base directory (ie, the cwd) to use if the path - is not already absolute, and should itsef be absolute. - - Does not attempt to deal with edge cases or ensure security with - untrusted inputs. -} absPathFrom :: FilePath -> FilePath -> FilePath absPathFrom dir path = simplifyPath (combine dir path) {- On Windows, this converts the paths to unix-style, in order to run - MissingH's absNormPath on them. -} absNormPathUnix :: FilePath -> FilePath -> Maybe FilePath #ifndef mingw32_HOST_OS absNormPathUnix dir path = MissingH.absNormPath dir path #else absNormPathUnix dir path = todos <$> MissingH.absNormPath (fromdos dir) (fromdos path) where fromdos = replace "\\" "/" todos = replace "/" "\\" #endif {- takeDirectory "foo/bar/" is "foo/bar". This instead yields "foo" -} parentDir :: FilePath -> FilePath parentDir = takeDirectory . dropTrailingPathSeparator {- Just the parent directory of a path, or Nothing if the path has no - parent (ie for "/" or ".") -} upFrom :: FilePath -> Maybe FilePath upFrom dir | length dirs < 2 = Nothing | otherwise = Just $ joinDrive drive (intercalate s $ init dirs) where -- on Unix, the drive will be "/" when the dir is absolute, otherwise "" (drive, path) = splitDrive dir dirs = filter (not . null) $ split s path s = [pathSeparator] prop_upFrom_basics :: FilePath -> Bool prop_upFrom_basics dir | null dir = True | dir == "/" = p == Nothing | otherwise = p /= Just dir where p = upFrom dir {- Checks if the first FilePath is, or could be said to contain the second. - For example, "foo/" contains "foo/bar". Also, "foo", "./foo", "foo/" etc - are all equivilant. -} dirContains :: FilePath -> FilePath -> Bool dirContains a b = a == b || a' == b' || (addTrailingPathSeparator a') `isPrefixOf` b' where a' = norm a b' = norm b norm = normalise . simplifyPath {- Converts a filename into an absolute path. - - Unlike Directory.canonicalizePath, this does not require the path - already exists. -} absPath :: FilePath -> IO FilePath absPath file = do cwd <- getCurrentDirectory return $ absPathFrom cwd file {- Constructs a relative path from the CWD to a file. - - For example, assuming CWD is /tmp/foo/bar: - relPathCwdToFile "/tmp/foo" == ".." - relPathCwdToFile "/tmp/foo/bar" == "" -} relPathCwdToFile :: FilePath -> IO FilePath relPathCwdToFile f = do c <- getCurrentDirectory relPathDirToFile c f {- Constructs a relative path from a directory to a file. -} relPathDirToFile :: FilePath -> FilePath -> IO FilePath relPathDirToFile from to = relPathDirToFileAbs <$> absPath from <*> absPath to {- This requires the first path to be absolute, and the - second path cannot contain ../ or ./ - - On Windows, if the paths are on different drives, - a relative path is not possible and the path is simply - returned as-is. -} relPathDirToFileAbs :: FilePath -> FilePath -> FilePath relPathDirToFileAbs from to | takeDrive from /= takeDrive to = to | otherwise = intercalate s $ dotdots ++ uncommon where s = [pathSeparator] pfrom = split s from pto = split s to common = map fst $ takeWhile same $ zip pfrom pto same (c,d) = c == d uncommon = drop numcommon pto dotdots = replicate (length pfrom - numcommon) ".." numcommon = length common prop_relPathDirToFile_basics :: FilePath -> FilePath -> Bool prop_relPathDirToFile_basics from to | null from || null to = True | from == to = null r | otherwise = not (null r) where r = relPathDirToFileAbs from to prop_relPathDirToFile_regressionTest :: Bool prop_relPathDirToFile_regressionTest = same_dir_shortcurcuits_at_difference where {- Two paths have the same directory component at the same - location, but it's not really the same directory. - Code used to get this wrong. -} same_dir_shortcurcuits_at_difference = relPathDirToFileAbs (joinPath [pathSeparator : "tmp", "r", "lll", "xxx", "yyy", "18"]) (joinPath [pathSeparator : "tmp", "r", ".git", "annex", "objects", "18", "gk", "SHA256-foo", "SHA256-foo"]) == joinPath ["..", "..", "..", "..", ".git", "annex", "objects", "18", "gk", "SHA256-foo", "SHA256-foo"] {- Given an original list of paths, and an expanded list derived from it, - which may be arbitrarily reordered, generates a list of lists, where - each sublist corresponds to one of the original paths. - - When the original path is a directory, any items in the expanded list - that are contained in that directory will appear in its segment. - - The order of the original list of paths is attempted to be preserved in - the order of the returned segments. However, doing so has a O^NM - growth factor. So, if the original list has more than 100 paths on it, - we stop preserving ordering at that point. Presumably a user passing - that many paths in doesn't care too much about order of the later ones. -} segmentPaths :: [FilePath] -> [FilePath] -> [[FilePath]] segmentPaths [] new = [new] segmentPaths [_] new = [new] -- optimisation segmentPaths (l:ls) new = found : segmentPaths ls rest where (found, rest) = if length ls < 100 then partition (l `dirContains`) new else break (\p -> not (l `dirContains` p)) new {- This assumes that it's cheaper to call segmentPaths on the result, - than it would be to run the action separately with each path. In - the case of git file list commands, that assumption tends to hold. -} runSegmentPaths :: ([FilePath] -> IO [FilePath]) -> [FilePath] -> IO [[FilePath]] runSegmentPaths a paths = segmentPaths paths <$> a paths {- Converts paths in the home directory to use ~/ -} relHome :: FilePath -> IO String relHome path = do home <- myHomeDir return $ if dirContains home path then "~/" ++ relPathDirToFileAbs home path else path {- Checks if a command is available in PATH. - - The command may be fully-qualified, in which case, this succeeds as - long as it exists. -} inPath :: String -> IO Bool inPath command = isJust <$> searchPath command {- Finds a command in PATH and returns the full path to it. - - The command may be fully qualified already, in which case it will - be returned if it exists. -} searchPath :: String -> IO (Maybe FilePath) searchPath command | isAbsolute command = check command | otherwise = getSearchPath >>= getM indir where indir d = check $ d </> command check f = firstM doesFileExist #ifdef mingw32_HOST_OS [f, f ++ ".exe"] #else [f] #endif {- Checks if a filename is a unix dotfile. All files inside dotdirs - count as dotfiles. -} dotfile :: FilePath -> Bool dotfile file | f == "." = False | f == ".." = False | f == "" = False | otherwise = "." `isPrefixOf` f || dotfile (takeDirectory file) where f = takeFileName file {- Converts a DOS style path to a msys2 style path. Only on Windows. - Any trailing '\' is preserved as a trailing '/' - - Taken from: http://sourceforge.net/p/msys2/wiki/MSYS2%20introduction/i - - The virtual filesystem contains: - /c, /d, ... mount points for Windows drives -} toMSYS2Path :: FilePath -> FilePath #ifndef mingw32_HOST_OS toMSYS2Path = id #else toMSYS2Path p | null drive = recombine parts | otherwise = recombine $ "/" : driveletter drive : parts where (drive, p') = splitDrive p parts = splitDirectories p' driveletter = map toLower . takeWhile (/= ':') recombine = fixtrailing . Posix.joinPath fixtrailing s | hasTrailingPathSeparator p = Posix.addTrailingPathSeparator s | otherwise = s #endif {- Maximum size to use for a file in a specified directory. - - Many systems have a 255 byte limit to the name of a file, - so that's taken as the max if the system has a larger limit, or has no - limit. -} fileNameLengthLimit :: FilePath -> IO Int #ifdef mingw32_HOST_OS fileNameLengthLimit _ = return 255 #else fileNameLengthLimit dir = do -- getPathVar can fail due to statfs(2) overflow l <- catchDefaultIO 0 $ fromIntegral <$> getPathVar dir FileNameLimit if l <= 0 then return 255 else return $ minimum [l, 255] #endif {- Given a string that we'd like to use as the basis for FilePath, but that - was provided by a third party and is not to be trusted, returns the closest - sane FilePath. - - All spaces and punctuation and other wacky stuff are replaced - with '_', except for '.' - "../" will thus turn into ".._", which is safe. -} sanitizeFilePath :: String -> FilePath sanitizeFilePath = map sanitize where sanitize c | c == '.' = c | isSpace c || isPunctuation c || isSymbol c || isControl c || c == '/' = '_' | otherwise = c {- Similar to splitExtensions, but knows that some things in FilePaths - after a dot are too long to be extensions. -} splitShortExtensions :: FilePath -> (FilePath, [String]) splitShortExtensions = splitShortExtensions' 5 -- enough for ".jpeg" splitShortExtensions' :: Int -> FilePath -> (FilePath, [String]) splitShortExtensions' maxextension = go [] where go c f | len > 0 && len <= maxextension && not (null base) = go (ext:c) base | otherwise = (f, c) where (base, ext) = splitExtension f len = length ext
ArchiveTeam/glowing-computing-machine
src/Utility/Path.hs
Haskell
bsd-2-clause
10,692
module Args ( theLast , ljust , nonNegative , parseArgs , positive , printUsage ) where import Data.Monoid (Monoid(..), Last(..)) import System.Console.GetOpt (OptDescr, ArgOrder(Permute), getOpt, usageInfo) import System.Environment (getProgName) import System.Exit (ExitCode(..), exitWith) import System.IO (hPutStrLn, stderr) -- | Deconstructor for 'Last' values. theLast :: (cfg -> Last a) -- ^ Field to access. -> cfg -> a theLast f cfg = case f cfg of Last Nothing -> error "some horrible config sin has occurred" Last (Just a) -> a -- | Parse command line options. parseArgs :: Monoid cfg => cfg -> [OptDescr (IO cfg)] -> [String] -> IO (cfg, [String]) parseArgs defCfg options args = case getOpt Permute options args of (_, _, (err:_)) -> parseError err (opts, rest, _) -> do cfg <- (mappend defCfg . mconcat) `fmap` sequence opts return (cfg, rest) -- | Constructor for 'Last' values. ljust :: a -> Last a ljust = Last . Just -- | Parse a positive number. nonNegative :: (Num a, Ord a, Read a) => String -> (Last a -> cfg) -> String -> IO cfg nonNegative q f s = case reads s of [(n,"")] | n >= 0 -> return . f $ ljust n | otherwise -> parseError $ q ++ " must be non negative" _ -> parseError $ "invalid " ++ q ++ " provided" -- | Parse a positive number. positive :: (Num a, Ord a, Read a) => String -> (Last a -> cfg) -> String -> IO cfg positive q f s = case reads s of [(n,"")] | n > 0 -> return . f $ ljust n | otherwise -> parseError $ q ++ " must be positive" _ -> parseError $ "invalid " ++ q ++ " provided" -- | Display an error message from a command line parsing failure, and -- exit. parseError :: String -> IO a parseError msg = do progName <- getProgName hPutStrLn stderr $ "Error: " ++ msg hPutStrLn stderr $ "Run \"" ++ progName ++ " --help\" for usage information\n" exitWith (ExitFailure 64) printUsage :: [OptDescr b] -> ExitCode -> IO a printUsage options exitCode = do p <- getProgName putStr (usageInfo ("Usage: " ++ p ++ " [OPTIONS] [ARGS]") options) mapM_ putStrLn [ "" , "hi mom!" ] exitWith exitCode
tibbe/event
benchmarks/Args.hs
Haskell
bsd-2-clause
2,332
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Haddock -- Copyright : Isaac Jones 2003-2005 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This module deals with the @haddock@ and @hscolour@ commands. -- It uses information about installed packages (from @ghc-pkg@) to find the -- locations of documentation for dependent packages, so it can create links. -- -- The @hscolour@ support allows generating HTML versions of the original -- source, with coloured syntax highlighting. module Distribution.Simple.Haddock ( haddock, hscolour, haddockPackagePaths ) where import Prelude () import Distribution.Compat.Prelude import qualified Distribution.Simple.GHC as GHC import qualified Distribution.Simple.GHCJS as GHCJS -- local import Distribution.Backpack.DescribeUnitId import Distribution.Types.ForeignLib import Distribution.Types.UnqualComponentName import Distribution.Types.ComponentLocalBuildInfo import Distribution.Types.ExecutableScope import Distribution.Package import qualified Distribution.ModuleName as ModuleName import Distribution.PackageDescription as PD hiding (Flag) import Distribution.Simple.Compiler hiding (Flag) import Distribution.Simple.Program.GHC import Distribution.Simple.Program import Distribution.Simple.PreProcess import Distribution.Simple.Setup import Distribution.Simple.Build import Distribution.Simple.InstallDirs import Distribution.Simple.LocalBuildInfo hiding (substPathTemplate) import Distribution.Simple.BuildPaths import qualified Distribution.Simple.PackageIndex as PackageIndex import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import Distribution.Simple.Utils import Distribution.System import Distribution.Text import Distribution.Utils.NubList import Distribution.Version import Distribution.Verbosity import Language.Haskell.Extension import Distribution.Compat.Semigroup (All (..), Any (..)) import Data.Either ( rights ) import System.Directory (doesFileExist) import System.FilePath ( (</>), (<.>), normalise, isAbsolute ) import System.IO (hClose, hPutStr, hPutStrLn, hSetEncoding, utf8) -- ------------------------------------------------------------------------------ -- Types -- | A record that represents the arguments to the haddock executable, a product -- monoid. data HaddockArgs = HaddockArgs { argInterfaceFile :: Flag FilePath, -- ^ Path to the interface file, relative to argOutputDir, required. argPackageName :: Flag PackageIdentifier, -- ^ Package name, required. argHideModules :: (All,[ModuleName.ModuleName]), -- ^ (Hide modules ?, modules to hide) argIgnoreExports :: Any, -- ^ Ignore export lists in modules? argLinkSource :: Flag (Template,Template,Template), -- ^ (Template for modules, template for symbols, template for lines). argCssFile :: Flag FilePath, -- ^ Optional custom CSS file. argContents :: Flag String, -- ^ Optional URL to contents page. argVerbose :: Any, argOutput :: Flag [Output], -- ^ HTML or Hoogle doc or both? Required. argInterfaces :: [(FilePath, Maybe String)], -- ^ [(Interface file, URL to the HTML docs for links)]. argOutputDir :: Directory, -- ^ Where to generate the documentation. argTitle :: Flag String, -- ^ Page title, required. argPrologue :: Flag String, -- ^ Prologue text, required. argGhcOptions :: Flag (GhcOptions, Version), -- ^ Additional flags to pass to GHC. argGhcLibDir :: Flag FilePath, -- ^ To find the correct GHC, required. argTargets :: [FilePath] -- ^ Modules to process. } deriving Generic -- | The FilePath of a directory, it's a monoid under '(</>)'. newtype Directory = Dir { unDir' :: FilePath } deriving (Read,Show,Eq,Ord) unDir :: Directory -> FilePath unDir = normalise . unDir' type Template = String data Output = Html | Hoogle -- ------------------------------------------------------------------------------ -- Haddock support haddock :: PackageDescription -> LocalBuildInfo -> [PPSuffixHandler] -> HaddockFlags -> IO () haddock pkg_descr _ _ haddockFlags | not (hasLibs pkg_descr) && not (fromFlag $ haddockExecutables haddockFlags) && not (fromFlag $ haddockTestSuites haddockFlags) && not (fromFlag $ haddockBenchmarks haddockFlags) && not (fromFlag $ haddockForeignLibs haddockFlags) = warn (fromFlag $ haddockVerbosity haddockFlags) $ "No documentation was generated as this package does not contain " ++ "a library. Perhaps you want to use the --executables, --tests," ++ " --benchmarks or --foreign-libraries flags." haddock pkg_descr lbi suffixes flags' = do let verbosity = flag haddockVerbosity comp = compiler lbi platform = hostPlatform lbi flags = case haddockTarget of ForDevelopment -> flags' ForHackage -> flags' { haddockHoogle = Flag True , haddockHtml = Flag True , haddockHtmlLocation = Flag (pkg_url ++ "/docs") , haddockContents = Flag (toPathTemplate pkg_url) , haddockHscolour = Flag True } pkg_url = "/package/$pkg-$version" flag f = fromFlag $ f flags tmpFileOpts = defaultTempFileOptions { optKeepTempFiles = flag haddockKeepTempFiles } htmlTemplate = fmap toPathTemplate . flagToMaybe . haddockHtmlLocation $ flags haddockTarget = fromFlagOrDefault ForDevelopment (haddockForHackage flags') (haddockProg, version, _) <- requireProgramVersion verbosity haddockProgram (orLaterVersion (mkVersion [2,0])) (withPrograms lbi) -- various sanity checks when ( flag haddockHoogle && version < mkVersion [2,2]) $ die' verbosity "haddock 2.0 and 2.1 do not support the --hoogle flag." haddockGhcVersionStr <- getProgramOutput verbosity haddockProg ["--ghc-version"] case (simpleParse haddockGhcVersionStr, compilerCompatVersion GHC comp) of (Nothing, _) -> die' verbosity "Could not get GHC version from Haddock" (_, Nothing) -> die' verbosity "Could not get GHC version from compiler" (Just haddockGhcVersion, Just ghcVersion) | haddockGhcVersion == ghcVersion -> return () | otherwise -> die' verbosity $ "Haddock's internal GHC version must match the configured " ++ "GHC version.\n" ++ "The GHC version is " ++ display ghcVersion ++ " but " ++ "haddock is using GHC version " ++ display haddockGhcVersion -- the tools match the requests, we can proceed when (flag haddockHscolour) $ hscolour' (warn verbosity) haddockTarget pkg_descr lbi suffixes (defaultHscolourFlags `mappend` haddockToHscolour flags) libdirArgs <- getGhcLibDir verbosity lbi let commonArgs = mconcat [ libdirArgs , fromFlags (haddockTemplateEnv lbi (packageId pkg_descr)) flags , fromPackageDescription haddockTarget pkg_descr ] withAllComponentsInBuildOrder pkg_descr lbi $ \component clbi -> do componentInitialBuildSteps (flag haddockDistPref) pkg_descr lbi clbi verbosity preprocessComponent pkg_descr component lbi clbi False verbosity suffixes let doExe com = case (compToExe com) of Just exe -> do withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $ \tmp -> do exeArgs <- fromExecutable verbosity tmp lbi clbi htmlTemplate version exe let exeArgs' = commonArgs `mappend` exeArgs runHaddock verbosity tmpFileOpts comp platform haddockProg exeArgs' Nothing -> do warn (fromFlag $ haddockVerbosity flags) "Unsupported component, skipping..." return () -- We define 'smsg' once and then reuse it inside the case, so that -- we don't say we are running Haddock when we actually aren't -- (e.g., Haddock is not run on non-libraries) smsg :: IO () smsg = setupMessage' verbosity "Running Haddock on" (packageId pkg_descr) (componentLocalName clbi) (maybeComponentInstantiatedWith clbi) case component of CLib lib -> do withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $ \tmp -> do smsg libArgs <- fromLibrary verbosity tmp lbi clbi htmlTemplate version lib let libArgs' = commonArgs `mappend` libArgs runHaddock verbosity tmpFileOpts comp platform haddockProg libArgs' CFLib flib -> when (flag haddockForeignLibs) $ do withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $ \tmp -> do smsg flibArgs <- fromForeignLib verbosity tmp lbi clbi htmlTemplate version flib let libArgs' = commonArgs `mappend` flibArgs runHaddock verbosity tmpFileOpts comp platform haddockProg libArgs' CExe _ -> when (flag haddockExecutables) $ smsg >> doExe component CTest _ -> when (flag haddockTestSuites) $ smsg >> doExe component CBench _ -> when (flag haddockBenchmarks) $ smsg >> doExe component for_ (extraDocFiles pkg_descr) $ \ fpath -> do files <- matchFileGlob fpath for_ files $ copyFileTo verbosity (unDir $ argOutputDir commonArgs) -- ------------------------------------------------------------------------------ -- Contributions to HaddockArgs (see also Doctest.hs for very similar code). fromFlags :: PathTemplateEnv -> HaddockFlags -> HaddockArgs fromFlags env flags = mempty { argHideModules = (maybe mempty (All . not) $ flagToMaybe (haddockInternal flags), mempty), argLinkSource = if fromFlag (haddockHscolour flags) then Flag ("src/%{MODULE/./-}.html" ,"src/%{MODULE/./-}.html#%{NAME}" ,"src/%{MODULE/./-}.html#line-%{LINE}") else NoFlag, argCssFile = haddockCss flags, argContents = fmap (fromPathTemplate . substPathTemplate env) (haddockContents flags), argVerbose = maybe mempty (Any . (>= deafening)) . flagToMaybe $ haddockVerbosity flags, argOutput = Flag $ case [ Html | Flag True <- [haddockHtml flags] ] ++ [ Hoogle | Flag True <- [haddockHoogle flags] ] of [] -> [ Html ] os -> os, argOutputDir = maybe mempty Dir . flagToMaybe $ haddockDistPref flags } fromPackageDescription :: HaddockTarget -> PackageDescription -> HaddockArgs fromPackageDescription haddockTarget pkg_descr = mempty { argInterfaceFile = Flag $ haddockName pkg_descr, argPackageName = Flag $ packageId $ pkg_descr, argOutputDir = Dir $ "doc" </> "html" </> haddockDirName haddockTarget pkg_descr, argPrologue = Flag $ if null desc then synopsis pkg_descr else desc, argTitle = Flag $ showPkg ++ subtitle } where desc = PD.description pkg_descr showPkg = display (packageId pkg_descr) subtitle | null (synopsis pkg_descr) = "" | otherwise = ": " ++ synopsis pkg_descr componentGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> GhcOptions componentGhcOptions verbosity lbi bi clbi odir = let f = case compilerFlavor (compiler lbi) of GHC -> GHC.componentGhcOptions GHCJS -> GHCJS.componentGhcOptions _ -> error $ "Distribution.Simple.Haddock.componentGhcOptions:" ++ "haddock only supports GHC and GHCJS" in f verbosity lbi bi clbi odir mkHaddockArgs :: Verbosity -> FilePath -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> Version -> [FilePath] -> BuildInfo -> IO HaddockArgs mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles bi = do ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) { -- Noooooooooo!!!!!111 -- haddock stomps on our precious .hi -- and .o files. Workaround by telling -- haddock to write them elsewhere. ghcOptObjDir = toFlag tmp, ghcOptHiDir = toFlag tmp, ghcOptStubDir = toFlag tmp } `mappend` getGhcCppOpts haddockVersion bi sharedOpts = vanillaOpts { ghcOptDynLinkMode = toFlag GhcDynamicOnly, ghcOptFPic = toFlag True, ghcOptHiSuffix = toFlag "dyn_hi", ghcOptObjSuffix = toFlag "dyn_o", ghcOptExtra = toNubListR $ hcSharedOptions GHC bi } opts <- if withVanillaLib lbi then return vanillaOpts else if withSharedLib lbi then return sharedOpts else die' verbosity $ "Must have vanilla or shared libraries " ++ "enabled in order to run haddock" ghcVersion <- maybe (die' verbosity "Compiler has no GHC version") return (compilerCompatVersion GHC (compiler lbi)) return ifaceArgs { argGhcOptions = toFlag (opts, ghcVersion), argTargets = inFiles } fromLibrary :: Verbosity -> FilePath -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> Version -> Library -> IO HaddockArgs fromLibrary verbosity tmp lbi clbi htmlTemplate haddockVersion lib = do inFiles <- map snd `fmap` getLibSourceFiles verbosity lbi lib clbi args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles (libBuildInfo lib) return args { argHideModules = (mempty, otherModules (libBuildInfo lib)) } fromExecutable :: Verbosity -> FilePath -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> Version -> Executable -> IO HaddockArgs fromExecutable verbosity tmp lbi clbi htmlTemplate haddockVersion exe = do inFiles <- map snd `fmap` getExeSourceFiles verbosity lbi exe clbi args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles (buildInfo exe) return args { argOutputDir = Dir $ unUnqualComponentName $ exeName exe, argTitle = Flag $ unUnqualComponentName $ exeName exe } fromForeignLib :: Verbosity -> FilePath -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> Version -> ForeignLib -> IO HaddockArgs fromForeignLib verbosity tmp lbi clbi htmlTemplate haddockVersion flib = do inFiles <- map snd `fmap` getFLibSourceFiles verbosity lbi flib clbi args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles (foreignLibBuildInfo flib) return args { argOutputDir = Dir $ unUnqualComponentName $ foreignLibName flib, argTitle = Flag $ unUnqualComponentName $ foreignLibName flib } compToExe :: Component -> Maybe Executable compToExe comp = case comp of CTest test@TestSuite { testInterface = TestSuiteExeV10 _ f } -> Just Executable { exeName = testName test, modulePath = f, exeScope = ExecutablePublic, buildInfo = testBuildInfo test } CBench bench@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f } -> Just Executable { exeName = benchmarkName bench, modulePath = f, exeScope = ExecutablePublic, buildInfo = benchmarkBuildInfo bench } CExe exe -> Just exe _ -> Nothing getInterfaces :: Verbosity -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -- ^ template for HTML location -> IO HaddockArgs getInterfaces verbosity lbi clbi htmlTemplate = do (packageFlags, warnings) <- haddockPackageFlags verbosity lbi clbi htmlTemplate traverse_ (warn (verboseUnmarkOutput verbosity)) warnings return $ mempty { argInterfaces = packageFlags } getGhcCppOpts :: Version -> BuildInfo -> GhcOptions getGhcCppOpts haddockVersion bi = mempty { ghcOptExtensions = toNubListR [EnableExtension CPP | needsCpp], ghcOptCppOptions = toNubListR defines } where needsCpp = EnableExtension CPP `elem` usedExtensions bi defines = [haddockVersionMacro] haddockVersionMacro = "-D__HADDOCK_VERSION__=" ++ show (v1 * 1000 + v2 * 10 + v3) where [v1, v2, v3] = take 3 $ versionNumbers haddockVersion ++ [0,0] getGhcLibDir :: Verbosity -> LocalBuildInfo -> IO HaddockArgs getGhcLibDir verbosity lbi = do l <- case compilerFlavor (compiler lbi) of GHC -> GHC.getLibDir verbosity lbi GHCJS -> GHCJS.getLibDir verbosity lbi _ -> error "haddock only supports GHC and GHCJS" return $ mempty { argGhcLibDir = Flag l } -- ------------------------------------------------------------------------------ -- | Call haddock with the specified arguments. runHaddock :: Verbosity -> TempFileOptions -> Compiler -> Platform -> ConfiguredProgram -> HaddockArgs -> IO () runHaddock verbosity tmpFileOpts comp platform haddockProg args = do let haddockVersion = fromMaybe (error "unable to determine haddock version") (programVersion haddockProg) renderArgs verbosity tmpFileOpts haddockVersion comp platform args $ \(flags,result)-> do runProgram verbosity haddockProg flags notice verbosity $ "Documentation created: " ++ result renderArgs :: Verbosity -> TempFileOptions -> Version -> Compiler -> Platform -> HaddockArgs -> (([String], FilePath) -> IO a) -> IO a renderArgs verbosity tmpFileOpts version comp platform args k = do let haddockSupportsUTF8 = version >= mkVersion [2,14,4] haddockSupportsResponseFiles = version > mkVersion [2,16,2] createDirectoryIfMissingVerbose verbosity True outputDir withTempFileEx tmpFileOpts outputDir "haddock-prologue.txt" $ \prologueFileName h -> do do when haddockSupportsUTF8 (hSetEncoding h utf8) hPutStrLn h $ fromFlag $ argPrologue args hClose h let pflag = "--prologue=" ++ prologueFileName renderedArgs = pflag : renderPureArgs version comp platform args if haddockSupportsResponseFiles then withTempFileEx tmpFileOpts outputDir "haddock-response.txt" $ \responseFileName hf -> do when haddockSupportsUTF8 (hSetEncoding hf utf8) let responseContents = unlines $ map escapeArg renderedArgs hPutStr hf responseContents hClose hf info verbosity $ responseFileName ++ " contents: <<<" info verbosity responseContents info verbosity $ ">>> " ++ responseFileName let respFile = "@" ++ responseFileName k ([respFile], result) else k (renderedArgs, result) where outputDir = (unDir $ argOutputDir args) result = intercalate ", " . map (\o -> outputDir </> case o of Html -> "index.html" Hoogle -> pkgstr <.> "txt") $ arg argOutput where pkgstr = display $ packageName pkgid pkgid = arg argPackageName arg f = fromFlag $ f args -- Support a gcc-like response file syntax. Each separate -- argument and its possible parameter(s), will be separated in the -- response file by an actual newline; all other whitespace, -- single quotes, double quotes, and the character used for escaping -- (backslash) are escaped. The called program will need to do a similar -- inverse operation to de-escape and re-constitute the argument list. escape cs c | isSpace c || '\\' == c || '\'' == c || '"' == c = c:'\\':cs -- n.b., our caller must reverse the result | otherwise = c:cs escapeArg = reverse . foldl' escape [] renderPureArgs :: Version -> Compiler -> Platform -> HaddockArgs -> [String] renderPureArgs version comp platform args = concat [ (:[]) . (\f -> "--dump-interface="++ unDir (argOutputDir args) </> f) . fromFlag . argInterfaceFile $ args , if isVersion 2 16 then (\pkg -> [ "--package-name=" ++ display (pkgName pkg) , "--package-version="++display (pkgVersion pkg) ]) . fromFlag . argPackageName $ args else [] , (\(All b,xs) -> bool (map (("--hide=" ++). display) xs) [] b) . argHideModules $ args , bool ["--ignore-all-exports"] [] . getAny . argIgnoreExports $ args , maybe [] (\(m,e,l) -> ["--source-module=" ++ m ,"--source-entity=" ++ e] ++ if isVersion 2 14 then ["--source-entity-line=" ++ l] else [] ) . flagToMaybe . argLinkSource $ args , maybe [] ((:[]) . ("--css="++)) . flagToMaybe . argCssFile $ args , maybe [] ((:[]) . ("--use-contents="++)) . flagToMaybe . argContents $ args , bool [] [verbosityFlag] . getAny . argVerbose $ args , map (\o -> case o of Hoogle -> "--hoogle"; Html -> "--html") . fromFlag . argOutput $ args , renderInterfaces . argInterfaces $ args , (:[]) . ("--odir="++) . unDir . argOutputDir $ args , (:[]) . ("--title="++) . (bool (++" (internal documentation)") id (getAny $ argIgnoreExports args)) . fromFlag . argTitle $ args , [ "--optghc=" ++ opt | (opts, _ghcVer) <- flagToList (argGhcOptions args) , opt <- renderGhcOptions comp platform opts ] , maybe [] (\l -> ["-B"++l]) $ flagToMaybe (argGhcLibDir args) -- error if Nothing? , argTargets $ args ] where renderInterfaces = map (\(i,mh) -> "--read-interface=" ++ maybe "" (++",") mh ++ i) bool a b c = if c then a else b isVersion major minor = version >= mkVersion [major,minor] verbosityFlag | isVersion 2 5 = "--verbosity=1" | otherwise = "--verbose" --------------------------------------------------------------------------------- -- | Given a list of 'InstalledPackageInfo's, return a list of interfaces and -- HTML paths, and an optional warning for packages with missing documentation. haddockPackagePaths :: [InstalledPackageInfo] -> Maybe (InstalledPackageInfo -> FilePath) -> NoCallStackIO ([(FilePath, Maybe FilePath)], Maybe String) haddockPackagePaths ipkgs mkHtmlPath = do interfaces <- sequenceA [ case interfaceAndHtmlPath ipkg of Nothing -> return (Left (packageId ipkg)) Just (interface, html) -> do exists <- doesFileExist interface if exists then return (Right (interface, html)) else return (Left pkgid) | ipkg <- ipkgs, let pkgid = packageId ipkg , pkgName pkgid `notElem` noHaddockWhitelist ] let missing = [ pkgid | Left pkgid <- interfaces ] warning = "The documentation for the following packages are not " ++ "installed. No links will be generated to these packages: " ++ intercalate ", " (map display missing) flags = rights interfaces return (flags, if null missing then Nothing else Just warning) where -- Don't warn about missing documentation for these packages. See #1231. noHaddockWhitelist = map mkPackageName [ "rts" ] -- Actually extract interface and HTML paths from an 'InstalledPackageInfo'. interfaceAndHtmlPath :: InstalledPackageInfo -> Maybe (FilePath, Maybe FilePath) interfaceAndHtmlPath pkg = do interface <- listToMaybe (InstalledPackageInfo.haddockInterfaces pkg) html <- case mkHtmlPath of Nothing -> fmap fixFileUrl (listToMaybe (InstalledPackageInfo.haddockHTMLs pkg)) Just mkPath -> Just (mkPath pkg) return (interface, if null html then Nothing else Just html) where -- The 'haddock-html' field in the hc-pkg output is often set as a -- native path, but we need it as a URL. See #1064. fixFileUrl f | isAbsolute f = "file://" ++ f | otherwise = f haddockPackageFlags :: Verbosity -> LocalBuildInfo -> ComponentLocalBuildInfo -> Maybe PathTemplate -> IO ([(FilePath, Maybe FilePath)], Maybe String) haddockPackageFlags verbosity lbi clbi htmlTemplate = do let allPkgs = installedPkgs lbi directDeps = map fst (componentPackageDeps clbi) transitiveDeps <- case PackageIndex.dependencyClosure allPkgs directDeps of Left x -> return x Right inf -> die' verbosity $ "internal error when calculating transitive " ++ "package dependencies.\nDebug info: " ++ show inf haddockPackagePaths (PackageIndex.allPackages transitiveDeps) mkHtmlPath where mkHtmlPath = fmap expandTemplateVars htmlTemplate expandTemplateVars tmpl pkg = fromPathTemplate . substPathTemplate (env pkg) $ tmpl env pkg = haddockTemplateEnv lbi (packageId pkg) haddockTemplateEnv :: LocalBuildInfo -> PackageIdentifier -> PathTemplateEnv haddockTemplateEnv lbi pkg_id = (PrefixVar, prefix (installDirTemplates lbi)) -- We want the legacy unit ID here, because it gives us nice paths -- (Haddock people don't care about the dependencies) : initialPathTemplateEnv pkg_id (mkLegacyUnitId pkg_id) (compilerInfo (compiler lbi)) (hostPlatform lbi) -- ------------------------------------------------------------------------------ -- hscolour support. hscolour :: PackageDescription -> LocalBuildInfo -> [PPSuffixHandler] -> HscolourFlags -> IO () hscolour = hscolour' dieNoVerbosity ForDevelopment hscolour' :: (String -> IO ()) -- ^ Called when the 'hscolour' exe is not found. -> HaddockTarget -> PackageDescription -> LocalBuildInfo -> [PPSuffixHandler] -> HscolourFlags -> IO () hscolour' onNoHsColour haddockTarget pkg_descr lbi suffixes flags = either onNoHsColour (\(hscolourProg, _, _) -> go hscolourProg) =<< lookupProgramVersion verbosity hscolourProgram (orLaterVersion (mkVersion [1,8])) (withPrograms lbi) where go :: ConfiguredProgram -> IO () go hscolourProg = do setupMessage verbosity "Running hscolour for" (packageId pkg_descr) createDirectoryIfMissingVerbose verbosity True $ hscolourPref haddockTarget distPref pkg_descr withAllComponentsInBuildOrder pkg_descr lbi $ \comp clbi -> do componentInitialBuildSteps distPref pkg_descr lbi clbi verbosity preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes let doExe com = case (compToExe com) of Just exe -> do let outputDir = hscolourPref haddockTarget distPref pkg_descr </> unUnqualComponentName (exeName exe) </> "src" runHsColour hscolourProg outputDir =<< getExeSourceFiles verbosity lbi exe clbi Nothing -> do warn (fromFlag $ hscolourVerbosity flags) "Unsupported component, skipping..." return () case comp of CLib lib -> do let outputDir = hscolourPref haddockTarget distPref pkg_descr </> "src" runHsColour hscolourProg outputDir =<< getLibSourceFiles verbosity lbi lib clbi CFLib flib -> do let outputDir = hscolourPref haddockTarget distPref pkg_descr </> unUnqualComponentName (foreignLibName flib) </> "src" runHsColour hscolourProg outputDir =<< getFLibSourceFiles verbosity lbi flib clbi CExe _ -> when (fromFlag (hscolourExecutables flags)) $ doExe comp CTest _ -> when (fromFlag (hscolourTestSuites flags)) $ doExe comp CBench _ -> when (fromFlag (hscolourBenchmarks flags)) $ doExe comp stylesheet = flagToMaybe (hscolourCSS flags) verbosity = fromFlag (hscolourVerbosity flags) distPref = fromFlag (hscolourDistPref flags) runHsColour prog outputDir moduleFiles = do createDirectoryIfMissingVerbose verbosity True outputDir case stylesheet of -- copy the CSS file Nothing | programVersion prog >= Just (mkVersion [1,9]) -> runProgram verbosity prog ["-print-css", "-o" ++ outputDir </> "hscolour.css"] | otherwise -> return () Just s -> copyFileVerbose verbosity s (outputDir </> "hscolour.css") for_ moduleFiles $ \(m, inFile) -> runProgram verbosity prog ["-css", "-anchor", "-o" ++ outFile m, inFile] where outFile m = outputDir </> intercalate "-" (ModuleName.components m) <.> "html" haddockToHscolour :: HaddockFlags -> HscolourFlags haddockToHscolour flags = HscolourFlags { hscolourCSS = haddockHscolourCss flags, hscolourExecutables = haddockExecutables flags, hscolourTestSuites = haddockTestSuites flags, hscolourBenchmarks = haddockBenchmarks flags, hscolourForeignLibs = haddockForeignLibs flags, hscolourVerbosity = haddockVerbosity flags, hscolourDistPref = haddockDistPref flags } -- ------------------------------------------------------------------------------ -- Boilerplate Monoid instance. instance Monoid HaddockArgs where mempty = gmempty mappend = (<>) instance Semigroup HaddockArgs where (<>) = gmappend instance Monoid Directory where mempty = Dir "." mappend = (<>) instance Semigroup Directory where Dir m <> Dir n = Dir $ m </> n
mydaum/cabal
Cabal/Distribution/Simple/Haddock.hs
Haskell
bsd-3-clause
32,090
{-# LANGUAGE QuasiQuotes #-} module Huff ( huff, Spec, Domain(), Problem(), Literal(), Term(), module Huff ) where import Huff.Compile.AST (Problem,Term(..),Literal(..)) import Huff.Input (Spec,Domain,Operator(..)) import Huff.QQ (huff) import qualified Huff.FF.Planner as FF import Data.Maybe (mapMaybe) infixr 3 /\ (/\) :: Term -> Term -> Term p /\ q = TAnd [p,q] infixr 4 \/ (\/) :: Term -> Term -> Term p \/ q = TOr [p,q] imply :: Term -> Term -> Term imply = TImply class Has_neg a where neg :: a -> a instance Has_neg Literal where neg (LAtom a) = LNot a neg (LNot a) = LAtom a instance Has_neg Term where neg = TNot findPlan :: Spec a -> IO (Maybe [a]) findPlan (prob,dom) = do mb <- FF.findPlan prob dom case mb of Just xs -> return (Just (mapMaybe opVal (FF.resSteps xs))) Nothing -> return Nothing
elliottt/huff
src/Huff.hs
Haskell
bsd-3-clause
913
{-# LANGUAGE NoImplicitPrelude , CPP , GADTs , FlexibleContexts , ScopedTypeVariables , KindSignatures , TypeFamilies , DeriveDataTypeable , TypeOperators #-} ----------------------------------------------------------------------------- -- | -- Module : Math.Combinatorics.Species.Enumerate -- Copyright : (c) Brent Yorgey 2010 -- License : BSD-style (see LICENSE) -- Maintainer : byorgey@cis.upenn.edu -- Stability : experimental -- -- Enumeration (i.e. exhaustive generation of structures) of both -- labeled and unlabeled species. -- ----------------------------------------------------------------------------- module Math.Combinatorics.Species.Enumerate ( -- * Enumeration methods enumerate , enumerateL , enumerateU , enumerateM , enumerateAll , enumerateAllU -- * Tools for dealing with structure types , Enumerable(..) , Structure(..), extractStructure, unsafeExtractStructure , structureType, showStructureType -- * Where all the work actually happens , enumerate', enumerateE ) where import Math.Combinatorics.Species.Class import Math.Combinatorics.Species.Types import Math.Combinatorics.Species.AST import Math.Combinatorics.Species.Structures import qualified Math.Combinatorics.Species.Util.Interval as I import qualified Math.Combinatorics.Multiset as MS import Math.Combinatorics.Multiset (Multiset(..), (+:)) import Data.Typeable import NumericPrelude #if MIN_VERSION_numeric_prelude(0,2,0) #else import PreludeBase hiding (cycle) #endif -- | Given an AST describing a species, with a phantom type parameter -- representing the structure of the species, and an underlying -- multiset of elements, compute a list of all possible structures -- built over the underlying multiset. (Of course, it would be -- really nice to have a real dependently-typed language for this!) -- -- Unfortunately, 'TSpeciesAST' cannot be made an instance of -- 'Species', so if we want to be able to enumerate structures given -- an expression of the 'Species' DSL as input, the output must be -- existentially quantified; see 'enumerateE'. -- -- Generating structures over base elements from a /multiset/ -- unifies labeled and unlabeled generation into one framework. -- To enumerate labeled structures, use a multiset where each -- element occurs exactly once; to enumerate unlabeled structures, -- use a multiset with the desired number of copies of a single -- element. To do labeled generation we could get away without the -- generality of multisets, but to do unlabeled generation we need -- the full generality anyway. -- -- 'enumerate'' does all the actual work, but is not meant to be used -- directly; use one of the specialized @enumerateXX@ methods. enumerate' :: TSpeciesAST s -> Multiset a -> [s a] enumerate' TZero _ = [] enumerate' TOne (MS []) = [Unit] enumerate' TOne _ = [] enumerate' (TN n) (MS []) = map Const [1..n] enumerate' (TN _) _ = [] enumerate' TX (MS [(x,1)]) = [Id x] enumerate' TX _ = [] enumerate' TE xs = [Set (MS.toList xs)] enumerate' TC m = map Cycle (MS.cycles m) enumerate' TL xs = MS.permutations xs enumerate' TSubset xs = map (Set . MS.toList . fst) (MS.splits xs) enumerate' (TKSubset k) xs = map (Set . MS.toList) (MS.kSubsets (fromIntegral k) xs) enumerate' TElt xs = map (Id . fst) . MS.toCounts $ xs enumerate' (f :+:: g) xs = map Inl (enumerate' (stripI f) xs) ++ map Inr (enumerate' (stripI g) xs) -- A better solution here might be to change MS.splits to only -- return splits which are of appropriate sizes. enumerate' (f :*:: g) xs = [ x :*: y | (s1,s2) <- MS.splits xs , (fromIntegral $ MS.size s1) `I.elem` (getI f) , (fromIntegral $ MS.size s2) `I.elem` (getI g) , x <- enumerate' (stripI f) s1 , y <- enumerate' (stripI g) s2 ] enumerate' (f :.:: g) xs = [ Comp y | p <- MS.partitions xs , (fromIntegral $ MS.size p) `I.elem` (getI f) , all ((`I.elem` (getI g)) . fromIntegral . MS.size) (MS.toList p) , xs' <- MS.sequenceMS . fmap (enumerate' (stripI g)) $ p , y <- enumerate' (stripI f) xs' ] enumerate' (f :><:: g) xs | any (/= 1) $ MS.getCounts xs = error "Unlabeled enumeration does not (yet) work with cartesian product." enumerate' (f :><:: g) xs = [ x :*: y | x <- enumerate' (stripI f) xs , y <- enumerate' (stripI g) xs ] enumerate' (f :@:: g) xs | any (/= 1) $ MS.getCounts xs = error "Unlabeled enumeration does not (yet) work with functor composition." enumerate' (f :@:: g) xs = map Comp . enumerate' (stripI f) . MS.fromDistinctList . enumerate' (stripI g) $ xs enumerate' (TDer f) xs = map Comp . enumerate' (stripI f) $ (Star,1) +: fmap Original xs enumerate' (TNonEmpty f) (MS []) = [] enumerate' (TNonEmpty f) xs = enumerate' (stripI f) xs enumerate' (TRec f) xs = map Mu $ enumerate' (apply f (TRec f)) xs enumerate' (TOfSize f p) xs | p (fromIntegral . sum . MS.getCounts $ xs) = enumerate' (stripI f) xs | otherwise = [] enumerate' (TOfSizeExactly f n) xs | (fromIntegral . sum . MS.getCounts $ xs) == n = enumerate' (stripI f) xs | otherwise = [] -- | An existential wrapper for structures, hiding the structure -- functor and ensuring that it is 'Typeable'. data Structure a where Structure :: Typeable f => f a -> Structure a -- | Extract the contents from a 'Structure' wrapper, if we know the -- type, and map it into an isomorphic type. If the type doesn't -- match, return a helpful error message instead. extractStructure :: forall f a. (Enumerable f, Typeable a) => Structure a -> Either String (f a) extractStructure (Structure s) = case cast s of Nothing -> Left $ "Structure type mismatch.\n" ++ " Expected: " ++ showStructureType (typeOf (undefined :: StructTy f a)) ++ "\n" ++ " Inferred: " ++ showStructureType (typeOf s) Just y -> Right (iso y) -- | A version of 'extractStructure' which calls 'error' with the -- message in the case of a type mismatch, instead of returning an -- 'Either'. unsafeExtractStructure :: (Enumerable f, Typeable a) => Structure a -> f a unsafeExtractStructure = either error id . extractStructure -- | @'structureType' s@ returns a String representation of the -- functor type which represents the structure of the species @s@. -- In particular, if @structureType s@ prints @\"T\"@, then you can -- safely use 'enumerate' and friends by writing -- -- > enumerate s ls :: [T a] -- -- where @ls :: [a]@. -- -- For example, -- -- > > structureType octopus -- > "Comp Cycle []" -- > > enumerate octopus [1,2,3] :: [Comp Cycle [] Int] -- > [<[3,2,1]>,<[3,1,2]>,<[2,3,1]>,<[2,1,3]>,<[1,3,2]> -- > ,<[1,2,3]>,<[1],[3,2]>,<[1],[2,3]>,<[3,1],[2]> -- > ,<[1,3],[2]>,<[2,1],[3]>,<[1,2],[3]>,<[2],[1],[3]> -- > ,<[1],[2],[3]>] -- -- Note, however, that providing a type annotation on 'enumerate' in -- this way is usually only necessary at the @ghci@ prompt; when used -- in the context of a larger program the type of a call to -- 'enumerate' can often be inferred. structureType :: ESpeciesAST -> String structureType (Wrap s) = showStructureType . extractType $ (stripI s) where extractType :: forall s. Typeable s => TSpeciesAST s -> TypeRep extractType _ = typeOf1 (undefined :: s ()) -- | Show a 'TypeRep' while stripping off qualifier portions of 'TyCon' -- names. This is essentially copied and pasted from the -- "Data.Typeable" source, with a number of cases taken out that we -- don't care about (special cases for @(->)@, tuples, etc.). showStructureType :: TypeRep -> String showStructureType t = showsPrecST 0 t "" where showsPrecST :: Int -> TypeRep -> ShowS showsPrecST p t = case splitTyConApp t of (tycon, []) -> showString (dropQuals $ tyConName tycon) (tycon, [x]) | tyConName tycon == "[]" -> showChar '[' . showsPrecST 11 x . showChar ']' (tycon, args) -> showParen (p > 9) $ showString (dropQuals $ tyConName tycon) . showChar ' ' . showArgsST args showArgsST :: [TypeRep] -> ShowS showArgsST [] = id showArgsST [t] = showsPrecST 10 t showArgsST (t:ts) = showsPrecST 10 t . showChar ' ' . showArgsST ts dropQuals :: String -> String dropQuals = reverse . takeWhile (/= '.') . reverse -- | 'enumerateE' is a variant of 'enumerate'' which takes an -- (existentially quantified) typed AST and returns a list of -- existentially quantified structures. This is also not meant to -- be used directly. Instead, you should use one of the other -- @enumerateX@ methods. enumerateE :: ESpeciesAST -> Multiset a -> [Structure a] enumerateE (Wrap s) m | fromIntegral (sum (MS.getCounts m)) `I.elem` (getI s) = map Structure (enumerate' (stripI s) m) | otherwise = [] -- XXX add examples to all of these. -- | @enumerate s ls@ computes a complete list of distinct -- @s@-structures over the underlying multiset of labels @ls@. For -- example: -- -- > > enumerate octopi [1,2,3] :: [Comp Cycle [] Int] -- > [<[3,2,1]>,<[3,1,2]>,<[2,3,1]>,<[2,1,3]>,<[1,3,2]>,<[1,2,3]>, -- > <[1],[3,2]>,<[1],[2,3]>,<[3,1],[2]>,<[1,3],[2]>,<[2,1],[3]>, -- > <[1,2],[3]>,<[2],[1],[3]>,<[1],[2],[3]>] -- > -- > > enumerate octopi [1,1,2] :: [Comp Cycle [] Int] -- > [<[2,1,1]>,<[1,2,1]>,<[1,1,2]>,<[2,1],[1]>,<[1,2],[1]>, -- > <[1,1],[2]>,<[1],[1],[2]>] -- > -- > > enumerate subsets "abc" :: [Set Int] -- > [{'a','b','c'},{'a','b'},{'a','c'},{'a'},{'b','c'},{'b'},{'c'},{}] -- > -- > > enumerate simpleGraphs [1,2,3] :: [Comp Set Set Int] -- > [{{1,2},{1,3},{2,3}},{{1,2},{1,3}},{{1,2},{2,3}},{{1,2}},{{1,3},{2,3}}, -- > {{1,3}},{{2,3}},{}] -- -- There is one caveat: since the type of the generated structures -- is different for each species, they must be cast (using the magic -- of "Data.Typeable") out of an existential wrapper; this is why -- type annotations are required in all the examples above. Of -- course, if a call to 'enumerate' is used in the context of some -- larger program, a type annotation will probably not be needed, -- due to the magic of type inference. -- -- For help in knowing what type annotation you can give when -- enumerating the structures of a particular species at the @ghci@ -- prompt, see the 'structureType' function. To be able to use your -- own custom data type in an enumeration, just make your data type -- an instance of the 'Enumerable' type class; this can be done for -- you automatically by "Math.Combinatorics.Species.TH". -- -- If an invalid type annotation is given, 'enumerate' will call -- 'error' with a helpful error message. This should not be much of -- an issue in practice, since usually 'enumerate' will be used at a -- specific type; it's hard to imagine a usage of 'enumerate' which -- will sometimes work and sometimes fail. However, those who like -- their functions total can use 'extractStructure' to make a -- version of 'enumerate' (or the other variants) with a return type -- of @['Either' 'String' (f a)]@ (which will return an annoying ton of -- duplicate error messages) or @'Either' 'String' [f a]@ (which has the -- unfortunate property of being much less lazy than the current -- versions, since it must compute the entire list before deciding -- whether to return @'Left'@ or @'Right'@). -- -- For slight variants on 'enumerate', see 'enumerateL', -- 'enumerateU', and 'enumerateM'. enumerate :: (Enumerable f, Typeable a, Eq a) => SpeciesAST -> [a] -> [f a] enumerate s = enumerateM s . MS.fromListEq -- | Labeled enumeration: given a species expression and a list of -- labels (which are assumed to be distinct), compute the list of -- all structures built from the given labels. If the type given -- for the enumeration does not match the species expression (via an -- 'Enumerable' instance), call 'error' with an error message -- explaining the mismatch. This is slightly more efficient than -- 'enumerate' for lists of labels which are known to be distinct, -- since it doesn't have to waste time checking for -- duplicates. (However, it probably doesn't really make much -- difference, since the time to do the actual enumeration will -- usually dwarf the time to process the list of labels anyway.) -- -- For example: -- -- > > enumerateL ballots [1,2,3] :: [Comp [] Set Int] -- > [[{1,2,3}],[{2,3},{1}],[{1},{2,3}],[{2},{1,3}],[{1,3},{2}],[{3},{1,2}] -- > ,[{1,2},{3}],[{3},{2},{1}],[{3},{1},{2}],[{2},{3},{1}],[{2},{1},{3}] -- > ,[{1},{3},{2}],[{1},{2},{3}]] enumerateL :: (Enumerable f, Typeable a) => SpeciesAST -> [a] -> [f a] enumerateL s = enumerateM s . MS.fromDistinctList -- | Unlabeled enumeration: given a species expression and an integer -- indicating the number of labels to use, compute the list of all -- unlabeled structures of the given size. If the type given for -- the enumeration does not match the species expression, call -- 'error' with an error message explaining the mismatch. -- -- Note that @'enumerateU' s n@ is equivalent to @'enumerate' s -- (replicate n ())@. -- -- For example: -- -- > > enumerateU octopi 4 :: [Comp Cycle [] ()] -- > [<[(),(),(),()]>,<[(),()],[(),()]>,<[(),(),()],[()]> -- > ,<[(),()],[()],[()]>,<[()],[()],[()],[()]>] enumerateU :: Enumerable f => SpeciesAST -> Int -> [f ()] enumerateU s n = enumerateM s (MS.fromCounts [((),n)]) -- | General enumeration: given a species expression and a multiset of -- labels, compute the list of all distinct structures built from -- the given labels. If the type given for the enumeration does not -- match the species expression, call 'error' with a message -- explaining the mismatch. enumerateM :: (Enumerable f, Typeable a) => SpeciesAST -> Multiset a -> [f a] enumerateM s m = map unsafeExtractStructure $ enumerateE (annotate s) m -- | Lazily enumerate all unlabeled structures. -- -- For example: -- -- > > take 10 $ enumerateAllU octopi :: [Comp Cycle [] ()] -- > [<[()]>,<[(),()]>,<[()],[()]>,<[(),(),()]>,<[(),()],[()]> -- > ,<[()],[()],[()]>,<[(),(),(),()]>,<[(),()],[(),()]> -- > ,<[(),(),()],[()]>,<[(),()],[()],[()]>] enumerateAllU :: Enumerable f => SpeciesAST -> [f ()] enumerateAllU s = concatMap (enumerateU s) [0..] -- | Lazily enumerate all labeled structures, using [1..] as the -- labels. -- -- For example: -- -- > > take 10 $ enumerateAll ballots :: [Comp [] Set Int] -- > [[],[{1}],[{1,2}],[{2},{1}],[{1},{2}],[{1,2,3}],[{2,3},{1}] -- > ,[{1},{2,3}],[{2},{1,3}],[{1,3},{2}]] enumerateAll :: Enumerable f => SpeciesAST -> [f Int] enumerateAll s = concatMap (\n -> enumerateL s (take n [1..])) [0..] -- | The 'Enumerable' class allows you to enumerate structures of any -- type, by declaring an instance of 'Enumerable'. The 'Enumerable' -- instance requires you to declare a standard structure type (see -- "Math.Combinatorics.Species.Structures") associated with your -- type, and a mapping 'iso' from the standard type to your custom -- one. Instances are provided for all the standard structure types -- so you can enumerate species without having to provide your own -- custom data type as the target of the enumeration if you don't -- want to. -- -- You should only rarely have to explicitly make an instance of -- 'Enumerable' yourself; Template Haskell code to derive instances -- for you is provided in "Math.Combinatorics.Species.TH". class Typeable (StructTy f) => Enumerable (f :: * -> *) where -- | The standard structure type (see -- "Math.Combinatorics.Species.Structures") that will map into @f@. type StructTy f :: * -> * -- | The mapping from @'StructTy' f@ to @f@. iso :: StructTy f a -> f a instance Enumerable Void where type StructTy Void = Void iso = id instance Enumerable Unit where type StructTy Unit = Unit iso = id instance Typeable a => Enumerable (Const a) where type StructTy (Const a) = Const a iso = id instance Enumerable Id where type StructTy Id = Id iso = id instance (Enumerable f, Enumerable g) => Enumerable (f :+: g) where type StructTy (f :+: g) = StructTy f :+: StructTy g iso (Inl x) = Inl (iso x) iso (Inr y) = Inr (iso y) instance (Enumerable f, Enumerable g) => Enumerable (f :*: g) where type StructTy (f :*: g) = StructTy f :*: StructTy g iso (x :*: y) = iso x :*: iso y instance (Enumerable f, Functor f, Enumerable g) => Enumerable (f :.: g) where type StructTy (f :.: g) = StructTy f :.: StructTy g iso (Comp fgx) = Comp (fmap iso (iso fgx)) instance Enumerable [] where type StructTy [] = [] iso = id instance Enumerable Cycle where type StructTy Cycle = Cycle iso = id instance Enumerable Set where type StructTy Set = Set iso = id instance Enumerable Star where type StructTy Star = Star iso = id instance Typeable f => Enumerable (Mu f) where type StructTy (Mu f) = Mu f iso = id instance Enumerable Maybe where type StructTy Maybe = Unit :+: Id iso (Inl Unit) = Nothing iso (Inr (Id x)) = Just x
timsears/species
Math/Combinatorics/Species/Enumerate.hs
Haskell
bsd-3-clause
18,320
module Language.Granule.Syntax.Preprocessor.Latex ( processGranuleLatex , unLatex ) where import Data.Char (isSpace) import Control.Arrow ((>>>)) data DocType = Latex | GranuleBlock -- | Extract @\begin{env}@ code blocks @\end{env}@ from tex files on a -- line-by-line basis, where @env@ is the name of the relevant environment. Maps -- other lines to the empty string, such that line numbers are preserved. unLatex :: String -> (String -> String) unLatex env = processGranuleLatex (const "") env id -- | Transform the input by the given processing functions for Granule and Latex -- (currently operating on a line-by-line basis) processGranuleLatex :: (String -> String) -- ^ the processing function to apply to each line of latex -> String -- ^ the name of the environment to check -> (String -> String) -- ^ the processing function to apply to each line of granule code -> (String -> String) processGranuleLatex fTex env fGr = lines >>> (`zip` [1..]) >>> go Latex >>> unlines where go :: DocType -> [(String, Int)] -> [String] go Latex ((line, lineNumber) : ls) | strip line == "\\begin{" <> env <> "}" = fTex line : go GranuleBlock ls | strip line == "\\end{" <> env <> "}" = error $ "Unmatched `\\end{" <> env <> "}` on line " <> show lineNumber | otherwise = fTex line : go Latex ls go GranuleBlock ((line, lineNumber) : ls) | strip line == "\\end{" <> env <> "}" = fTex line : go Latex ls | strip line == "\\begin{" <> env <> "}" = error $ "Unmatched `\\begin{" <> env <> "}` on line " <> show lineNumber | otherwise = fGr line : go GranuleBlock ls go _ [] = [] -- Remove trailing whitespace (hey, should we be using @Text@?) strip :: String -> String strip = reverse . dropWhile isSpace . reverse . dropWhile isSpace
dorchard/gram_lang
frontend/src/Language/Granule/Syntax/Preprocessor/Latex.hs
Haskell
bsd-3-clause
1,907
{-# LANGUAGE OverloadedStrings #-} import Network.NetSpec import Network.NetSpec.Text -- Notice the restrictions NetSpec places on how you can communicate. -- Working within NetSpec isn't well-suited for all situations; -- it is specialized for situations where there is -- a deterministic sequence of communication. main :: IO () main = runSpec ServerSpec { _ports = [PortNumber 5001, PortNumber 5002] , _begin = \hs -> do hs ! "Welcome to the one-for-one chat program." hs ! "Send a message in order to receive one." hs ! "Say \"bye\" to stop." , _loop = \[a, b] () -> do lineA <- receive a lineB <- receive b a ! lineB b ! lineA if lineA == "bye\r" || lineB == "bye\r" then stop_ else continue_ , _end = \hs () -> hs ! "That's all folks." }
DanBurton/netspec
examples/Chat.hs
Haskell
bsd-3-clause
826
------------------------------------------------------------------------------ -- | -- Maintainer : Ralf Laemmel, Joost Visser -- Stability : experimental -- Portability : portable -- -- This module is part of 'Sdf2Haskell', a tool for generating a set of -- Haskell data types from an SDF grammar. This module provides functionality -- for calling the external parser SGLR from within Haskell and marshalling -- the resulting abstract syntax tree to a strongly-typed Haskell term. ------------------------------------------------------------------------------ module SGLR where import System.Exit import System.Environment (getProgName) import System.Cmd (system) import Data.Unique (newUnique, hashUnique) import System.IO (readFile,hPutStrLn,stderr) import System.Directory (removeFile) import Data.ATerm.Lib (fromATerm, readATerm, ATermConvertible, dehyphenAST, afunCap, ATerm(..) ) import ImplodePT (compensateImplodePT) ------------------------------------------------------------------------------ -- * Interaction with the system. -- | Call the external sglr parser. sglr :: ATermConvertible a => FilePath -- ^ table -> FilePath -- ^ term -> String -- ^ top sort -> IO a sglr tableName termName sortName = do unique <- newUnique let newName = termName++(show . hashUnique $ unique) let asfixName = newName++".asfix" let afName = newName++".af" let sglrCmd = "sglr -p "++tableName++ " -i "++termName++ " -o "++asfixName++ " -s "++sortName let implodeCmd = "implodePT -t -ALclpqX"++ " -i "++asfixName++ " -o "++afName progName <- getProgName errLn $ "["++progName++"] "++sglrCmd exitOK $ system sglrCmd errLn $ "["++progName++"] "++implodeCmd exitOK $ system implodeCmd af <- readFile afName --return . fromATerm . afunCap . implodeLit . readATerm . dehyphen $ af --let t1 = readATerm . dehyphen $ af let t1 = dehyphenAST . readATerm $ af --putStrLn $ "After dehyphen: \n"++show t1 let t2 = compensateImplodePT t1 --putStrLn $ "After implodeOpt: \n"++show t2 let t3 = afunCap t2 return . fromATerm $ t3 -- | Call the external sglr parser but only sends msgs on error and cleans -- temporary files. sglrSilent :: ATermConvertible a => FilePath -> FilePath -> String -> IO a sglrSilent tableName termName sortName = do progName <- getProgName unique <- newUnique let newName = termName ++ (show . hashUnique $ unique) let asfixName = newName ++ ".asfix" let sglrCmd = concat [ "sglr -p ", tableName, " -i ", termName , " -o ", asfixName, " -s ", sortName] exitCode <- system sglrCmd case exitCode of (ExitFailure code) -> do errLn $ "["++progName++"] "++sglrCmd removeFile asfixName fail $ "Exit code: " ++ show code (ExitSuccess) -> return () let afName = newName ++ ".af" let implodeCmd = concat [ "implodePT -t -ALclpqX -i ", asfixName , " -o ", afName] exitCode <- system implodeCmd case exitCode of (ExitFailure code) -> do errLn $ "["++progName++"] "++implodeCmd removeFile afName fail $ "Exit code: " ++ show code (ExitSuccess) -> return () af <- readFile afName _ <- removeFile asfixName _ <- removeFile afName let t1 = dehyphenAST . readATerm $ af let t2 = compensateImplodePT t1 let t3 = afunCap t2 return . fromATerm $ t3 -- | Helper function for reporting errors and progress to stderr errLn :: String -> IO () errLn str = hPutStrLn stderr str -- | Ensure that the given computation exits with an error code -- that indicates successful execution. exitOK :: IO ExitCode -> IO () exitOK io = do exitCode <- io case exitCode of (ExitSuccess) -> return () (ExitFailure code) -> fail $ "Exit code: " ++ show code
jkoppel/Strafunski-Sdf2Haskell
generator/SGLR.hs
Haskell
bsd-3-clause
4,290
{-# LANGUAGE TypeFamilies, DataKinds, TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} module Database.SQLFragment.Operators where -- standard import Data.Monoid import Data.List (intercalate) import Data.String import GHC.TypeLits -- third-party import Data.HList -- local import Database.SQLFragment.SQLFragment import Database.SQLFragment.Internal import Database.SQLFragment.TypeFamilies -- $setup -- >>> :set -XOverloadedStrings -- >>> :set -XDataKinds -- -- >>> let toSelectQuery' q = unwords.lines.toSelectQuery $ q -- -- * Combination infixl 1 !&!, !::!, !:@!, !::#! infixl 3 !\!, !%!, !%%! infixl 4 !>!, !<!, !>=!, !<=!, !=!, !/=!, !&&!, !||!, !=%!, !=~! infixl 4 !>?!, !<?!, !>=?!, !<=?!, !=?!, !/=?!, !&&?!, !||?!, !=%?!, !=~?! infixl 8 !#!, !#:!, !#:@!, !#:#! -- | Combines two fragments. Similar to '<>' but combines -- phantom types as well. -- -- >>> toSelectQuery' $ "a" !&! "t." -- "SELECT a FROM t" -- >>> toSelectQuery' $ "a" !&! "b" -- "SELECT a, b" -- >>> toSelectQuery' $ "t.a1" !&! "s.b" !&! "t.a2" -- "SELECT t.a1, s.b, t.a2 FROM t, s" (!&!) :: SQLFragment e p -> SQLFragment e' p' -> SQLFragment (HAppendListR e e') (HAppendListR p p') q !&! q' = forgetTypes $ (clearTypes q) <> (clearTypes q') -- | Same as !&! but higher fixity (!#!) :: SQLFragment e p -> SQLFragment e' p' -> SQLFragment (HAppendListR e e') (HAppendListR p p') q !#! q' = forgetTypes $ q !&! q' -- * Columns Promotions -- -- | Promotes columns to the WHERE clause -- -- >>> toSelectQuery' $ "" !\! "a > 1" !#! "b > 1" -- "WHERE (a > 1) AND (b > 1)" -- >>> toSelectQuery' $ "a" !\! "b > 1" -- "SELECT a WHERE (b > 1)" -- (!\!) :: SQLFragment a b -> SQLFragment a' b' -> SQLFragment a (HAppendListR b b') q !\! q' = forgetTypes $ q !&! q0' !&! q'' where q0' = clearSection COLUMN q' q'' = pickSection COLUMN WHERE q' -- | Promotes columns to the HAVINg clause. -- -- >>> toSelectQuery' $ "a" !\\! "b > 1" -- "SELECT a HAVING (b > 1)" -- (!\\!) :: SQLFragment a b -> SQLFragment a' b' -> SQLFragment a (HAppendListR b b') q !\\! q' = forgetTypes $ q !&! q0' !&! q'' where q0' = clearSection COLUMN q' q'' = pickSection COLUMN HAVING q' -- | Promotes columns to GROUP clause and -- criteria to HAVING Clauses -- -- >>> toSelectQuery' $ "t.a" !~! ("a" !\! "b > 1") -- "SELECT t.a FROM t GROUP BY a HAVING (b > 1)" -- (!~!) :: SQLFragment a b -> SQLFragment a' b' -> SQLFragment a (HAppendListR b b') q !~! q' = forgetTypes$ q !&! q0' !&! q'' where q0' = clearSection COLUMN . clearSection WHERE $ q' q'' = pickSection COLUMN GROUP q' !&! pickSection WHERE HAVING q' -- | Promotes columns to ORDER BY clause (Ascending) -- -- >>> toSelectQuery' $ "t.a" !^! "order" -- "SELECT t.a FROM t ORDER BY order" -- (!^!) :: SQLFragment a b -> SQLFragment a' '[] -> SQLFragment a b q !^! q' = forgetTypes$ q !&! qorder where qorder = pickSection COLUMN ORDER q' -- | Promotes columns to ORDER BY clause (Descending) -- -- >>> toSelectQuery' $ "t.a" !^-! "order" -- "SELECT t.a FROM t ORDER BY order DESC" -- (!^-!) :: SQLFragment a b -> SQLFragment a' '[] -> SQLFragment a b q !^-! q' = q !^! (fromString "$1 DESC" !%! q') -- * Combining & Formating -- | Replaces "$n" with columns. Can be chained to combined -- 2 or more columns into one. -- -- >>> toSelectQuery' $ "IF($1>0, $1, 0)" !%! "t.a" -- "SELECT IF(t.a>0, t.a, 0) FROM t" -- >>> let a = forgetTypes $ "a1" !#! "b1" :: SQLFragment '[String, Double] '[] -- >>> let b = forgetTypes $ "a2" !#! "b2" :: SQLFragment '[String, Double] '[] -- >>> toSelectQuery' $ "$1 > $2" !%! a !%! b -- "SELECT a1 > a2, b1 > b2" (!%!) :: SQLFragment e '[] -> SQLFragment e '[] -> SQLFragment e '[] q !%! q' = forgetTypes $ setSection COLUMN formatted (q !&! q') where formatted = zipWith format (cycle $ getSection COLUMN q) (getSection COLUMN q') -- | Replace $1 with all the column together. -- -- >>> toSelectQuery' $ "DISTINCT $1" !%%! "a" !#! "b" -- "SELECT DISTINCT a, b" (!%%!) :: SQLFragment e p -> SQLFragment e p -> SQLFragment e p q !%%! q' = forgetTypes $ setSection COLUMN formatted q where cols = getSection COLUMN q' cols' = intercalate ", " cols formatted = zipWith format (cycle $ getSection COLUMN q) [cols'] -- ** Arithemitic operators internOperator1 :: String-> SQLFragment e '[] -> SQLFragment e' '[] internOperator1 op q = forgetTypes $ fromString op !%! q internOperator2 :: String-> SQLFragment e '[] -> SQLFragment e '[] -> SQLFragment e '[] internOperator2 op q q' = forgetTypes $ fromString op !%! q !%! q' -- SQLFragment are also number, allowings for example -- >>> "count" * 5 -- | List of Num. class Nums (a::[*]) instance Nums '[] instance (Num a, Nums as) => Nums (a ': as) instance Nums a => Num (SQLFragment a '[]) where -- instance Num (SQLFragment a '[]) where (+) = internOperator2 "$1+$2" (*) = internOperator2 "$1*$2" (-) = internOperator2 "$1-$2" negate = internOperator1 "-$1" abs = internOperator1 "ABS($1)" signum = error "`signum` not defined for `SQLFragment`" fromInteger a = fromString $ show a instance Fractionals a => Fractional (SQLFragment a '[]) where (/) = internOperator2 "$1/$2" recip a = 1/a -- internOperator1 "1/$1" a fromRational a = fromString $ show a -- | List of Fractional. class Nums a => Fractionals (a :: [*]) instance Fractionals '[] instance (Fractional a, Fractionals as) => Fractionals (a ': as) -- ** Comparaison Operators -- | columns comparaison operators. Note the result is a column -- and has to be promoted to a where clause if necessary. -- -- >>> let a = "a" :: SQLFragment '[String, Maybe Double, String] '[] -- >>> let b = "b" :: SQLFragment '[Maybe String, Double, String] '[] -- >>> :t a !>! b -- a !>! b :: SQLFragment '[Maybe Bool, Maybe Bool, Bool] '[] -- >>> toSelectQuery$ a !>! b -- "SELECT (a)>(b)" -- >>> let x = "x" :: SQLFragment '[String] '[] -- >>> let y = "y" :: SQLFragment '[Int] '[] -- >>> toSelectQuery'$ x !\! y !>! "5" -- "SELECT x WHERE ((y)>(5))" (!>!) = boolOperator ">" (!<!) = boolOperator "<" (!>=!) = boolOperator ">=" (!<=!) = boolOperator "<=" (!=!) = boolOperator "=" (!/=!) = boolOperator "!=" (!&&!) = boolOperator " AND " (!||!) = boolOperator " OR " (!=%!) = boolOperator " LIKE " (!=~!) = boolOperator " RLIKE " boolOperator :: String -> SQLFragment a '[] -> SQLFragment b '[] -> SQLFragment (ZipToBool a b) '[] boolOperator op q q' = forgetTypes$ fromString ("($1)"++op++"($2)") !%! q0 !%! q0' where q0 = clearTypes q q0' = clearTypes q' -- ** Comparaison -- | Comparaison operators with external parameters -- Note, the result is promoted as in where clause. -- -- >>> let a = "a" :: SQLFragment '[String, Maybe Double, String] '[] -- >>> let b = "b" :: SQLFragment '[String] '[] -- >>> :t a !>?! b -- a !>?! b :: SQLFragment '[String, Maybe Double, String] '[String] -- >>> toSelectQuery' $ a !>?! b -- "SELECT a WHERE ((b)>(?))" (!>?!) = buildBoolParamOp (!>!) (!<?!) = buildBoolParamOp (!<!) (!>=?!) = buildBoolParamOp (!>=!) (!<=?!) = buildBoolParamOp (!<=!) (!=?!) = buildBoolParamOp (!=!) (!/=?!) = buildBoolParamOp (!/=!) (!&&?!) = buildBoolParamOp (!&&!) (!||?!) = buildBoolParamOp (!||!) (!=%?!) = buildBoolParamOp (!=%!) (!=~?!) = buildBoolParamOp (!=~!) buildBoolParamOp :: (SQLFragment p' '[] -> SQLFragment b '[] -> SQLFragment (ZipToBool p' b) '[]) -> SQLFragment e p -> SQLFragment p' '[] -> SQLFragment e (HAppendListR p p') buildBoolParamOp op q q' = forgetTypes $ q !\! op q' (fromString "?") type family ZipToBool (a :: [*]) (b :: [*]) :: [*] where ZipToBool '[] '[] = '[] ZipToBool ((Tagged l a) ': as) ((Tagged l' b) ': bs) = Tagged l (IfMaybe2 a b Bool) ': ZipToBool as bs ZipToBool (a ': as) (b ': bs) = IfMaybe2 a b Bool ': ZipToBool as bs -- * Type operations -- ** Full type -- | Retype a fragment with the right one (!::!) :: SQLFragment e p -> SQLFragment e' p' -> SQLFragment e' p' q !::! _ = forgetTypes q -- | Same as !::! but with higher fixity (!#:!) :: SQLFragment e p -> SQLFragment e' p' -> SQLFragment e' p' q !#:! _ = forgetTypes q -- ** Label -- | Label a fragment with the given label (!:@!) :: SQLFragment '[a] p -> Label (l' :: Symbol) -> SQLFragment '[Tagged l' (GetValue a)] p q !:@! _ = forgetTypes q -- | Same as !:@! but with hight fixity (!#:@!) :: SQLFragment '[a] p -> Label (l' :: Symbol) -> SQLFragment '[Tagged l' (GetValue a)] p q !#:@! _ = forgetTypes q -- ** Underlying Type -- | Change the underlying type but keep the actual label (!::#!) :: SQLFragment '[Tagged (l::Symbol) a] p -> SQLFragment '[b] '[] -> SQLFragment '[Tagged l (GetValue b)] p q !::#! _ = forgetTypes q (!#:#!) :: SQLFragment '[Tagged (l:: Symbol) a] p -> SQLFragment '[b] '[] -> SQLFragment '[Tagged l (GetValue b)] p q !#:#! _ = forgetTypes q
maxigit/sql-fragment
src/Database/SQLFragment/Operators.hs
Haskell
bsd-3-clause
9,043
-- | TODO: Put some kind of a tutorial here module Sound.Fluidsynth ( module Sound.Fluidsynth.Audio , module Sound.Fluidsynth.Event , module Sound.Fluidsynth.Gen , module Sound.Fluidsynth.Log , module Sound.Fluidsynth.Midi , module Sound.Fluidsynth.Misc , module Sound.Fluidsynth.Settings , module Sound.Fluidsynth.Synth , module Sound.Fluidsynth.Types ) where import Sound.Fluidsynth.Audio import Sound.Fluidsynth.Event import Sound.Fluidsynth.Gen import Sound.Fluidsynth.Log import Sound.Fluidsynth.Midi import Sound.Fluidsynth.Misc import Sound.Fluidsynth.Settings import Sound.Fluidsynth.Synth import Sound.Fluidsynth.Types
projedi/fluidsynth-hs-complete
src/Sound/Fluidsynth.hs
Haskell
bsd-3-clause
659
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, PatternGuards #-} {- A high level language of tactic composition, for building elaborators from a high level language into the core theory. This is our interface to proof construction, rather than ProofState, because this gives us a language to build derived tactics out of the primitives. -} module Idris.Core.Elaborate(module Idris.Core.Elaborate, module Idris.Core.ProofState) where import Idris.Core.ProofState import Idris.Core.ProofTerm(bound_in, getProofTerm, mkProofTerm, bound_in_term, refocus) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Typecheck import Idris.Core.Unify import Idris.Core.DeepSeq import Control.DeepSeq import Control.Monad.State.Strict import Data.Char import Data.List import Debug.Trace import Util.Pretty hiding (fill) data ElabState aux = ES (ProofState, aux) String (Maybe (ElabState aux)) deriving Show type Elab' aux a = StateT (ElabState aux) TC a type Elab a = Elab' () a proof :: ElabState aux -> ProofState proof (ES (p, _) _ _) = p -- Insert a 'proofSearchFail' error if necessary to shortcut any further -- fruitless searching proofFail :: Elab' aux a -> Elab' aux a proofFail e = do s <- get case runStateT e s of OK (a, s') -> do put s' return $! a Error err -> lift $ Error (ProofSearchFail err) explicit :: Name -> Elab' aux () explicit n = do ES (p, a) s m <- get let p' = p { dontunify = n : dontunify p } put (ES (p', a) s m) saveState :: Elab' aux () saveState = do e@(ES p s _) <- get put (ES p s (Just e)) loadState :: Elab' aux () loadState = do (ES p s e) <- get case e of Just st -> put st _ -> lift $ Error . Msg $ "Nothing to undo" getNameFrom :: Name -> Elab' aux Name getNameFrom n = do (ES (p, a) s e) <- get let next = nextname p let p' = p { nextname = next + 1 } put (ES (p', a) s e) let n' = case n of UN x -> MN (next+100) x MN i x -> if i == 99999 then MN (next+500) x else MN (next+100) x NS (UN x) s -> MN (next+100) x _ -> n return $! n' setNextName :: Elab' aux () setNextName = do env <- get_env ES (p, a) s e <- get let pargs = map fst (getArgTys (ptype p)) initNextNameFrom (pargs ++ map fst env) initNextNameFrom :: [Name] -> Elab' aux () initNextNameFrom ns = do ES (p, a) s e <- get let n' = maxName (nextname p) ns put (ES (p { nextname = n' }, a) s e) where maxName m ((MN i _) : xs) = maxName (max m i) xs maxName m (_ : xs) = maxName m xs maxName m [] = m + 1 errAt :: String -> Name -> Elab' aux a -> Elab' aux a errAt thing n elab = do s <- get case runStateT elab s of OK (a, s') -> do put s' return $! a Error (At f e) -> lift $ Error (At f (Elaborating thing n e)) Error e -> lift $ Error (Elaborating thing n e) erun :: FC -> Elab' aux a -> Elab' aux a erun f elab = do s <- get case runStateT elab s of OK (a, s') -> do put s' return $! a Error (ProofSearchFail (At f e)) -> lift $ Error (ProofSearchFail (At f e)) Error (At f e) -> lift $ Error (At f e) Error e -> lift $ Error (At f e) runElab :: aux -> Elab' aux a -> ProofState -> TC (a, ElabState aux) runElab a e ps = runStateT e (ES (ps, a) "" Nothing) execElab :: aux -> Elab' aux a -> ProofState -> TC (ElabState aux) execElab a e ps = execStateT e (ES (ps, a) "" Nothing) initElaborator :: Name -> Context -> Ctxt TypeInfo -> Type -> ProofState initElaborator = newProof elaborate :: Context -> Ctxt TypeInfo -> Name -> Type -> aux -> Elab' aux a -> TC (a, String) elaborate ctxt datatypes n ty d elab = do let ps = initElaborator n ctxt datatypes ty (a, ES ps' str _) <- runElab d elab ps return $! (a, str) -- | Modify the auxiliary state updateAux :: (aux -> aux) -> Elab' aux () updateAux f = do ES (ps, a) l p <- get put (ES (ps, f a) l p) -- | Get the auxiliary state getAux :: Elab' aux aux getAux = do ES (ps, a) _ _ <- get return $! a -- | Set whether to show the unifier log unifyLog :: Bool -> Elab' aux () unifyLog log = do ES (ps, a) l p <- get put (ES (ps { unifylog = log }, a) l p) getUnifyLog :: Elab' aux Bool getUnifyLog = do ES (ps, a) l p <- get return (unifylog ps) -- | Process a tactic within the current elaborator state processTactic' :: Tactic -> Elab' aux () processTactic' t = do ES (p, a) logs prev <- get (p', log) <- lift $ processTactic t p put (ES (p', a) (logs ++ log) prev) return $! () updatePS :: (ProofState -> ProofState) -> Elab' aux () updatePS f = do ES (ps, a) logs prev <- get put $ ES (f ps, a) logs prev now_elaborating :: FC -> Name -> Name -> Elab' aux () now_elaborating fc f a = updatePS (nowElaboratingPS fc f a) done_elaborating_app :: Name -> Elab' aux () done_elaborating_app f = updatePS (doneElaboratingAppPS f) done_elaborating_arg :: Name -> Name -> Elab' aux () done_elaborating_arg f a = updatePS (doneElaboratingArgPS f a) elaborating_app :: Elab' aux [(FC, Name, Name)] elaborating_app = do ES (ps, _) _ _ <- get return $ map (\ (FailContext x y z) -> (x, y, z)) (while_elaborating ps) -- Some handy gadgets for pulling out bits of state -- | Get the global context get_context :: Elab' aux Context get_context = do ES p _ _ <- get return $! (context (fst p)) -- | Update the context. -- (should only be used for adding temporary definitions or all sorts of -- stuff could go wrong) set_context :: Context -> Elab' aux () set_context ctxt = do ES (p, a) logs prev <- get put (ES (p { context = ctxt }, a) logs prev) get_datatypes :: Elab' aux (Ctxt TypeInfo) get_datatypes = do ES p _ _ <- get return $! (datatypes (fst p)) set_datatypes :: Ctxt TypeInfo -> Elab' aux () set_datatypes ds = do ES (p, a) logs prev <- get put (ES (p { datatypes = ds }, a) logs prev) -- | get the proof term get_term :: Elab' aux Term get_term = do ES p _ _ <- get return $! (getProofTerm (pterm (fst p))) -- | modify the proof term update_term :: (Term -> Term) -> Elab' aux () update_term f = do ES (p,a) logs prev <- get let p' = p { pterm = mkProofTerm (f (getProofTerm (pterm p))) } put (ES (p', a) logs prev) -- | get the local context at the currently in focus hole get_env :: Elab' aux Env get_env = do ES p _ _ <- get lift $ envAtFocus (fst p) get_inj :: Elab' aux [Name] get_inj = do ES p _ _ <- get return $! (injective (fst p)) get_holes :: Elab' aux [Name] get_holes = do ES p _ _ <- get return $! (holes (fst p)) get_probs :: Elab' aux Fails get_probs = do ES p _ _ <- get return $! (problems (fst p)) -- | Return recently solved names (that is, the names solved since the -- last call to get_recents) get_recents :: Elab' aux [Name] get_recents = do ES (p, a) l prev <- get put (ES (p { recents = [] }, a) l prev) return (recents p) -- | get the current goal type goal :: Elab' aux Type goal = do ES p _ _ <- get b <- lift $ goalAtFocus (fst p) return $! (binderTy b) is_guess :: Elab' aux Bool is_guess = do ES p _ _ <- get b <- lift $ goalAtFocus (fst p) case b of Guess _ _ -> return True _ -> return False -- | Get the guess at the current hole, if there is one get_guess :: Elab' aux Term get_guess = do ES p _ _ <- get b <- lift $ goalAtFocus (fst p) case b of Guess t v -> return $! v _ -> fail "Not a guess" -- | Typecheck locally get_type :: Raw -> Elab' aux Type get_type tm = do ctxt <- get_context env <- get_env (val, ty) <- lift $ check ctxt env tm return $! (finalise ty) get_type_val :: Raw -> Elab' aux (Term, Type) get_type_val tm = do ctxt <- get_context env <- get_env (val, ty) <- lift $ check ctxt env tm return $! (finalise val, finalise ty) -- | get holes we've deferred for later definition get_deferred :: Elab' aux [Name] get_deferred = do ES p _ _ <- get return $! (deferred (fst p)) checkInjective :: (Term, Term, Term) -> Elab' aux () checkInjective (tm, l, r) = do ctxt <- get_context if isInj ctxt tm then return $! () else lift $ tfail (NotInjective tm l r) where isInj ctxt (P _ n _) | isConName n ctxt = True isInj ctxt (App _ f a) = isInj ctxt f isInj ctxt (Constant _) = True isInj ctxt (TType _) = True isInj ctxt (Bind _ (Pi _ _ _) sc) = True isInj ctxt _ = False -- | get instance argument names get_instances :: Elab' aux [Name] get_instances = do ES p _ _ <- get return $! (instances (fst p)) -- | get auto argument names get_autos :: Elab' aux [(Name, [Name])] get_autos = do ES p _ _ <- get return $! (autos (fst p)) -- | given a desired hole name, return a unique hole name unique_hole :: Name -> Elab' aux Name unique_hole = unique_hole' False unique_hole' :: Bool -> Name -> Elab' aux Name unique_hole' reusable n = do ES p _ _ <- get let bs = bound_in (pterm (fst p)) ++ bound_in_term (ptype (fst p)) let nouse = holes (fst p) ++ bs ++ dontunify (fst p) ++ usedns (fst p) n' <- return $! uniqueNameCtxt (context (fst p)) n nouse ES (p, a) s u <- get case n' of MN i _ -> when (i >= nextname p) $ put (ES (p { nextname = i + 1 }, a) s u) _ -> return $! () return $! n' elog :: String -> Elab' aux () elog str = do ES p logs prev <- get put (ES p (logs ++ str ++ "\n") prev) getLog :: Elab' aux String getLog = do ES p logs _ <- get return $! logs -- The primitives, from ProofState attack :: Elab' aux () attack = processTactic' Attack claim :: Name -> Raw -> Elab' aux () claim n t = processTactic' (Claim n t) claimFn :: Name -> Name -> Raw -> Elab' aux () claimFn n bn t = processTactic' (ClaimFn n bn t) unifyGoal :: Raw -> Elab' aux () unifyGoal t = processTactic' (UnifyGoal t) exact :: Raw -> Elab' aux () exact t = processTactic' (Exact t) fill :: Raw -> Elab' aux () fill t = processTactic' (Fill t) match_fill :: Raw -> Elab' aux () match_fill t = processTactic' (MatchFill t) prep_fill :: Name -> [Name] -> Elab' aux () prep_fill n ns = processTactic' (PrepFill n ns) complete_fill :: Elab' aux () complete_fill = processTactic' CompleteFill solve :: Elab' aux () solve = processTactic' Solve start_unify :: Name -> Elab' aux () start_unify n = processTactic' (StartUnify n) end_unify :: Elab' aux () end_unify = processTactic' EndUnify -- Clear the list of variables not to unify, and try to solve them unify_all :: Elab' aux () unify_all = processTactic' UnifyAll regret :: Elab' aux () regret = processTactic' Regret compute :: Elab' aux () compute = processTactic' Compute computeLet :: Name -> Elab' aux () computeLet n = processTactic' (ComputeLet n) simplify :: Elab' aux () simplify = processTactic' Simplify hnf_compute :: Elab' aux () hnf_compute = processTactic' HNF_Compute eval_in :: Raw -> Elab' aux () eval_in t = processTactic' (EvalIn t) check_in :: Raw -> Elab' aux () check_in t = processTactic' (CheckIn t) intro :: Maybe Name -> Elab' aux () intro n = processTactic' (Intro n) introTy :: Raw -> Maybe Name -> Elab' aux () introTy ty n = processTactic' (IntroTy ty n) forall :: Name -> Maybe ImplicitInfo -> Raw -> Elab' aux () forall n i t = processTactic' (Forall n i t) letbind :: Name -> Raw -> Raw -> Elab' aux () letbind n t v = processTactic' (LetBind n t v) expandLet :: Name -> Term -> Elab' aux () expandLet n v = processTactic' (ExpandLet n v) rewrite :: Raw -> Elab' aux () rewrite tm = processTactic' (Rewrite tm) induction :: Raw -> Elab' aux () induction tm = processTactic' (Induction tm) casetac :: Raw -> Elab' aux () casetac tm = processTactic' (CaseTac tm) equiv :: Raw -> Elab' aux () equiv tm = processTactic' (Equiv tm) -- | Turn the current hole into a pattern variable with the provided -- name, made unique if MN patvar :: Name -> Elab' aux () patvar n@(SN _) = do apply (Var n) []; solve patvar n = do env <- get_env hs <- get_holes if (n `elem` map fst env) then do apply (Var n) []; solve else do n' <- case n of UN _ -> return $! n MN _ _ -> unique_hole n NS _ _ -> return $! n x -> return $! n processTactic' (PatVar n') -- | Turn the current hole into a pattern variable with the provided -- name, but don't make MNs unique. patvar' :: Name -> Elab' aux () patvar' n@(SN _) = do apply (Var n) [] ; solve patvar' n = do env <- get_env hs <- get_holes if (n `elem` map fst env) then do apply (Var n) [] ; solve else processTactic' (PatVar n) patbind :: Name -> Elab' aux () patbind n = processTactic' (PatBind n) focus :: Name -> Elab' aux () focus n = processTactic' (Focus n) movelast :: Name -> Elab' aux () movelast n = processTactic' (MoveLast n) dotterm :: Elab' aux () dotterm = do ES (p, a) s m <- get tm <- get_term case holes p of [] -> return () (h : hs) -> do let outer = findOuter h [] tm let p' = p { dotted = (h, outer) : dotted p } -- trace ("DOTTING " ++ show (h, outer) ++ "\n" ++ -- show tm) $ put $ ES (p', a) s m where findOuter h env (P _ n _) | h == n = env findOuter h env (Bind n b sc) = union (foB b) (findOuter h env (instantiate (P Bound n (binderTy b)) sc)) where foB (Guess t v) = union (findOuter h env t) (findOuter h (n:env) v) foB (Let t v) = union (findOuter h env t) (findOuter h env v) foB b = findOuter h env (binderTy b) findOuter h env (App _ f a) = union (findOuter h env f) (findOuter h env a) findOuter h env _ = [] get_dotterm :: Elab' aux [(Name, [Name])] get_dotterm = do ES (p, a) s m <- get return (dotted p) -- | Set the zipper in the proof state to point at the current sub term -- (This currently happens automatically, so this will have no effect...) zipHere :: Elab' aux () zipHere = do ES (ps, a) s m <- get let pt' = refocus (Just (head (holes ps))) (pterm ps) put (ES (ps { pterm = pt' }, a) s m) matchProblems :: Bool -> Elab' aux () matchProblems all = processTactic' (MatchProblems all) unifyProblems :: Elab' aux () unifyProblems = processTactic' UnifyProblems defer :: [Name] -> Name -> Elab' aux () defer ds n = do n' <- unique_hole n processTactic' (Defer ds n') deferType :: Name -> Raw -> [Name] -> Elab' aux () deferType n ty ns = processTactic' (DeferType n ty ns) instanceArg :: Name -> Elab' aux () instanceArg n = processTactic' (Instance n) autoArg :: Name -> Elab' aux () autoArg n = processTactic' (AutoArg n) setinj :: Name -> Elab' aux () setinj n = processTactic' (SetInjective n) proofstate :: Elab' aux () proofstate = processTactic' ProofState reorder_claims :: Name -> Elab' aux () reorder_claims n = processTactic' (Reorder n) qed :: Elab' aux Term qed = do processTactic' QED ES p _ _ <- get return $! (getProofTerm (pterm (fst p))) undo :: Elab' aux () undo = processTactic' Undo -- | Prepare to apply a function by creating holes to be filled by the arguments prepare_apply :: Raw -- ^ The operation being applied -> [Bool] -- ^ Whether arguments are implicit -> Elab' aux [(Name, Name)] -- ^ The names of the arguments and their holes to be filled with elaborated argument values prepare_apply fn imps = do ty <- get_type fn ctxt <- get_context env <- get_env -- let claims = getArgs ty imps -- claims <- mkClaims (normalise ctxt env ty) imps [] claims <- -- trace (show (fn, imps, ty, map fst env, normalise ctxt env (finalise ty))) $ mkClaims (finalise ty) (normalise ctxt env (finalise ty)) imps [] (map fst env) ES (p, a) s prev <- get -- reverse the claims we made so that args go left to right let n = length (filter not imps) let (h : hs) = holes p put (ES (p { holes = h : (reverse (take n hs) ++ drop n hs) }, a) s prev) return $! claims where mkClaims :: Type -- ^ The type of the operation being applied -> Type -- ^ Normalised version if we need it -> [Bool] -- ^ Whether the arguments are implicit -> [(Name, Name)] -- ^ Accumulator for produced claims -> [Name] -- ^ Hypotheses -> Elab' aux [(Name, Name)] -- ^ The names of the arguments and their holes, resp. mkClaims (Bind n' (Pi _ t_in _) sc) (Bind _ _ scn) (i : is) claims hs = do let t = rebind hs t_in n <- getNameFrom (mkMN n') -- when (null claims) (start_unify n) let sc' = instantiate (P Bound n t) sc env <- get_env claim n (forgetEnv (map fst env) t) when i (movelast n) mkClaims sc' scn is ((n', n) : claims) hs -- if we run out of arguments, we need the normalised version... mkClaims t tn@(Bind _ _ sc) (i : is) cs hs = mkClaims tn tn (i : is) cs hs mkClaims t _ [] claims _ = return $! (reverse claims) mkClaims _ _ _ _ _ | Var n <- fn = do ctxt <- get_context case lookupTy n ctxt of [] -> lift $ tfail $ NoSuchVariable n _ -> lift $ tfail $ TooManyArguments n | otherwise = fail $ "Too many arguments for " ++ show fn doClaim ((i, _), n, t) = do claim n t when i (movelast n) mkMN n@(MN i _) = n mkMN n@(UN x) = MN 99999 x mkMN n@(SN s) = sMN 99999 (show s) mkMN (NS n xs) = NS (mkMN n) xs rebind hs (Bind n t sc) | n `elem` hs = let n' = uniqueName n hs in Bind n' (fmap (rebind hs) t) (rebind (n':hs) sc) | otherwise = Bind n (fmap (rebind hs) t) (rebind (n:hs) sc) rebind hs (App s f a) = App s (rebind hs f) (rebind hs a) rebind hs t = t -- | Apply an operator, solving some arguments by unification or matching. apply, match_apply :: Raw -- ^ The operator to apply -> [(Bool, Int)] -- ^ For each argument, whether to -- attempt to solve it and the -- priority in which to do so -> Elab' aux [(Name, Name)] apply = apply' fill match_apply = apply' match_fill apply' :: (Raw -> Elab' aux ()) -> Raw -> [(Bool, Int)] -> Elab' aux [(Name, Name)] apply' fillt fn imps = do args <- prepare_apply fn (map fst imps) -- _Don't_ solve the arguments we're specifying by hand. -- (remove from unified list before calling end_unify) hs <- get_holes ES (p, a) s prev <- get let dont = if null imps then head hs : dontunify p else getNonUnify (head hs : dontunify p) imps args let (n, hunis) = -- trace ("AVOID UNIFY: " ++ show (fn, dont)) $ unified p let unify = -- trace ("Not done " ++ show hs) $ dropGiven dont hunis hs let notunify = -- trace ("Not done " ++ show (hs, hunis)) $ keepGiven dont hunis hs put (ES (p { dontunify = dont, unified = (n, unify), notunified = notunify ++ notunified p }, a) s prev) fillt (raw_apply fn (map (Var . snd) args)) ulog <- getUnifyLog g <- goal traceWhen ulog ("Goal " ++ show g ++ " -- when elaborating " ++ show fn) $ end_unify return $! (map (\(argName, argHole) -> (argName, updateUnify unify argHole)) args) where updateUnify us n = case lookup n us of Just (P _ t _) -> t _ -> n getNonUnify acc [] _ = acc getNonUnify acc _ [] = acc getNonUnify acc ((i,_):is) ((a, t):as) | i = getNonUnify acc is as | otherwise = getNonUnify (t : acc) is as -- getNonUnify imps args = map fst (filter (not . snd) (zip (map snd args) (map fst imps))) apply2 :: Raw -> [Maybe (Elab' aux ())] -> Elab' aux () apply2 fn elabs = do args <- prepare_apply fn (map isJust elabs) fill (raw_apply fn (map (Var . snd) args)) elabArgs (map snd args) elabs ES (p, a) s prev <- get let (n, hs) = unified p end_unify solve where elabArgs [] [] = return $! () elabArgs (n:ns) (Just e:es) = do focus n; e elabArgs ns es elabArgs (n:ns) (_:es) = elabArgs ns es isJust (Just _) = False isJust _ = True apply_elab :: Name -> [Maybe (Int, Elab' aux ())] -> Elab' aux () apply_elab n args = do ty <- get_type (Var n) ctxt <- get_context env <- get_env claims <- doClaims (hnf ctxt env ty) args [] prep_fill n (map fst claims) let eclaims = sortBy (\ (_, x) (_,y) -> priOrder x y) claims elabClaims [] False claims complete_fill end_unify where priOrder Nothing Nothing = EQ priOrder Nothing _ = LT priOrder _ Nothing = GT priOrder (Just (x, _)) (Just (y, _)) = compare x y doClaims (Bind n' (Pi _ t _) sc) (i : is) claims = do n <- unique_hole (mkMN n') when (null claims) (start_unify n) let sc' = instantiate (P Bound n t) sc claim n (forget t) case i of Nothing -> return $! () Just _ -> -- don't solve by unification as there is an explicit value do ES (p, a) s prev <- get put (ES (p { dontunify = n : dontunify p }, a) s prev) doClaims sc' is ((n, i) : claims) doClaims t [] claims = return $! (reverse claims) doClaims _ _ _ = fail $ "Wrong number of arguments for " ++ show n elabClaims failed r [] | null failed = return $! () | otherwise = if r then elabClaims [] False failed else return $! () elabClaims failed r ((n, Nothing) : xs) = elabClaims failed r xs elabClaims failed r (e@(n, Just (_, elaboration)) : xs) | r = try (do ES p _ _ <- get focus n; elaboration; elabClaims failed r xs) (elabClaims (e : failed) r xs) | otherwise = do ES p _ _ <- get focus n; elaboration; elabClaims failed r xs mkMN n@(MN _ _) = n mkMN n@(UN x) = MN 0 x mkMN (NS n ns) = NS (mkMN n) ns -- If the goal is not a Pi-type, invent some names and make it a pi type checkPiGoal :: Name -> Elab' aux () checkPiGoal n = do g <- goal case g of Bind _ (Pi _ _ _) _ -> return () _ -> do a <- getNameFrom (sMN 0 "pargTy") b <- getNameFrom (sMN 0 "pretTy") f <- getNameFrom (sMN 0 "pf") claim a RType claim b RType claim f (RBind n (Pi Nothing (Var a) RType) (Var b)) movelast a movelast b fill (Var f) solve focus f simple_app :: Bool -> Elab' aux () -> Elab' aux () -> String -> Elab' aux () simple_app infer fun arg str = do a <- getNameFrom (sMN 0 "argTy") b <- getNameFrom (sMN 0 "retTy") f <- getNameFrom (sMN 0 "f") s <- getNameFrom (sMN 0 "s") claim a RType claim b RType claim f (RBind (sMN 0 "aX") (Pi Nothing (Var a) RType) (Var b)) tm <- get_term start_unify s -- if 'infer' is set, we're assuming it's a simply typed application -- so safe to unify with the goal type (as there'll be no dependencies) when infer $ unifyGoal (Var b) hs <- get_holes claim s (Var a) prep_fill f [s] focus f; fun focus s; arg tm <- get_term ps <- get_probs ty <- goal hs <- get_holes complete_fill env <- get_env -- We don't need a and b in the hole queue any more since they were -- just for checking f, so move them to the end. If they never end up -- getting solved, we'll get an 'Incomplete term' error. hs <- get_holes when (a `elem` hs) $ do movelast a when (b `elem` hs) $ do movelast b end_unify where regretWith err = try regret (lift $ tfail err) -- Abstract over an argument of unknown type, giving a name for the hole -- which we'll fill with the argument type too. arg :: Name -> Maybe ImplicitInfo -> Name -> Elab' aux () arg n i tyhole = do ty <- unique_hole tyhole claim ty RType movelast ty forall n i (Var ty) -- try a tactic, if it adds any unification problem, return an error no_errors :: Elab' aux () -> Maybe Err -> Elab' aux () no_errors tac err = do ps <- get_probs s <- get case err of Nothing -> tac Just e -> -- update the error, if there is one. case runStateT tac s of Error _ -> lift $ Error e OK (a, s') -> do put s' return a unifyProblems ps' <- get_probs if (length ps' > length ps) then case reverse ps' of ((x, y, _, env, inerr, while, _) : _) -> let (xp, yp) = getProvenance inerr env' = map (\(x, b) -> (x, binderTy b)) env in lift $ tfail $ case err of Nothing -> CantUnify False (x, xp) (y, yp) inerr env' 0 Just e -> e else return $! () -- Try a tactic, if it fails, try another try :: Elab' aux a -> Elab' aux a -> Elab' aux a try t1 t2 = try' t1 t2 False handleError :: (Err -> Bool) -> Elab' aux a -> Elab' aux a -> Elab' aux a handleError p t1 t2 = do s <- get ps <- get_probs case runStateT t1 s of OK (v, s') -> do put s' return $! v Error e1 -> if p e1 then do case runStateT t2 s of OK (v, s') -> do put s'; return $! v Error e2 -> if score e1 >= score e2 then lift (tfail e1) else lift (tfail e2) else lift (tfail e1) try' :: Elab' aux a -> Elab' aux a -> Bool -> Elab' aux a try' t1 t2 proofSearch = do s <- get ps <- get_probs ulog <- getUnifyLog ivs <- get_instances case prunStateT 999999 False ps t1 s of OK ((v, _, _), s') -> do put s' return $! v Error e1 -> traceWhen ulog ("try failed " ++ show e1) $ if recoverableErr e1 then do case runStateT t2 s of OK (v, s') -> do put s'; return $! v Error e2 -> if score e1 >= score e2 then lift (tfail e1) else lift (tfail e2) else lift (tfail e1) where recoverableErr err@(CantUnify r x y _ _ _) = -- traceWhen r (show err) $ r || proofSearch recoverableErr (CantSolveGoal _ _) = False recoverableErr (CantResolveAlts _) = False recoverableErr (ProofSearchFail (Msg _)) = True recoverableErr (ProofSearchFail _) = False recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e recoverableErr (At _ e) = recoverableErr e recoverableErr (ElabScriptDebug _ _ _) = False recoverableErr _ = True tryCatch :: Elab' aux a -> (Err -> Elab' aux a) -> Elab' aux a tryCatch t1 t2 = do s <- get ps <- get_probs ulog <- getUnifyLog case prunStateT 999999 False ps t1 s of OK ((v, _, _), s') -> do put s' return $! v Error e1 -> traceWhen ulog ("tryCatch failed " ++ show e1) $ case runStateT (t2 e1) s of OK (v, s') -> do put s' return $! v Error e2 -> if score e1 >= score e2 then lift (tfail e1) else lift (tfail e2) tryWhen :: Bool -> Elab' aux a -> Elab' aux a -> Elab' aux a tryWhen True a b = try a b tryWhen False a b = a -- Bool says whether it's okay to create new unification problems. If set -- to False, then the whole tactic fails if there are any new problems tryAll :: [(Elab' aux a, Name)] -> Elab' aux a tryAll [(x, _)] = x tryAll xs = tryAll' [] 999999 (cantResolve, 0) xs where cantResolve :: Elab' aux a cantResolve = lift $ tfail $ CantResolveAlts (map snd xs) tryAll' :: [Elab' aux a] -> -- successes Int -> -- most problems (Elab' aux a, Int) -> -- smallest failure [(Elab' aux a, Name)] -> -- still to try Elab' aux a tryAll' [res] pmax _ [] = res tryAll' (_:_) pmax _ [] = cantResolve tryAll' [] pmax (f, _) [] = f tryAll' cs pmax f ((x, msg):xs) = do s <- get ps <- get_probs case prunStateT pmax True ps x s of OK ((v, newps, probs), s') -> do let cs' = if (newps < pmax) then [do put s'; return $! v] else (do put s'; return $! v) : cs tryAll' cs' newps f xs Error err -> do put s -- if (score err) < 100 tryAll' cs pmax (better err f) xs -- else tryAll' [] pmax (better err f) xs -- give up better err (f, i) = let s = score err in if (s >= i) then (lift (tfail err), s) else (f, i) prunStateT :: Int -> Bool -> [a] -> Control.Monad.State.Strict.StateT (ElabState t) TC t1 -> ElabState t -> TC ((t1, Int, Idris.Core.Unify.Fails), ElabState t) prunStateT pmax zok ps x s = case runStateT x s of OK (v, s'@(ES (p, _) _ _)) -> let newps = length (problems p) - length ps newpmax = if newps < 0 then 0 else newps in if (newpmax > pmax || (not zok && newps > 0)) -- length ps == 0 && newpmax > 0)) then case reverse (problems p) of ((_,_,_,_,e,_,_):_) -> Error e else OK ((v, newpmax, problems p), s') Error e -> Error e debugElaborator :: [ErrorReportPart] -> Elab' aux a debugElaborator msg = do ps <- fmap proof get saveState -- so we don't need to remember the hole order hs <- get_holes holeInfo <- mapM getHoleInfo hs loadState lift . Error $ ElabScriptDebug msg (getProofTerm (pterm ps)) holeInfo where getHoleInfo :: Name -> Elab' aux (Name, Type, [(Name, Binder Type)]) getHoleInfo h = do focus h g <- goal env <- get_env return (h, g, env) qshow :: Fails -> String qshow fs = show (map (\ (x, y, _, _, _, _, _) -> (x, y)) fs) dumpprobs [] = "" dumpprobs ((_,_,_,e):es) = show e ++ "\n" ++ dumpprobs es
bkoropoff/Idris-dev
src/Idris/Core/Elaborate.hs
Haskell
bsd-3-clause
34,029
{-# LANGUAGE RecordWildCards, PolymorphicComponents, GADTs, TemplateHaskell #-} module Synthesis.Interface where import Control.Monad.ST import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Control.Monad.State import Control.Arrow import Data.List as List import Safe import Data.Tuple.All import Control.Lens import Cudd.MTR import Synthesis.BddRecord import Synthesis.RefineUtil --types that appear in the backend syntax tree data BAVar sp lp where StateVar :: sp -> Int -> BAVar sp lp LabelVar :: lp -> Int -> BAVar sp lp OutVar :: lp -> Int -> BAVar sp lp deriving (Show, Eq, Ord) --Operations that are given to the backend for compilation. data VarOps pdb v s u = VarOps { getVar :: v -> Maybe String -> StateT pdb (ST s) [DDNode s u], withTmp :: forall a. (DDNode s u -> StateT pdb (ST s) a) -> StateT pdb (ST s) a, allVars :: StateT pdb (ST s) [v] } --Generic utility functions findWithDefaultM :: (Monad m, Ord k) => (v -> v') -> k -> Map k v -> m v' -> m v' findWithDefaultM modF key theMap func = maybe func (return . modF) $ Map.lookup key theMap findWithDefaultProcessM :: (Monad m, Ord k) => (v -> v') -> k -> Map k v -> m v' -> (v -> m ()) -> m v' findWithDefaultProcessM modF key theMap funcAbsent funcPresent = maybe funcAbsent func $ Map.lookup key theMap where func v = do funcPresent v return $ modF v modifyM :: Monad m => (s -> m s) -> StateT s m () modifyM f = get >>= (lift . f) >>= put --Variable type getNode = fst getIdx = snd --Symbol table data SymbolInfo s u sp lp = SymbolInfo { --below maps are used for update function compilation and constructing _initVars :: Map sp ([DDNode s u], [Int], [DDNode s u], [Int]), _stateVars :: Map sp ([DDNode s u], [Int], [DDNode s u], [Int]), _labelVars :: Map lp ([DDNode s u], [Int], DDNode s u, Int), _outcomeVars :: Map lp ([DDNode s u], [Int]), --mappings from index to variable/predicate _stateRev :: Map Int sp, _labelRev :: Map Int (lp, Bool) } makeLenses ''SymbolInfo initialSymbolTable = SymbolInfo Map.empty Map.empty Map.empty Map.empty Map.empty Map.empty --Sections data SectionInfo s u = SectionInfo { _trackedCube :: DDNode s u, _trackedNodes :: [DDNode s u], _trackedInds :: [Int], _untrackedCube :: DDNode s u, _untrackedInds :: [Int], _labelCube :: DDNode s u, _outcomeCube :: DDNode s u, _nextCube :: DDNode s u, _nextNodes :: [DDNode s u] } makeLenses ''SectionInfo initialSectionInfo Ops{..} = SectionInfo btrue [] [] btrue [] btrue btrue btrue [] derefSectionInfo :: Ops s u -> SectionInfo s u -> ST s () derefSectionInfo Ops{..} SectionInfo{..} = do deref _trackedCube deref _untrackedCube deref _labelCube deref _outcomeCube deref _nextCube --Variable/predicate database data DB s u sp lp = DB { _symbolTable :: SymbolInfo s u sp lp, _sections :: SectionInfo s u, _avlOffset :: Int, _freeInds :: [Int], _groups :: Map String (Int, Int, Int) } makeLenses ''DB initialDB ops@Ops{..} = do let isi@SectionInfo{..} = initialSectionInfo ops let res = DB initialSymbolTable isi 0 [] Map.empty ref _trackedCube ref _untrackedCube ref _labelCube ref _outcomeCube ref _nextCube return res extractStatePreds :: DB s u sp lp -> [sp] extractStatePreds db = map sel1 $ filter (filt . snd) $ Map.toList (_stateVars $ _symbolTable db) where filt vars = not $ null $ sel2 vars `intersect` _trackedInds (_sections db) extractUntrackedPreds :: DB s u sp lp -> [sp] extractUntrackedPreds db = map sel1 $ filter (filt . snd) $ Map.toList (_stateVars $ _symbolTable db) where filt vars = not $ null $ sel2 vars `intersect` _untrackedInds (_sections db) --Below two functions are only used for temporary variables allocIdx :: StateT (DB s u sp lp) (ST s) Int allocIdx = do st <- use freeInds case st of [] -> do ind <- use avlOffset avlOffset += 1 return ind x:xs -> do freeInds .= xs return x freeIdx :: Int -> StateT (DB s u sp lp) (ST s) () freeIdx idx = freeInds %= (idx :) --Generic variable allocations allocN :: Ops s u -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) ([DDNode s u], [Int]) allocN Ops{..} size group = do offset <- use avlOffset avlOffset += size case group of Nothing -> do let indices = take size $ iterate (+1) offset res <- lift $ mapM ithVar indices lift $ makeTreeNode offset size 4 return (res, indices) Just grName -> do grps <- use groups case Map.lookup grName grps of Nothing -> do let indices = take size $ iterate (+1) offset res <- lift $ mapM ithVar indices lift $ makeTreeNode offset size 4 lift $ makeTreeNode offset size 4 groups %= Map.insert grName (offset, size, last indices) return (res, indices) Just (startIdx, sizeGrp, lastIdx) -> do lvl <- lift $ readPerm lastIdx let levels = take size $ iterate (+1) (lvl + 1) let indices = take size $ iterate (+1) offset res <- lift $ mapM varAtLevel levels lift $ makeTreeNode (head indices) size 4 lift $ makeTreeNode startIdx (sizeGrp + size) 4 tr <- lift readTree lvl <- lift $ readPerm startIdx oldGroup <- lift $ mtrFindGroup tr lvl sizeGrp lift $ mtrDissolveGroup oldGroup groups %= Map.insert grName (startIdx, sizeGrp + size, last indices) return (res, indices) deinterleave :: [a] -> ([a], [a]) deinterleave [] = ([], []) deinterleave (x:y:rst) = (x:xs, y:ys) where (xs, ys) = deinterleave rst allocNPair :: Ops s u -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s ) (([DDNode s u], [Int]), ([DDNode s u], [Int])) allocNPair ops size group = do (vars, idxs) <- allocN ops (size*2) group let (vc, vn) = deinterleave vars (ic, inn) = deinterleave idxs return ((vc, ic), (vn, inn)) --Do the variable allocation and symbol table tracking addToCubeDeref :: Ops s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u) addToCubeDeref Ops{..} add cb = do res <- add .& cb deref add deref cb return res subFromCubeDeref :: Ops s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u) subFromCubeDeref Ops{..} sub cb = do res <- bexists sub cb deref sub deref cb return res --initial state helpers allocInitVar :: (Ord sp) => Ops s u -> sp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u] allocInitVar ops@Ops{..} v size group = do ((cn, ci), (nn, ni)) <- allocNPair ops size group symbolTable . initVars %= Map.insert v (cn, ci, nn, ni) symbolTable . stateRev %= flip (foldl func) ci return cn where func theMap idx = Map.insert idx v theMap -- === goal helpers === data NewVars s u sp = NewVars { _allocatedStateVars :: [(sp, [DDNode s u])] } makeLenses ''NewVars data GoalState s u sp lp = GoalState { _nv :: NewVars s u sp, _db :: DB s u sp lp } makeLenses ''GoalState liftToGoalState :: StateT (DB s u sp lp) (ST s) a -> StateT (GoalState s u sp lp) (ST s) a liftToGoalState (StateT func) = StateT $ \st -> do (res, st') <- func (_db st) return (res, GoalState (_nv st) st') allocStateVar :: (Ord sp) => Ops s u -> sp -> Int -> Maybe String -> StateT (GoalState s u sp lp) (ST s) [DDNode s u] allocStateVar ops@Ops{..} name size group = do ((cn, ci), (nn, ni)) <- liftToGoalState $ allocNPair ops size group addVarToState ops name cn ci nn ni return cn type Update a = a -> a addStateVarSymbol :: (Ord sp) => sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> Update (SymbolInfo s u sp lp) addStateVarSymbol name vars idxs vars' idxs' = stateVars %~ Map.insert name (vars, idxs, vars', idxs') >>> --TODO dont need to do this every time stateRev %~ flip (foldl func) idxs where func theMap idx = Map.insert idx name theMap addVarToStateSection :: Ops s u -> sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> StateT (GoalState s u sp lp )(ST s) () addVarToStateSection ops@Ops{..} name varsCurrent idxsCurrent varsNext idxsNext = do db . sections . trackedNodes %= (varsCurrent ++) db . sections . trackedInds %= (idxsCurrent ++) modifyM $ db . sections . trackedCube %%~ \c -> do cb <- nodesToCube varsCurrent addToCubeDeref ops c cb db . sections . nextNodes %= (varsNext ++) modifyM $ db . sections . nextCube %%~ \c -> do cb <- nodesToCube varsNext addToCubeDeref ops c cb nv . allocatedStateVars %= ((name, varsNext) :) addVarToState :: (Ord sp) => Ops s u -> sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> StateT (GoalState s u sp lp) (ST s) () addVarToState ops@Ops{..} name vars idxs vars' idxs' = do db . symbolTable %= addStateVarSymbol name vars idxs vars' idxs' addVarToStateSection ops name vars idxs vars' idxs' -- === update helpers === allocUntrackedVar :: (Ord sp) => Ops s u -> sp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u] allocUntrackedVar ops@Ops{..} var size group = do ((cn, ci), (nn, ni)) <- allocNPair ops size group addVarToUntracked ops var cn ci nn ni return cn addVarToUntracked :: (Ord sp) => Ops s u -> sp -> [DDNode s u] -> [Int] -> [DDNode s u] -> [Int] -> StateT (DB s u sp lp) (ST s) () addVarToUntracked ops@Ops {..} name vars idxs vars' idxs' = do symbolTable %= addStateVarSymbol name vars idxs vars' idxs' sections . untrackedInds %= (idxs ++) modifyM $ sections . untrackedCube %%~ \c -> do cb <- nodesToCube vars addToCubeDeref ops c cb allocLabelVar :: (Ord lp) => Ops s u -> lp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u] allocLabelVar ops@Ops{..} var size group = do (vars', idxs') <- allocN ops (size + 1) group let (en, enIdx) = (head vars', head idxs') (vars, idxs) = (tail vars', tail idxs') symbolTable . labelVars %= Map.insert var (vars, idxs, en, enIdx) symbolTable . labelRev %= ( flip (foldl (func vars idxs)) idxs >>> Map.insert enIdx (var, True) ) modifyM $ sections . labelCube %%~ \c -> do cb <- nodesToCube vars r1 <- addToCubeDeref ops cb c addToCubeDeref ops en r1 return vars where func vars idxs theMap idx = Map.insert idx (var, False) theMap allocOutcomeVar :: (Ord lp) => Ops s u -> lp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u] allocOutcomeVar ops@Ops{..} name size group = do (vars, idxs) <- allocN ops size group symbolTable . outcomeVars %= Map.insert name (vars, idxs) modifyM $ sections . outcomeCube %%~ \c -> do cb <- nodesToCube vars addToCubeDeref ops cb c return vars -- === Variable promotion helpers === promoteUntrackedVar :: (Ord sp) => Ops s u -> sp -> StateT (GoalState s u sp lp) (ST s) () promoteUntrackedVar ops@Ops{..} var = do mp <- use $ db . symbolTable . stateVars let (vars, idxs, vars', idxs') = fromJustNote "promoteUntrackedVar" $ Map.lookup var mp addVarToStateSection ops var vars idxs vars' idxs' db . sections . untrackedInds %= (\\ idxs) modifyM $ db . sections . untrackedCube %%~ \c -> do cb <- nodesToCube vars subFromCubeDeref ops cb c promoteUntrackedVars :: (Ord sp) => Ops s u -> [sp] -> StateT (DB s u sp lp) (ST s) (NewVars s u sp) promoteUntrackedVars ops vars = StateT $ \st -> do (_, GoalState{..}) <- runStateT (mapM_ (promoteUntrackedVar ops) vars) (GoalState (NewVars []) st) return (_nv, _db) withTmp' :: Ops s u -> (DDNode s u -> StateT (DB s u sp lp) (ST s) a) -> StateT (DB s u sp lp) (ST s) a withTmp' Ops{..} func = do ind <- allocIdx var <- lift $ ithVar ind res <- func var freeIdx ind lift $ deref var return res withTmpGoal' :: Ops s u -> (DDNode s u -> StateT (GoalState s u sp lp) (ST s) a) -> StateT (GoalState s u sp lp) (ST s) a withTmpGoal' Ops{..} func = do ind <- liftToGoalState allocIdx var <- lift $ ithVar ind res <- func var liftToGoalState $ freeIdx ind lift $ deref var return res allVars' :: StateT (DB s u sp lp) (ST s) [BAVar sp lp] allVars' = do SymbolInfo {..} <- use symbolTable return $ map (uncurry StateVar . second (length . sel1)) (Map.toList _stateVars) ++ map (uncurry LabelVar . second (length . sel1)) (Map.toList _labelVars) ++ map (uncurry OutVar . second (length . sel1)) (Map.toList _outcomeVars) --Construct the VarOps for compiling particular parts of the spec goalOps :: Ord sp => Ops s u -> VarOps (GoalState s u sp lp) (BAVar sp lp) s u goalOps ops = VarOps {withTmp = withTmpGoal' ops, allVars = liftToGoalState allVars', ..} where getVar (StateVar var size) group = do SymbolInfo{..} <- use $ db . symbolTable findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var) getVar _ _ = error "Requested non-state variable when compiling goal section" doGoal :: (Ord sp, Monad (rm (ST s))) => Ops s u -> (VarOps (GoalState s u sp lp) (BAVar sp lp) s u -> StateT st (StateT (GoalState s u sp lp) (rm (ST s))) a) -> StateT st (StateT (DB s u sp lp) (rm (ST s))) (a, NewVars s u sp) doGoal ops complFunc = StateT $ \st1 -> StateT $ \st -> do ((res, st1'), GoalState{..}) <- runStateT (runStateT (complFunc $ goalOps ops) st1) (GoalState (NewVars []) st) return (((res, _nv), st1'), _db) stateLabelOps :: (Ord sp, Ord lp) => Ops s u -> VarOps (GoalState s u sp lp) (BAVar sp lp) s u stateLabelOps ops = VarOps {withTmp = withTmpGoal' ops, allVars = liftToGoalState allVars', ..} where getVar (StateVar var size) group = do SymbolInfo{..} <- use $ db . symbolTable findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var) getVar (LabelVar var size) group = do SymbolInfo{..} <- use $ db . symbolTable liftToGoalState $ findWithDefaultM sel1 var _labelVars $ allocLabelVar ops var size group getVar _ _ = error "Requested non-state variable when compiling goal section" doStateLabel :: (Ord sp, Ord lp, Monad (rm (ST s))) => Ops s u -> (VarOps (GoalState s u sp lp) (BAVar sp lp) s u -> StateT st (StateT (GoalState s u sp lp) (rm (ST s))) a) -> StateT st (StateT (DB s u sp lp) (rm (ST s))) (a, NewVars s u sp) doStateLabel ops complFunc = StateT $ \st1 -> StateT $ \st -> do ((res, st1'), GoalState{..}) <- runStateT (runStateT (complFunc $ stateLabelOps ops) st1) (GoalState (NewVars []) st) return (((res, _nv), st1'), _db) stateLabelOutcomeOps :: (Ord sp, Ord lp) => Ops s u -> VarOps (GoalState s u sp lp) (BAVar sp lp) s u stateLabelOutcomeOps ops = VarOps {withTmp = withTmpGoal' ops, allVars = liftToGoalState allVars', ..} where getVar (StateVar var size) group = do SymbolInfo{..} <- use $ db . symbolTable findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var) getVar (LabelVar var size) group = do SymbolInfo{..} <- use $ db . symbolTable liftToGoalState $ findWithDefaultM sel1 var _labelVars $ allocLabelVar ops var size group getVar (OutVar var size) group = do SymbolInfo{..} <- use $ db . symbolTable liftToGoalState $ findWithDefaultM sel1 var _outcomeVars $ allocOutcomeVar ops var size group getVar _ _ = error "Requested non-state variable when compiling goal section" doStateLabelOutcome :: (Ord sp, Ord lp) => Ops s u -> (VarOps (GoalState s u sp lp) (BAVar sp lp) s u -> StateT (GoalState s u sp lp) (ST s) a) -> StateT (DB s u sp lp) (ST s) (a, NewVars s u sp) doStateLabelOutcome ops complFunc = StateT $ \st -> do (res, GoalState{..}) <- runStateT (complFunc $ stateLabelOps ops) (GoalState (NewVars []) st) return ((res, _nv), _db) initOps :: Ord sp => Ops s u -> VarOps (DB s u sp lp) (BAVar sp lp) s u initOps ops = VarOps {withTmp = withTmp' ops, allVars = allVars', ..} where getVar (StateVar var size) group = do SymbolInfo{..} <- use symbolTable findWithDefaultM sel1 var _initVars (allocInitVar ops var size group) getVar _ _ = error "Requested non-state variable when compiling init section" doInit :: Ord sp => Ops s u -> (VarOps (DB s u sp lp) (BAVar sp lp) s u -> a) -> a doInit ops complFunc = complFunc (initOps ops) updateOps :: (Ord sp, Ord lp) => Ops s u -> VarOps (DB s u sp lp) (BAVar sp lp) s u updateOps ops = VarOps {withTmp = withTmp' ops, allVars = allVars', ..} where getVar (StateVar var size) group = do SymbolInfo{..} <- use symbolTable findWithDefaultM sel1 var _stateVars $ findWithDefaultProcessM sel1 var _initVars (allocUntrackedVar ops var size group) (uncurryN $ addVarToUntracked ops var) getVar (LabelVar var size) group = do SymbolInfo{..} <- use symbolTable findWithDefaultM sel1 var _labelVars $ allocLabelVar ops var size group getVar (OutVar var size) group = do SymbolInfo{..} <- use symbolTable findWithDefaultM sel1 var _outcomeVars $ allocOutcomeVar ops var size group doUpdate :: (Ord sp, Ord lp) => Ops s u -> (VarOps (DB s u sp lp) (BAVar sp lp) s u -> a) -> a doUpdate ops complFunc = complFunc (updateOps ops) getStaticVar :: Ord sp => Ops s u -> sp -> Int -> Maybe String -> StateT (DB s u sp lp) (ST s) [DDNode s u] getStaticVar ops var size group = StateT $ \st -> do (res, st') <- flip runStateT (GoalState (NewVars []) st) $ do SymbolInfo{..} <- use $ db . symbolTable findWithDefaultM sel3 var _stateVars $ findWithDefaultProcessM sel3 var _initVars (allocStateVar ops var size group) (uncurryN $ addVarToState ops var) return (res, _db st')
termite2/synthesis
Synthesis/Interface.hs
Haskell
bsd-3-clause
18,474
module BoardSpec (spec) where import Control.Exception (evaluate) import Data.Function (on) import Data.List (nubBy, (\\)) import Test.Hspec import Test.QuickCheck import Board import Clues (clueAt) import Position (axis, positionsByColumn) import Tile (clueFor, isVoltorb, isOptional, isRequired) import ArrayGenerators (completeBoundedArray, incompleteBoundedArray, distinctAssocsTuple) import TileSpec () import PositionSpec () instance Arbitrary Board where arbitrary = board <$> completeBoundedArray fst3 :: (a, b, c) -> a fst3 (a, _, _) = a spec :: Spec spec = do describe "board" $ do context "given an Array with complete bounds" $ do it "is inverted by unBoard" $ property $ forAll (completeBoundedArray) $ \a -> unBoard (board a) `shouldBe` a context "given an Array with incomplete bounds" $ do it "returns an error" $ property $ forAll (incompleteBoundedArray) $ \arr -> evaluate (board arr) `shouldThrow` errorCall "Array does not have complete bounds" describe "tileAt" $ do context "getting the Tile at a Position of a Board that was just updated" $ do it "returns the Tile that was updated" $ property $ \b p t -> tileAt (updateTileAt b p t) p `shouldBe` t describe "updateTileAt" $ do it "returns a valid Board" $ property $ \b p t -> updateTileAt b p t `shouldSatisfy` isValidBoard context "updating the Tile at a Position of a Board with the Tile at that Position" $ do it "returns the original Board" $ property $ \b p -> updateTileAt b p (tileAt b p) `shouldBe` b context "updating a Tile at a Position of a Board twice" $ do it "returns the same Board that results from only updating the Board the second time" $ property $ \b p t t' -> updateTileAt (updateTileAt b p t) p t' `shouldBe` updateTileAt b p t' describe "tilesAt" $ do context "getting the Tiles at some Positions of a Board that were just updated" $ do it "returns the Tiles that were updated" $ property $ forAll (arbitrary) $ \b -> forAll (distinctAssocsTuple) $ \(ps, ts) -> tilesAt (updateTilesAt b $ ps `zip` ts) ps `shouldBe` ts describe "updateTilesAt" $ do it "returns a valid Board" $ property $ \b as -> updateTilesAt b as `shouldSatisfy` isValidBoard context "updating the Tiles at some Positions of a Board with the Tiles at those Positions" $ do it "returns the original Board" $ property $ \b ps -> updateTilesAt b (ps `zip` tilesAt b ps) `shouldBe` b context "updating some Tiles at some Positions of a Board twice" $ do it "returns the same result Board that results from only updating the Board a second time" $ property $ forAll (arbitrary) $ \b -> forAll (fmap (unzip3 . nubBy ((==) `on` fst3)) arbitrary) $ \(ps, ts, ts') -> updateTilesAt (updateTilesAt b $ ps `zip` ts) (ps `zip` ts') `shouldBe` updateTilesAt b (ps `zip` ts') describe "findVoltorbTiles" $ do it "returns a list of Positions such that every Position in the list contains an Voltorb Tile" $ property $ \b -> findVoltorbTiles b `shouldSatisfy` all (isVoltorb . tileAt b) it "returns a list of Positions such that every Position not in the list contains a non-Voltorb Tile" $ property $ \b -> positionsByColumn \\ findVoltorbTiles b `shouldSatisfy` all (not . isVoltorb . tileAt b) describe "findOptionalTiles" $ do it "returns a list of Positions such that every Position in the list contains an optional Tile" $ property $ \b -> findOptionalTiles b `shouldSatisfy` all (isOptional . tileAt b) it "returns a list of Positions such that every Position not in the list contains a non-optional Tile" $ property $ \b -> positionsByColumn \\ findOptionalTiles b `shouldSatisfy` all (not . isOptional . tileAt b) describe "findRequiredTiles" $ do it "returns a list of Positions such that every Position in the list contains a non-trivial Tile" $ property $ \b -> findRequiredTiles b `shouldSatisfy` all (isRequired . tileAt b) it "returns a list of Positions such that every Position not in the list contains a trivial Tile" $ property $ \b -> positionsByColumn \\ findRequiredTiles b `shouldSatisfy` all (not . isRequired . tileAt b) describe "cluesFor" $ do it "returns Clues containing the Clue for each Axis" $ property $ \b a -> cluesFor b `clueAt` a `shouldBe` (clueFor $ tilesAt b $ axis a)
jameshales/voltorb-flip
test/BoardSpec.hs
Haskell
bsd-3-clause
4,488
module Control.Monad.Extensions (satisfiesM,if') where import Control.Applicative (Applicative,liftA3) satisfiesM :: Monad m => (a -> Bool) -> m a -> m a satisfiesM p x = x >>= if' p return (const (satisfiesM p x)) if' :: Applicative f => f Bool -> f a -> f a -> f a if' = liftA3 (\ c t e -> if c then t else e)
bitemyapp/checkers
src/Control/Monad/Extensions.hs
Haskell
bsd-3-clause
315
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Plugins.MBox -- Copyright : (c) Jose A Ortega Ruiz -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- A plugin for checking mail in mbox files. -- ----------------------------------------------------------------------------- module Plugins.MBox (MBox(..)) where import Prelude import Plugins #ifdef INOTIFY import Plugins.Utils (changeLoop, expandHome) import Control.Monad (when) import Control.Concurrent.STM import Control.Exception (SomeException (..), handle, evaluate) import System.Console.GetOpt import System.Directory (doesFileExist) import System.FilePath ((</>)) import System.INotify (Event(..), EventVariety(..), initINotify, addWatch) import qualified Data.ByteString.Lazy.Char8 as B data Options = Options { oAll :: Bool , oUniq :: Bool , oDir :: FilePath , oPrefix :: String , oSuffix :: String } defaults :: Options defaults = Options { oAll = False, oUniq = False, oDir = "", oPrefix = "", oSuffix = "" } options :: [OptDescr (Options -> Options)] options = [ Option "a" ["all"] (NoArg (\o -> o { oAll = True })) "" , Option "u" [] (NoArg (\o -> o { oUniq = True })) "" , Option "d" ["dir"] (ReqArg (\x o -> o { oDir = x }) "") "" , Option "p" ["prefix"] (ReqArg (\x o -> o { oPrefix = x }) "") "" , Option "s" ["suffix"] (ReqArg (\x o -> o { oSuffix = x }) "") "" ] parseOptions :: [String] -> IO Options parseOptions args = case getOpt Permute options args of (o, _, []) -> return $ foldr id defaults o (_, _, errs) -> ioError . userError $ concat errs #else import System.IO #endif -- | A list of display names, paths to mbox files and display colours, -- followed by a list of options. data MBox = MBox [(String, FilePath, String)] [String] String deriving (Read, Show) instance Exec MBox where alias (MBox _ _ a) = a #ifndef INOTIFY start _ _ = do hPutStrLn stderr $ "Warning: xmobar is not compiled with -fwith_inotify" ++ " but the MBox plugin requires it" #else start (MBox boxes args _) cb = do opts <- parseOptions args let showAll = oAll opts prefix = oPrefix opts suffix = oSuffix opts uniq = oUniq opts names = map (\(t, _, _) -> t) boxes colors = map (\(_, _, c) -> c) boxes extractPath (_, f, _) = expandHome $ oDir opts </> f events = [CloseWrite] i <- initINotify vs <- mapM (\b -> do f <- extractPath b exists <- doesFileExist f n <- if exists then countMails f else return (-1) v <- newTVarIO (f, n) when exists $ addWatch i events f (handleNotification v) >> return () return v) boxes changeLoop (mapM (fmap snd . readTVar) vs) $ \ns -> let s = unwords [ showC uniq m n c | (m, n, c) <- zip3 names ns colors , showAll || n > 0 ] in cb (if null s then "" else prefix ++ s ++ suffix) showC :: Bool -> String -> Int -> String -> String showC u m n c = if c == "" then msg else "<fc=" ++ c ++ ">" ++ msg ++ "</fc>" where msg = m ++ if not u || n > 1 then show n else "" countMails :: FilePath -> IO Int countMails f = handle (\(SomeException _) -> evaluate 0) (do txt <- B.readFile f evaluate $! length . filter (B.isPrefixOf from) . B.lines $ txt) where from = B.pack "From " handleNotification :: TVar (FilePath, Int) -> Event -> IO () handleNotification v _ = do (p, _) <- atomically $ readTVar v n <- countMails p atomically $ writeTVar v (p, n) #endif
apoikos/pkg-xmobar
src/Plugins/MBox.hs
Haskell
bsd-3-clause
3,906
module QuoteUtils ( compileQuote , compileSimpleQuoteBTCBuy , compileSimpleQuoteBTCSell , QuoteCompilation(..) , QCError(..) ) where import Control.Error import Control.Monad.IO.Class import Network.MtGoxAPI import Network.MtGoxAPI.DepthStore import qualified Data.Text as T import CommonTypes import Config import DbUtils data QuoteCompilation a = SuccessfulQuote a | QuoteCompilationError QCError data QCError = HadNotEnoughDepth | DepthStoreWasUnavailable deriving (Show) compileSimpleQuoteBTCBuy :: BridgewalkerHandles -> Integer -> IO (QuoteCompilation Integer) compileSimpleQuoteBTCBuy bwHandles btcAmount = runAsQuoteCompilation $ do usdAmount <- simulateBTCBuy' bwHandles btcAmount return $ addFee usdAmount (getActualFee bwHandles) compileSimpleQuoteBTCSell :: BridgewalkerHandles -> Integer -> IO (QuoteCompilation Integer) compileSimpleQuoteBTCSell bwHandles btcAmount = runAsQuoteCompilation $ do usdAmount <- simulateBTCSell' bwHandles btcAmount return $ addFee usdAmount (-1 * getActualFee bwHandles) compileQuote :: BridgewalkerHandles-> BridgewalkerAccount -> Maybe T.Text -> AmountType -> IO (QuoteCompilation QuoteData) compileQuote bwHandles account mAddress amountType = runAsQuoteCompilation $ do let typicalTxFee = bcTypicalTxFee . bhConfig $ bwHandles actualFee = getActualFee bwHandles dbConn = bhDBConnCH bwHandles -- some preparation otherAccountM <- case mAddress of Nothing -> return Nothing Just address -> liftIO $ getAccountByAddress dbConn address let isInternalTransfer = isJust otherAccountM txFeeUSD <- do usdAmount <- simulateBTCBuy' bwHandles typicalTxFee return $ addFee usdAmount actualFee -- main calculation pqdInternal <- case amountType of AmountBasedOnBTC btc -> do usdForRecipient <- simulateBTCSell' bwHandles btc return PureQuoteData { pqdBTC = btc , pqdUSDRecipient = usdForRecipient , pqdUSDAccount = usdForRecipient } AmountBasedOnUSDBeforeFees usdForRecipient -> do btc <- simulateUSDBuy' bwHandles usdForRecipient return PureQuoteData { pqdBTC = btc , pqdUSDRecipient = usdForRecipient , pqdUSDAccount = usdForRecipient } AmountBasedOnUSDAfterFees usdFromOurAccount -> do btc <- simulateUSDBuy' bwHandles usdFromOurAccount return PureQuoteData { pqdBTC = btc , pqdUSDRecipient = usdFromOurAccount , pqdUSDAccount = usdFromOurAccount } pqdExternal <- case amountType of AmountBasedOnBTC btc -> do usdNeeded <- simulateBTCBuy' bwHandles btc let usdNeededWithFee = addFee usdNeeded actualFee usdForRecipient <- simulateBTCSell' bwHandles btc return PureQuoteData { pqdBTC = btc , pqdUSDRecipient = usdForRecipient , pqdUSDAccount = usdNeededWithFee + txFeeUSD } AmountBasedOnUSDBeforeFees usdForRecipient -> do btc <- simulateUSDBuy' bwHandles usdForRecipient usdNeeded <- simulateBTCBuy' bwHandles btc let usdNeededWithFee = addFee usdNeeded actualFee return PureQuoteData { pqdBTC = btc , pqdUSDRecipient = usdForRecipient , pqdUSDAccount = usdNeededWithFee + txFeeUSD } AmountBasedOnUSDAfterFees usdFromOurAccount -> do let usdBeforeFee = subtractFee (usdFromOurAccount - txFeeUSD) actualFee if usdBeforeFee > 0 then do btc <- simulateUSDSell' bwHandles usdBeforeFee usdForRecipient <- simulateBTCSell' bwHandles btc return PureQuoteData { pqdBTC = btc , pqdUSDRecipient = usdForRecipient , pqdUSDAccount = usdFromOurAccount } else return PureQuoteData { pqdBTC = 0 , pqdUSDRecipient = 0 , pqdUSDAccount = usdFromOurAccount } let pqd = if isInternalTransfer then pqdInternal else pqdExternal -- fill in some additional infos usdBalance <- liftIO $ getUSDBalance dbConn (bAccount account) return QuoteData { qdBTC = pqdBTC pqd , qdUSDRecipient = pqdUSDRecipient pqd , qdUSDAccount = pqdUSDAccount pqd , qdSufficientBalance = pqdUSDAccount pqd <= usdBalance } runAsQuoteCompilation :: Monad m => EitherT QCError m a -> m (QuoteCompilation a) runAsQuoteCompilation f = do result <- runEitherT f return $ case result of Right quote -> SuccessfulQuote quote Left errMsg -> QuoteCompilationError errMsg getActualFee :: BridgewalkerHandles -> Double getActualFee bwHandles = let mtgoxFee = bhMtGoxFee bwHandles targetFee = bcTargetExchangeFee . bhConfig $ bwHandles in max mtgoxFee targetFee addFee :: Integer -> Double -> Integer addFee amount fee = let markup = round $ fromIntegral amount * (fee / 100) in amount + markup subtractFee :: Integer -> Double -> Integer subtractFee amount fee = round $ fromIntegral amount * (100.0 / (100.0 + fee)) simulateBTCBuy' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer simulateBTCBuy' = depthStoreAction simulateBTCBuy simulateBTCSell' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer simulateBTCSell' = depthStoreAction simulateBTCSell simulateUSDBuy' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer simulateUSDBuy' = depthStoreAction simulateUSDBuy simulateUSDSell' :: MonadIO m =>BridgewalkerHandles -> Integer -> EitherT QCError m Integer simulateUSDSell' = depthStoreAction simulateUSDSell depthStoreAction :: MonadIO m =>(DepthStoreHandle -> t -> IO DepthStoreAnswer)-> BridgewalkerHandles -> t -> EitherT QCError m Integer depthStoreAction action bwHandles amount = do let depthStoreHandle = mtgoxDepthStoreHandle . bhMtGoxHandles $ bwHandles answerM <- liftIO $ action depthStoreHandle amount case answerM of DepthStoreAnswer answer -> return answer NotEnoughDepth -> left HadNotEnoughDepth DepthStoreUnavailable -> left DepthStoreWasUnavailable _debugQuoting :: Show a => IO (QuoteCompilation a) -> IO () _debugQuoting f = do result <- f case result of SuccessfulQuote quote -> print quote QuoteCompilationError errMsg -> print errMsg
javgh/bridgewalker
src/QuoteUtils.hs
Haskell
bsd-3-clause
7,325
module Bamboo.Plugin.Photo.Util where import Bamboo.Plugin.Photo.Config import MPSUTF8 import Prelude hiding ((.), (>), (^), (/), id) import System.Directory mkdir :: String -> IO () mkdir = u2b > createDirectory show_data :: (Show a) => a -> String show_data = show > snake_case parse_boolean :: String -> Bool parse_boolean = belongs_to ["true", "1", "y", "yes", "yeah"] ls_l :: String -> IO [String] ls_l x = ls x ^ map (x /) image_path :: String -> String image_path id = image_uri / id spaced_url :: String -> String spaced_url = gsub "/" " / " id_to_resource :: String -> String id_to_resource x = x.split "/" .tail.join "/"
nfjinjing/bamboo-plugin-photo
src/Bamboo/Plugin/Photo/Util.hs
Haskell
bsd-3-clause
638
{-# LANGUAGE TemplateHaskell #-} module Game.GameLocalsT where import Control.Lens (makeLenses) import qualified Data.Vector as V import qualified Constants import Game.GClientT import Types makeLenses ''GameLocalsT newGameLocalsT :: GameLocalsT newGameLocalsT = GameLocalsT { _glHelpMessage1 = "" , _glHelpMessage2 = "" , _glHelpChanged = 0 , _glClients = V.generate Constants.maxClients newGClientT , _glSpawnPoint = "" , _glMaxClients = 0 , _glMaxEntities = 0 , _glServerFlags = 0 , _glNumItems = 0 , _glAutosaved = False }
ksaveljev/hake-2
src/Game/GameLocalsT.hs
Haskell
bsd-3-clause
624
{-# LANGUAGE OverlappingInstances, FunctionalDependencies, ScopedTypeVariables, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, FlexibleContexts, DeriveFunctor #-} {-# OPTIONS_HADDOCK hide #-} module Happstack.StaticRouting.Internal where import Happstack.Server(askRq, rqPaths, rqMethod, localRq, ServerMonad, HasRqData, methodM, look, FromReqURI) import qualified Happstack.Server as H import Control.Monad(msum, MonadPlus, mzero, mplus) import Control.Monad.IO.Class(MonadIO) import Control.Arrow(first, second) import qualified Data.ListTrie.Map as Trie import Data.Map(Map) import qualified Data.Map as Map import Data.List(intercalate) import Data.Maybe -- | Static routing tables consisting of handlers of type 'a'. data Route a = Dir Segment (Route a) | Handler EndSegment a | Param String (Route a) | Choice [Route a] deriving Functor -- For backwards compatibility with GHC 6.12 handler :: EndSegment -> a -> Route a handler = Handler newtype Segment = StringS String deriving (Show, Eq, Ord) type EndSegment = (Maybe Int, H.Method) -- | Support for varying number of arguments to 'path' handlers. class Path m hm a b | a b -> m hm where pathHandler :: (m b -> hm c) -> a -> hm c arity :: m b -> a -> Int instance (FromReqURI d, ServerMonad hm, MonadPlus hm, Path m hm a b) => Path m hm (d -> a) b where pathHandler w f = H.path (pathHandler w . f) arity m f = 1 + arity m (f undefined) instance Path m hm (m b) b where pathHandler w m = w m arity _ _ = 0 -- | Pop a path element if it matches the given string. dir :: String -> Route a -> Route a dir = Dir . StringS -- | Combine several route alternatives into one. choice :: [Route a] -> Route a choice = Choice -- | Expect the given method, and exactly 'n' more segments, where 'n' is the arity of the handler. path :: forall m hm h a b. Path m hm h a => H.Method -> (m a -> hm b) -> h -> Route (hm b) path m w h = Handler (Just (arity (undefined::m a) h),m) (pathHandler w h) -- | Expect zero or more segments. remainingPath :: H.Method -> h -> Route h remainingPath m = Handler (Nothing,m) -- | DEPRECATED. Expect a specific parameter to be present. param :: String -> Route a -> Route a param = Param -- | Extract handler monad from a route. extract :: (ServerMonad m, MonadPlus m, HasRqData m, MonadIO m) => Route (m a) -> m a extract = f Nothing where f p (Dir (StringS s) r) = H.dir s (f p r) f (Just p) (Param p' _) = error $ "extract: cannot handle more than one param: "++ show(p,p') f _ (Param p r) = f (Just p) r f p (Handler (_,m) a) = doParam p >> methodM m >> a f p (Choice rs) = msum (map (f p) rs) doParam :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) => Maybe String -> m () doParam Nothing = return () doParam (Just p) = H.getDataFn (look p) >>= either (const mzero) (const (return ())) type Param = Maybe String newtype RouteTree a = R { unR :: Trie.TrieMap Map Segment (Map EndSegment (Map Param [a])) } deriving (Show) type Segments = ([Segment],EndSegment) routeTree :: (ServerMonad m, MonadPlus m) => Route (m a) -> RouteTree (m a) routeTree r = R $ foldr (\(((ps,es),mp),m) -> Trie.insertWith (Map.unionWith (Map.unionWith (++))) ps (Map.singleton es (Map.singleton mp [m]))) Trie.empty (flatten r) flatten :: (ServerMonad m, MonadPlus m) => Route (m a) -> [((Segments, Param), m a)] flatten = f Nothing where f p (Dir s r) = map (first (first (first (s:)))) (f p r) f (Just p) (Param p' _) = error $ "flatten: cannot handle more than one param: "++show (p,p') f _ (Param p' r) = f (Just p') r f p (Handler e a) = [((([], e),p), a)] f p (Choice rs) = concatMap (f p) rs -- | Compile routes, also return possible overlap report. If the -- overlap report is 'Nothing', the routing table is order -- independent. If the overlap report is @Just s@, then @s@ is a -- textual representation of all the paths that are order dependent, -- suitable for a warning message. compile :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) => Route (m a) -> (m a, Maybe String) compile r = ( dispatch t , if null os then Nothing else Just $ "Overlapping handlers: \n"++ showOverlaps os ) where t = routeTree r os = overlaps True t maybezero :: MonadPlus m => Maybe a -> (a -> m b) -> m b maybezero = flip (maybe mzero) -- | Dispatch a request given a route. Give priority to more specific paths -- in case of overlap. dispatch :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) => RouteTree (m a) -> m a dispatch (R t) = do let m = Trie.children1 t rq <- askRq let ps = rqPaths rq (case ps of p:xs -> maybezero (Map.lookup (StringS p) m) (localRq (\newRq -> newRq{rqPaths = xs}) . dispatch . R) [] -> mzero) -- most specific: match against a given next segment `mplus` (maybezero (Trie.lookup [] t) $ \em -> maybezero (Map.lookup (Just (length ps), rqMethod rq) em) dispatchParams -- or else a 'path' taking a given specific number of remaining segments `mplus` maybezero (Map.lookup (Nothing, rqMethod rq) em) dispatchRemainingPath -- least specific: a 'remainingPath' taking any number of remaining segments ) -- We want first to handle ones with params dispatchParams :: (MonadIO m, HasRqData m, ServerMonad m, MonadPlus m) => Map (Maybe String) [m a] -> m a dispatchParams m = let (paramfull,paramless) = Map.partitionWithKey (const . isJust) m in msum $ [doParam p >> msum hs | (p,hs) <- Map.assocs paramfull] ++ [msum hs | (Nothing,hs) <- Map.assocs paramless] dispatchRemainingPath :: MonadPlus m => Map k [m a] -> m a dispatchRemainingPath m = msum (map msum (Map.elems m)) -- | All paths with more than one handler. overlaps :: forall a . Bool -- ^ Only include order-dependent paths (exclude paths overlapping with more specific paths) -> RouteTree a -> [[([Segment],[(EndSegment,[(Param,[a])])])]] overlaps eso t = (filter (not . null) $ map (filter (not . null . snd) . (:[]) . second f) $ flattenTree t) ++ if eso then [] else pathOverlaps t where f :: [(EndSegment,[(Param,[a])])] -> [(EndSegment,[(Param,[a])])] f l = (filter (not . null . snd) . map (second g)) l g l@((Nothing,_):_:_) | not eso = l -- non-parameter handler overlaps with parameter handlers g l = filter ((>1) . length . snd) l -- more than one handler for this path pathOverlaps :: RouteTree a -> [[([Segment], [(EndSegment, [(Param, [a])])])]] pathOverlaps (R t) = (case Trie.lookup [] t of Just em -> filter ((>1) . length) $ map f (Map.keys em) where f es1 = filter ((>0) . length . snd) [ (ks, filter (lengthOverlaps es1 (length ks)) as) | (ks,as) <- flattenTree (R t) ] lengthOverlaps (a1,m1) ksl ((a2,m2),_) = m1 == m2 && case (a1,a2) of (Nothing,_) -> True (Just i1,Nothing) -> i1 >= ksl (Just i1,Just i2) -> i1 == ksl + i2 Nothing -> []) ++ [ [ (k:ks,a) | (ks,a) <- l ] | (k,t') <- Map.assocs (Trie.children1 t) , l <- pathOverlaps (R t') ] showOverlaps :: [[([Segment],[(EndSegment,[(Param,[a])])])]] -> String showOverlaps = unlines . intercalate [[]] . map (concatMap showPath) showPath :: ([Segment],[(EndSegment,[(Param,[a])])]) -> [String] showPath (ss,es) = [ intercalate "/" (map showSegment ss++ showArity i)++ showParam p++showMethod m++ showHandlers hs | ((i,m),ps) <- es, (p,hs) <- ps ] where showParam Nothing = "" showParam (Just p) = "?"++p++"=*" showMethod H.GET = "" showMethod m = " ("++show m++")" showSegment (StringS s) = s showArity Nothing = ["**"] showArity (Just i) = replicate i "*" showHandlers hs | length hs == 1 = "" | otherwise = " -> "++show (length hs) -- | Convert to a list of path-value pairs. flattenTree :: RouteTree a -> [([Segment],[(EndSegment,[(Param,[a])])])] flattenTree (R t) = (case Trie.lookup [] t of Just em -> [([], map (second Map.assocs) (Map.assocs em))] Nothing -> []) ++ [ (k:ks,a) | (k,t') <- Map.assocs (Trie.children1 t) , (ks,a) <- flattenTree (R t') ]
carlssonia/happstack-static-routing
src/Happstack/StaticRouting/Internal.hs
Haskell
bsd-3-clause
8,603
{-# language CPP #-} -- No documentation found for Chapter "Promoted_From_VK_KHR_format_feature_flags2" module Vulkan.Core13.Promoted_From_VK_KHR_format_feature_flags2 ( FormatProperties3(..) , StructureType(..) , FormatFeatureFlagBits2(..) , FormatFeatureFlags2 ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Kind (Type) import Vulkan.Core13.Enums.FormatFeatureFlags2 (FormatFeatureFlags2) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_FORMAT_PROPERTIES_3)) import Vulkan.Core13.Enums.FormatFeatureFlags2 (FormatFeatureFlagBits2(..)) import Vulkan.Core13.Enums.FormatFeatureFlags2 (FormatFeatureFlags2) import Vulkan.Core10.Enums.StructureType (StructureType(..)) -- | VkFormatProperties3 - Structure specifying image format properties -- -- = Description -- -- The bits reported in @linearTilingFeatures@, @optimalTilingFeatures@ and -- @bufferFeatures@ /must/ include the bits reported in the corresponding -- fields of -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.FormatProperties2'::@formatProperties@. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_format_feature_flags2 VK_KHR_format_feature_flags2>, -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_3 VK_VERSION_1_3>, -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlags2', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data FormatProperties3 = FormatProperties3 { -- | @linearTilingFeatures@ is a bitmask of -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlagBits2' -- specifying features supported by images created with a @tiling@ -- parameter of 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_LINEAR'. linearTilingFeatures :: FormatFeatureFlags2 , -- | @optimalTilingFeatures@ is a bitmask of -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlagBits2' -- specifying features supported by images created with a @tiling@ -- parameter of 'Vulkan.Core10.Enums.ImageTiling.IMAGE_TILING_OPTIMAL'. optimalTilingFeatures :: FormatFeatureFlags2 , -- | @bufferFeatures@ is a bitmask of -- 'Vulkan.Core13.Enums.FormatFeatureFlags2.FormatFeatureFlagBits2' -- specifying features supported by buffers. bufferFeatures :: FormatFeatureFlags2 } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (FormatProperties3) #endif deriving instance Show FormatProperties3 instance ToCStruct FormatProperties3 where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p FormatProperties3{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_FORMAT_PROPERTIES_3) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr FormatFeatureFlags2)) (linearTilingFeatures) poke ((p `plusPtr` 24 :: Ptr FormatFeatureFlags2)) (optimalTilingFeatures) poke ((p `plusPtr` 32 :: Ptr FormatFeatureFlags2)) (bufferFeatures) f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_FORMAT_PROPERTIES_3) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct FormatProperties3 where peekCStruct p = do linearTilingFeatures <- peek @FormatFeatureFlags2 ((p `plusPtr` 16 :: Ptr FormatFeatureFlags2)) optimalTilingFeatures <- peek @FormatFeatureFlags2 ((p `plusPtr` 24 :: Ptr FormatFeatureFlags2)) bufferFeatures <- peek @FormatFeatureFlags2 ((p `plusPtr` 32 :: Ptr FormatFeatureFlags2)) pure $ FormatProperties3 linearTilingFeatures optimalTilingFeatures bufferFeatures instance Storable FormatProperties3 where sizeOf ~_ = 40 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero FormatProperties3 where zero = FormatProperties3 zero zero zero
expipiplus1/vulkan
src/Vulkan/Core13/Promoted_From_VK_KHR_format_feature_flags2.hs
Haskell
bsd-3-clause
4,812
{-# LANGUAGE OverloadedStrings #-} module Cataskell.Server.MessageTypesSpec (main, spec) where import Test.Hspec import Cataskell.Server.MessageTypes import Data.Aeson main :: IO () main = hspec spec spec :: Spec spec = parallel $ describe "Message types" $ do describe "AddUser" $ it "can be decoded from a string" $ do let obj = AddUser "Test" let obj' = fromJSON "Test" :: Result AddUser obj' `shouldBe` Success obj describe "NewMessage" $ it "contains a message from the user" $ do let obj = NewMessage "Hello world." let obj' = fromJSON "Hello world." :: Result NewMessage obj' `shouldBe` Success obj describe "UserName" $ it "contains a username" $ do let obj = UserName "Test2" let obj' = fromJSON "Test2" :: Result UserName obj' `shouldBe` Success obj describe "UserJoined" $ it "contains a username and the current number of users" $ do let obj = UserJoined "Joiner" 3 let obj' = decode "{\"username\": \"Joiner\", \"numUsers\": 3}" :: Maybe UserJoined obj' `shouldBe` Just obj
corajr/cataskell
test-server/Cataskell/Server/MessageTypesSpec.hs
Haskell
bsd-3-clause
1,128
module Utils where pkgToDir str = let xs = map (\c -> if c == '.' then '/' else c) str in "src/" ++ xs ++ "/"
robstewart57/ripl
src/Utils.hs
Haskell
bsd-3-clause
186
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Generics -- Copyright : (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2014 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- @since 4.6.0.0 -- -- If you're using @GHC.Generics@, you should consider using the -- <http://hackage.haskell.org/package/generic-deriving> package, which -- contains many useful generic functions. module GHC.Generics ( -- * Introduction -- -- | -- -- Datatype-generic functions are based on the idea of converting values of -- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@. -- The type @'Rep' T@ is -- built from a limited set of type constructors, all provided by this module. A -- datatype-generic function is then an overloaded function with instances -- for most of these type constructors, together with a wrapper that performs -- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need -- a few generic instances in order to implement functionality that works for any -- representable type. -- -- Representable types are collected in the 'Generic' class, which defines the -- associated type 'Rep' as well as conversion functions 'from' and 'to'. -- Typically, you will not define 'Generic' instances by hand, but have the compiler -- derive them for you. -- ** Representing datatypes -- -- | -- -- The key to defining your own datatype-generic functions is to understand how to -- represent datatypes using the given set of type constructors. -- -- Let us look at an example first: -- -- @ -- data Tree a = Leaf a | Node (Tree a) (Tree a) -- deriving 'Generic' -- @ -- -- The above declaration (which requires the language pragma @DeriveGeneric@) -- causes the following representation to be generated: -- -- @ -- instance 'Generic' (Tree a) where -- type 'Rep' (Tree a) = -- 'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False) -- ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ('Rec0' a)) -- ':+:' -- 'C1' ('MetaCons \"Node\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ('Rec0' (Tree a)) -- ':*:' -- 'S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ('Rec0' (Tree a)))) -- ... -- @ -- -- /Hint:/ You can obtain information about the code being generated from GHC by passing -- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using -- the @:kind!@ command. -- -- This is a lot of information! However, most of it is actually merely meta-information -- that makes names of datatypes and constructors and more available on the type level. -- -- Here is a reduced representation for @Tree@ with nearly all meta-information removed, -- for now keeping only the most essential aspects: -- -- @ -- instance 'Generic' (Tree a) where -- type 'Rep' (Tree a) = -- 'Rec0' a -- ':+:' -- ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a)) -- @ -- -- The @Tree@ datatype has two constructors. The representation of individual constructors -- is combined using the binary type constructor ':+:'. -- -- The first constructor consists of a single field, which is the parameter @a@. This is -- represented as @'Rec0' a@. -- -- The second constructor consists of two fields. Each is a recursive field of type @Tree a@, -- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using -- the binary type constructor ':*:'. -- -- Now let us explain the additional tags being used in the complete representation: -- -- * The @'S1' ('MetaSel 'Nothing 'NoSourceUnpackedness 'NoSourceStrictness -- 'DecidedLazy)@ tag indicates several things. The @'Nothing@ indicates -- that there is no record field selector associated with this field of -- the constructor (if there were, it would have been marked @'Just -- \"recordName\"@ instead). The other types contain meta-information on -- the field's strictness: -- -- * There is no @{\-\# UNPACK \#-\}@ or @{\-\# NOUNPACK \#-\}@ annotation -- in the source, so it is tagged with @'NoSourceUnpackedness@. -- -- * There is no strictness (@!@) or laziness (@~@) annotation in the -- source, so it is tagged with @'NoSourceStrictness@. -- -- * The compiler infers that the field is lazy, so it is tagged with -- @'DecidedLazy@. Bear in mind that what the compiler decides may be -- quite different from what is written in the source. See -- 'DecidedStrictness' for a more detailed explanation. -- -- The @'MetaSel@ type is also an instance of the type class 'Selector', -- which can be used to obtain information about the field at the value -- level. -- -- * The @'C1' ('MetaCons \"Leaf\" 'PrefixI 'False)@ and -- @'C1' ('MetaCons \"Node\" 'PrefixI 'False)@ invocations indicate that the enclosed part is -- the representation of the first and second constructor of datatype @Tree@, respectively. -- Here, the meta-information regarding constructor names, fixity and whether -- it has named fields or not is encoded at the type level. The @'MetaCons@ -- type is also an instance of the type class 'Constructor'. This type class can be used -- to obtain information about the constructor at the value level. -- -- * The @'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)@ tag -- indicates that the enclosed part is the representation of the -- datatype @Tree@. Again, the meta-information is encoded at the type level. -- The @'MetaData@ type is an instance of class 'Datatype', which -- can be used to obtain the name of a datatype, the module it has been -- defined in, the package it is located under, and whether it has been -- defined using @data@ or @newtype@ at the value level. -- ** Derived and fundamental representation types -- -- | -- -- There are many datatype-generic functions that do not distinguish between positions that -- are parameters or positions that are recursive calls. There are also many datatype-generic -- functions that do not care about the names of datatypes and constructors at all. To keep -- the number of cases to consider in generic functions in such a situation to a minimum, -- it turns out that many of the type constructors introduced above are actually synonyms, -- defining them to be variants of a smaller set of constructors. -- *** Individual fields of constructors: 'K1' -- -- | -- -- The type constructor 'Rec0' is a variant of 'K1': -- -- @ -- type 'Rec0' = 'K1' 'R' -- @ -- -- Here, 'R' is a type-level proxy that does not have any associated values. -- -- There used to be another variant of 'K1' (namely @Par0@), but it has since -- been deprecated. -- *** Meta information: 'M1' -- -- | -- -- The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1': -- -- @ -- type 'S1' = 'M1' 'S' -- type 'C1' = 'M1' 'C' -- type 'D1' = 'M1' 'D' -- @ -- -- The types 'S', 'C' and 'D' are once again type-level proxies, just used to create -- several variants of 'M1'. -- *** Additional generic representation type constructors -- -- | -- -- Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur -- in the representations of other datatypes. -- **** Empty datatypes: 'V1' -- -- | -- -- For empty datatypes, 'V1' is used as a representation. For example, -- -- @ -- data Empty deriving 'Generic' -- @ -- -- yields -- -- @ -- instance 'Generic' Empty where -- type 'Rep' Empty = -- 'D1' ('MetaData \"Empty\" \"Main\" \"package-name\" 'False) 'V1' -- @ -- **** Constructors without fields: 'U1' -- -- | -- -- If a constructor has no arguments, then 'U1' is used as its representation. For example -- the representation of 'Bool' is -- -- @ -- instance 'Generic' Bool where -- type 'Rep' Bool = -- 'D1' ('MetaData \"Bool\" \"Data.Bool\" \"package-name\" 'False) -- ('C1' ('MetaCons \"False\" 'PrefixI 'False) 'U1' ':+:' 'C1' ('MetaCons \"True\" 'PrefixI 'False) 'U1') -- @ -- *** Representation of types with many constructors or many fields -- -- | -- -- As ':+:' and ':*:' are just binary operators, one might ask what happens if the -- datatype has more than two constructors, or a constructor with more than two -- fields. The answer is simple: the operators are used several times, to combine -- all the constructors and fields as needed. However, users /should not rely on -- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is -- free to choose any nesting it prefers. (In practice, the current implementation -- tries to produce a more-or-less balanced nesting, so that the traversal of -- the structure of the datatype from the root to a particular component can be -- performed in logarithmic rather than linear time.) -- ** Defining datatype-generic functions -- -- | -- -- A datatype-generic function comprises two parts: -- -- 1. /Generic instances/ for the function, implementing it for most of the representation -- type constructors introduced above. -- -- 2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion -- between the original value and its `Rep`-based representation and then invokes the -- generic instances. -- -- As an example, let us look at a function @encode@ that produces a naive, but lossless -- bit encoding of values of various datatypes. So we are aiming to define a function -- -- @ -- encode :: 'Generic' a => a -> [Bool] -- @ -- -- where we use 'Bool' as our datatype for bits. -- -- For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized -- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation -- type constructors operate with kind @* -> *@ as base kind. But the type argument is never -- being used. This may be changed at some point in the future. The class has a single method, -- and we use the type we want our final function to have, but we replace the occurrences of -- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used). -- -- > class Encode' f where -- > encode' :: f p -> [Bool] -- -- With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define -- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'. -- *** Definition of the generic representation types -- -- | -- -- In order to be able to do this, we need to know the actual definitions of these types: -- -- @ -- data 'V1' p -- lifted version of Empty -- data 'U1' p = 'U1' -- lifted version of () -- data (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either' -- data (':*:') f g p = (f p) ':*:' (g p) -- lifted version of (,) -- newtype 'K1' i c p = 'K1' { 'unK1' :: c } -- a container for a c -- newtype 'M1' i t f p = 'M1' { 'unM1' :: f p } -- a wrapper -- @ -- -- So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either', -- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value -- of a specific type @c@, and 'M1' wraps a value of the generic type argument, -- which in the lifted world is an @f p@ (where we do not care about @p@). -- *** Generic instances -- -- | -- -- The instance for 'V1' is slightly awkward (but also rarely used): -- -- @ -- instance Encode' 'V1' where -- encode' x = undefined -- @ -- -- There are no values of type @V1 p@ to pass (except undefined), so this is -- actually impossible. One can ask why it is useful to define an instance for -- 'V1' at all in this case? Well, an empty type can be used as an argument to -- a non-empty type, and you might still want to encode the resulting type. -- As a somewhat contrived example, consider @[Empty]@, which is not an empty -- type, but contains just the empty list. The 'V1' instance ensures that we -- can call the generic function on such types. -- -- There is exactly one value of type 'U1', so encoding it requires no -- knowledge, and we can use zero bits: -- -- @ -- instance Encode' 'U1' where -- encode' 'U1' = [] -- @ -- -- In the case for ':+:', we produce 'False' or 'True' depending on whether -- the constructor of the value provided is located on the left or on the right: -- -- @ -- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where -- encode' ('L1' x) = False : encode' x -- encode' ('R1' x) = True : encode' x -- @ -- -- (Note that this encoding strategy may not be reliable across different -- versions of GHC. Recall that the compiler is free to choose any nesting -- of ':+:' it chooses, so if GHC chooses @(a ':+:' b) ':+:' c@, then the -- encoding for @a@ would be @[False, False]@, @b@ would be @[False, True]@, -- and @c@ would be @[True]@. However, if GHC chooses @a ':+:' (b ':+:' c)@, -- then the encoding for @a@ would be @[False]@, @b@ would be @[True, False]@, -- and @c@ would be @[True, True]@.) -- -- In the case for ':*:', we append the encodings of the two subcomponents: -- -- @ -- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where -- encode' (x ':*:' y) = encode' x ++ encode' y -- @ -- -- The case for 'K1' is rather interesting. Here, we call the final function -- @encode@ that we yet have to define, recursively. We will use another type -- class @Encode@ for that function: -- -- @ -- instance (Encode c) => Encode' ('K1' i c) where -- encode' ('K1' x) = encode x -- @ -- -- Note how we can define a uniform instance for 'M1', because we completely -- disregard all meta-information: -- -- @ -- instance (Encode' f) => Encode' ('M1' i t f) where -- encode' ('M1' x) = encode' x -- @ -- -- Unlike in 'K1', the instance for 'M1' refers to @encode'@, not @encode@. -- *** The wrapper and generic default -- -- | -- -- We now define class @Encode@ for the actual @encode@ function: -- -- @ -- class Encode a where -- encode :: a -> [Bool] -- default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool] -- encode x = encode' ('from' x) -- @ -- -- The incoming @x@ is converted using 'from', then we dispatch to the -- generic instances using @encode'@. We use this as a default definition -- for @encode@. We need the @default encode@ signature because ordinary -- Haskell default methods must not introduce additional class constraints, -- but our generic default does. -- -- Defining a particular instance is now as simple as saying -- -- @ -- instance (Encode a) => Encode (Tree a) -- @ -- #if 0 -- /TODO:/ Add usage example? -- #endif -- The generic default is being used. In the future, it will hopefully be -- possible to use @deriving Encode@ as well, but GHC does not yet support -- that syntax for this situation. -- -- Having @Encode@ as a class has the advantage that we can define -- non-generic special cases, which is particularly useful for abstract -- datatypes that have no structural representation. For example, given -- a suitable integer encoding function @encodeInt@, we can define -- -- @ -- instance Encode Int where -- encode = encodeInt -- @ -- *** Omitting generic instances -- -- | -- -- It is not always required to provide instances for all the generic -- representation types, but omitting instances restricts the set of -- datatypes the functions will work for: -- -- * If no ':+:' instance is given, the function may still work for -- empty datatypes or datatypes that have a single constructor, -- but will fail on datatypes with more than one constructor. -- -- * If no ':*:' instance is given, the function may still work for -- datatypes where each constructor has just zero or one field, -- in particular for enumeration types. -- -- * If no 'K1' instance is given, the function may still work for -- enumeration types, where no constructor has any fields. -- -- * If no 'V1' instance is given, the function may still work for -- any datatype that is not empty. -- -- * If no 'U1' instance is given, the function may still work for -- any datatype where each constructor has at least one field. -- -- An 'M1' instance is always required (but it can just ignore the -- meta-information, as is the case for @encode@ above). #if 0 -- *** Using meta-information -- -- | -- -- TODO #endif -- ** Generic constructor classes -- -- | -- -- Datatype-generic functions as defined above work for a large class -- of datatypes, including parameterized datatypes. (We have used @Tree@ -- as our example above, which is of kind @* -> *@.) However, the -- 'Generic' class ranges over types of kind @*@, and therefore, the -- resulting generic functions (such as @encode@) must be parameterized -- by a generic type argument of kind @*@. -- -- What if we want to define generic classes that range over type -- constructors (such as 'Data.Functor.Functor', -- 'Data.Traversable.Traversable', or 'Data.Foldable.Foldable')? -- *** The 'Generic1' class -- -- | -- -- Like 'Generic', there is a class 'Generic1' that defines a -- representation 'Rep1' and conversion functions 'from1' and 'to1', -- only that 'Generic1' ranges over types of kind @* -> *@. (More generally, -- it can range over types of kind @k -> *@, for any kind @k@, if the -- @PolyKinds@ extension is enabled. More on this later.) -- The 'Generic1' class is also derivable. -- -- The representation 'Rep1' is ever so slightly different from 'Rep'. -- Let us look at @Tree@ as an example again: -- -- @ -- data Tree a = Leaf a | Node (Tree a) (Tree a) -- deriving 'Generic1' -- @ -- -- The above declaration causes the following representation to be generated: -- -- @ -- instance 'Generic1' Tree where -- type 'Rep1' Tree = -- 'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False) -- ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- 'Par1') -- ':+:' -- 'C1' ('MetaCons \"Node\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ('Rec1' Tree) -- ':*:' -- 'S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ('Rec1' Tree))) -- ... -- @ -- -- The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well -- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we -- carry around the dummy type argument for kind-@*@-types, but there are -- already enough different names involved without duplicating each of -- these.) -- -- What's different is that we now use 'Par1' to refer to the parameter -- (and that parameter, which used to be @a@), is not mentioned explicitly -- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@. -- *** Representation of @* -> *@ types -- -- | -- -- Unlike 'Rec0', the 'Par1' and 'Rec1' type constructors do not -- map to 'K1'. They are defined directly, as follows: -- -- @ -- newtype 'Par1' p = 'Par1' { 'unPar1' :: p } -- gives access to parameter p -- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper -- @ -- -- In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply -- wraps an application of @f@ to @p@. -- -- Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation, -- namely when the datatype has a field that does not mention the parameter. -- -- The declaration -- -- @ -- data WithInt a = WithInt Int a -- deriving 'Generic1' -- @ -- -- yields -- -- @ -- instance 'Generic1' WithInt where -- type 'Rep1' WithInt = -- 'D1' ('MetaData \"WithInt\" \"Main\" \"package-name\" 'False) -- ('C1' ('MetaCons \"WithInt\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ('Rec0' Int) -- ':*:' -- 'S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- 'Par1')) -- @ -- -- If the parameter @a@ appears underneath a composition of other type constructors, -- then the representation involves composition, too: -- -- @ -- data Rose a = Fork a [Rose a] -- @ -- -- yields -- -- @ -- instance 'Generic1' Rose where -- type 'Rep1' Rose = -- 'D1' ('MetaData \"Rose\" \"Main\" \"package-name\" 'False) -- ('C1' ('MetaCons \"Fork\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- 'Par1' -- ':*:' -- 'S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- ([] ':.:' 'Rec1' Rose))) -- @ -- -- where -- -- @ -- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) } -- @ -- *** Representation of @k -> *@ types -- -- | -- -- The 'Generic1' class can be generalized to range over types of kind -- @k -> *@, for any kind @k@. To do so, derive a 'Generic1' instance with the -- @PolyKinds@ extension enabled. For example, the declaration -- -- @ -- data Proxy (a :: k) = Proxy deriving 'Generic1' -- @ -- -- yields a slightly different instance depending on whether @PolyKinds@ is -- enabled. If compiled without @PolyKinds@, then @'Rep1' Proxy :: * -> *@, but -- if compiled with @PolyKinds@, then @'Rep1' Proxy :: k -> *@. -- *** Representation of unlifted types -- -- | -- -- If one were to attempt to derive a Generic instance for a datatype with an -- unlifted argument (for example, 'Int#'), one might expect the occurrence of -- the 'Int#' argument to be marked with @'Rec0' 'Int#'@. This won't work, -- though, since 'Int#' is of an unlifted kind, and 'Rec0' expects a type of -- kind @*@. -- -- One solution would be to represent an occurrence of 'Int#' with 'Rec0 Int' -- instead. With this approach, however, the programmer has no way of knowing -- whether the 'Int' is actually an 'Int#' in disguise. -- -- Instead of reusing 'Rec0', a separate data family 'URec' is used to mark -- occurrences of common unlifted types: -- -- @ -- data family URec a p -- -- data instance 'URec' ('Ptr' ()) p = 'UAddr' { 'uAddr#' :: 'Addr#' } -- data instance 'URec' 'Char' p = 'UChar' { 'uChar#' :: 'Char#' } -- data instance 'URec' 'Double' p = 'UDouble' { 'uDouble#' :: 'Double#' } -- data instance 'URec' 'Int' p = 'UFloat' { 'uFloat#' :: 'Float#' } -- data instance 'URec' 'Float' p = 'UInt' { 'uInt#' :: 'Int#' } -- data instance 'URec' 'Word' p = 'UWord' { 'uWord#' :: 'Word#' } -- @ -- -- Several type synonyms are provided for convenience: -- -- @ -- type 'UAddr' = 'URec' ('Ptr' ()) -- type 'UChar' = 'URec' 'Char' -- type 'UDouble' = 'URec' 'Double' -- type 'UFloat' = 'URec' 'Float' -- type 'UInt' = 'URec' 'Int' -- type 'UWord' = 'URec' 'Word' -- @ -- -- The declaration -- -- @ -- data IntHash = IntHash Int# -- deriving 'Generic' -- @ -- -- yields -- -- @ -- instance 'Generic' IntHash where -- type 'Rep' IntHash = -- 'D1' ('MetaData \"IntHash\" \"Main\" \"package-name\" 'False) -- ('C1' ('MetaCons \"IntHash\" 'PrefixI 'False) -- ('S1' ('MetaSel 'Nothing -- 'NoSourceUnpackedness -- 'NoSourceStrictness -- 'DecidedLazy) -- 'UInt')) -- @ -- -- Currently, only the six unlifted types listed above are generated, but this -- may be extended to encompass more unlifted types in the future. #if 0 -- *** Limitations -- -- | -- -- /TODO/ -- -- /TODO:/ Also clear up confusion about 'Rec0' and 'Rec1' not really indicating recursion. -- #endif ----------------------------------------------------------------------------- -- * Generic representation types V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..) , (:+:)(..), (:*:)(..), (:.:)(..) -- ** Unboxed representation types , URec(..) , type UAddr, type UChar, type UDouble , type UFloat, type UInt, type UWord -- ** Synonyms for convenience , Rec0, R , D1, C1, S1, D, C, S -- * Meta-information , Datatype(..), Constructor(..), Selector(..) , Fixity(..), FixityI(..), Associativity(..), prec , SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..) , Meta(..) -- * Generic type classes , Generic(..), Generic1(..) ) where -- We use some base types import Data.Either ( Either (..) ) import Data.Maybe ( Maybe(..), fromMaybe ) import Data.Ord ( Down(..) ) import GHC.Integer ( Integer, integerToInt ) import GHC.Prim ( Addr#, Char#, Double#, Float#, Int#, Word# ) import GHC.Ptr ( Ptr ) import GHC.Types -- Needed for instances import GHC.Ix ( Ix ) import GHC.Base ( Alternative(..), Applicative(..), Functor(..) , Monad(..), MonadPlus(..), NonEmpty(..), String, coerce , Semigroup(..), Monoid(..) ) import GHC.Classes ( Eq(..), Ord(..) ) import GHC.Enum ( Bounded, Enum ) import GHC.Read ( Read(..) ) import GHC.Show ( Show(..), showString ) -- Needed for metadata import Data.Proxy ( Proxy(..) ) import GHC.TypeLits ( KnownSymbol, KnownNat, symbolVal, natVal ) -------------------------------------------------------------------------------- -- Representation types -------------------------------------------------------------------------------- -- | Void: used for datatypes without constructors data V1 (p :: k) deriving ( Eq -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Read -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.12.0.0 instance Semigroup (V1 p) where v <> _ = v -- | Unit: used for constructors without arguments data U1 (p :: k) = U1 deriving ( Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.9.0.0 instance Eq (U1 p) where _ == _ = True -- | @since 4.7.0.0 instance Ord (U1 p) where compare _ _ = EQ -- | @since 4.9.0.0 deriving instance Read (U1 p) -- | @since 4.9.0.0 instance Show (U1 p) where showsPrec _ _ = showString "U1" -- | @since 4.9.0.0 instance Functor U1 where fmap _ _ = U1 -- | @since 4.9.0.0 instance Applicative U1 where pure _ = U1 _ <*> _ = U1 liftA2 _ _ _ = U1 -- | @since 4.9.0.0 instance Alternative U1 where empty = U1 _ <|> _ = U1 -- | @since 4.9.0.0 instance Monad U1 where _ >>= _ = U1 -- | @since 4.9.0.0 instance MonadPlus U1 -- | @since 4.12.0.0 instance Semigroup (U1 p) where _ <> _ = U1 -- | @since 4.12.0.0 instance Monoid (U1 p) where mempty = U1 -- | Used for marking occurrences of the parameter newtype Par1 p = Par1 { unPar1 :: p } deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.9.0.0 instance Applicative Par1 where pure = Par1 (<*>) = coerce liftA2 = coerce -- | @since 4.9.0.0 instance Monad Par1 where Par1 x >>= f = f x -- | @since 4.12.0.0 deriving instance Semigroup p => Semigroup (Par1 p) -- | @since 4.12.0.0 deriving instance Monoid p => Monoid (Par1 p) -- | Recursive calls of kind @* -> *@ (or kind @k -> *@, when @PolyKinds@ -- is enabled) newtype Rec1 (f :: k -> Type) (p :: k) = Rec1 { unRec1 :: f p } deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.9.0.0 deriving instance Applicative f => Applicative (Rec1 f) -- | @since 4.9.0.0 deriving instance Alternative f => Alternative (Rec1 f) -- | @since 4.9.0.0 instance Monad f => Monad (Rec1 f) where Rec1 x >>= f = Rec1 (x >>= \a -> unRec1 (f a)) -- | @since 4.9.0.0 deriving instance MonadPlus f => MonadPlus (Rec1 f) -- | @since 4.12.0.0 deriving instance Semigroup (f p) => Semigroup (Rec1 f p) -- | @since 4.12.0.0 deriving instance Monoid (f p) => Monoid (Rec1 f p) -- | Constants, additional parameters and recursion of kind @*@ newtype K1 (i :: Type) c (p :: k) = K1 { unK1 :: c } deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.12.0.0 instance Monoid c => Applicative (K1 i c) where pure _ = K1 mempty liftA2 = \_ -> coerce (mappend :: c -> c -> c) (<*>) = coerce (mappend :: c -> c -> c) -- | @since 4.12.0.0 deriving instance Semigroup c => Semigroup (K1 i c p) -- | @since 4.12.0.0 deriving instance Monoid c => Monoid (K1 i c p) -- | @since 4.9.0.0 deriving instance Applicative f => Applicative (M1 i c f) -- | @since 4.9.0.0 deriving instance Alternative f => Alternative (M1 i c f) -- | @since 4.9.0.0 deriving instance Monad f => Monad (M1 i c f) -- | @since 4.9.0.0 deriving instance MonadPlus f => MonadPlus (M1 i c f) -- | @since 4.12.0.0 deriving instance Semigroup (f p) => Semigroup (M1 i c f p) -- | @since 4.12.0.0 deriving instance Monoid (f p) => Monoid (M1 i c f p) -- | Meta-information (constructor names, etc.) newtype M1 (i :: Type) (c :: Meta) (f :: k -> Type) (p :: k) = M1 { unM1 :: f p } deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Sums: encode choice between constructors infixr 5 :+: data (:+:) (f :: k -> Type) (g :: k -> Type) (p :: k) = L1 (f p) | R1 (g p) deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Products: encode multiple arguments to constructors infixr 6 :*: data (:*:) (f :: k -> Type) (g :: k -> Type) (p :: k) = f p :*: g p deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.9.0.0 instance (Applicative f, Applicative g) => Applicative (f :*: g) where pure a = pure a :*: pure a (f :*: g) <*> (x :*: y) = (f <*> x) :*: (g <*> y) liftA2 f (a :*: b) (x :*: y) = liftA2 f a x :*: liftA2 f b y -- | @since 4.9.0.0 instance (Alternative f, Alternative g) => Alternative (f :*: g) where empty = empty :*: empty (x1 :*: y1) <|> (x2 :*: y2) = (x1 <|> x2) :*: (y1 <|> y2) -- | @since 4.9.0.0 instance (Monad f, Monad g) => Monad (f :*: g) where (m :*: n) >>= f = (m >>= \a -> fstP (f a)) :*: (n >>= \a -> sndP (f a)) where fstP (a :*: _) = a sndP (_ :*: b) = b -- | @since 4.9.0.0 instance (MonadPlus f, MonadPlus g) => MonadPlus (f :*: g) -- | @since 4.12.0.0 instance (Semigroup (f p), Semigroup (g p)) => Semigroup ((f :*: g) p) where (x1 :*: y1) <> (x2 :*: y2) = (x1 <> x2) :*: (y1 <> y2) -- | @since 4.12.0.0 instance (Monoid (f p), Monoid (g p)) => Monoid ((f :*: g) p) where mempty = mempty :*: mempty -- | Composition of functors infixr 7 :.: newtype (:.:) (f :: k2 -> Type) (g :: k1 -> k2) (p :: k1) = Comp1 { unComp1 :: f (g p) } deriving ( Eq -- ^ @since 4.7.0.0 , Ord -- ^ @since 4.7.0.0 , Read -- ^ @since 4.7.0.0 , Show -- ^ @since 4.7.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | @since 4.9.0.0 instance (Applicative f, Applicative g) => Applicative (f :.: g) where pure x = Comp1 (pure (pure x)) Comp1 f <*> Comp1 x = Comp1 (liftA2 (<*>) f x) liftA2 f (Comp1 x) (Comp1 y) = Comp1 (liftA2 (liftA2 f) x y) -- | @since 4.9.0.0 instance (Alternative f, Applicative g) => Alternative (f :.: g) where empty = Comp1 empty (<|>) = coerce ((<|>) :: f (g a) -> f (g a) -> f (g a)) :: forall a . (f :.: g) a -> (f :.: g) a -> (f :.: g) a -- | @since 4.12.0.0 deriving instance Semigroup (f (g p)) => Semigroup ((f :.: g) p) -- | @since 4.12.0.0 deriving instance Monoid (f (g p)) => Monoid ((f :.: g) p) -- | Constants of unlifted kinds -- -- @since 4.9.0.0 data family URec (a :: Type) (p :: k) -- | Used for marking occurrences of 'Addr#' -- -- @since 4.9.0.0 data instance URec (Ptr ()) (p :: k) = UAddr { uAddr# :: Addr# } deriving ( Eq -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Used for marking occurrences of 'Char#' -- -- @since 4.9.0.0 data instance URec Char (p :: k) = UChar { uChar# :: Char# } deriving ( Eq -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Used for marking occurrences of 'Double#' -- -- @since 4.9.0.0 data instance URec Double (p :: k) = UDouble { uDouble# :: Double# } deriving ( Eq -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Used for marking occurrences of 'Float#' -- -- @since 4.9.0.0 data instance URec Float (p :: k) = UFloat { uFloat# :: Float# } deriving ( Eq, Ord, Show , Functor -- ^ @since 4.9.0.0 , Generic , Generic1 -- ^ @since 4.9.0.0 ) -- | Used for marking occurrences of 'Int#' -- -- @since 4.9.0.0 data instance URec Int (p :: k) = UInt { uInt# :: Int# } deriving ( Eq -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Used for marking occurrences of 'Word#' -- -- @since 4.9.0.0 data instance URec Word (p :: k) = UWord { uWord# :: Word# } deriving ( Eq -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Functor -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 , Generic1 -- ^ @since 4.9.0.0 ) -- | Type synonym for @'URec' 'Addr#'@ -- -- @since 4.9.0.0 type UAddr = URec (Ptr ()) -- | Type synonym for @'URec' 'Char#'@ -- -- @since 4.9.0.0 type UChar = URec Char -- | Type synonym for @'URec' 'Double#'@ -- -- @since 4.9.0.0 type UDouble = URec Double -- | Type synonym for @'URec' 'Float#'@ -- -- @since 4.9.0.0 type UFloat = URec Float -- | Type synonym for @'URec' 'Int#'@ -- -- @since 4.9.0.0 type UInt = URec Int -- | Type synonym for @'URec' 'Word#'@ -- -- @since 4.9.0.0 type UWord = URec Word -- | Tag for K1: recursion (of kind @Type@) data R -- | Type synonym for encoding recursion (of kind @Type@) type Rec0 = K1 R -- | Tag for M1: datatype data D -- | Tag for M1: constructor data C -- | Tag for M1: record selector data S -- | Type synonym for encoding meta-information for datatypes type D1 = M1 D -- | Type synonym for encoding meta-information for constructors type C1 = M1 C -- | Type synonym for encoding meta-information for record selectors type S1 = M1 S -- | Class for datatypes that represent datatypes class Datatype d where -- | The name of the datatype (unqualified) datatypeName :: t d (f :: k -> Type) (a :: k) -> [Char] -- | The fully-qualified name of the module where the type is declared moduleName :: t d (f :: k -> Type) (a :: k) -> [Char] -- | The package name of the module where the type is declared -- -- @since 4.9.0.0 packageName :: t d (f :: k -> Type) (a :: k) -> [Char] -- | Marks if the datatype is actually a newtype -- -- @since 4.7.0.0 isNewtype :: t d (f :: k -> Type) (a :: k) -> Bool isNewtype _ = False -- | @since 4.9.0.0 instance (KnownSymbol n, KnownSymbol m, KnownSymbol p, SingI nt) => Datatype ('MetaData n m p nt) where datatypeName _ = symbolVal (Proxy :: Proxy n) moduleName _ = symbolVal (Proxy :: Proxy m) packageName _ = symbolVal (Proxy :: Proxy p) isNewtype _ = fromSing (sing :: Sing nt) -- | Class for datatypes that represent data constructors class Constructor c where -- | The name of the constructor conName :: t c (f :: k -> Type) (a :: k) -> [Char] -- | The fixity of the constructor conFixity :: t c (f :: k -> Type) (a :: k) -> Fixity conFixity _ = Prefix -- | Marks if this constructor is a record conIsRecord :: t c (f :: k -> Type) (a :: k) -> Bool conIsRecord _ = False -- | @since 4.9.0.0 instance (KnownSymbol n, SingI f, SingI r) => Constructor ('MetaCons n f r) where conName _ = symbolVal (Proxy :: Proxy n) conFixity _ = fromSing (sing :: Sing f) conIsRecord _ = fromSing (sing :: Sing r) -- | Datatype to represent the fixity of a constructor. An infix -- | declaration directly corresponds to an application of 'Infix'. data Fixity = Prefix | Infix Associativity Int deriving ( Eq -- ^ @since 4.6.0.0 , Show -- ^ @since 4.6.0.0 , Ord -- ^ @since 4.6.0.0 , Read -- ^ @since 4.6.0.0 , Generic -- ^ @since 4.7.0.0 ) -- | This variant of 'Fixity' appears at the type level. -- -- @since 4.9.0.0 data FixityI = PrefixI | InfixI Associativity Nat -- | Get the precedence of a fixity value. prec :: Fixity -> Int prec Prefix = 10 prec (Infix _ n) = n -- | Datatype to represent the associativity of a constructor data Associativity = LeftAssociative | RightAssociative | NotAssociative deriving ( Eq -- ^ @since 4.6.0.0 , Show -- ^ @since 4.6.0.0 , Ord -- ^ @since 4.6.0.0 , Read -- ^ @since 4.6.0.0 , Enum -- ^ @since 4.9.0.0 , Bounded -- ^ @since 4.9.0.0 , Ix -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.7.0.0 ) -- | The unpackedness of a field as the user wrote it in the source code. For -- example, in the following data type: -- -- @ -- data E = ExampleConstructor Int -- {\-\# NOUNPACK \#-\} Int -- {\-\# UNPACK \#-\} Int -- @ -- -- The fields of @ExampleConstructor@ have 'NoSourceUnpackedness', -- 'SourceNoUnpack', and 'SourceUnpack', respectively. -- -- @since 4.9.0.0 data SourceUnpackedness = NoSourceUnpackedness | SourceNoUnpack | SourceUnpack deriving ( Eq -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Read -- ^ @since 4.9.0.0 , Enum -- ^ @since 4.9.0.0 , Bounded -- ^ @since 4.9.0.0 , Ix -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 ) -- | The strictness of a field as the user wrote it in the source code. For -- example, in the following data type: -- -- @ -- data E = ExampleConstructor Int ~Int !Int -- @ -- -- The fields of @ExampleConstructor@ have 'NoSourceStrictness', -- 'SourceLazy', and 'SourceStrict', respectively. -- -- @since 4.9.0.0 data SourceStrictness = NoSourceStrictness | SourceLazy | SourceStrict deriving ( Eq -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Read -- ^ @since 4.9.0.0 , Enum -- ^ @since 4.9.0.0 , Bounded -- ^ @since 4.9.0.0 , Ix -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 ) -- | The strictness that GHC infers for a field during compilation. Whereas -- there are nine different combinations of 'SourceUnpackedness' and -- 'SourceStrictness', the strictness that GHC decides will ultimately be one -- of lazy, strict, or unpacked. What GHC decides is affected both by what the -- user writes in the source code and by GHC flags. As an example, consider -- this data type: -- -- @ -- data E = ExampleConstructor {\-\# UNPACK \#-\} !Int !Int Int -- @ -- -- * If compiled without optimization or other language extensions, then the -- fields of @ExampleConstructor@ will have 'DecidedStrict', 'DecidedStrict', -- and 'DecidedLazy', respectively. -- -- * If compiled with @-XStrictData@ enabled, then the fields will have -- 'DecidedStrict', 'DecidedStrict', and 'DecidedStrict', respectively. -- -- * If compiled with @-O2@ enabled, then the fields will have 'DecidedUnpack', -- 'DecidedStrict', and 'DecidedLazy', respectively. -- -- @since 4.9.0.0 data DecidedStrictness = DecidedLazy | DecidedStrict | DecidedUnpack deriving ( Eq -- ^ @since 4.9.0.0 , Show -- ^ @since 4.9.0.0 , Ord -- ^ @since 4.9.0.0 , Read -- ^ @since 4.9.0.0 , Enum -- ^ @since 4.9.0.0 , Bounded -- ^ @since 4.9.0.0 , Ix -- ^ @since 4.9.0.0 , Generic -- ^ @since 4.9.0.0 ) -- | Class for datatypes that represent records class Selector s where -- | The name of the selector selName :: t s (f :: k -> Type) (a :: k) -> [Char] -- | The selector's unpackedness annotation (if any) -- -- @since 4.9.0.0 selSourceUnpackedness :: t s (f :: k -> Type) (a :: k) -> SourceUnpackedness -- | The selector's strictness annotation (if any) -- -- @since 4.9.0.0 selSourceStrictness :: t s (f :: k -> Type) (a :: k) -> SourceStrictness -- | The strictness that the compiler inferred for the selector -- -- @since 4.9.0.0 selDecidedStrictness :: t s (f :: k -> Type) (a :: k) -> DecidedStrictness -- | @since 4.9.0.0 instance (SingI mn, SingI su, SingI ss, SingI ds) => Selector ('MetaSel mn su ss ds) where selName _ = fromMaybe "" (fromSing (sing :: Sing mn)) selSourceUnpackedness _ = fromSing (sing :: Sing su) selSourceStrictness _ = fromSing (sing :: Sing ss) selDecidedStrictness _ = fromSing (sing :: Sing ds) -- | Representable types of kind @*@. -- This class is derivable in GHC with the @DeriveGeneric@ flag on. -- -- A 'Generic' instance must satisfy the following laws: -- -- @ -- 'from' . 'to' ≡ 'Prelude.id' -- 'to' . 'from' ≡ 'Prelude.id' -- @ class Generic a where -- | Generic representation type type Rep a :: Type -> Type -- | Convert from the datatype to its representation from :: a -> (Rep a) x -- | Convert from the representation to the datatype to :: (Rep a) x -> a -- | Representable types of kind @* -> *@ (or kind @k -> *@, when @PolyKinds@ -- is enabled). -- This class is derivable in GHC with the @DeriveGeneric@ flag on. -- -- A 'Generic1' instance must satisfy the following laws: -- -- @ -- 'from1' . 'to1' ≡ 'Prelude.id' -- 'to1' . 'from1' ≡ 'Prelude.id' -- @ class Generic1 (f :: k -> Type) where -- | Generic representation type type Rep1 f :: k -> Type -- | Convert from the datatype to its representation from1 :: f a -> (Rep1 f) a -- | Convert from the representation to the datatype to1 :: (Rep1 f) a -> f a -------------------------------------------------------------------------------- -- Meta-data -------------------------------------------------------------------------------- -- | Datatype to represent metadata associated with a datatype (@MetaData@), -- constructor (@MetaCons@), or field selector (@MetaSel@). -- -- * In @MetaData n m p nt@, @n@ is the datatype's name, @m@ is the module in -- which the datatype is defined, @p@ is the package in which the datatype -- is defined, and @nt@ is @'True@ if the datatype is a @newtype@. -- -- * In @MetaCons n f s@, @n@ is the constructor's name, @f@ is its fixity, -- and @s@ is @'True@ if the constructor contains record selectors. -- -- * In @MetaSel mn su ss ds@, if the field uses record syntax, then @mn@ is -- 'Just' the record name. Otherwise, @mn@ is 'Nothing'. @su@ and @ss@ are -- the field's unpackedness and strictness annotations, and @ds@ is the -- strictness that GHC infers for the field. -- -- @since 4.9.0.0 data Meta = MetaData Symbol Symbol Symbol Bool | MetaCons Symbol FixityI Bool | MetaSel (Maybe Symbol) SourceUnpackedness SourceStrictness DecidedStrictness -------------------------------------------------------------------------------- -- Derived instances -------------------------------------------------------------------------------- -- | @since 4.6.0.0 deriving instance Generic [a] -- | @since 4.6.0.0 deriving instance Generic (NonEmpty a) -- | @since 4.6.0.0 deriving instance Generic (Maybe a) -- | @since 4.6.0.0 deriving instance Generic (Either a b) -- | @since 4.6.0.0 deriving instance Generic Bool -- | @since 4.6.0.0 deriving instance Generic Ordering -- | @since 4.6.0.0 deriving instance Generic (Proxy t) -- | @since 4.6.0.0 deriving instance Generic () -- | @since 4.6.0.0 deriving instance Generic ((,) a b) -- | @since 4.6.0.0 deriving instance Generic ((,,) a b c) -- | @since 4.6.0.0 deriving instance Generic ((,,,) a b c d) -- | @since 4.6.0.0 deriving instance Generic ((,,,,) a b c d e) -- | @since 4.6.0.0 deriving instance Generic ((,,,,,) a b c d e f) -- | @since 4.6.0.0 deriving instance Generic ((,,,,,,) a b c d e f g) -- | @since 4.12.0.0 deriving instance Generic (Down a) -- | @since 4.6.0.0 deriving instance Generic1 [] -- | @since 4.6.0.0 deriving instance Generic1 NonEmpty -- | @since 4.6.0.0 deriving instance Generic1 Maybe -- | @since 4.6.0.0 deriving instance Generic1 (Either a) -- | @since 4.6.0.0 deriving instance Generic1 Proxy -- | @since 4.6.0.0 deriving instance Generic1 ((,) a) -- | @since 4.6.0.0 deriving instance Generic1 ((,,) a b) -- | @since 4.6.0.0 deriving instance Generic1 ((,,,) a b c) -- | @since 4.6.0.0 deriving instance Generic1 ((,,,,) a b c d) -- | @since 4.6.0.0 deriving instance Generic1 ((,,,,,) a b c d e) -- | @since 4.6.0.0 deriving instance Generic1 ((,,,,,,) a b c d e f) -- | @since 4.12.0.0 deriving instance Generic1 Down -------------------------------------------------------------------------------- -- Copied from the singletons package -------------------------------------------------------------------------------- -- | The singleton kind-indexed data family. data family Sing (a :: k) -- | A 'SingI' constraint is essentially an implicitly-passed singleton. class SingI (a :: k) where -- | Produce the singleton explicitly. You will likely need the @ScopedTypeVariables@ -- extension to use this method the way you want. sing :: Sing a -- | The 'SingKind' class is essentially a /kind/ class. It classifies all kinds -- for which singletons are defined. The class supports converting between a singleton -- type and the base (unrefined) type which it is built from. class SingKind k where -- | Get a base type from a proxy for the promoted kind. For example, -- @DemoteRep Bool@ will be the type @Bool@. type DemoteRep k :: Type -- | Convert a singleton to its unrefined version. fromSing :: Sing (a :: k) -> DemoteRep k -- Singleton symbols data instance Sing (s :: Symbol) where SSym :: KnownSymbol s => Sing s -- | @since 4.9.0.0 instance KnownSymbol a => SingI a where sing = SSym -- | @since 4.9.0.0 instance SingKind Symbol where type DemoteRep Symbol = String fromSing (SSym :: Sing s) = symbolVal (Proxy :: Proxy s) -- Singleton booleans data instance Sing (a :: Bool) where STrue :: Sing 'True SFalse :: Sing 'False -- | @since 4.9.0.0 instance SingI 'True where sing = STrue -- | @since 4.9.0.0 instance SingI 'False where sing = SFalse -- | @since 4.9.0.0 instance SingKind Bool where type DemoteRep Bool = Bool fromSing STrue = True fromSing SFalse = False -- Singleton Maybe data instance Sing (b :: Maybe a) where SNothing :: Sing 'Nothing SJust :: Sing a -> Sing ('Just a) -- | @since 4.9.0.0 instance SingI 'Nothing where sing = SNothing -- | @since 4.9.0.0 instance SingI a => SingI ('Just a) where sing = SJust sing -- | @since 4.9.0.0 instance SingKind a => SingKind (Maybe a) where type DemoteRep (Maybe a) = Maybe (DemoteRep a) fromSing SNothing = Nothing fromSing (SJust a) = Just (fromSing a) -- Singleton Fixity data instance Sing (a :: FixityI) where SPrefix :: Sing 'PrefixI SInfix :: Sing a -> Integer -> Sing ('InfixI a n) -- | @since 4.9.0.0 instance SingI 'PrefixI where sing = SPrefix -- | @since 4.9.0.0 instance (SingI a, KnownNat n) => SingI ('InfixI a n) where sing = SInfix (sing :: Sing a) (natVal (Proxy :: Proxy n)) -- | @since 4.9.0.0 instance SingKind FixityI where type DemoteRep FixityI = Fixity fromSing SPrefix = Prefix fromSing (SInfix a n) = Infix (fromSing a) (I# (integerToInt n)) -- Singleton Associativity data instance Sing (a :: Associativity) where SLeftAssociative :: Sing 'LeftAssociative SRightAssociative :: Sing 'RightAssociative SNotAssociative :: Sing 'NotAssociative -- | @since 4.9.0.0 instance SingI 'LeftAssociative where sing = SLeftAssociative -- | @since 4.9.0.0 instance SingI 'RightAssociative where sing = SRightAssociative -- | @since 4.9.0.0 instance SingI 'NotAssociative where sing = SNotAssociative -- | @since 4.0.0.0 instance SingKind Associativity where type DemoteRep Associativity = Associativity fromSing SLeftAssociative = LeftAssociative fromSing SRightAssociative = RightAssociative fromSing SNotAssociative = NotAssociative -- Singleton SourceUnpackedness data instance Sing (a :: SourceUnpackedness) where SNoSourceUnpackedness :: Sing 'NoSourceUnpackedness SSourceNoUnpack :: Sing 'SourceNoUnpack SSourceUnpack :: Sing 'SourceUnpack -- | @since 4.9.0.0 instance SingI 'NoSourceUnpackedness where sing = SNoSourceUnpackedness -- | @since 4.9.0.0 instance SingI 'SourceNoUnpack where sing = SSourceNoUnpack -- | @since 4.9.0.0 instance SingI 'SourceUnpack where sing = SSourceUnpack -- | @since 4.9.0.0 instance SingKind SourceUnpackedness where type DemoteRep SourceUnpackedness = SourceUnpackedness fromSing SNoSourceUnpackedness = NoSourceUnpackedness fromSing SSourceNoUnpack = SourceNoUnpack fromSing SSourceUnpack = SourceUnpack -- Singleton SourceStrictness data instance Sing (a :: SourceStrictness) where SNoSourceStrictness :: Sing 'NoSourceStrictness SSourceLazy :: Sing 'SourceLazy SSourceStrict :: Sing 'SourceStrict -- | @since 4.9.0.0 instance SingI 'NoSourceStrictness where sing = SNoSourceStrictness -- | @since 4.9.0.0 instance SingI 'SourceLazy where sing = SSourceLazy -- | @since 4.9.0.0 instance SingI 'SourceStrict where sing = SSourceStrict -- | @since 4.9.0.0 instance SingKind SourceStrictness where type DemoteRep SourceStrictness = SourceStrictness fromSing SNoSourceStrictness = NoSourceStrictness fromSing SSourceLazy = SourceLazy fromSing SSourceStrict = SourceStrict -- Singleton DecidedStrictness data instance Sing (a :: DecidedStrictness) where SDecidedLazy :: Sing 'DecidedLazy SDecidedStrict :: Sing 'DecidedStrict SDecidedUnpack :: Sing 'DecidedUnpack -- | @since 4.9.0.0 instance SingI 'DecidedLazy where sing = SDecidedLazy -- | @since 4.9.0.0 instance SingI 'DecidedStrict where sing = SDecidedStrict -- | @since 4.9.0.0 instance SingI 'DecidedUnpack where sing = SDecidedUnpack -- | @since 4.9.0.0 instance SingKind DecidedStrictness where type DemoteRep DecidedStrictness = DecidedStrictness fromSing SDecidedLazy = DecidedLazy fromSing SDecidedStrict = DecidedStrict fromSing SDecidedUnpack = DecidedUnpack
sdiehl/ghc
libraries/base/GHC/Generics.hs
Haskell
bsd-3-clause
54,675
{-# LANGUAGE Rank2Types, ScopedTypeVariables, FlexibleInstances, OverloadedStrings, TypeSynonymInstances, TypeOperators, GADTs #-} module Paskell.Syntax.Haskell where import Paskell.Expr import Paskell.EvalM import Control.Monad import Data.Maybe import System.IO.Unsafe import Control.Monad.Error import Control.Monad.Writer import Control.Monad.Trans import Data.String instance IsString E where fromString s = EVar s instance IsString Pat where fromString s = PVar s instance IsString [Pat] where fromString = map fromString . words infixl 0 =: infixl 1 $- f $- x = f x class HasAssign a where (=:) :: Pat -> E -> a instance HasAssign D where p =: e = DLet p e instance HasAssign E where p =: e = EAssign p e tint = TCon "Int" treal = TCon "Real" tstring = TCon "String" tunit = TCon "Unit" a = TVar "a" b = TVar "b" c = TVar "c" vunit = pack () infixr 3 ~> targs ~> t2 = TLam targs t2 instance Num E where e1 + e2 = EVar "+" $> [e1, e2] e1 - e2 = EVar "-" $> [e1, e2] e1 * e2 = EVar "*" $> [e1, e2] abs e = EVar "abs" $> [e] signum e = EVar "signum" $> [e] fromInteger n = ECon (VInt $ fromInteger n) instance Num Pat where e1 + e2 = error "Pattern nummeric instance" e1 - e2 = error "Pattern nummeric instance" e1 * e2 = error "Pattern nummeric instance" abs e = error "Pattern nummeric instance" signum e = error "Pattern nummeric instance" fromInteger n = PLit (VInt $ fromInteger n) class Reify a where reify :: V-> Maybe a pack :: a->V packType :: a->T instance Reify V where reify = Just pack = id packType = undefined instance Reify Double where reify (VReal x) = Just x reify v = Nothing pack = VReal packType _ = treal instance Reify Int where reify (VInt x) = Just x reify v = Nothing pack = VInt packType _ = tint instance Reify () where reify (VCons "unit" []) = Just () reify v = Nothing pack () = VCons "unit" [] packType _ = TCon "Unit" newtype String_ = String_ { unString :: [Char] } instance Reify String_ where reify (VString s) = Just $ String_ s reify v = Nothing pack (String_ s) = VString s packType _ = tint instance Reify Bool where reify (VCons "True" []) = Just True reify (VCons "False" []) = Just False reify v = Nothing pack True = VCons "True" [] pack False = VCons "False" [] packType _ = TCon "Bool" instance (Reify a, Reify b) => Reify (a-> IO b) where reify (VLam f) = Just $ \hsArgs-> do res <- runErrorT $ f $ [pack hsArgs] case res of Left s -> error $ "error in reify function: "++s Right v -> return $ fromJust $ reify v reify _ = Nothing pack f = VLam $ \[v]-> case reify v of Nothing -> fail $ "pack function: fail for argument" ++ show v++" for function of type "++show (packType f) Just x -> do v<- liftIO $ f x return $ pack v packType f = typeFIO f typeFIO :: forall a b. (Reify a, Reify b) => (a-> IO b) -> T typeFIO f = let x = undefined :: a --undefined y = unsafePerformIO $ f x in [packType x] ~> packType y typeF :: forall a b. (Reify a, Reify b) => (a-> b) -> T typeF f = let x = undefined :: a --undefined y = f x in [packType x] ~> packType y typeF2 :: forall a b c. (Reify a, Reify b, Reify c) => (a-> b -> c) -> T typeF2 f = let x = undefined :: a --undefined y = undefined :: b z = f x y in [packType x, packType y] ~> packType y packF1 :: (Reify a, Reify b) => (a->b) -> (T,V) packF1 f = (typeF f, VLam $ \[v] -> case reify v of Nothing -> error $ "pack function: fail for argument" ++ show v++" for function of type "++show (typeF f) Just x -> return $ pack $ (f x )) packF2 :: (Reify a, Reify b, Reify c) => (a->b->c) -> (T,V) packF2 f = (typeF2 f, VLam $ \[vx,vy] -> case liftM2 (,) (reify vx) (reify vy) of Nothing -> error $ "pack function: fail for argument" ++ show vx++" for function of type "++show (typeF2 f) Just (x,y) -> return $ pack $ (f x y)) type TopLevel a = Writer [D] a type CasePates = Writer [Pat :-> Function ()] () type Function a = Writer [E] a infixl 1 -:> p -:> es = tell [p :-> es] instance HasAssign (TopLevel a) where p =: e = tell [DLet p e] >> return undefined instance HasAssign (Function a) where p =: e = tell [p =: e] >> return undefined lam :: [Pat] -> Function () -> E lam pats fwriter = ELam pats $ execWriter fwriter module_ :: TopLevel () -> [D] module_ = execWriter d :: D -> TopLevel () d = tell . (:[]) e :: ToExprs a => a -> Function () e = tell . toExprs e $>> es = tell [e $> es] for n m ix bd = "for" $>> [n, m, ELam ix (execWriter bd)] infixl 5 :-> data a :-> b = a :-> b data Then = Then data Else = Else if_ :: E -> Then ->Function () -> Else -> Function () -> Function () if_ p _ c _ a = tell [EIf p (execWriter c) (execWriter a)] caseOf :: E -> CasePates -> Function () caseOf e pates = tell [ECase e $ map f $ execWriter pates] where f (p:->es) = (p,execWriter es) class ToExprs a where toExprs :: a -> [E] instance ToExprs E where toExprs = (:[]) instance ToExprs [Char] where toExprs = (:[]) . EVar instance ToExprs [E] where toExprs = id instance ToExprs V where toExprs = (:[]) . ECon instance ToExprs () where toExprs _ = [ECon (pack ())] instance ToExprs (Function ()) where toExprs w = execWriter w class CallResult a where ($>) :: E -> [E] -> a instance CallResult (Function a) where f $> args = tell [EApp f args] >> return undefined instance CallResult (E) where f $> args = EApp f args --($>) = call --($>) :: E -> [E] -> E --f $> es = EApp f es
glutamate/paskell
Paskell/Syntax/Haskell.hs
Haskell
bsd-3-clause
6,071
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE CPP #-} -- #define DEBUG {-| Module : AERN2.Poly.Ball Description : Polynomial enclosures with large radii Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable Polynomial enclosures with large radii -} module AERN2.Poly.Ball -- ( -- ) where #ifdef DEBUG import Debug.Trace (trace) #define maybeTrace trace #else #define maybeTrace (flip const) #endif import MixedTypesNumPrelude -- import qualified Prelude as P -- import Text.Printf -- import qualified Data.Map as Map -- import qualified Data.List as List -- import Test.Hspec -- import Test.QuickCheck import Control.CollectErrors import AERN2.Normalize import AERN2.MP hiding (ball_value, ball_error) -- import qualified AERN2.MP.Ball as MPBall import AERN2.MP.Dyadic import AERN2.Real hiding (ball_value) import AERN2.Interval import AERN2.RealFun.Operations import AERN2.Poly.Cheb as ChPoly {- examples -} _pb_const1 :: PolyBall _pb_const1 = constFn (dom, bits 100) 1 where dom = dyadicInterval (0.0,1.0) _pb_X :: PolyBall _pb_X = varFn (dom, bits 100) () where dom = dyadicInterval (0.0,1.0) {- type -} type PolyBall = Ball (ChPoly MPBall) polyBall :: (ConvertibleExactly t PolyBall) => t -> PolyBall polyBall = convertExactly data Ball t = Ball { ball_value :: t, ball_radius :: ErrorBound } instance (Show t) => Show (Ball t) where show (Ball c e) = "Ball " ++ (show c) ++ "+-" ++ (show e) instance (CanBeErrors es) => CanEnsureCE es (Ball t) instance (CanBeErrors es) => CanExtractCE es Ball where extractCE sample_es (Ball cCE e) = case ensureNoCE sample_es cCE of (Just c, es) -> CollectErrors (Just (Ball c e)) es (_, es) -> CollectErrors Nothing es degree :: PolyBall -> Integer degree (Ball c _e) = ChPoly.degree c ballLift1R :: (IsBall t) => (t -> t1) -> (Ball t -> t1) ballLift1R f (Ball c e) = f (updateRadius (+ e) c) ballLift1TR :: (IsBall t) => (t -> t1 -> t2) -> (Ball t -> t1 -> t2) ballLift1TR f (Ball c e) = f (updateRadius (+ e) c) ballLift1T :: (IsBall t) => (t -> t1 -> t) -> (Ball t -> t1 -> Ball t) ballLift1T f (Ball c e) t = Ball fceC fceE where fceC = centreAsBall fce fceE = radius fce fce = f (updateRadius (+e) c) t ballLift1TCN :: (IsBall t, CanEnsureCN t) => (t -> t1 -> EnsureCN t) -> (Ball t -> t1 -> CN (Ball t)) ballLift1TCN f b@(Ball c e) t = case deEnsureCN fceCN of Right fce -> let fceC = centreAsBall fce fceE = radius fce in cn $ Ball fceC fceE Left es -> noValueECN (Just b) es where fceCN = f (updateRadius (+e) c) t -- instance CanExtractCE es Ball where -- extractCE sample_es ballLift1 :: (IsBall t) => (t -> t) -> (Ball t -> Ball t) ballLift1 f (Ball c1 e1) = Ball fceC fceE where fceC = centreAsBall fce fceE = radius fce fce = f (updateRadius (+e1) c1) ballLift2 :: (IsBall t) => (t -> t -> t) -> (Ball t -> Ball t -> Ball t) ballLift2 f (Ball c1 e1) (Ball c2 e2) = Ball fceC fceE where fceC = centreAsBall fce fceE = radius fce fce = f (updateRadius (+e1) c1) (updateRadius (+e2) c2) instance (IsBall t) => IsBall (Ball t) where type CentreType (Ball t) = t centre = ball_value radius = ball_radius updateRadius updateFn (Ball c r) = Ball c (updateFn r) centreAsBallAndRadius (Ball c r) = (Ball c (errorBound 0), r) instance (IsBall t, CanNormalize t) => CanNormalize (Ball t) where normalize (Ball x e) = Ball (centreAsBall xN) (radius xN + e) where xN = normalize x instance HasFnConstructorInfo t => HasFnConstructorInfo (Ball t) where type FnConstructorInfo (Ball t) = FnConstructorInfo t getFnConstructorInfo (Ball c _) = getFnConstructorInfo c instance (ConvertibleExactly (i, t2) t) => ConvertibleExactly (i, t2) (Ball t) where safeConvertExactly (constrInfo, x) = case safeConvertExactly (constrInfo, x) of Right c -> Right $ Ball c (errorBound 0) Left e -> Left e -- instance (ConvertibleExactly (t, t2) t) => -- ConvertibleExactly (Ball t, t2) (Ball t) -- where -- safeConvertExactly (Ball sample eb, x) = -- case safeConvertExactly (sample, x) of -- Right c -> Right $ Ball c eb -- Left e -> Left e instance (HasDomain t) => HasDomain (Ball t) where type Domain (Ball t) = Domain t getDomain = getDomain . ball_value instance (HasVars t) => HasVars (Ball t) where type Var (Ball t) = Var t varFn constrInfo var = Ball (varFn constrInfo var) (errorBound 0) {- precision -} instance (HasPrecision t, IsBall t) => HasPrecision (Ball t) where getPrecision = ballLift1R getPrecision instance (CanSetPrecision t, IsBall t) => CanSetPrecision (Ball t) where setPrecision prc (Ball c e) = Ball (setPrecision prc c) e {- accuracy -} instance (HasAccuracy t, IsBall t) => HasAccuracy (Ball t) where getAccuracy= ballLift1R getAccuracy getFiniteAccuracy= ballLift1R getFiniteAccuracy instance (HasAccuracyGuide t, IsBall t) => HasAccuracyGuide (Ball t) where getAccuracyGuide = ballLift1R getAccuracyGuide instance (CanSetAccuracyGuide t, IsBall t) => CanSetAccuracyGuide (Ball t) where setAccuracyGuide acGuide = ballLift1 (setAccuracyGuide acGuide) instance (IsBall t, CanNormalize t, CanReduceSizeUsingAccuracyGuide t) => CanReduceSizeUsingAccuracyGuide (Ball t) where reduceSizeUsingAccuracyGuide ac (Ball c e) = normalize $ Ball (reduceSizeUsingAccuracyGuide ac c) e {- negation -} instance CanNegSameType t => CanNeg (Ball t) where type NegType (Ball t) = Ball t negate (Ball x e) = Ball (negate x) e {- addition -} instance (IsBall t, CanNormalize t, CanAddSameType t) => CanAddAsymmetric (Ball t) (Ball t) where type AddType (Ball t) (Ball t) = Ball t add (Ball x1 e1) (Ball x2 e2) = normalize $ Ball (x1 + x2) (e1 + e2) $(declForTypes [[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]] (\ t -> [d| instance (CanAddThis t $t, IsBall t, CanNormalize t) => CanAddAsymmetric $t (Ball t) where type AddType $t (Ball t) = Ball t add n (Ball x e) = normalize $ Ball (x + n) e instance (CanAddThis t $t, IsBall t, CanNormalize t) => CanAddAsymmetric (Ball t) $t where type AddType (Ball t) $t = Ball t add (Ball x e) n = normalize $ Ball (x + n) e |])) {- subtraction -} instance (IsBall t, CanNormalize t, CanAddSameType t, CanNegSameType t) => CanSub (Ball t) (Ball t) $(declForTypes [[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]] (\ t -> [d| instance (IsBall t, CanNormalize t, CanAddThis t $t, CanNegSameType t) => CanSub $t (Ball t) instance (IsBall t, CanNormalize t, CanAddThis t $t) => CanSub (Ball t) $t |])) {- multiplication -} multiplyWithBounds :: PolyBall -> MPBall -> PolyBall -> MPBall -> PolyBall multiplyWithBounds (Ball p ep) bp (Ball q eq) bq = makeExactCentre res where res = Ball (p * q) e e = ep*(errorBound bq) + (errorBound bp)*eq + ep*eq multiplyAccurate :: PolyBall -> PolyBall -> PolyBall multiplyAccurate f g = multiplyWithAccuracy (min ((getFiniteAccuracy f) + 1) ((getFiniteAccuracy g) + 1)) f g multiplyWithAccuracy :: Accuracy -> PolyBall -> PolyBall -> PolyBall multiplyWithAccuracy ac f@(Ball p _) g@(Ball q _) = multiplyWithBounds f (rangeWithAccuracy p) g (rangeWithAccuracy q) where rangeWithAccuracy h = let Interval a' b' = chPoly_dom h pr = getPrecision h a = setPrecision pr $ mpBall a' b = setPrecision pr $ mpBall b' in max (abs $ maximumOptimisedWithAccuracy ac h a b 5 5) (abs $ minimumOptimisedWithAccuracy ac h a b 5 5) instance -- (IsBall t, CanNormalize t, CanMulSameType t) -- => -- CanMulAsymmetric (Ball t) (Ball t) where -- type MulType (Ball t) (Ball t) = Ball t CanMulAsymmetric PolyBall PolyBall where type MulType PolyBall PolyBall = PolyBall mul = ballLift2 mul -- mul = multiplyWithAccuracy (bits 0) $(declForTypes [[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]] (\ t -> [d| instance (CanMulBy t $t, IsBall t, CanNormalize t) => CanMulAsymmetric $t (Ball t) where type MulType $t (Ball t) = Ball t mul = flip (ballLift1T (flip mul)) instance (CanMulBy t $t, IsBall t, CanNormalize t) => CanMulAsymmetric (Ball t) $t where type MulType (Ball t) $t = Ball t mul = ballLift1T mul |])) $(declForTypes [[t| Integer |], [t| Int |], [t| Rational |], [t| Dyadic |], [t| MPBall |], [t| CauchyReal |]] (\ t -> [d| instance (CanDivCNBy t $t, IsBall t, CanNormalize t, CanEnsureCN t) => CanDiv (Ball t) $t where type DivTypeNoCN (Ball t) $t = Ball t divideNoCN = ballLift1T divideNoCN type DivType (Ball t) $t = EnsureCN (Ball t) divide = ballLift1TCN divide |])) {- evaluation -} instance CanApply PolyBall MPBall where type ApplyType PolyBall MPBall = MPBall apply (Ball c e) y = updateRadius (+e) (apply c y) instance CanApplyApprox PolyBall DyadicInterval where type ApplyApproxType PolyBall DyadicInterval = MPBall applyApprox (Ball c e) y = updateRadius (+e) (applyApprox c y) {- maximisation -} instance CanMaximiseOverDom PolyBall DyadicInterval where type MaximumOverDomType PolyBall DyadicInterval = MPBall maximumOverDom (Ball c e) di = maximumOverDom (updateRadius (+e) c) di instance CanMinimiseOverDom PolyBall DyadicInterval where type MinimumOverDomType PolyBall DyadicInterval = MPBall minimumOverDom (Ball c e) di = minimumOverDom (updateRadius (+e) c) di {- integration -} instance CanIntegrateOverDom PolyBall DyadicInterval where type IntegralOverDomType PolyBall DyadicInterval = MPBall integrateOverDom (Ball c e) di = integrateOverDom (updateRadius (+e) c) di instance CanSinCosSameType t => CanSinCos (Ball t) where type SinCosType (Ball t) = Ball t sin (Ball x e) = Ball (sin x) e cos (Ball x e) = Ball (cos x) e
michalkonecny/aern2
aern2-fun-univariate/src/AERN2/Poly/Ball.hs
Haskell
bsd-3-clause
10,071
module Paths ( vheDirStructure , cabalConfigLocation , getVirtualEnvironment ) where import System.FilePath ((</>)) import System.Directory (getCurrentDirectory) import System.Environment (getEnvironment) import Types import MyMonad -- returns record containing paths to all important directories -- inside virtual environment dir structure vheDirStructure :: MyMonad DirStructure vheDirStructure = do cwd <- liftIO getCurrentDirectory let virthualEnvLocation = cwd virthualEnvDirLocation = virthualEnvLocation </> ".virthualenv" cabalDirLocation = virthualEnvDirLocation </> "cabal" ghcDirLocation = virthualEnvDirLocation </> "ghc" return DirStructure { virthualEnv = virthualEnvLocation , virthualEnvDir = virthualEnvDirLocation , ghcPackagePath = virthualEnvDirLocation </> "ghc_pkg_db" , cabalDir = cabalDirLocation , cabalBinDir = cabalDirLocation </> "bin" , virthualEnvBinDir = virthualEnvDirLocation </> "bin" , ghcDir = ghcDirLocation , ghcBinDir = ghcDirLocation </> "bin" } -- returns location of cabal's config file inside virtual environment dir structure cabalConfigLocation :: MyMonad FilePath cabalConfigLocation = do dirStructure <- vheDirStructure return $ cabalDir dirStructure </> "config" -- returns environment dictionary used in Virtual Haskell Environment -- it's inherited from the current process, but variable -- GHC_PACKAGE_PATH is altered. getVirtualEnvironment :: MyMonad [(String, String)] getVirtualEnvironment = do env <- liftIO getEnvironment dirStructure <- vheDirStructure return $ ("GHC_PACKAGE_PATH", ghcPackagePath dirStructure) : filter (\(k,_) -> k /= "GHC_PACKAGE_PATH") env
Paczesiowa/virthualenv
src/Paths.hs
Haskell
bsd-3-clause
1,935
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Zodiac.HttpClient.TSRP( authedHttpClientRequest , macHttpClientRequest , httpAuthHeader , httpClientKeyId , httpClientAuthHeader , verifyHttpClientRequest , verifyHttpClientRequest' ) where import Data.Time.Clock (UTCTime, getCurrentTime) import Network.HTTP.Client (Request(..), requestHeaders) import Network.HTTP.Types (Header) import Network.HTTP.Types.Header (hAuthorization) import P import System.IO (IO) import Tinfoil.Data (Verified(..), MAC) import Zodiac.Core.Request import Zodiac.TSRP.Data import Zodiac.TSRP.Symmetric import Zodiac.HttpClient.Error import Zodiac.HttpClient.Request -- | Authenticate an http-client request. If the request isn't -- malformed, the output is a Request object with the necessary -- Authorization header added which can be sent directly to a server -- supporting TSRP. authedHttpClientRequest :: KeyId -> TSRPKey -> RequestExpiry -> Request -> RequestTimestamp -> Either RequestError Request authedHttpClientRequest kid sk re r rt = toCanonicalRequest r >>= \cr -> let mac = macRequest TSRPv1 kid rt re cr sk authH = httpAuthHeader TSRPv1 kid rt re cr mac newHeaders = authH : (requestHeaders r) in Right $ r { requestHeaders = newHeaders } -- | Works as 'verifyHttpClientRequest'', but uses the current time to verify -- the request. verifyHttpClientRequest :: KeyId -> TSRPKey -> Request -> IO Verified verifyHttpClientRequest kid sk r = getCurrentTime >>= (verifyHttpClientRequest' kid sk r) -- | Verify an authenticated http-client request. The 'KeyId' parameter -- can be extracted with 'httpClientKeyId'; the 'TSRPKey' should be -- the one associated with the 'KeyId'. verifyHttpClientRequest' :: KeyId -> TSRPKey -> Request -> UTCTime -> IO Verified verifyHttpClientRequest' kid sk req now = case httpClientAuthHeader req of Left _ -> pure NotVerified Right sah -> case toCanonicalRequest req of Left _ -> pure NotVerified Right cr -> verifyRequest kid sk cr sah now -- | Extract the 'KeyId' from a request. httpClientKeyId :: Request -> Either ProtocolError KeyId httpClientKeyId r = httpClientAuthHeader r >>= (pure . sahKeyId) httpClientAuthHeader :: Request -> Either ProtocolError SymmetricAuthHeader httpClientAuthHeader r = let hs = requestHeaders r in case filter ((== hAuthorization) . fst) hs of [] -> Left NoAuthHeader [(_, v)] -> maybe' (Left MalformedAuthHeader) Right $ parseSymmetricAuthHeader v _ -> Left MultipleAuthHeaders -- | Given a precomputed MAC of a request, construct the appropriate -- Authorization header in a form suitable to be used with -- http-client. httpAuthHeader :: SymmetricProtocol -> KeyId -> RequestTimestamp -> RequestExpiry -> CRequest -> MAC -> Header httpAuthHeader TSRPv1 kid rt re cr mac = let sh = signedHeaders cr sah = SymmetricAuthHeader TSRPv1 kid rt re sh mac in (hAuthorization, renderSymmetricAuthHeader sah) -- | Create a detached MAC of an http-client request. This MAC can be -- converted to an http-client-compatible Authorization header using -- 'httpAuthHeader'. macHttpClientRequest :: KeyId -> TSRPKey -> RequestExpiry -> Request -> RequestTimestamp -> Either RequestError MAC macHttpClientRequest kid sk re r rts = do cr <- toCanonicalRequest r pure $ macRequest TSRPv1 kid rts re cr sk
ambiata/zodiac
zodiac-http-client/src/Zodiac/HttpClient/TSRP.hs
Haskell
bsd-3-clause
4,068
{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE RankNTypes #-} module Test.Integration.Framework.DSL ( -- * Scenario scenario , xscenario , pendingWith , Scenarios , Context(..) -- * Steps , Setup(..) , setup , request , request_ , successfulRequest , unsafeRequest , verify -- * Requests (Only API types) , NewAddress(..) , NewWallet (..) , NewAccount (..) , PasswordUpdate (..) , Payment (..) , Redemption (..) , WalletUpdate(..) , ShieldedRedemptionCode (..) , FilterOperations(..) , SortOperations(..) , WalletOperation(..) , AssuranceLevel(..) , DestinationChoice(..) , defaultAccountId , defaultAssuranceLevel , defaultDistribution , customDistribution , defaultGroupingPolicy , defaultPage , defaultPerPage , defaultSetup , defaultSource , defaultSpendingPassword , defaultWalletName , mkSpendingPassword , noRedemptionMnemonic , noSpendingPassword -- * Expectations , WalletError(..) , ErrNotEnoughMoney(..) , TransactionStatus(..) , expectAddressInIndexOf , expectListSizeEqual , expectListItemFieldEqual , expectEqual , expectError , expectFieldEqual , expectFieldDiffer , expectJSONError , expectSuccess , expectTxInHistoryOf , expectTxStatusEventually , expectTxStatusNever , expectWalletError , expectWalletEventuallyRestored , expectWalletUTxO -- * Helpers , ($-) , (</>) , (!!) , addresses , walAddresses , amount , assuranceLevel , backupPhrase , failures , initialCoins , mnemonicWords , spendingPassword , totalSuccess , rawPassword , address , wallet , wallets , walletId , walletName , spendingPasswordLastUpdate , json , hasSpendingPassword , mkAddress , mkBackupPhrase ) where import Universum hiding (getArgs, second) import Control.Concurrent (threadDelay) import Control.Concurrent.Async (race) import Crypto.Hash (hash) import Crypto.Hash.Algorithms (Blake2b_256) import Data.Aeson.QQ (aesonQQ) import qualified Data.ByteArray as ByteArray import qualified Data.Foldable as F import Data.Generics.Internal.VL.Lens (lens) import Data.Generics.Product.Fields (field) import Data.Generics.Product.Typed (HasType, typed) import Data.List ((!!)) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map.Strict as Map import qualified Data.Text as T import qualified Data.Text.Encoding as T import Language.Haskell.TH.Quote (QuasiQuoter) import Test.Hspec.Core.Spec (SpecM, it, xit) import qualified Test.Hspec.Core.Spec as H import Test.Hspec.Expectations.Lifted import Test.QuickCheck (arbitrary, generate) import Web.HttpApiData (ToHttpApiData (..)) import Cardano.Mnemonic (mkMnemonic, mnemonicToSeed) import Cardano.Wallet.API.Request.Filter (FilterOperations (..)) import Cardano.Wallet.API.Request.Pagination (Page, PerPage) import Cardano.Wallet.API.Request.Sort (SortOperations (..)) import Cardano.Wallet.API.Response (JSONValidationError (..)) import Cardano.Wallet.API.V1.Types import Cardano.Wallet.Client.Http (BaseUrl, ClientError (..), Manager, WalletClient) import qualified Cardano.Wallet.Client.Http as Client import Pos.Chain.Txp (TxIn (..), TxOut (..), TxOutAux (..)) import Pos.Core (Coin, IsBootstrapEraAddr (..), deriveLvl2KeyPair, mkCoin, unsafeGetCoin) import Pos.Core.NetworkMagic (NetworkMagic (..)) import Pos.Crypto (ShouldCheckPassphrase (..), safeDeterministicKeyGen) import Test.Integration.Framework.Request (HasHttpClient, request, request_, successfulRequest, unsafeRequest, ($-)) import Test.Integration.Framework.Scenario (Scenario) -- -- SCENARIO -- -- Prior to starting integration tests, we setup a global context -- and "prepare" a few faucet wallets which all contains some funds. -- This helps speed up testing and isolate them. data Context = Context { _faucets :: [FilePath] -- Already funded faucet wallets , _client :: WalletClient IO -- A handle to the underlying wallet backend server , _manager :: (BaseUrl, Manager) -- The underlying BaseUrl and Manager used by the Wallet Client } deriving (Generic) -- | Just a type-alias to 'SpecM', like 'scenario'. Ultimately, everything is -- made in such way that we can use normal (albeit lifted) HSpec functions and -- utilities if needed (and rely on its CLI as well when needed). type Scenarios ctx = SpecM (MVar ctx) () -- | Just a slightly-specialized alias for 'it' to help lil'GHC. Also, makes -- sure the wallet has been cleared out completely before running the scenario. scenario :: String -> Scenario Context IO () -> Scenarios Context scenario title spec = it title (successfulRequest Client.resetWalletState >> spec) xscenario :: String -> Scenario Context IO () -> Scenarios Context xscenario = xit -- | Lifted version of `H.pendingWith` allowing for temporarily skipping -- scenarios from execution with a reason, like: -- -- scenario title $ do -- pendingWith "This test fails due to bug #213" -- test pendingWith :: (MonadIO m) => String -> m () pendingWith = liftIO . H.pendingWith -- -- TYPES -- data DestinationChoice = RandomDestination | LockedDestination deriving (Show, Generic) newtype RawPassword = RawPassword { getRawPassword :: Text } deriving stock (Show, Generic) deriving newtype (Monoid, Semigroup) instance IsString RawPassword where fromString = RawPassword . T.pack -- -- STEPS -- data Setup = Setup { _initialCoins :: [Coin] , _walletName :: Text , _assuranceLevel :: AssuranceLevel , _mnemonicWords :: [Text] , _rawPassword :: RawPassword } deriving (Show, Generic) data Fixture = Fixture { _wallet :: Wallet , _destinations :: NonEmpty Address , _backupPhrase :: BackupPhrase , _spendingPassword :: SpendingPassword } deriving (Show, Generic) -- | Setup a wallet with the given parameters. setup :: Setup -> Scenario Context IO Fixture setup args = do phrase <- if null (args ^. mnemonicWords) then liftIO $ generate arbitrary else mkBackupPhrase (args ^. mnemonicWords) let password = mkPassword (args ^. rawPassword) wal <- setupWallet args phrase addrs <- forM (RandomDestination :| []) setupDestination return $ Fixture wal addrs phrase password -- | Apply 'a' to all actions in sequence verify :: (Monad m) => a -> [a -> m ()] -> m () verify a = mapM_ (a &) -- -- DEFAULT VALUES -- defaultAccountId :: AccountIndex defaultAccountId = minBound defaultAssuranceLevel :: AssuranceLevel defaultAssuranceLevel = NormalAssurance defaultDistribution :: HasType (NonEmpty Address) s => Word64 -> s -> NonEmpty PaymentDistribution defaultDistribution c s = pure $ PaymentDistribution (V1 $ head $ s ^. typed) (V1 $ mkCoin c) customDistribution :: NonEmpty (Account, Word64) -> NonEmpty PaymentDistribution customDistribution payees = let recepientWalAddresses = NonEmpty.fromList $ map (view walAddresses) $ concatMap (view addresses . fst) $ payees in NonEmpty.zipWith PaymentDistribution recepientWalAddresses (map ((\coin -> V1 $ mkCoin coin) . snd) payees) defaultGroupingPolicy :: Maybe (V1 InputSelectionPolicy) defaultGroupingPolicy = Nothing defaultPage :: Maybe Page defaultPage = Nothing defaultPerPage :: Maybe PerPage defaultPerPage = Nothing defaultSetup :: Setup defaultSetup = Setup { _initialCoins = [] , _walletName = defaultWalletName , _assuranceLevel = defaultAssuranceLevel , _mnemonicWords = [] , _rawPassword = mempty } defaultSource :: HasType Wallet s => s -> PaymentSource defaultSource s = PaymentSource (s ^. wallet . walletId) defaultAccountId defaultSpendingPassword :: SpendingPassword defaultSpendingPassword = mempty defaultWalletName :: Text defaultWalletName = "Fixture Wallet" noRedemptionMnemonic :: Maybe RedemptionMnemonic noRedemptionMnemonic = Nothing noSpendingPassword :: Maybe SpendingPassword noSpendingPassword = Nothing -- -- HELPERS -- json :: QuasiQuoter json = aesonQQ infixr 5 </> (</>) :: ToHttpApiData a => Text -> a -> Text base </> next = mconcat [base, "/", toQueryParam next] address :: HasType (V1 Address) s => Lens' s (V1 Address) address = typed amount :: HasType (V1 Coin) s => Lens' s Word64 amount = lens _get _set where _get :: HasType (V1 Coin) s => s -> Word64 _get = unsafeGetCoin . unV1 . view typed _set :: HasType (V1 Coin) s => (s, Word64) -> s _set (s, v) = set typed (V1 $ mkCoin v) s assuranceLevel :: HasType AssuranceLevel s => Lens' s AssuranceLevel assuranceLevel = typed backupPhrase :: HasType BackupPhrase s => Lens' s BackupPhrase backupPhrase = typed failures :: Lens' (BatchImportResult a) [a] failures = field @"aimFailures" faucets :: HasType [FilePath] s => Lens' s [FilePath] faucets = typed initialCoins :: HasType [Coin] s => Lens' s [Word64] initialCoins = lens _get _set where _get :: HasType [Coin] s => s -> [Word64] _get = map unsafeGetCoin . view typed _set :: HasType [Coin] s => (s, [Word64]) -> s _set (s, v) = set typed (map mkCoin v) s mnemonicWords :: HasType [Text] s => Lens' s [Text] mnemonicWords = typed hasSpendingPassword :: HasType Bool s => Lens' s Bool hasSpendingPassword = typed rawPassword :: HasType RawPassword s => Lens' s RawPassword rawPassword = typed spendingPassword :: HasType SpendingPassword s => Lens' s SpendingPassword spendingPassword = typed totalSuccess :: Lens' (BatchImportResult a) Natural totalSuccess = field @"aimTotalSuccess" wallet :: HasType Wallet s => Lens' s Wallet wallet = typed wallets :: HasType [Wallet] s => Lens' s [Wallet] wallets = typed walletId :: HasType WalletId s => Lens' s WalletId walletId = typed walletName :: HasType Text s => Lens' s Text walletName = typed spendingPasswordLastUpdate :: Lens' Wallet (V1 Timestamp) spendingPasswordLastUpdate = field @"walSpendingPasswordLastUpdate" addresses :: HasType [WalletAddress] s => Lens' s [WalletAddress] addresses = typed walAddresses :: HasType (V1 Address) s => Lens' s (V1 Address) walAddresses = typed -- -- EXPECTATIONS -- -- | Expects data list returned by the API to be of certain length expectListSizeEqual :: (MonadIO m, MonadFail m, Foldable xs) => Int -> Either ClientError (xs a) -> m () expectListSizeEqual l = \case Left e -> wantedSuccessButError e Right xs -> length (F.toList xs) `shouldBe` l -- | Expects that returned data list's particular item field matches the expected value -- -- e.g. -- verify response -- [ expectDataListItemFieldEqual 0 walletName "first" -- , expectDataListItemFieldEqual 1 walletName "second" -- ] expectListItemFieldEqual :: (MonadIO m, MonadFail m, Show a, Eq a) => Int -> Lens' s a -> a -> Either ClientError [s] -> m () expectListItemFieldEqual i getter a = \case Left e -> wantedSuccessButError e Right s | length s > i -> expectFieldEqual getter a (Right (s !! i)) | otherwise -> fail $ "expectListItemFieldEqual: trying to access the #" <> show i <> " element from a list but there's none! " -- | The type signature is more scary than it seems. This drills into a given -- `a` type through the provided lens and sees whether field matches. -- -- e.g. -- do -- expectFieldEqual #walAssuranceLevel AssuranceStrict response -- expectFieldEqual #walName "My Wallet" response expectFieldEqual :: (MonadIO m, MonadFail m, Show a, Eq a) => Lens' s a -> a -> Either ClientError s -> m () expectFieldEqual getter a = \case Left e -> wantedSuccessButError e Right s -> view getter s `shouldBe` a -- | The opposite to 'expectFieldEqual'. expectFieldDiffer :: (MonadIO m, MonadFail m, Show a, Eq a) => Lens' s a -> a -> Either ClientError s -> m () expectFieldDiffer getter a = \case Left e -> wantedSuccessButError e Right s -> view getter s `shouldNotBe` a -- | Expects entire equality of two types expectEqual :: (MonadIO m, MonadFail m, Show a, Eq a) => a -> Either ClientError a -> m () expectEqual = expectFieldEqual id -- | Expect an errored response, without any further assumptions expectError :: (MonadIO m, MonadFail m, Show a) => Either ClientError a -> m () expectError = \case Left _ -> return () Right a -> wantedErrorButSuccess a -- | Expect a successful response, without any further assumptions expectSuccess :: (MonadIO m, MonadFail m) => Either ClientError a -> m () expectSuccess = \case Left e -> wantedSuccessButError e Right _ -> return () -- | Expect a transaction to be part of a wallet history. expectTxInHistoryOf :: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx) => Wallet -> Either ClientError Transaction -> m () expectTxInHistoryOf w = \case Left e -> wantedSuccessButError e Right txn -> tryNextPage (on (==) txId txn) 1 where tryNextPage predicate i = do txns <- successfulRequest $ Client.getTransactionIndexFilterSorts $- Just (walId w) $- Nothing $- Nothing $- Just (fromInteger i) $- Just 50 $- NoFilters $- NoSorts when (null txns) $ fail "expectTxInHistoryOf: couldn't find transaction in history" case find predicate txns of Nothing -> tryNextPage predicate (i + 1) Just _ -> return () -- | Expect an address to be part of the global index expectAddressInIndexOf :: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx) => Either ClientError WalletAddress -> m () expectAddressInIndexOf = \case Left e -> wantedSuccessButError e Right addr -> tryNextPage ((==) addr) 1 where tryNextPage predicate i = do addrs <- successfulRequest $ Client.getAddressIndexPaginated $- Just (fromInteger i) $- Just 50 when (null addrs) $ fail "expectAddressInIndexOf: couldn't find address in history" case find predicate addrs of Nothing -> tryNextPage predicate (i + 1) Just _ -> return () -- | Wait for a transaction to reach one of the given status. Fails after 60 -- seconds if not. expectTxStatusEventually :: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx) => [TransactionStatus] -> Either ClientError Transaction -> m () expectTxStatusEventually statuses = \case Left e -> wantedSuccessButError e Right txn -> do result <- ask >>= \ctx -> timeout (120 * second) (waitForTxStatus ctx statuses txn) case result of Nothing -> fail "expectTxStatusEventually: waited too long for statuses." Just _ -> return () -- | Checks that a transacton "never" reaches one of the given status. Never -- really means 60 seconds, you know... expectTxStatusNever :: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx) => [TransactionStatus] -> Either ClientError Transaction -> m () expectTxStatusNever statuses = \case Left e -> wantedSuccessButError e Right txn -> do result <- ask >>= \ctx -> timeout (120 * second) (waitForTxStatus ctx statuses txn) case result of Nothing -> return () Just _ -> fail "expectTxStatusNever: reached one of the provided statuses." -- | Wait until a wallet is restored, up to a certain point. expectWalletEventuallyRestored :: (MonadIO m, MonadFail m, MonadReader ctx m, HasHttpClient ctx) => Either ClientError Wallet -> m () expectWalletEventuallyRestored = \case Left e -> wantedSuccessButError e Right w -> do result <- ask >>= \ctx -> timeout (120 * second) (waitForRestored ctx w) case result of Nothing -> fail "expectWalletEventuallyRestored: waited too long for restoration." Just _ -> return () expectWalletError :: (MonadIO m, MonadFail m, Show a) => WalletError -> Either ClientError a -> m () expectWalletError e' = \case Right a -> wantedErrorButSuccess a Left e -> e `shouldBe` (ClientWalletError e') -- | Verifies that the response is errored from a failed JSON validation -- matching part of the given message. expectJSONError :: (MonadIO m, MonadFail m, Show a) => String -> Either ClientError a -> m () expectJSONError excerpt = \case Right a -> wantedErrorButSuccess a Left (ClientJSONError (JSONValidationFailed msg)) -> T.unpack msg `shouldContain` excerpt Left e -> fail $ "expectJSONError: got something else than a JSON validation failure: " <> show e expectWalletUTxO :: (MonadIO m, MonadFail m) => [Word64] -> Either ClientError UtxoStatistics -> m () expectWalletUTxO coins = \case Left e -> wantedSuccessButError e Right stats -> do addr <- liftIO $ generate arbitrary let constructUtxoEntry input coin = ( TxInUnknown input "arbitrary input" , TxOutAux (TxOut addr (mkCoin coin)) ) let utxo = Map.fromList $ zipWith constructUtxoEntry [0..] coins computeUtxoStatistics log10 [utxo] `shouldBe` stats -- -- INTERNALS -- wantedSuccessButError :: (MonadFail m, Show e) => e -> m void wantedSuccessButError = fail . ("expected a successful response but got an error: " <>) . show wantedErrorButSuccess :: (MonadFail m, Show a) => a -> m void wantedErrorButSuccess = fail . ("expected an error but got a successful response: " <>) . show timeout :: (MonadIO m) => Int -> IO a -> m (Maybe a) timeout maxWaitingTime action = liftIO $ do race (threadDelay maxWaitingTime) action >>= \case Left _ -> return Nothing Right a -> return (Just a) second :: Int second = 1000000 -- | Wait until the given transaction reaches the given status. Potentially -- loop ad infinitum; Caller is expected to cancel the thread at some point. waitForTxStatus :: HasHttpClient ctx => ctx -> [TransactionStatus] -> Transaction -> IO () waitForTxStatus ctx statuses txn = do -- NOTE -- A bit tricky here, we can't just fire async operation on anything else -- but plain `IO`. Hence the explicit context passing here. txns <- flip runReaderT ctx $ successfulRequest $ Client.getTransactionIndex $- Nothing $- Nothing $- Nothing let tx = find (on (==) txId txn) txns if ((fmap txStatus tx) `elem` (fmap Just statuses)) then return () else threadDelay (5 * second) >> waitForTxStatus ctx statuses txn -- | Wait until the given wallet is restored. waitForRestored :: HasHttpClient ctx => ctx -> Wallet -> IO () waitForRestored ctx w = do response <- flip runReaderT ctx $ successfulRequest $ Client.getWallet $- w ^. walletId case walSyncState response of Synced -> return () _ -> threadDelay (5 * second) >> waitForRestored ctx w -- | Make a backup phrase from a raw list of words. mkBackupPhrase :: (MonadIO m, MonadFail m) => [Text] -> m BackupPhrase mkBackupPhrase ws = either onError onSuccess (mkMnemonic ws) where onError err = fail $ "Invalid BackupPhrase provided: " <> show ws <> ". We expect 12\ \ valid english mnemonic words but the following error has occured:" <> show err onSuccess = return . BackupPhrase -- | Create a Base16-encoded spending password from raw text mkPassword :: RawPassword -> SpendingPassword mkPassword (RawPassword txt) | null txt = mempty | otherwise = txt & T.encodeUtf8 & hash @ByteString @Blake2b_256 & ByteArray.convert & V1 mkAddress :: (MonadIO m, MonadFail m) => BackupPhrase -> Word32 -> m (V1 Address) mkAddress (BackupPhrase mnemonic) ix = do let (_, esk) = safeDeterministicKeyGen (mnemonicToSeed mnemonic) mempty let maddr = fst <$> deriveLvl2KeyPair NetworkMainOrStage (IsBootstrapEraAddr True) (ShouldCheckPassphrase False) mempty esk (getAccIndex minBound) ix case maddr of Nothing -> fail "The impossible happened: failed to generate a\ \ random address. This can only happened if you\ \ provided a derivation index that is out-of-bound!" Just addr -> return (V1 addr) -- | Execute the given setup action with using the next faucet wallet. It fails -- hard if there's no more faucet wallet available. withNextFaucet :: (Wallet -> Scenario Context IO c) -> Scenario Context IO c withNextFaucet actionWithFaucet = do ctx <- get when (null $ ctx ^. faucets) $ fail $ "\nFailed to setup new scenario: there's no more available faucet wallets!\ \\nWe import a faucet wallet for each scenario but only have a limited\ \ number of them. This can be modified directly in the configuration file,\ \ by default in: \n\n\ttest/integration/configuration.yaml\ \\n\ntry increasing the number of available 'poors' wallets\ \\n\nspec: &default_core_genesis_spec\ \\n\tinitializer:\ \\n\t\ttestBalance:\ \\n\t\t\tpoors: ???\n" let acquireFaucet = do let (key:rest) = ctx ^. faucets put (ctx & faucets .~ rest) successfulRequest $ Client.importWallet $- WalletImport Nothing key let releaseFaucet faucet = do successfulRequest (Client.deleteWallet $- walId faucet) bracket acquireFaucet releaseFaucet actionWithFaucet -- | Setup a given wallet and pre-fill it with given coins. setupWallet :: Setup -> BackupPhrase -> Scenario Context IO Wallet setupWallet args phrase = do wal <- successfulRequest $ Client.postWallet $- NewWallet phrase Nothing (args ^. assuranceLevel) (args ^. walletName) CreateWallet unless (null $ args ^. initialCoins) $ withNextFaucet $ \faucet -> do let paymentSource = PaymentSource (walId faucet) minBound let paymentDist (addr, coin) = pure $ PaymentDistribution (addrId addr) (V1 $ mkCoin coin) forM_ (args ^. initialCoins) $ \coin -> do -- NOTE -- Making payments to a different address each time to cope with -- grouping policy. That's actually a behavior we might want to -- test in the future. So, we'll need to do something smarter here. addr <- successfulRequest $ Client.postAddress $- NewAddress Nothing minBound (walId wal) txn <- request $ Client.postTransaction $- Payment paymentSource (paymentDist (addr, coin)) Nothing Nothing expectTxStatusEventually [InNewestBlocks, Persisted] txn return wal -- | Generate some destinations for payments. -- -- - RandomDestination generates fake addresses going nowhere (hopefully :) ...) -- - LockedDestination generates addresses that points to an asset-locked wallet setupDestination :: DestinationChoice -> Scenario Context IO Address setupDestination = \case RandomDestination -> do bp <- liftIO (generate arbitrary) unV1 <$> mkAddress bp 1 LockedDestination -> fail "Asset-locked destination aren't yet implemented. This\ \ requires slightly more work than it seems and will be\ \ implemented later."
input-output-hk/pos-haskell-prototype
wallet/test/integration/Test/Integration/Framework/DSL.hs
Haskell
mit
24,605
{-# LANGUAGE CPP, GADTs #-} ----------------------------------------------------------------------------- -- -- Generating machine code (instruction selection) -- -- (c) The University of Glasgow 1996-2004 -- ----------------------------------------------------------------------------- -- This is a big module, but, if you pay attention to -- (a) the sectioning, and (b) the type signatures, -- the structure should not be too overwhelming. module PPC.CodeGen ( cmmTopCodeGen, generateJumpTableForInstr, InstrBlock ) where #include "HsVersions.h" #include "nativeGen/NCG.h" #include "../includes/MachDeps.h" -- NCG stuff: import GhcPrelude import CodeGen.Platform import PPC.Instr import PPC.Cond import PPC.Regs import CPrim import NCGMonad import Instruction import PIC import Format import RegClass import Reg import TargetReg import Platform -- Our intermediate code: import BlockId import PprCmm ( pprExpr ) import Cmm import CmmUtils import CmmSwitch import CLabel import Hoopl.Block import Hoopl.Graph -- The rest: import OrdList import Outputable import DynFlags import Control.Monad ( mapAndUnzipM, when ) import Data.Bits import Data.Word import BasicTypes import FastString import Util -- ----------------------------------------------------------------------------- -- Top-level of the instruction selector -- | 'InstrBlock's are the insn sequences generated by the insn selectors. -- They are really trees of insns to facilitate fast appending, where a -- left-to-right traversal (pre-order?) yields the insns in the correct -- order. cmmTopCodeGen :: RawCmmDecl -> NatM [NatCmmDecl CmmStatics Instr] cmmTopCodeGen (CmmProc info lab live graph) = do let blocks = toBlockListEntryFirst graph (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks dflags <- getDynFlags let proc = CmmProc info lab live (ListGraph $ concat nat_blocks) tops = proc : concat statics os = platformOS $ targetPlatform dflags arch = platformArch $ targetPlatform dflags case arch of ArchPPC | os == OSAIX -> return tops | otherwise -> do picBaseMb <- getPicBaseMaybeNat case picBaseMb of Just picBase -> initializePicBase_ppc arch os picBase tops Nothing -> return tops ArchPPC_64 ELF_V1 -> fixup_entry tops -- generating function descriptor is handled in -- pretty printer ArchPPC_64 ELF_V2 -> fixup_entry tops -- generating function prologue is handled in -- pretty printer _ -> panic "PPC.cmmTopCodeGen: unknown arch" where fixup_entry (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = do let BasicBlock bID insns = entry bID' <- if lab == (blockLbl bID) then newBlockId else return bID let b' = BasicBlock bID' insns return (CmmProc info lab live (ListGraph (b':blocks)) : statics) fixup_entry _ = panic "cmmTopCodegen: Broken CmmProc" cmmTopCodeGen (CmmData sec dat) = do return [CmmData sec dat] -- no translation, we just use CmmStatic basicBlockCodeGen :: Block CmmNode C C -> NatM ( [NatBasicBlock Instr] , [NatCmmDecl CmmStatics Instr]) basicBlockCodeGen block = do let (_, nodes, tail) = blockSplit block id = entryLabel block stmts = blockToList nodes mid_instrs <- stmtsToInstrs stmts tail_instrs <- stmtToInstrs tail let instrs = mid_instrs `appOL` tail_instrs -- code generation may introduce new basic block boundaries, which -- are indicated by the NEWBLOCK instruction. We must split up the -- instruction stream into basic blocks again. Also, we extract -- LDATAs here too. let (top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs mkBlocks (NEWBLOCK id) (instrs,blocks,statics) = ([], BasicBlock id instrs : blocks, statics) mkBlocks (LDATA sec dat) (instrs,blocks,statics) = (instrs, blocks, CmmData sec dat:statics) mkBlocks instr (instrs,blocks,statics) = (instr:instrs, blocks, statics) return (BasicBlock id top : other_blocks, statics) stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock stmtsToInstrs stmts = do instrss <- mapM stmtToInstrs stmts return (concatOL instrss) stmtToInstrs :: CmmNode e x -> NatM InstrBlock stmtToInstrs stmt = do dflags <- getDynFlags case stmt of CmmComment s -> return (unitOL (COMMENT s)) CmmTick {} -> return nilOL CmmUnwind {} -> return nilOL CmmAssign reg src | isFloatType ty -> assignReg_FltCode format reg src | target32Bit (targetPlatform dflags) && isWord64 ty -> assignReg_I64Code reg src | otherwise -> assignReg_IntCode format reg src where ty = cmmRegType dflags reg format = cmmTypeFormat ty CmmStore addr src | isFloatType ty -> assignMem_FltCode format addr src | target32Bit (targetPlatform dflags) && isWord64 ty -> assignMem_I64Code addr src | otherwise -> assignMem_IntCode format addr src where ty = cmmExprType dflags src format = cmmTypeFormat ty CmmUnsafeForeignCall target result_regs args -> genCCall target result_regs args CmmBranch id -> genBranch id CmmCondBranch arg true false prediction -> do b1 <- genCondJump true arg prediction b2 <- genBranch false return (b1 `appOL` b2) CmmSwitch arg ids -> do dflags <- getDynFlags genSwitch dflags arg ids CmmCall { cml_target = arg } -> genJump arg _ -> panic "stmtToInstrs: statement should have been cps'd away" -------------------------------------------------------------------------------- -- | 'InstrBlock's are the insn sequences generated by the insn selectors. -- They are really trees of insns to facilitate fast appending, where a -- left-to-right traversal yields the insns in the correct order. -- type InstrBlock = OrdList Instr -- | Register's passed up the tree. If the stix code forces the register -- to live in a pre-decided machine register, it comes out as @Fixed@; -- otherwise, it comes out as @Any@, and the parent can decide which -- register to put it in. -- data Register = Fixed Format Reg InstrBlock | Any Format (Reg -> InstrBlock) swizzleRegisterRep :: Register -> Format -> Register swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code swizzleRegisterRep (Any _ codefn) format = Any format codefn -- | Grab the Reg for a CmmReg getRegisterReg :: Platform -> CmmReg -> Reg getRegisterReg _ (CmmLocal (LocalReg u pk)) = RegVirtual $ mkVirtualReg u (cmmTypeFormat pk) getRegisterReg platform (CmmGlobal mid) = case globalRegMaybe platform mid of Just reg -> RegReal reg Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid) -- By this stage, the only MagicIds remaining should be the -- ones which map to a real machine register on this -- platform. Hence ... -- | Convert a BlockId to some CmmStatic data jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags)) jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel) where blockLabel = blockLbl blockid -- ----------------------------------------------------------------------------- -- General things for putting together code sequences -- Expand CmmRegOff. ToDo: should we do it this way around, or convert -- CmmExprs into CmmRegOff? mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr mangleIndexTree dflags (CmmRegOff reg off) = CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)] where width = typeWidth (cmmRegType dflags reg) mangleIndexTree _ _ = panic "PPC.CodeGen.mangleIndexTree: no match" -- ----------------------------------------------------------------------------- -- Code gen for 64-bit arithmetic on 32-bit platforms {- Simple support for generating 64-bit code (ie, 64 bit values and 64 bit assignments) on 32-bit platforms. Unlike the main code generator we merely shoot for generating working code as simply as possible, and pay little attention to code quality. Specifically, there is no attempt to deal cleverly with the fixed-vs-floating register distinction; all values are generated into (pairs of) floating registers, even if this would mean some redundant reg-reg moves as a result. Only one of the VRegUniques is returned, since it will be of the VRegUniqueLo form, and the upper-half VReg can be determined by applying getHiVRegFromLo to it. -} data ChildCode64 -- a.k.a "Register64" = ChildCode64 InstrBlock -- code Reg -- the lower 32-bit temporary which contains the -- result; use getHiVRegFromLo to find the other -- VRegUnique. Rules of this simplified insn -- selection game are therefore that the returned -- Reg may be modified -- | Compute an expression into a register, but -- we don't mind which one it is. getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock) getSomeReg expr = do r <- getRegister expr case r of Any rep code -> do tmp <- getNewRegNat rep return (tmp, code tmp) Fixed _ reg code -> return (reg, code) getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock) getI64Amodes addrTree = do Amode hi_addr addr_code <- getAmode D addrTree case addrOffset hi_addr 4 of Just lo_addr -> return (hi_addr, lo_addr, addr_code) Nothing -> do (hi_ptr, code) <- getSomeReg addrTree return (AddrRegImm hi_ptr (ImmInt 0), AddrRegImm hi_ptr (ImmInt 4), code) assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock assignMem_I64Code addrTree valueTree = do (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree ChildCode64 vcode rlo <- iselExpr64 valueTree let rhi = getHiVRegFromLo rlo -- Big-endian store mov_hi = ST II32 rhi hi_addr mov_lo = ST II32 rlo lo_addr return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi) assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do ChildCode64 vcode r_src_lo <- iselExpr64 valueTree let r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32 r_dst_hi = getHiVRegFromLo r_dst_lo r_src_hi = getHiVRegFromLo r_src_lo mov_lo = MR r_dst_lo r_src_lo mov_hi = MR r_dst_hi r_src_hi return ( vcode `snocOL` mov_lo `snocOL` mov_hi ) assignReg_I64Code _ _ = panic "assignReg_I64Code(powerpc): invalid lvalue" iselExpr64 :: CmmExpr -> NatM ChildCode64 iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree (rlo, rhi) <- getNewRegPairNat II32 let mov_hi = LD II32 rhi hi_addr mov_lo = LD II32 rlo lo_addr return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) rlo iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty = return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32)) iselExpr64 (CmmLit (CmmInt i _)) = do (rlo,rhi) <- getNewRegPairNat II32 let half0 = fromIntegral (fromIntegral i :: Word16) half1 = fromIntegral (fromIntegral (i `shiftR` 16) :: Word16) half2 = fromIntegral (fromIntegral (i `shiftR` 32) :: Word16) half3 = fromIntegral (fromIntegral (i `shiftR` 48) :: Word16) code = toOL [ LIS rlo (ImmInt half1), OR rlo rlo (RIImm $ ImmInt half0), LIS rhi (ImmInt half3), OR rhi rhi (RIImm $ ImmInt half2) ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do ChildCode64 code1 r1lo <- iselExpr64 e1 ChildCode64 code2 r2lo <- iselExpr64 e2 (rlo,rhi) <- getNewRegPairNat II32 let r1hi = getHiVRegFromLo r1lo r2hi = getHiVRegFromLo r2lo code = code1 `appOL` code2 `appOL` toOL [ ADDC rlo r1lo r2lo, ADDE rhi r1hi r2hi ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do ChildCode64 code1 r1lo <- iselExpr64 e1 ChildCode64 code2 r2lo <- iselExpr64 e2 (rlo,rhi) <- getNewRegPairNat II32 let r1hi = getHiVRegFromLo r1lo r2hi = getHiVRegFromLo r2lo code = code1 `appOL` code2 `appOL` toOL [ SUBFC rlo r2lo (RIReg r1lo), SUBFE rhi r2hi r1hi ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_UU_Conv W32 W64) [expr]) = do (expr_reg,expr_code) <- getSomeReg expr (rlo, rhi) <- getNewRegPairNat II32 let mov_hi = LI rhi (ImmInt 0) mov_lo = MR rlo expr_reg return $ ChildCode64 (expr_code `snocOL` mov_lo `snocOL` mov_hi) rlo iselExpr64 expr = pprPanic "iselExpr64(powerpc)" (pprExpr expr) getRegister :: CmmExpr -> NatM Register getRegister e = do dflags <- getDynFlags getRegister' dflags e getRegister' :: DynFlags -> CmmExpr -> NatM Register getRegister' dflags (CmmReg (CmmGlobal PicBaseReg)) | OSAIX <- platformOS (targetPlatform dflags) = do let code dst = toOL [ LD II32 dst tocAddr ] tocAddr = AddrRegImm toc (ImmLit (text "ghc_toc_table[TC]")) return (Any II32 code) | target32Bit (targetPlatform dflags) = do reg <- getPicBaseNat $ archWordFormat (target32Bit (targetPlatform dflags)) return (Fixed (archWordFormat (target32Bit (targetPlatform dflags))) reg nilOL) | otherwise = return (Fixed II64 toc nilOL) getRegister' dflags (CmmReg reg) = return (Fixed (cmmTypeFormat (cmmRegType dflags reg)) (getRegisterReg (targetPlatform dflags) reg) nilOL) getRegister' dflags tree@(CmmRegOff _ _) = getRegister' dflags (mangleIndexTree dflags tree) -- for 32-bit architectuers, support some 64 -> 32 bit conversions: -- TO_W_(x), TO_W_(x >> 32) getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 (getHiVRegFromLo rlo) code getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 (getHiVRegFromLo rlo) code getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [x]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 rlo code getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [x]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 rlo code getRegister' dflags (CmmLoad mem pk) | not (isWord64 pk) = do let platform = targetPlatform dflags Amode addr addr_code <- getAmode D mem let code dst = ASSERT((targetClassOfReg platform dst == RcDouble) == isFloatType pk) addr_code `snocOL` LD format dst addr return (Any format code) | not (target32Bit (targetPlatform dflags)) = do Amode addr addr_code <- getAmode DS mem let code dst = addr_code `snocOL` LD II64 dst addr return (Any II64 code) where format = cmmTypeFormat pk -- catch simple cases of zero- or sign-extended load getRegister' _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr)) getRegister' _ (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr)) -- Note: there is no Load Byte Arithmetic instruction, so no signed case here getRegister' _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr)) getRegister' _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr)) getRegister' _ (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LD II16 dst addr)) getRegister' _ (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LA II16 dst addr)) getRegister' _ (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LD II32 dst addr)) getRegister' _ (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad mem _]) = do -- lwa is DS-form. See Note [Power instruction format] Amode addr addr_code <- getAmode DS mem return (Any II64 (\dst -> addr_code `snocOL` LA II32 dst addr)) getRegister' dflags (CmmMachOp mop [x]) -- unary MachOps = case mop of MO_Not rep -> triv_ucode_int rep NOT MO_F_Neg w -> triv_ucode_float w FNEG MO_S_Neg w -> triv_ucode_int w NEG MO_FF_Conv W64 W32 -> trivialUCode FF32 FRSP x MO_FF_Conv W32 W64 -> conversionNop FF64 x MO_FS_Conv from to -> coerceFP2Int from to x MO_SF_Conv from to -> coerceInt2FP from to x MO_SS_Conv from to | from == to -> conversionNop (intFormat to) x -- narrowing is a nop: we treat the high bits as undefined MO_SS_Conv W64 to | arch32 -> panic "PPC.CodeGen.getRegister no 64 bit int register" | otherwise -> conversionNop (intFormat to) x MO_SS_Conv W32 to | arch32 -> conversionNop (intFormat to) x | otherwise -> case to of W64 -> triv_ucode_int to (EXTS II32) W16 -> conversionNop II16 x W8 -> conversionNop II8 x _ -> panic "PPC.CodeGen.getRegister: no match" MO_SS_Conv W16 W8 -> conversionNop II8 x MO_SS_Conv W8 to -> triv_ucode_int to (EXTS II8) MO_SS_Conv W16 to -> triv_ucode_int to (EXTS II16) MO_UU_Conv from to | from == to -> conversionNop (intFormat to) x -- narrowing is a nop: we treat the high bits as undefined MO_UU_Conv W64 to | arch32 -> panic "PPC.CodeGen.getRegister no 64 bit target" | otherwise -> conversionNop (intFormat to) x MO_UU_Conv W32 to | arch32 -> conversionNop (intFormat to) x | otherwise -> case to of W64 -> trivialCode to False AND x (CmmLit (CmmInt 4294967295 W64)) W16 -> conversionNop II16 x W8 -> conversionNop II8 x _ -> panic "PPC.CodeGen.getRegister: no match" MO_UU_Conv W16 W8 -> conversionNop II8 x MO_UU_Conv W8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 W32)) MO_UU_Conv W16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 W32)) _ -> panic "PPC.CodeGen.getRegister: no match" where triv_ucode_int width instr = trivialUCode (intFormat width) instr x triv_ucode_float width instr = trivialUCode (floatFormat width) instr x conversionNop new_format expr = do e_code <- getRegister' dflags expr return (swizzleRegisterRep e_code new_format) arch32 = target32Bit $ targetPlatform dflags getRegister' dflags (CmmMachOp mop [x, y]) -- dyadic PrimOps = case mop of MO_F_Eq _ -> condFltReg EQQ x y MO_F_Ne _ -> condFltReg NE x y MO_F_Gt _ -> condFltReg GTT x y MO_F_Ge _ -> condFltReg GE x y MO_F_Lt _ -> condFltReg LTT x y MO_F_Le _ -> condFltReg LE x y MO_Eq rep -> condIntReg EQQ (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_Ne rep -> condIntReg NE (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_S_Gt rep -> condIntReg GTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Ge rep -> condIntReg GE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Lt rep -> condIntReg LTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Le rep -> condIntReg LE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Gt rep -> condIntReg GU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_U_Ge rep -> condIntReg GEU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_U_Lt rep -> condIntReg LU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_U_Le rep -> condIntReg LEU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_F_Add w -> triv_float w FADD MO_F_Sub w -> triv_float w FSUB MO_F_Mul w -> triv_float w FMUL MO_F_Quot w -> triv_float w FDIV -- optimize addition with 32-bit immediate -- (needed for PIC) MO_Add W32 -> case y of CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate W32 True imm -> trivialCode W32 True ADD x (CmmLit $ CmmInt imm immrep) CmmLit lit -> do (src, srcCode) <- getSomeReg x let imm = litToImm lit code dst = srcCode `appOL` toOL [ ADDIS dst src (HA imm), ADD dst dst (RIImm (LO imm)) ] return (Any II32 code) _ -> trivialCode W32 True ADD x y MO_Add rep -> trivialCode rep True ADD x y MO_Sub rep -> case y of CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm) -> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep) _ -> case x of CmmLit (CmmInt imm _) | Just _ <- makeImmediate rep True imm -- subfi ('substract from' with immediate) doesn't exist -> trivialCode rep True SUBFC y x _ -> trivialCodeNoImm' (intFormat rep) SUBF y x MO_Mul rep -> shiftMulCode rep True MULL x y MO_S_MulMayOflo rep -> do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let format = intFormat rep code dst = code1 `appOL` code2 `appOL` toOL [ MULLO format dst src1 src2 , MFOV format dst ] return (Any format code) MO_S_Quot rep -> trivialCodeNoImmSign (intFormat rep) True DIV (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Quot rep -> trivialCodeNoImmSign (intFormat rep) False DIV (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_S_Rem rep -> remainderCode rep True (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Rem rep -> remainderCode rep False (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_And rep -> case y of (CmmLit (CmmInt imm _)) | imm == -8 || imm == -4 -> do (src, srcCode) <- getSomeReg x let clear_mask = if imm == -4 then 2 else 3 fmt = intFormat rep code dst = srcCode `appOL` unitOL (CLRRI fmt dst src clear_mask) return (Any fmt code) _ -> trivialCode rep False AND x y MO_Or rep -> trivialCode rep False OR x y MO_Xor rep -> trivialCode rep False XOR x y MO_Shl rep -> shiftMulCode rep False SL x y MO_S_Shr rep -> shiftMulCode rep False SRA (extendSExpr dflags rep x) y MO_U_Shr rep -> shiftMulCode rep False SR (extendUExpr dflags rep x) y _ -> panic "PPC.CodeGen.getRegister: no match" where triv_float :: Width -> (Format -> Reg -> Reg -> Reg -> Instr) -> NatM Register triv_float width instr = trivialCodeNoImm (floatFormat width) instr x y getRegister' _ (CmmLit (CmmInt i rep)) | Just imm <- makeImmediate rep True i = let code dst = unitOL (LI dst imm) in return (Any (intFormat rep) code) getRegister' _ (CmmLit (CmmFloat f frep)) = do lbl <- getNewLabelNat dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode D dynRef let format = floatFormat frep code dst = LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit (CmmFloat f frep)]) `consOL` (addr_code `snocOL` LD format dst addr) return (Any format code) getRegister' dflags (CmmLit lit) | target32Bit (targetPlatform dflags) = let rep = cmmLitType dflags lit imm = litToImm lit code dst = toOL [ LIS dst (HA imm), ADD dst dst (RIImm (LO imm)) ] in return (Any (cmmTypeFormat rep) code) | otherwise = do lbl <- getNewLabelNat dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode D dynRef let rep = cmmLitType dflags lit format = cmmTypeFormat rep code dst = LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit lit]) `consOL` (addr_code `snocOL` LD format dst addr) return (Any format code) getRegister' _ other = pprPanic "getRegister(ppc)" (pprExpr other) -- extend?Rep: wrap integer expression of type rep -- in a conversion to II32 or II64 resp. extendSExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr extendSExpr dflags W32 x | target32Bit (targetPlatform dflags) = x extendSExpr dflags W64 x | not (target32Bit (targetPlatform dflags)) = x extendSExpr dflags rep x = let size = if target32Bit $ targetPlatform dflags then W32 else W64 in CmmMachOp (MO_SS_Conv rep size) [x] extendUExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr extendUExpr dflags W32 x | target32Bit (targetPlatform dflags) = x extendUExpr dflags W64 x | not (target32Bit (targetPlatform dflags)) = x extendUExpr dflags rep x = let size = if target32Bit $ targetPlatform dflags then W32 else W64 in CmmMachOp (MO_UU_Conv rep size) [x] -- ----------------------------------------------------------------------------- -- The 'Amode' type: Memory addressing modes passed up the tree. data Amode = Amode AddrMode InstrBlock {- Now, given a tree (the argument to a CmmLoad) that references memory, produce a suitable addressing mode. A Rule of the Game (tm) for Amodes: use of the addr bit must immediately follow use of the code part, since the code part puts values in registers which the addr then refers to. So you can't put anything in between, lest it overwrite some of those registers. If you need to do some other computation between the code part and use of the addr bit, first store the effective address from the amode in a temporary, then do the other computation, and then use the temporary: code LEA amode, tmp ... other computation ... ... (tmp) ... -} {- Note [Power instruction format] In some instructions the 16 bit offset must be a multiple of 4, i.e. the two least significant bits must be zero. The "Power ISA" specification calls these instruction formats "DS-FORM" and the instructions with arbitrary 16 bit offsets are "D-FORM". The Power ISA specification document can be obtained from www.power.org. -} data InstrForm = D | DS getAmode :: InstrForm -> CmmExpr -> NatM Amode getAmode inf tree@(CmmRegOff _ _) = do dflags <- getDynFlags getAmode inf (mangleIndexTree dflags tree) getAmode _ (CmmMachOp (MO_Sub W32) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W32 True (-i) = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W32 True i = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode D (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True (-i) = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode D (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True i = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode DS (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True (-i) = do (reg, code) <- getSomeReg x (reg', off', code') <- if i `mod` 4 == 0 then do return (reg, off, code) else do tmp <- getNewRegNat II64 return (tmp, ImmInt 0, code `snocOL` ADD tmp reg (RIImm off)) return (Amode (AddrRegImm reg' off') code') getAmode DS (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True i = do (reg, code) <- getSomeReg x (reg', off', code') <- if i `mod` 4 == 0 then do return (reg, off, code) else do tmp <- getNewRegNat II64 return (tmp, ImmInt 0, code `snocOL` ADD tmp reg (RIImm off)) return (Amode (AddrRegImm reg' off') code') -- optimize addition with 32-bit immediate -- (needed for PIC) getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit lit]) = do dflags <- getDynFlags (src, srcCode) <- getSomeReg x let imm = litToImm lit case () of _ | OSAIX <- platformOS (targetPlatform dflags) , isCmmLabelType lit -> -- HA16/LO16 relocations on labels not supported on AIX return (Amode (AddrRegImm src imm) srcCode) | otherwise -> do tmp <- getNewRegNat II32 let code = srcCode `snocOL` ADDIS tmp src (HA imm) return (Amode (AddrRegImm tmp (LO imm)) code) where isCmmLabelType (CmmLabel {}) = True isCmmLabelType (CmmLabelOff {}) = True isCmmLabelType (CmmLabelDiffOff {}) = True isCmmLabelType _ = False getAmode _ (CmmLit lit) = do dflags <- getDynFlags case platformArch $ targetPlatform dflags of ArchPPC -> do tmp <- getNewRegNat II32 let imm = litToImm lit code = unitOL (LIS tmp (HA imm)) return (Amode (AddrRegImm tmp (LO imm)) code) _ -> do -- TODO: Load from TOC, -- see getRegister' _ (CmmLit lit) tmp <- getNewRegNat II64 let imm = litToImm lit code = toOL [ LIS tmp (HIGHESTA imm), OR tmp tmp (RIImm (HIGHERA imm)), SL II64 tmp tmp (RIImm (ImmInt 32)), ORIS tmp tmp (HA imm) ] return (Amode (AddrRegImm tmp (LO imm)) code) getAmode _ (CmmMachOp (MO_Add W32) [x, y]) = do (regX, codeX) <- getSomeReg x (regY, codeY) <- getSomeReg y return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY)) getAmode _ (CmmMachOp (MO_Add W64) [x, y]) = do (regX, codeX) <- getSomeReg x (regY, codeY) <- getSomeReg y return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY)) getAmode _ other = do (reg, code) <- getSomeReg other let off = ImmInt 0 return (Amode (AddrRegImm reg off) code) -- The 'CondCode' type: Condition codes passed up the tree. data CondCode = CondCode Bool Cond InstrBlock -- Set up a condition code for a conditional branch. getCondCode :: CmmExpr -> NatM CondCode -- almost the same as everywhere else - but we need to -- extend small integers to 32 bit or 64 bit first getCondCode (CmmMachOp mop [x, y]) = do dflags <- getDynFlags case mop of MO_F_Eq W32 -> condFltCode EQQ x y MO_F_Ne W32 -> condFltCode NE x y MO_F_Gt W32 -> condFltCode GTT x y MO_F_Ge W32 -> condFltCode GE x y MO_F_Lt W32 -> condFltCode LTT x y MO_F_Le W32 -> condFltCode LE x y MO_F_Eq W64 -> condFltCode EQQ x y MO_F_Ne W64 -> condFltCode NE x y MO_F_Gt W64 -> condFltCode GTT x y MO_F_Ge W64 -> condFltCode GE x y MO_F_Lt W64 -> condFltCode LTT x y MO_F_Le W64 -> condFltCode LE x y MO_Eq rep -> condIntCode EQQ (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_Ne rep -> condIntCode NE (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_S_Gt rep -> condIntCode GTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Ge rep -> condIntCode GE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Lt rep -> condIntCode LTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Le rep -> condIntCode LE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Gt rep -> condIntCode GU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Ge rep -> condIntCode GEU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Lt rep -> condIntCode LU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Le rep -> condIntCode LEU (extendSExpr dflags rep x) (extendSExpr dflags rep y) _ -> pprPanic "getCondCode(powerpc)" (pprMachOp mop) getCondCode _ = panic "getCondCode(2)(powerpc)" -- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be -- passed back up the tree. condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode -- optimize pointer tag checks. Operation andi. sets condition register -- so cmpi ..., 0 is redundant. condIntCode cond (CmmMachOp (MO_And _) [x, CmmLit (CmmInt imm rep)]) (CmmLit (CmmInt 0 _)) | not $ condUnsigned cond, Just src2 <- makeImmediate rep False imm = do (src1, code) <- getSomeReg x let code' = code `snocOL` AND r0 src1 (RIImm src2) return (CondCode False cond code') condIntCode cond x (CmmLit (CmmInt y rep)) | Just src2 <- makeImmediate rep (not $ condUnsigned cond) y = do (src1, code) <- getSomeReg x dflags <- getDynFlags let format = archWordFormat $ target32Bit $ targetPlatform dflags code' = code `snocOL` (if condUnsigned cond then CMPL else CMP) format src1 (RIImm src2) return (CondCode False cond code') condIntCode cond x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y dflags <- getDynFlags let format = archWordFormat $ target32Bit $ targetPlatform dflags code' = code1 `appOL` code2 `snocOL` (if condUnsigned cond then CMPL else CMP) format src1 (RIReg src2) return (CondCode False cond code') condFltCode cond x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code' = code1 `appOL` code2 `snocOL` FCMP src1 src2 code'' = case cond of -- twiddle CR to handle unordered case GE -> code' `snocOL` CRNOR ltbit eqbit gtbit LE -> code' `snocOL` CRNOR gtbit eqbit ltbit _ -> code' where ltbit = 0 ; eqbit = 2 ; gtbit = 1 return (CondCode True cond code'') -- ----------------------------------------------------------------------------- -- Generating assignments -- Assignments are really at the heart of the whole code generation -- business. Almost all top-level nodes of any real importance are -- assignments, which correspond to loads, stores, or register -- transfers. If we're really lucky, some of the register transfers -- will go away, because we can use the destination register to -- complete the code generation for the right hand side. This only -- fails when the right hand side is forced into a fixed register -- (e.g. the result of a call). assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock assignMem_IntCode pk addr src = do (srcReg, code) <- getSomeReg src Amode dstAddr addr_code <- case pk of II64 -> getAmode DS addr _ -> getAmode D addr return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr -- dst is a reg, but src could be anything assignReg_IntCode _ reg src = do dflags <- getDynFlags let dst = getRegisterReg (targetPlatform dflags) reg r <- getRegister src return $ case r of Any _ code -> code dst Fixed _ freg fcode -> fcode `snocOL` MR dst freg -- Easy, isn't it? assignMem_FltCode = assignMem_IntCode assignReg_FltCode = assignReg_IntCode genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock genJump (CmmLit (CmmLabel lbl)) = return (unitOL $ JMP lbl) genJump tree = do dflags <- getDynFlags genJump' tree (platformToGCP (targetPlatform dflags)) genJump' :: CmmExpr -> GenCCallPlatform -> NatM InstrBlock genJump' tree (GCPLinux64ELF 1) = do (target,code) <- getSomeReg tree return (code `snocOL` LD II64 r11 (AddrRegImm target (ImmInt 0)) `snocOL` LD II64 toc (AddrRegImm target (ImmInt 8)) `snocOL` MTCTR r11 `snocOL` LD II64 r11 (AddrRegImm target (ImmInt 16)) `snocOL` BCTR [] Nothing) genJump' tree (GCPLinux64ELF 2) = do (target,code) <- getSomeReg tree return (code `snocOL` MR r12 target `snocOL` MTCTR r12 `snocOL` BCTR [] Nothing) genJump' tree _ = do (target,code) <- getSomeReg tree return (code `snocOL` MTCTR target `snocOL` BCTR [] Nothing) -- ----------------------------------------------------------------------------- -- Unconditional branches genBranch :: BlockId -> NatM InstrBlock genBranch = return . toOL . mkJumpInstr -- ----------------------------------------------------------------------------- -- Conditional jumps {- Conditional jumps are always to local labels, so we can use branch instructions. We peek at the arguments to decide what kind of comparison to do. -} genCondJump :: BlockId -- the branch target -> CmmExpr -- the condition on which to branch -> Maybe Bool -> NatM InstrBlock genCondJump id bool prediction = do CondCode _ cond code <- getCondCode bool return (code `snocOL` BCC cond id prediction) -- ----------------------------------------------------------------------------- -- Generating C calls -- Now the biggest nightmare---calls. Most of the nastiness is buried in -- @get_arg@, which moves the arguments to the correct registers/stack -- locations. Apart from that, the code is easy. genCCall :: ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock genCCall (PrimTarget MO_WriteBarrier) _ _ = return $ unitOL LWSYNC genCCall (PrimTarget MO_Touch) _ _ = return $ nilOL genCCall (PrimTarget (MO_Prefetch_Data _)) _ _ = return $ nilOL genCCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = do dflags <- getDynFlags let platform = targetPlatform dflags fmt = intFormat width reg_dst = getRegisterReg platform (CmmLocal dst) (instr, n_code) <- case amop of AMO_Add -> getSomeRegOrImm ADD True reg_dst AMO_Sub -> case n of CmmLit (CmmInt i _) | Just imm <- makeImmediate width True (-i) -> return (ADD reg_dst reg_dst (RIImm imm), nilOL) _ -> do (n_reg, n_code) <- getSomeReg n return (SUBF reg_dst n_reg reg_dst, n_code) AMO_And -> getSomeRegOrImm AND False reg_dst AMO_Nand -> do (n_reg, n_code) <- getSomeReg n return (NAND reg_dst reg_dst n_reg, n_code) AMO_Or -> getSomeRegOrImm OR False reg_dst AMO_Xor -> getSomeRegOrImm XOR False reg_dst Amode addr_reg addr_code <- getAmodeIndex addr lbl_retry <- getBlockIdNat return $ n_code `appOL` addr_code `appOL` toOL [ HWSYNC , BCC ALWAYS lbl_retry Nothing , NEWBLOCK lbl_retry , LDR fmt reg_dst addr_reg , instr , STC fmt reg_dst addr_reg , BCC NE lbl_retry (Just False) , ISYNC ] where getAmodeIndex (CmmMachOp (MO_Add _) [x, y]) = do (regX, codeX) <- getSomeReg x (regY, codeY) <- getSomeReg y return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY)) getAmodeIndex other = do (reg, code) <- getSomeReg other return (Amode (AddrRegReg r0 reg) code) -- NB: r0 is 0 here! getSomeRegOrImm op sign dst = case n of CmmLit (CmmInt i _) | Just imm <- makeImmediate width sign i -> return (op dst dst (RIImm imm), nilOL) _ -> do (n_reg, n_code) <- getSomeReg n return (op dst dst (RIReg n_reg), n_code) genCCall (PrimTarget (MO_AtomicRead width)) [dst] [addr] = do dflags <- getDynFlags let platform = targetPlatform dflags fmt = intFormat width reg_dst = getRegisterReg platform (CmmLocal dst) form = if widthInBits width == 64 then DS else D Amode addr_reg addr_code <- getAmode form addr lbl_end <- getBlockIdNat return $ addr_code `appOL` toOL [ HWSYNC , LD fmt reg_dst addr_reg , CMP fmt reg_dst (RIReg reg_dst) , BCC NE lbl_end (Just False) , BCC ALWAYS lbl_end Nothing -- See Note [Seemingly useless cmp and bne] , NEWBLOCK lbl_end , ISYNC ] -- Note [Seemingly useless cmp and bne] -- In Power ISA, Book II, Section 4.4.1, Instruction Synchronize Instruction -- the second paragraph says that isync may complete before storage accesses -- "associated" with a preceding instruction have been performed. The cmp -- operation and the following bne introduce a data and control dependency -- on the load instruction (See also Power ISA, Book II, Appendix B.2.3, Safe -- Fetch). -- This is also what gcc does. genCCall (PrimTarget (MO_AtomicWrite width)) [] [addr, val] = do code <- assignMem_IntCode (intFormat width) addr val return $ unitOL(HWSYNC) `appOL` code genCCall (PrimTarget (MO_Clz width)) [dst] [src] = do dflags <- getDynFlags let platform = targetPlatform dflags reg_dst = getRegisterReg platform (CmmLocal dst) if target32Bit platform && width == W64 then do ChildCode64 code vr_lo <- iselExpr64 src lbl1 <- getBlockIdNat lbl2 <- getBlockIdNat lbl3 <- getBlockIdNat let vr_hi = getHiVRegFromLo vr_lo cntlz = toOL [ CMPL II32 vr_hi (RIImm (ImmInt 0)) , BCC NE lbl2 Nothing , BCC ALWAYS lbl1 Nothing , NEWBLOCK lbl1 , CNTLZ II32 reg_dst vr_lo , ADD reg_dst reg_dst (RIImm (ImmInt 32)) , BCC ALWAYS lbl3 Nothing , NEWBLOCK lbl2 , CNTLZ II32 reg_dst vr_hi , BCC ALWAYS lbl3 Nothing , NEWBLOCK lbl3 ] return $ code `appOL` cntlz else do let format = if width == W64 then II64 else II32 (s_reg, s_code) <- getSomeReg src (pre, reg , post) <- case width of W64 -> return (nilOL, s_reg, nilOL) W32 -> return (nilOL, s_reg, nilOL) W16 -> do reg_tmp <- getNewRegNat format return ( unitOL $ AND reg_tmp s_reg (RIImm (ImmInt 65535)) , reg_tmp , unitOL $ ADD reg_dst reg_dst (RIImm (ImmInt (-16))) ) W8 -> do reg_tmp <- getNewRegNat format return ( unitOL $ AND reg_tmp s_reg (RIImm (ImmInt 255)) , reg_tmp , unitOL $ ADD reg_dst reg_dst (RIImm (ImmInt (-24))) ) _ -> panic "genCall: Clz wrong format" let cntlz = unitOL (CNTLZ format reg_dst reg) return $ s_code `appOL` pre `appOL` cntlz `appOL` post genCCall (PrimTarget (MO_Ctz width)) [dst] [src] = do dflags <- getDynFlags let platform = targetPlatform dflags reg_dst = getRegisterReg platform (CmmLocal dst) if target32Bit platform && width == W64 then do let format = II32 ChildCode64 code vr_lo <- iselExpr64 src lbl1 <- getBlockIdNat lbl2 <- getBlockIdNat lbl3 <- getBlockIdNat x' <- getNewRegNat format x'' <- getNewRegNat format r' <- getNewRegNat format cnttzlo <- cnttz format reg_dst vr_lo let vr_hi = getHiVRegFromLo vr_lo cnttz64 = toOL [ CMPL format vr_lo (RIImm (ImmInt 0)) , BCC NE lbl2 Nothing , BCC ALWAYS lbl1 Nothing , NEWBLOCK lbl1 , ADD x' vr_hi (RIImm (ImmInt (-1))) , ANDC x'' x' vr_hi , CNTLZ format r' x'' -- 32 + (32 - clz(x'')) , SUBFC reg_dst r' (RIImm (ImmInt 64)) , BCC ALWAYS lbl3 Nothing , NEWBLOCK lbl2 ] `appOL` cnttzlo `appOL` toOL [ BCC ALWAYS lbl3 Nothing , NEWBLOCK lbl3 ] return $ code `appOL` cnttz64 else do let format = if width == W64 then II64 else II32 (s_reg, s_code) <- getSomeReg src (reg_ctz, pre_code) <- case width of W64 -> return (s_reg, nilOL) W32 -> return (s_reg, nilOL) W16 -> do reg_tmp <- getNewRegNat format return (reg_tmp, unitOL $ ORIS reg_tmp s_reg (ImmInt 1)) W8 -> do reg_tmp <- getNewRegNat format return (reg_tmp, unitOL $ OR reg_tmp s_reg (RIImm (ImmInt 256))) _ -> panic "genCall: Ctz wrong format" ctz_code <- cnttz format reg_dst reg_ctz return $ s_code `appOL` pre_code `appOL` ctz_code where -- cnttz(x) = sizeof(x) - cntlz(~x & (x - 1)) -- see Henry S. Warren, Hacker's Delight, p 107 cnttz format dst src = do let format_bits = 8 * formatInBytes format x' <- getNewRegNat format x'' <- getNewRegNat format r' <- getNewRegNat format return $ toOL [ ADD x' src (RIImm (ImmInt (-1))) , ANDC x'' x' src , CNTLZ format r' x'' , SUBFC dst r' (RIImm (ImmInt (format_bits))) ] genCCall target dest_regs argsAndHints = do dflags <- getDynFlags let platform = targetPlatform dflags case target of PrimTarget (MO_S_QuotRem width) -> divOp1 platform True width dest_regs argsAndHints PrimTarget (MO_U_QuotRem width) -> divOp1 platform False width dest_regs argsAndHints PrimTarget (MO_U_QuotRem2 width) -> divOp2 platform width dest_regs argsAndHints PrimTarget (MO_U_Mul2 width) -> multOp2 platform width dest_regs argsAndHints PrimTarget (MO_Add2 _) -> add2Op platform dest_regs argsAndHints PrimTarget (MO_SubWordC _) -> subcOp platform dest_regs argsAndHints PrimTarget (MO_AddIntC width) -> addSubCOp ADDO platform width dest_regs argsAndHints PrimTarget (MO_SubIntC width) -> addSubCOp SUBFO platform width dest_regs argsAndHints PrimTarget MO_F64_Fabs -> fabs platform dest_regs argsAndHints PrimTarget MO_F32_Fabs -> fabs platform dest_regs argsAndHints _ -> genCCall' dflags (platformToGCP platform) target dest_regs argsAndHints where divOp1 platform signed width [res_q, res_r] [arg_x, arg_y] = do let reg_q = getRegisterReg platform (CmmLocal res_q) reg_r = getRegisterReg platform (CmmLocal res_r) fmt = intFormat width (x_reg, x_code) <- getSomeReg arg_x (y_reg, y_code) <- getSomeReg arg_y return $ y_code `appOL` x_code `appOL` toOL [ DIV fmt signed reg_q x_reg y_reg , MULL fmt reg_r reg_q (RIReg y_reg) , SUBF reg_r reg_r x_reg ] divOp1 _ _ _ _ _ = panic "genCCall: Wrong number of arguments for divOp1" divOp2 platform width [res_q, res_r] [arg_x_high, arg_x_low, arg_y] = do let reg_q = getRegisterReg platform (CmmLocal res_q) reg_r = getRegisterReg platform (CmmLocal res_r) fmt = intFormat width half = 4 * (formatInBytes fmt) (xh_reg, xh_code) <- getSomeReg arg_x_high (xl_reg, xl_code) <- getSomeReg arg_x_low (y_reg, y_code) <- getSomeReg arg_y s <- getNewRegNat fmt b <- getNewRegNat fmt v <- getNewRegNat fmt vn1 <- getNewRegNat fmt vn0 <- getNewRegNat fmt un32 <- getNewRegNat fmt tmp <- getNewRegNat fmt un10 <- getNewRegNat fmt un1 <- getNewRegNat fmt un0 <- getNewRegNat fmt q1 <- getNewRegNat fmt rhat <- getNewRegNat fmt tmp1 <- getNewRegNat fmt q0 <- getNewRegNat fmt un21 <- getNewRegNat fmt again1 <- getBlockIdNat no1 <- getBlockIdNat then1 <- getBlockIdNat endif1 <- getBlockIdNat again2 <- getBlockIdNat no2 <- getBlockIdNat then2 <- getBlockIdNat endif2 <- getBlockIdNat return $ y_code `appOL` xl_code `appOL` xh_code `appOL` -- see Hacker's Delight p 196 Figure 9-3 toOL [ -- b = 2 ^ (bits_in_word / 2) LI b (ImmInt 1) , SL fmt b b (RIImm (ImmInt half)) -- s = clz(y) , CNTLZ fmt s y_reg -- v = y << s , SL fmt v y_reg (RIReg s) -- vn1 = upper half of v , SR fmt vn1 v (RIImm (ImmInt half)) -- vn0 = lower half of v , CLRLI fmt vn0 v half -- un32 = (u1 << s) -- | (u0 >> (bits_in_word - s)) , SL fmt un32 xh_reg (RIReg s) , SUBFC tmp s (RIImm (ImmInt (8 * formatInBytes fmt))) , SR fmt tmp xl_reg (RIReg tmp) , OR un32 un32 (RIReg tmp) -- un10 = u0 << s , SL fmt un10 xl_reg (RIReg s) -- un1 = upper half of un10 , SR fmt un1 un10 (RIImm (ImmInt half)) -- un0 = lower half of un10 , CLRLI fmt un0 un10 half -- q1 = un32/vn1 , DIV fmt False q1 un32 vn1 -- rhat = un32 - q1*vn1 , MULL fmt tmp q1 (RIReg vn1) , SUBF rhat tmp un32 , BCC ALWAYS again1 Nothing , NEWBLOCK again1 -- if (q1 >= b || q1*vn0 > b*rhat + un1) , CMPL fmt q1 (RIReg b) , BCC GEU then1 Nothing , BCC ALWAYS no1 Nothing , NEWBLOCK no1 , MULL fmt tmp q1 (RIReg vn0) , SL fmt tmp1 rhat (RIImm (ImmInt half)) , ADD tmp1 tmp1 (RIReg un1) , CMPL fmt tmp (RIReg tmp1) , BCC LEU endif1 Nothing , BCC ALWAYS then1 Nothing , NEWBLOCK then1 -- q1 = q1 - 1 , ADD q1 q1 (RIImm (ImmInt (-1))) -- rhat = rhat + vn1 , ADD rhat rhat (RIReg vn1) -- if (rhat < b) goto again1 , CMPL fmt rhat (RIReg b) , BCC LTT again1 Nothing , BCC ALWAYS endif1 Nothing , NEWBLOCK endif1 -- un21 = un32*b + un1 - q1*v , SL fmt un21 un32 (RIImm (ImmInt half)) , ADD un21 un21 (RIReg un1) , MULL fmt tmp q1 (RIReg v) , SUBF un21 tmp un21 -- compute second quotient digit -- q0 = un21/vn1 , DIV fmt False q0 un21 vn1 -- rhat = un21- q0*vn1 , MULL fmt tmp q0 (RIReg vn1) , SUBF rhat tmp un21 , BCC ALWAYS again2 Nothing , NEWBLOCK again2 -- if (q0>b || q0*vn0 > b*rhat + un0) , CMPL fmt q0 (RIReg b) , BCC GEU then2 Nothing , BCC ALWAYS no2 Nothing , NEWBLOCK no2 , MULL fmt tmp q0 (RIReg vn0) , SL fmt tmp1 rhat (RIImm (ImmInt half)) , ADD tmp1 tmp1 (RIReg un0) , CMPL fmt tmp (RIReg tmp1) , BCC LEU endif2 Nothing , BCC ALWAYS then2 Nothing , NEWBLOCK then2 -- q0 = q0 - 1 , ADD q0 q0 (RIImm (ImmInt (-1))) -- rhat = rhat + vn1 , ADD rhat rhat (RIReg vn1) -- if (rhat<b) goto again2 , CMPL fmt rhat (RIReg b) , BCC LTT again2 Nothing , BCC ALWAYS endif2 Nothing , NEWBLOCK endif2 -- compute remainder -- r = (un21*b + un0 - q0*v) >> s , SL fmt reg_r un21 (RIImm (ImmInt half)) , ADD reg_r reg_r (RIReg un0) , MULL fmt tmp q0 (RIReg v) , SUBF reg_r tmp reg_r , SR fmt reg_r reg_r (RIReg s) -- compute quotient -- q = q1*b + q0 , SL fmt reg_q q1 (RIImm (ImmInt half)) , ADD reg_q reg_q (RIReg q0) ] divOp2 _ _ _ _ = panic "genCCall: Wrong number of arguments for divOp2" multOp2 platform width [res_h, res_l] [arg_x, arg_y] = do let reg_h = getRegisterReg platform (CmmLocal res_h) reg_l = getRegisterReg platform (CmmLocal res_l) fmt = intFormat width (x_reg, x_code) <- getSomeReg arg_x (y_reg, y_code) <- getSomeReg arg_y return $ y_code `appOL` x_code `appOL` toOL [ MULL fmt reg_l x_reg (RIReg y_reg) , MULHU fmt reg_h x_reg y_reg ] multOp2 _ _ _ _ = panic "genCall: Wrong number of arguments for multOp2" add2Op platform [res_h, res_l] [arg_x, arg_y] = do let reg_h = getRegisterReg platform (CmmLocal res_h) reg_l = getRegisterReg platform (CmmLocal res_l) (x_reg, x_code) <- getSomeReg arg_x (y_reg, y_code) <- getSomeReg arg_y return $ y_code `appOL` x_code `appOL` toOL [ LI reg_h (ImmInt 0) , ADDC reg_l x_reg y_reg , ADDZE reg_h reg_h ] add2Op _ _ _ = panic "genCCall: Wrong number of arguments/results for add2" -- PowerPC subfc sets the carry for rT = ~(rA) + rB + 1, -- which is 0 for borrow and 1 otherwise. We need 1 and 0 -- so xor with 1. subcOp platform [res_r, res_c] [arg_x, arg_y] = do let reg_r = getRegisterReg platform (CmmLocal res_r) reg_c = getRegisterReg platform (CmmLocal res_c) (x_reg, x_code) <- getSomeReg arg_x (y_reg, y_code) <- getSomeReg arg_y return $ y_code `appOL` x_code `appOL` toOL [ LI reg_c (ImmInt 0) , SUBFC reg_r y_reg (RIReg x_reg) , ADDZE reg_c reg_c , XOR reg_c reg_c (RIImm (ImmInt 1)) ] subcOp _ _ _ = panic "genCCall: Wrong number of arguments/results for subc" addSubCOp instr platform width [res_r, res_c] [arg_x, arg_y] = do let reg_r = getRegisterReg platform (CmmLocal res_r) reg_c = getRegisterReg platform (CmmLocal res_c) (x_reg, x_code) <- getSomeReg arg_x (y_reg, y_code) <- getSomeReg arg_y return $ y_code `appOL` x_code `appOL` toOL [ instr reg_r y_reg x_reg, -- SUBFO argument order reversed! MFOV (intFormat width) reg_c ] addSubCOp _ _ _ _ _ = panic "genCall: Wrong number of arguments/results for addC" fabs platform [res] [arg] = do let res_r = getRegisterReg platform (CmmLocal res) (arg_reg, arg_code) <- getSomeReg arg return $ arg_code `snocOL` FABS res_r arg_reg fabs _ _ _ = panic "genCall: Wrong number of arguments/results for fabs" -- TODO: replace 'Int' by an enum such as 'PPC_64ABI' data GenCCallPlatform = GCPLinux | GCPDarwin | GCPLinux64ELF !Int | GCPAIX platformToGCP :: Platform -> GenCCallPlatform platformToGCP platform = case platformOS platform of OSLinux -> case platformArch platform of ArchPPC -> GCPLinux ArchPPC_64 ELF_V1 -> GCPLinux64ELF 1 ArchPPC_64 ELF_V2 -> GCPLinux64ELF 2 _ -> panic "PPC.CodeGen.platformToGCP: Unknown Linux" OSAIX -> GCPAIX OSDarwin -> GCPDarwin _ -> panic "PPC.CodeGen.platformToGCP: not defined for this OS" genCCall' :: DynFlags -> GenCCallPlatform -> ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock {- The PowerPC calling convention for Darwin/Mac OS X is described in Apple's document "Inside Mac OS X - Mach-O Runtime Architecture". PowerPC Linux uses the System V Release 4 Calling Convention for PowerPC. It is described in the "System V Application Binary Interface PowerPC Processor Supplement". Both conventions are similar: Parameters may be passed in general-purpose registers starting at r3, in floating point registers starting at f1, or on the stack. But there are substantial differences: * The number of registers used for parameter passing and the exact set of nonvolatile registers differs (see MachRegs.hs). * On Darwin, stack space is always reserved for parameters, even if they are passed in registers. The called routine may choose to save parameters from registers to the corresponding space on the stack. * On Darwin, a corresponding amount of GPRs is skipped when a floating point parameter is passed in an FPR. * SysV insists on either passing I64 arguments on the stack, or in two GPRs, starting with an odd-numbered GPR. It may skip a GPR to achieve this. Darwin just treats an I64 like two separate II32s (high word first). * I64 and FF64 arguments are 8-byte aligned on the stack for SysV, but only 4-byte aligned like everything else on Darwin. * The SysV spec claims that FF32 is represented as FF64 on the stack. GCC on PowerPC Linux does not agree, so neither do we. PowerPC 64 Linux uses the System V Release 4 Calling Convention for 64-bit PowerPC. It is specified in "64-bit PowerPC ELF Application Binary Interface Supplement 1.9" (PPC64 ELF v1.9). PowerPC 64 Linux in little endian mode uses the "Power Architecture 64-Bit ELF V2 ABI Specification -- OpenPOWER ABI for Linux Supplement" (PPC64 ELF v2). AIX follows the "PowerOpen ABI: Application Binary Interface Big-Endian 32-Bit Hardware Implementation" According to all conventions, the parameter area should be part of the caller's stack frame, allocated in the caller's prologue code (large enough to hold the parameter lists for all called routines). The NCG already uses the stack for register spilling, leaving 64 bytes free at the top. If we need a larger parameter area than that, we just allocate a new stack frame just before ccalling. -} genCCall' dflags gcp target dest_regs args = ASSERT(not $ any (`elem` [II16]) $ map cmmTypeFormat argReps) -- we rely on argument promotion in the codeGen do (finalStack,passArgumentsCode,usedRegs) <- passArguments (zip args argReps) allArgRegs (allFPArgRegs platform) initialStackOffset (toOL []) [] (labelOrExpr, reduceToFF32) <- case target of ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do uses_pic_base_implicitly return (Left lbl, False) ForeignTarget expr _ -> do uses_pic_base_implicitly return (Right expr, False) PrimTarget mop -> outOfLineMachOp mop let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode codeAfter = move_sp_up finalStack `appOL` moveResult reduceToFF32 case labelOrExpr of Left lbl -> do -- the linker does all the work for us return ( codeBefore `snocOL` BL lbl usedRegs `appOL` maybeNOP -- some ABI require a NOP after BL `appOL` codeAfter) Right dyn -> do -- implement call through function pointer (dynReg, dynCode) <- getSomeReg dyn case gcp of GCPLinux64ELF 1 -> return ( dynCode `appOL` codeBefore `snocOL` ST spFormat toc (AddrRegImm sp (ImmInt 40)) `snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 0)) `snocOL` LD II64 toc (AddrRegImm dynReg (ImmInt 8)) `snocOL` MTCTR r11 `snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 16)) `snocOL` BCTRL usedRegs `snocOL` LD spFormat toc (AddrRegImm sp (ImmInt 40)) `appOL` codeAfter) GCPLinux64ELF 2 -> return ( dynCode `appOL` codeBefore `snocOL` ST spFormat toc (AddrRegImm sp (ImmInt 24)) `snocOL` MR r12 dynReg `snocOL` MTCTR r12 `snocOL` BCTRL usedRegs `snocOL` LD spFormat toc (AddrRegImm sp (ImmInt 24)) `appOL` codeAfter) GCPAIX -> return ( dynCode -- AIX/XCOFF follows the PowerOPEN ABI -- which is quite similiar to LinuxPPC64/ELFv1 `appOL` codeBefore `snocOL` ST spFormat toc (AddrRegImm sp (ImmInt 20)) `snocOL` LD II32 r11 (AddrRegImm dynReg (ImmInt 0)) `snocOL` LD II32 toc (AddrRegImm dynReg (ImmInt 4)) `snocOL` MTCTR r11 `snocOL` LD II32 r11 (AddrRegImm dynReg (ImmInt 8)) `snocOL` BCTRL usedRegs `snocOL` LD spFormat toc (AddrRegImm sp (ImmInt 20)) `appOL` codeAfter) _ -> return ( dynCode `snocOL` MTCTR dynReg `appOL` codeBefore `snocOL` BCTRL usedRegs `appOL` codeAfter) where platform = targetPlatform dflags uses_pic_base_implicitly = do -- See Note [implicit register in PPC PIC code] -- on why we claim to use PIC register here when (positionIndependent dflags && target32Bit platform) $ do _ <- getPicBaseNat $ archWordFormat True return () initialStackOffset = case gcp of GCPAIX -> 24 GCPDarwin -> 24 GCPLinux -> 8 GCPLinux64ELF 1 -> 48 GCPLinux64ELF 2 -> 32 _ -> panic "genCall': unknown calling convention" -- size of linkage area + size of arguments, in bytes stackDelta finalStack = case gcp of GCPAIX -> roundTo 16 $ (24 +) $ max 32 $ sum $ map (widthInBytes . typeWidth) argReps GCPDarwin -> roundTo 16 $ (24 +) $ max 32 $ sum $ map (widthInBytes . typeWidth) argReps GCPLinux -> roundTo 16 finalStack GCPLinux64ELF 1 -> roundTo 16 $ (48 +) $ max 64 $ sum $ map (roundTo 8 . widthInBytes . typeWidth) argReps GCPLinux64ELF 2 -> roundTo 16 $ (32 +) $ max 64 $ sum $ map (roundTo 8 . widthInBytes . typeWidth) argReps _ -> panic "genCall': unknown calling conv." argReps = map (cmmExprType dflags) args roundTo a x | x `mod` a == 0 = x | otherwise = x + a - (x `mod` a) spFormat = if target32Bit platform then II32 else II64 -- TODO: Do not create a new stack frame if delta is too large. move_sp_down finalStack | delta > stackFrameHeaderSize dflags = toOL [STU spFormat sp (AddrRegImm sp (ImmInt (-delta))), DELTA (-delta)] | otherwise = nilOL where delta = stackDelta finalStack move_sp_up finalStack | delta > stackFrameHeaderSize dflags = toOL [ADD sp sp (RIImm (ImmInt delta)), DELTA 0] | otherwise = nilOL where delta = stackDelta finalStack -- A NOP instruction is required after a call (bl instruction) -- on AIX and 64-Bit Linux. -- If the call is to a function with a different TOC (r2) the -- link editor replaces the NOP instruction with a load of the TOC -- from the stack to restore the TOC. maybeNOP = case gcp of -- See Section 3.9.4 of OpenPower ABI GCPAIX -> unitOL NOP -- See Section 3.5.11 of PPC64 ELF v1.9 GCPLinux64ELF 1 -> unitOL NOP -- See Section 2.3.6 of PPC64 ELF v2 GCPLinux64ELF 2 -> unitOL NOP _ -> nilOL passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed) passArguments ((arg,arg_ty):args) gprs fprs stackOffset accumCode accumUsed | isWord64 arg_ty && target32Bit (targetPlatform dflags) = do ChildCode64 code vr_lo <- iselExpr64 arg let vr_hi = getHiVRegFromLo vr_lo case gcp of GCPAIX -> -- same as for Darwin do let storeWord vr (gpr:_) _ = MR gpr vr storeWord vr [] offset = ST II32 vr (AddrRegImm sp (ImmInt offset)) passArguments args (drop 2 gprs) fprs (stackOffset+8) (accumCode `appOL` code `snocOL` storeWord vr_hi gprs stackOffset `snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4)) ((take 2 gprs) ++ accumUsed) GCPDarwin -> do let storeWord vr (gpr:_) _ = MR gpr vr storeWord vr [] offset = ST II32 vr (AddrRegImm sp (ImmInt offset)) passArguments args (drop 2 gprs) fprs (stackOffset+8) (accumCode `appOL` code `snocOL` storeWord vr_hi gprs stackOffset `snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4)) ((take 2 gprs) ++ accumUsed) GCPLinux -> do let stackOffset' = roundTo 8 stackOffset stackCode = accumCode `appOL` code `snocOL` ST II32 vr_hi (AddrRegImm sp (ImmInt stackOffset')) `snocOL` ST II32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4))) regCode hireg loreg = accumCode `appOL` code `snocOL` MR hireg vr_hi `snocOL` MR loreg vr_lo case gprs of hireg : loreg : regs | even (length gprs) -> passArguments args regs fprs stackOffset (regCode hireg loreg) (hireg : loreg : accumUsed) _skipped : hireg : loreg : regs -> passArguments args regs fprs stackOffset (regCode hireg loreg) (hireg : loreg : accumUsed) _ -> -- only one or no regs left passArguments args [] fprs (stackOffset'+8) stackCode accumUsed GCPLinux64ELF _ -> panic "passArguments: 32 bit code" passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed | reg : _ <- regs = do register <- getRegister arg let code = case register of Fixed _ freg fcode -> fcode `snocOL` MR reg freg Any _ acode -> acode reg stackOffsetRes = case gcp of -- The Darwin ABI requires that we reserve -- stack slots for register parameters GCPDarwin -> stackOffset + stackBytes -- ... so does the PowerOpen ABI. GCPAIX -> stackOffset + stackBytes -- ... the SysV ABI 32-bit doesn't. GCPLinux -> stackOffset -- ... but SysV ABI 64-bit does. GCPLinux64ELF _ -> stackOffset + stackBytes passArguments args (drop nGprs gprs) (drop nFprs fprs) stackOffsetRes (accumCode `appOL` code) (reg : accumUsed) | otherwise = do (vr, code) <- getSomeReg arg passArguments args (drop nGprs gprs) (drop nFprs fprs) (stackOffset' + stackBytes) (accumCode `appOL` code `snocOL` ST (cmmTypeFormat rep) vr stackSlot) accumUsed where stackOffset' = case gcp of GCPDarwin -> -- stackOffset is at least 4-byte aligned -- The Darwin ABI is happy with that. stackOffset GCPAIX -> -- The 32bit PowerOPEN ABI is happy with -- 32bit-alignment as well... stackOffset GCPLinux -- ... the SysV ABI requires 8-byte -- alignment for doubles. | isFloatType rep && typeWidth rep == W64 -> roundTo 8 stackOffset | otherwise -> stackOffset GCPLinux64ELF _ -> -- Everything on the stack is mapped to -- 8-byte aligned doublewords stackOffset stackOffset'' | isFloatType rep && typeWidth rep == W32 = case gcp of -- The ELF v1 ABI Section 3.2.3 requires: -- "Single precision floating point values -- are mapped to the second word in a single -- doubleword" GCPLinux64ELF 1 -> stackOffset' + 4 _ -> stackOffset' | otherwise = stackOffset' stackSlot = AddrRegImm sp (ImmInt stackOffset'') (nGprs, nFprs, stackBytes, regs) = case gcp of GCPAIX -> case cmmTypeFormat rep of II8 -> (1, 0, 4, gprs) II16 -> (1, 0, 4, gprs) II32 -> (1, 0, 4, gprs) -- The PowerOpen ABI requires that we skip a -- corresponding number of GPRs when we use -- the FPRs. -- -- E.g. for a `double` two GPRs are skipped, -- whereas for a `float` one GPR is skipped -- when parameters are assigned to -- registers. -- -- The PowerOpen ABI specification can be found at -- ftp://www.sourceware.org/pub/binutils/ppc-docs/ppc-poweropen/ FF32 -> (1, 1, 4, fprs) FF64 -> (2, 1, 8, fprs) II64 -> panic "genCCall' passArguments II64" FF80 -> panic "genCCall' passArguments FF80" GCPDarwin -> case cmmTypeFormat rep of II8 -> (1, 0, 4, gprs) II16 -> (1, 0, 4, gprs) II32 -> (1, 0, 4, gprs) -- The Darwin ABI requires that we skip a -- corresponding number of GPRs when we use -- the FPRs. FF32 -> (1, 1, 4, fprs) FF64 -> (2, 1, 8, fprs) II64 -> panic "genCCall' passArguments II64" FF80 -> panic "genCCall' passArguments FF80" GCPLinux -> case cmmTypeFormat rep of II8 -> (1, 0, 4, gprs) II16 -> (1, 0, 4, gprs) II32 -> (1, 0, 4, gprs) -- ... the SysV ABI doesn't. FF32 -> (0, 1, 4, fprs) FF64 -> (0, 1, 8, fprs) II64 -> panic "genCCall' passArguments II64" FF80 -> panic "genCCall' passArguments FF80" GCPLinux64ELF _ -> case cmmTypeFormat rep of II8 -> (1, 0, 8, gprs) II16 -> (1, 0, 8, gprs) II32 -> (1, 0, 8, gprs) II64 -> (1, 0, 8, gprs) -- The ELFv1 ABI requires that we skip a -- corresponding number of GPRs when we use -- the FPRs. FF32 -> (1, 1, 8, fprs) FF64 -> (1, 1, 8, fprs) FF80 -> panic "genCCall' passArguments FF80" moveResult reduceToFF32 = case dest_regs of [] -> nilOL [dest] | reduceToFF32 && isFloat32 rep -> unitOL (FRSP r_dest f1) | isFloat32 rep || isFloat64 rep -> unitOL (MR r_dest f1) | isWord64 rep && target32Bit (targetPlatform dflags) -> toOL [MR (getHiVRegFromLo r_dest) r3, MR r_dest r4] | otherwise -> unitOL (MR r_dest r3) where rep = cmmRegType dflags (CmmLocal dest) r_dest = getRegisterReg platform (CmmLocal dest) _ -> panic "genCCall' moveResult: Bad dest_regs" outOfLineMachOp mop = do dflags <- getDynFlags mopExpr <- cmmMakeDynamicReference dflags CallReference $ mkForeignLabel functionName Nothing ForeignLabelInThisPackage IsFunction let mopLabelOrExpr = case mopExpr of CmmLit (CmmLabel lbl) -> Left lbl _ -> Right mopExpr return (mopLabelOrExpr, reduce) where (functionName, reduce) = case mop of MO_F32_Exp -> (fsLit "exp", True) MO_F32_Log -> (fsLit "log", True) MO_F32_Sqrt -> (fsLit "sqrt", True) MO_F32_Fabs -> unsupported MO_F32_Sin -> (fsLit "sin", True) MO_F32_Cos -> (fsLit "cos", True) MO_F32_Tan -> (fsLit "tan", True) MO_F32_Asin -> (fsLit "asin", True) MO_F32_Acos -> (fsLit "acos", True) MO_F32_Atan -> (fsLit "atan", True) MO_F32_Sinh -> (fsLit "sinh", True) MO_F32_Cosh -> (fsLit "cosh", True) MO_F32_Tanh -> (fsLit "tanh", True) MO_F32_Pwr -> (fsLit "pow", True) MO_F64_Exp -> (fsLit "exp", False) MO_F64_Log -> (fsLit "log", False) MO_F64_Sqrt -> (fsLit "sqrt", False) MO_F64_Fabs -> unsupported MO_F64_Sin -> (fsLit "sin", False) MO_F64_Cos -> (fsLit "cos", False) MO_F64_Tan -> (fsLit "tan", False) MO_F64_Asin -> (fsLit "asin", False) MO_F64_Acos -> (fsLit "acos", False) MO_F64_Atan -> (fsLit "atan", False) MO_F64_Sinh -> (fsLit "sinh", False) MO_F64_Cosh -> (fsLit "cosh", False) MO_F64_Tanh -> (fsLit "tanh", False) MO_F64_Pwr -> (fsLit "pow", False) MO_UF_Conv w -> (fsLit $ word2FloatLabel w, False) MO_Memcpy _ -> (fsLit "memcpy", False) MO_Memset _ -> (fsLit "memset", False) MO_Memmove _ -> (fsLit "memmove", False) MO_Memcmp _ -> (fsLit "memcmp", False) MO_BSwap w -> (fsLit $ bSwapLabel w, False) MO_PopCnt w -> (fsLit $ popCntLabel w, False) MO_Pdep w -> (fsLit $ pdepLabel w, False) MO_Pext w -> (fsLit $ pextLabel w, False) MO_Clz _ -> unsupported MO_Ctz _ -> unsupported MO_AtomicRMW {} -> unsupported MO_Cmpxchg w -> (fsLit $ cmpxchgLabel w, False) MO_AtomicRead _ -> unsupported MO_AtomicWrite _ -> unsupported MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_SubWordC {} -> unsupported MO_AddIntC {} -> unsupported MO_SubIntC {} -> unsupported MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported MO_Prefetch_Data _ -> unsupported unsupported = panic ("outOfLineCmmOp: " ++ show mop ++ " not supported") -- ----------------------------------------------------------------------------- -- Generating a table-branch genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock genSwitch dflags expr targets | OSAIX <- platformOS (targetPlatform dflags) = do (reg,e_code) <- getSomeReg (cmmOffset dflags expr offset) let fmt = archWordFormat $ target32Bit $ targetPlatform dflags sha = if target32Bit $ targetPlatform dflags then 2 else 3 tmp <- getNewRegNat fmt lbl <- getNewLabelNat dynRef <- cmmMakeDynamicReference dflags DataReference lbl (tableReg,t_code) <- getSomeReg $ dynRef let code = e_code `appOL` t_code `appOL` toOL [ SL fmt tmp reg (RIImm (ImmInt sha)), LD fmt tmp (AddrRegReg tableReg tmp), MTCTR tmp, BCTR ids (Just lbl) ] return code | (positionIndependent dflags) || (not $ target32Bit $ targetPlatform dflags) = do (reg,e_code) <- getSomeReg (cmmOffset dflags expr offset) let fmt = archWordFormat $ target32Bit $ targetPlatform dflags sha = if target32Bit $ targetPlatform dflags then 2 else 3 tmp <- getNewRegNat fmt lbl <- getNewLabelNat dynRef <- cmmMakeDynamicReference dflags DataReference lbl (tableReg,t_code) <- getSomeReg $ dynRef let code = e_code `appOL` t_code `appOL` toOL [ SL fmt tmp reg (RIImm (ImmInt sha)), LD fmt tmp (AddrRegReg tableReg tmp), ADD tmp tmp (RIReg tableReg), MTCTR tmp, BCTR ids (Just lbl) ] return code | otherwise = do (reg,e_code) <- getSomeReg (cmmOffset dflags expr offset) let fmt = archWordFormat $ target32Bit $ targetPlatform dflags sha = if target32Bit $ targetPlatform dflags then 2 else 3 tmp <- getNewRegNat fmt lbl <- getNewLabelNat let code = e_code `appOL` toOL [ SL fmt tmp reg (RIImm (ImmInt sha)), ADDIS tmp tmp (HA (ImmCLbl lbl)), LD fmt tmp (AddrRegImm tmp (LO (ImmCLbl lbl))), MTCTR tmp, BCTR ids (Just lbl) ] return code where (offset, ids) = switchTargetsToTable targets generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl CmmStatics Instr) generateJumpTableForInstr dflags (BCTR ids (Just lbl)) = let jumpTable | (positionIndependent dflags) || (not $ target32Bit $ targetPlatform dflags) = map jumpTableEntryRel ids | otherwise = map (jumpTableEntry dflags) ids where jumpTableEntryRel Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags)) jumpTableEntryRel (Just blockid) = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0) where blockLabel = blockLbl blockid in Just (CmmData (Section ReadOnlyData lbl) (Statics lbl jumpTable)) generateJumpTableForInstr _ _ = Nothing -- ----------------------------------------------------------------------------- -- 'condIntReg' and 'condFltReg': condition codes into registers -- Turn those condition codes into integers now (when they appear on -- the right hand side of an assignment). condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register condReg :: NatM CondCode -> NatM Register condReg getCond = do CondCode _ cond cond_code <- getCond dflags <- getDynFlags let code dst = cond_code `appOL` negate_code `appOL` toOL [ MFCR dst, RLWINM dst dst (bit + 1) 31 31 ] negate_code | do_negate = unitOL (CRNOR bit bit bit) | otherwise = nilOL (bit, do_negate) = case cond of LTT -> (0, False) LE -> (1, True) EQQ -> (2, False) GE -> (0, True) GTT -> (1, False) NE -> (2, True) LU -> (0, False) LEU -> (1, True) GEU -> (0, True) GU -> (1, False) _ -> panic "PPC.CodeGen.codeReg: no match" format = archWordFormat $ target32Bit $ targetPlatform dflags return (Any format code) condIntReg cond x y = condReg (condIntCode cond x y) condFltReg cond x y = condReg (condFltCode cond x y) -- ----------------------------------------------------------------------------- -- 'trivial*Code': deal with trivial instructions -- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode', -- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions. -- Only look for constants on the right hand side, because that's -- where the generic optimizer will have put them. -- Similarly, for unary instructions, we don't have to worry about -- matching an StInt as the argument, because genericOpt will already -- have handled the constant-folding. {- Wolfgang's PowerPC version of The Rules: A slightly modified version of The Rules to take advantage of the fact that PowerPC instructions work on all registers and don't implicitly clobber any fixed registers. * The only expression for which getRegister returns Fixed is (CmmReg reg). * If getRegister returns Any, then the code it generates may modify only: (a) fresh temporaries (b) the destination register It may *not* modify global registers, unless the global register happens to be the destination register. It may not clobber any other registers. In fact, only ccalls clobber any fixed registers. Also, it may not modify the counter register (used by genCCall). Corollary: If a getRegister for a subexpression returns Fixed, you need not move it to a fresh temporary before evaluating the next subexpression. The Fixed register won't be modified. Therefore, we don't need a counterpart for the x86's getStableReg on PPC. * SDM's First Rule is valid for PowerPC, too: subexpressions can depend on the value of the destination register. -} trivialCode :: Width -> Bool -> (Reg -> Reg -> RI -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCode rep signed instr x (CmmLit (CmmInt y _)) | Just imm <- makeImmediate rep signed y = do (src1, code1) <- getSomeReg x let code dst = code1 `snocOL` instr dst src1 (RIImm imm) return (Any (intFormat rep) code) trivialCode rep _ instr x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2) return (Any (intFormat rep) code) shiftMulCode :: Width -> Bool -> (Format-> Reg -> Reg -> RI -> Instr) -> CmmExpr -> CmmExpr -> NatM Register shiftMulCode width sign instr x (CmmLit (CmmInt y _)) | Just imm <- makeImmediate width sign y = do (src1, code1) <- getSomeReg x let format = intFormat width let code dst = code1 `snocOL` instr format dst src1 (RIImm imm) return (Any format code) shiftMulCode width _ instr x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let format = intFormat width let code dst = code1 `appOL` code2 `snocOL` instr format dst src1 (RIReg src2) return (Any format code) trivialCodeNoImm' :: Format -> (Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCodeNoImm' format instr x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2 return (Any format code) trivialCodeNoImm :: Format -> (Format -> Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCodeNoImm format instr x y = trivialCodeNoImm' format (instr format) x y trivialCodeNoImmSign :: Format -> Bool -> (Format -> Bool -> Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCodeNoImmSign format sgn instr x y = trivialCodeNoImm' format (instr format sgn) x y trivialUCode :: Format -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register trivialUCode rep instr x = do (src, code) <- getSomeReg x let code' dst = code `snocOL` instr dst src return (Any rep code') -- There is no "remainder" instruction on the PPC, so we have to do -- it the hard way. -- The "sgn" parameter is the signedness for the division instruction remainderCode :: Width -> Bool -> CmmExpr -> CmmExpr -> NatM Register remainderCode rep sgn x y = do let fmt = intFormat rep (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code dst = code1 `appOL` code2 `appOL` toOL [ DIV fmt sgn dst src1 src2, MULL fmt dst dst (RIReg src2), SUBF dst dst src1 ] return (Any (intFormat rep) code) coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register coerceInt2FP fromRep toRep x = do dflags <- getDynFlags let arch = platformArch $ targetPlatform dflags coerceInt2FP' arch fromRep toRep x coerceInt2FP' :: Arch -> Width -> Width -> CmmExpr -> NatM Register coerceInt2FP' ArchPPC fromRep toRep x = do (src, code) <- getSomeReg x lbl <- getNewLabelNat itmp <- getNewRegNat II32 ftmp <- getNewRegNat FF64 dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode D dynRef let code' dst = code `appOL` maybe_exts `appOL` toOL [ LDATA (Section ReadOnlyData lbl) $ Statics lbl [CmmStaticLit (CmmInt 0x43300000 W32), CmmStaticLit (CmmInt 0x80000000 W32)], XORIS itmp src (ImmInt 0x8000), ST II32 itmp (spRel dflags 3), LIS itmp (ImmInt 0x4330), ST II32 itmp (spRel dflags 2), LD FF64 ftmp (spRel dflags 2) ] `appOL` addr_code `appOL` toOL [ LD FF64 dst addr, FSUB FF64 dst ftmp dst ] `appOL` maybe_frsp dst maybe_exts = case fromRep of W8 -> unitOL $ EXTS II8 src src W16 -> unitOL $ EXTS II16 src src W32 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" maybe_frsp dst = case toRep of W32 -> unitOL $ FRSP dst dst W64 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" return (Any (floatFormat toRep) code') -- On an ELF v1 Linux we use the compiler doubleword in the stack frame -- this is the TOC pointer doubleword on ELF v2 Linux. The latter is only -- set right before a call and restored right after return from the call. -- So it is fine. coerceInt2FP' (ArchPPC_64 _) fromRep toRep x = do (src, code) <- getSomeReg x dflags <- getDynFlags let code' dst = code `appOL` maybe_exts `appOL` toOL [ ST II64 src (spRel dflags 3), LD FF64 dst (spRel dflags 3), FCFID dst dst ] `appOL` maybe_frsp dst maybe_exts = case fromRep of W8 -> unitOL $ EXTS II8 src src W16 -> unitOL $ EXTS II16 src src W32 -> unitOL $ EXTS II32 src src W64 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" maybe_frsp dst = case toRep of W32 -> unitOL $ FRSP dst dst W64 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" return (Any (floatFormat toRep) code') coerceInt2FP' _ _ _ _ = panic "PPC.CodeGen.coerceInt2FP: unknown arch" coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register coerceFP2Int fromRep toRep x = do dflags <- getDynFlags let arch = platformArch $ targetPlatform dflags coerceFP2Int' arch fromRep toRep x coerceFP2Int' :: Arch -> Width -> Width -> CmmExpr -> NatM Register coerceFP2Int' ArchPPC _ toRep x = do dflags <- getDynFlags -- the reps don't really matter: F*->FF64 and II32->I* are no-ops (src, code) <- getSomeReg x tmp <- getNewRegNat FF64 let code' dst = code `appOL` toOL [ -- convert to int in FP reg FCTIWZ tmp src, -- store value (64bit) from FP to stack ST FF64 tmp (spRel dflags 2), -- read low word of value (high word is undefined) LD II32 dst (spRel dflags 3)] return (Any (intFormat toRep) code') coerceFP2Int' (ArchPPC_64 _) _ toRep x = do dflags <- getDynFlags -- the reps don't really matter: F*->FF64 and II64->I* are no-ops (src, code) <- getSomeReg x tmp <- getNewRegNat FF64 let code' dst = code `appOL` toOL [ -- convert to int in FP reg FCTIDZ tmp src, -- store value (64bit) from FP to compiler word on stack ST FF64 tmp (spRel dflags 3), LD II64 dst (spRel dflags 3)] return (Any (intFormat toRep) code') coerceFP2Int' _ _ _ _ = panic "PPC.CodeGen.coerceFP2Int: unknown arch" -- Note [.LCTOC1 in PPC PIC code] -- The .LCTOC1 label is defined to point 32768 bytes into the GOT table -- to make the most of the PPC's 16-bit displacements. -- As 16-bit signed offset is used (usually via addi/lwz instructions) -- first element will have '-32768' offset against .LCTOC1. -- Note [implicit register in PPC PIC code] -- PPC generates calls by labels in assembly -- in form of: -- bl puts+32768@plt -- in this form it's not seen directly (by GHC NCG) -- that r30 (PicBaseReg) is used, -- but r30 is a required part of PLT code setup: -- puts+32768@plt: -- lwz r11,-30484(r30) ; offset in .LCTOC1 -- mtctr r11 -- bctr
shlevy/ghc
compiler/nativeGen/PPC/CodeGen.hs
Haskell
bsd-3-clause
102,542
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Snap.Util.Proxy.Tests (tests) where ------------------------------------------------------------------------------ import Control.Monad.State.Strict (modify) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import Data.CaseInsensitive (CI (..)) import qualified Data.Map as Map import Snap.Core (Request (rqClientAddr, rqClientPort), Snap, rqRemotePort, withRequest) import Snap.Test (RequestBuilder, evalHandler, get, setHeader) import Snap.Test.Common (coverEqInstance, coverOrdInstance, coverReadInstance, coverShowInstance) import Snap.Util.Proxy (ProxyType (NoProxy, X_Forwarded_For), behindProxy) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertEqual) ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ tests :: [Test] tests = [ testNoProxy , testForwardedFor , testTrivials ] --------------- -- Constants -- --------------- ------------------------------------------------------------------------------ initialPort :: Int initialPort = 9999 initialAddr :: ByteString initialAddr = "127.0.0.1" ----------- -- Tests -- ----------- ------------------------------------------------------------------------------ testNoProxy :: Test testNoProxy = testCase "proxy/no-proxy" $ do a <- evalHandler (mkReq $ forwardedFor ["4.3.2.1"]) (behindProxy NoProxy reportRemoteAddr) p <- evalHandler (mkReq $ forwardedFor ["4.3.2.1"] >> xForwardedPort [10903]) (behindProxy NoProxy reportRemotePort) assertEqual "NoProxy leaves request alone" initialAddr a assertEqual "NoProxy leaves request alone" initialPort p -------------------------------------------------------------------------- b <- evalHandler (mkReq $ xForwardedFor ["2fe3::d4"]) (behindProxy NoProxy reportRemoteAddr) assertEqual "NoProxy leaves request alone" initialAddr b -------------------------------------------------------------------------- c <- evalHandler (mkReq $ return ()) (behindProxy NoProxy reportRemoteAddr) assertEqual "NoProxy leaves request alone" initialAddr c ------------------------------------------------------------------------------ testForwardedFor :: Test testForwardedFor = testCase "proxy/forwarded-for" $ do (a,p) <- evalHandler (mkReq $ return ()) handler assertEqual "No Forwarded-For, no change" initialAddr a assertEqual "port" initialPort p -------------------------------------------------------------------------- (b,q) <- evalHandler (mkReq $ forwardedFor [ip4]) handler assertEqual "Behind 5.6.7.8" ip4 b assertEqual "No Forwarded-Port, no port change" initialPort q -------------------------------------------------------------------------- (c,_) <- evalHandler (mkReq $ xForwardedFor [ip4, ip6]) handler assertEqual "Behind 23fe::d4" ip6 c -------------------------------------------------------------------------- (d,r) <- evalHandler (mkReq $ xForwardedFor [ip6, ip4] >> xForwardedPort [20202, port]) handler assertEqual "Behind 5.6.7.8" ip4 d assertEqual "port change" port r where handler = behindProxy X_Forwarded_For $ do !a <- reportRemoteAddr !p <- reportRemotePort' return $! (a,p) ip4 = "5.6.7.8" ip6 = "23fe::d4" port = 10101 ------------------------------------------------------------------------------ testTrivials :: Test testTrivials = testCase "proxy/trivials" $ do coverShowInstance NoProxy coverReadInstance NoProxy coverEqInstance NoProxy coverOrdInstance NoProxy --------------- -- Functions -- --------------- ------------------------------------------------------------------------------ mkReq :: RequestBuilder IO () -> RequestBuilder IO () mkReq m = do get "/" Map.empty modify $ \req -> req { rqClientAddr = initialAddr , rqClientPort = initialPort } m ------------------------------------------------------------------------------ reportRemoteAddr :: Snap ByteString reportRemoteAddr = withRequest $ \req -> return $ rqClientAddr req ------------------------------------------------------------------------------ reportRemotePort :: Snap Int reportRemotePort = withRequest $ \req -> return $ rqClientPort req ------------------------------------------------------------------------------ -- Cover deprecated rqRemotePort reportRemotePort' :: Snap Int reportRemotePort' = withRequest $ \req -> return $ rqRemotePort req ------------------------------------------------------------------------------ forwardedFor' :: CI ByteString -- ^ header name -> [ByteString] -- ^ list of "forwarded-for" -> RequestBuilder IO () forwardedFor' hdr addrs = setHeader hdr $ S.intercalate ", " addrs ------------------------------------------------------------------------------ forwardedFor :: [ByteString] -> RequestBuilder IO () forwardedFor = forwardedFor' "Forwarded-For" ------------------------------------------------------------------------------ xForwardedFor :: [ByteString] -> RequestBuilder IO () xForwardedFor = forwardedFor' "X-Forwarded-For" ------------------------------------------------------------------------------ xForwardedPort :: [Int] -- ^ list of "forwarded-port" -> RequestBuilder IO () xForwardedPort ports = setHeader "X-Forwarded-Port" $ S.intercalate ", " $ map (S.pack . show) $ ports
snapframework/snap-core
test/Snap/Util/Proxy/Tests.hs
Haskell
bsd-3-clause
6,436
{-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -funbox-strict-fields #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2010 -- -- The Session type and related functionality -- -- ----------------------------------------------------------------------------- module Eta.Main.GhcMonad ( -- * 'Ghc' monad stuff GhcMonad(..), Ghc(..), GhcT(..), liftGhcT, reflectGhc, reifyGhc, getSessionDynFlags, liftIO, Session(..), withSession, modifySession, withTempSession, -- ** Warnings logWarnings, printException, WarnErrLogger, defaultWarnErrLogger ) where import Eta.Utils.MonadUtils import Eta.Main.HscTypes import Eta.Main.DynFlags import Eta.Utils.Exception import Eta.Main.ErrUtils import Data.IORef -- ----------------------------------------------------------------------------- -- | A monad that has all the features needed by GHC API calls. -- -- In short, a GHC monad -- -- - allows embedding of IO actions, -- -- - can log warnings, -- -- - allows handling of (extensible) exceptions, and -- -- - maintains a current session. -- -- If you do not use 'Ghc' or 'GhcT', make sure to call 'GHC.initGhcMonad' -- before any call to the GHC API functions can occur. -- class (Functor m, MonadIO m, ExceptionMonad m, HasDynFlags m) => GhcMonad m where getSession :: m HscEnv setSession :: HscEnv -> m () -- | Call the argument with the current session. withSession :: GhcMonad m => (HscEnv -> m a) -> m a withSession f = getSession >>= f -- | Grabs the DynFlags from the Session getSessionDynFlags :: GhcMonad m => m DynFlags getSessionDynFlags = withSession (return . hsc_dflags) -- | Set the current session to the result of applying the current session to -- the argument. modifySession :: GhcMonad m => (HscEnv -> HscEnv) -> m () modifySession f = do h <- getSession setSession $! f h withSavedSession :: GhcMonad m => m a -> m a withSavedSession m = do saved_session <- getSession m `gfinally` setSession saved_session -- | Call an action with a temporarily modified Session. withTempSession :: GhcMonad m => (HscEnv -> HscEnv) -> m a -> m a withTempSession f m = withSavedSession $ modifySession f >> m -- ----------------------------------------------------------------------------- -- | A monad that allows logging of warnings. logWarnings :: GhcMonad m => WarningMessages -> m () logWarnings warns = do dflags <- getSessionDynFlags liftIO $ printOrThrowWarnings dflags warns -- ----------------------------------------------------------------------------- -- | A minimal implementation of a 'GhcMonad'. If you need a custom monad, -- e.g., to maintain additional state consider wrapping this monad or using -- 'GhcT'. newtype Ghc a = Ghc { unGhc :: Session -> IO a } -- | The Session is a handle to the complete state of a compilation -- session. A compilation session consists of a set of modules -- constituting the current program or library, the context for -- interactive evaluation, and various caches. data Session = Session !(IORef HscEnv) instance Functor Ghc where fmap f m = Ghc $ \s -> f `fmap` unGhc m s instance Applicative Ghc where pure = return g <*> m = do f <- g; a <- m; return (f a) instance Monad Ghc where return a = Ghc $ \_ -> return a m >>= g = Ghc $ \s -> do a <- unGhc m s; unGhc (g a) s instance MonadIO Ghc where liftIO ioA = Ghc $ \_ -> ioA instance MonadFix Ghc where mfix f = Ghc $ \s -> mfix (\x -> unGhc (f x) s) instance ExceptionMonad Ghc where gcatch act handle = Ghc $ \s -> unGhc act s `gcatch` \e -> unGhc (handle e) s gmask f = Ghc $ \s -> gmask $ \io_restore -> let g_restore (Ghc m) = Ghc $ \s -> io_restore (m s) in unGhc (f g_restore) s instance HasDynFlags Ghc where getDynFlags = getSessionDynFlags instance GhcMonad Ghc where getSession = Ghc $ \(Session r) -> readIORef r setSession s' = Ghc $ \(Session r) -> writeIORef r s' -- | Reflect a computation in the 'Ghc' monad into the 'IO' monad. -- -- You can use this to call functions returning an action in the 'Ghc' monad -- inside an 'IO' action. This is needed for some (too restrictive) callback -- arguments of some library functions: -- -- > libFunc :: String -> (Int -> IO a) -> IO a -- > ghcFunc :: Int -> Ghc a -- > -- > ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a -- > ghcFuncUsingLibFunc str = -- > reifyGhc $ \s -> -- > libFunc $ \i -> do -- > reflectGhc (ghcFunc i) s -- reflectGhc :: Ghc a -> Session -> IO a reflectGhc m = unGhc m -- > Dual to 'reflectGhc'. See its documentation. reifyGhc :: (Session -> IO a) -> Ghc a reifyGhc act = Ghc $ act -- ----------------------------------------------------------------------------- -- | A monad transformer to add GHC specific features to another monad. -- -- Note that the wrapped monad must support IO and handling of exceptions. newtype GhcT m a = GhcT { unGhcT :: Session -> m a } liftGhcT :: Monad m => m a -> GhcT m a liftGhcT m = GhcT $ \_ -> m instance Functor m => Functor (GhcT m) where fmap f m = GhcT $ \s -> f `fmap` unGhcT m s instance Applicative m => Applicative (GhcT m) where pure x = GhcT $ \_ -> pure x g <*> m = GhcT $ \s -> unGhcT g s <*> unGhcT m s instance Monad m => Monad (GhcT m) where return x = GhcT $ \_ -> return x m >>= k = GhcT $ \s -> do a <- unGhcT m s; unGhcT (k a) s instance MonadIO m => MonadIO (GhcT m) where liftIO ioA = GhcT $ \_ -> liftIO ioA instance ExceptionMonad m => ExceptionMonad (GhcT m) where gcatch act handle = GhcT $ \s -> unGhcT act s `gcatch` \e -> unGhcT (handle e) s gmask f = GhcT $ \s -> gmask $ \io_restore -> let g_restore (GhcT m) = GhcT $ \s -> io_restore (m s) in unGhcT (f g_restore) s instance (Functor m, ExceptionMonad m, MonadIO m) => HasDynFlags (GhcT m) where getDynFlags = getSessionDynFlags instance (Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) where getSession = GhcT $ \(Session r) -> liftIO $ readIORef r setSession s' = GhcT $ \(Session r) -> liftIO $ writeIORef r s' -- | Print the error message and all warnings. Useful inside exception -- handlers. Clears warnings after printing. printException :: GhcMonad m => SourceError -> m () printException err = do dflags <- getSessionDynFlags liftIO $ printBagOfErrors dflags (srcErrorMessages err) -- | A function called to log warnings and errors. type WarnErrLogger = forall m. GhcMonad m => Maybe SourceError -> m () defaultWarnErrLogger :: WarnErrLogger defaultWarnErrLogger Nothing = return () defaultWarnErrLogger (Just e) = printException e
rahulmutt/ghcvm
compiler/Eta/Main/GhcMonad.hs
Haskell
bsd-3-clause
6,934
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : cryptol@galois.com -- Stability : provisional -- Portability : portable {-# LANGUAGE PatternGuards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveGeneric #-} module Cryptol.ModuleSystem.Renamer ( NamingEnv(), shadowing , BindsNames(..) , checkNamingEnv , Rename(..), runRenamer , RenamerError(..) , RenamerWarning(..) ) where import Cryptol.ModuleSystem.NamingEnv import Cryptol.Prims.Syntax import Cryptol.Parser.AST import Cryptol.Parser.Names (tnamesP) import Cryptol.Parser.Position import Cryptol.Utils.Panic (panic) import Cryptol.Utils.PP import MonadLib import qualified Data.Map as Map import GHC.Generics (Generic) import Control.DeepSeq #if __GLASGOW_HASKELL__ < 710 import Control.Applicative(Applicative(..),(<$>)) import Data.Foldable (foldMap) import Data.Monoid (Monoid(..)) import Data.Traversable (traverse) #endif -- Errors ---------------------------------------------------------------------- data RenamerError = MultipleSyms (Located QName) [NameOrigin] -- ^ Multiple imported symbols contain this name | UnboundExpr (Located QName) -- ^ Expression name is not bound to any definition | UnboundType (Located QName) -- ^ Type name is not bound to any definition | OverlappingSyms [NameOrigin] -- ^ An environment has produced multiple overlapping symbols | ExpectedValue (Located QName) -- ^ When a value is expected from the naming environment, but one or more -- types exist instead. | ExpectedType (Located QName) -- ^ When a type is missing from the naming environment, but one or more -- values exist with the same name. | FixityError (Located QName) (Located QName) -- ^ When the fixity of two operators conflict | InvalidConstraint Type -- ^ When it's not possible to produce a Prop from a Type. | MalformedConstraint (Located Type) -- ^ When a constraint appears within another constraint deriving (Show,Generic) instance NFData RenamerError instance PP RenamerError where ppPrec _ e = case e of MultipleSyms lqn qns -> hang (text "[error] at" <+> pp (srcRange lqn)) 4 $ (text "Multiple definitions for symbol:" <+> pp (thing lqn)) $$ vcat (map pp qns) UnboundExpr lqn -> hang (text "[error] at" <+> pp (srcRange lqn)) 4 (text "Value not in scope:" <+> pp (thing lqn)) UnboundType lqn -> hang (text "[error] at" <+> pp (srcRange lqn)) 4 (text "Type not in scope:" <+> pp (thing lqn)) OverlappingSyms qns -> hang (text "[error]") 4 $ text "Overlapping symbols defined:" $$ vcat (map pp qns) ExpectedValue lqn -> hang (text "[error] at" <+> pp (srcRange lqn)) 4 (fsep [ text "Expected a value named", quotes (pp (thing lqn)) , text "but found a type instead" , text "Did you mean `(" <> pp (thing lqn) <> text")?" ]) ExpectedType lqn -> hang (text "[error] at" <+> pp (srcRange lqn)) 4 (fsep [ text "Expected a type named", quotes (pp (thing lqn)) , text "but found a value instead" ]) FixityError o1 o2 -> hang (text "[error]") 4 (fsep [ text "The fixities of", pp o1, text "and", pp o2 , text "are not compatible. " , text "You may use explicit parenthesis to disambiguate" ]) InvalidConstraint ty -> hang (text "[error]" <+> maybe empty (\r -> text "at" <+> pp r) (getLoc ty)) 4 (fsep [ pp ty, text "is not a valid constraint" ]) MalformedConstraint t -> hang (text "[error] at" <+> pp (srcRange t)) 4 (sep [ quotes (pp (thing t)) , text "is not a valid argument to a constraint" ]) -- Warnings -------------------------------------------------------------------- data RenamerWarning = SymbolShadowed NameOrigin [NameOrigin] deriving (Show,Generic) instance NFData RenamerWarning instance PP RenamerWarning where ppPrec _ (SymbolShadowed new originals) = hang (text "[warning] at" <+> loc) 4 $ fsep [ text "This binding for" <+> sym , text "shadows the existing binding" <> plural <+> text "from" ] $$ vcat (map pp originals) where plural | length originals > 1 = char 's' | otherwise = empty (loc,sym) = case new of Local lqn -> (pp (srcRange lqn), pp (thing lqn)) Imported qn -> (empty, pp qn) -- Renaming Monad -------------------------------------------------------------- data RO = RO { roLoc :: Range , roNames :: NamingEnv } data Out = Out { oWarnings :: [RenamerWarning] , oErrors :: [RenamerError] } deriving (Show) instance Monoid Out where mempty = Out [] [] mappend l r = Out (oWarnings l `mappend` oWarnings r) (oErrors l `mappend` oErrors r) newtype RenameM a = RenameM { unRenameM :: ReaderT RO (WriterT Out Id) a } instance Functor RenameM where {-# INLINE fmap #-} fmap f m = RenameM (fmap f (unRenameM m)) instance Applicative RenameM where {-# INLINE pure #-} pure x = RenameM (pure x) {-# INLINE (<*>) #-} l <*> r = RenameM (unRenameM l <*> unRenameM r) instance Monad RenameM where {-# INLINE return #-} return x = RenameM (return x) {-# INLINE (>>=) #-} m >>= k = RenameM (unRenameM m >>= unRenameM . k) runRenamer :: NamingEnv -> RenameM a -> (Either [RenamerError] a,[RenamerWarning]) runRenamer env m = (res,oWarnings out) where (a,out) = runM (unRenameM m) RO { roLoc = emptyRange, roNames = env } res | null (oErrors out) = Right a | otherwise = Left (oErrors out) record :: RenamerError -> RenameM () record err = records [err] records :: [RenamerError] -> RenameM () records errs = RenameM (put mempty { oErrors = errs }) located :: a -> RenameM (Located a) located a = RenameM $ do ro <- ask return Located { srcRange = roLoc ro, thing = a } withLoc :: HasLoc loc => loc -> RenameM a -> RenameM a withLoc loc m = RenameM $ case getLoc loc of Just range -> do ro <- ask local ro { roLoc = range } (unRenameM m) Nothing -> unRenameM m -- | Shadow the current naming environment with some more names. shadowNames :: BindsNames env => env -> RenameM a -> RenameM a shadowNames names m = RenameM $ do let env = namingEnv names ro <- ask put (checkEnv env (roNames ro)) let ro' = ro { roNames = env `shadowing` roNames ro } local ro' (unRenameM m) -- | Generate warnings when the left environment shadows things defined in -- the right. Additionally, generate errors when two names overlap in the -- left environment. checkEnv :: NamingEnv -> NamingEnv -> Out checkEnv l r = Map.foldlWithKey (step neExprs) mempty (neExprs l) `mappend` Map.foldlWithKey (step neTypes) mempty (neTypes l) where step prj acc k ns = acc `mappend` mempty { oWarnings = case Map.lookup k (prj r) of Nothing -> [] Just os -> [SymbolShadowed (origin (head ns)) (map origin os)] , oErrors = containsOverlap ns } -- | Check the RHS of a single name rewrite for conflicting sources. containsOverlap :: HasQName a => [a] -> [RenamerError] containsOverlap [_] = [] containsOverlap [] = panic "Renamer" ["Invalid naming environment"] containsOverlap ns = [OverlappingSyms (map origin ns)] -- | Throw errors for any names that overlap in a rewrite environment. checkNamingEnv :: NamingEnv -> ([RenamerError],[RenamerWarning]) checkNamingEnv env = (out, []) where out = Map.foldr check outTys (neExprs env) outTys = Map.foldr check mempty (neTypes env) check ns acc = containsOverlap ns ++ acc -- Renaming -------------------------------------------------------------------- class Rename a where rename :: a -> RenameM a instance Rename a => Rename [a] where rename = traverse rename instance Rename a => Rename (Maybe a) where rename = traverse rename instance Rename a => Rename (Located a) where rename loc = withLoc loc $ do a' <- rename (thing loc) return loc { thing = a' } instance Rename a => Rename (Named a) where rename n = do a' <-rename (value n) return n { value = a' } instance Rename Module where rename m = do decls' <- rename (mDecls m) return m { mDecls = decls' } instance Rename TopDecl where rename td = case td of Decl d -> Decl <$> rename d TDNewtype n -> TDNewtype <$> rename n Include{} -> return td instance Rename a => Rename (TopLevel a) where rename tl = do a' <- rename (tlValue tl) return tl { tlValue = a' } instance Rename Decl where rename d = case d of DSignature ns sig -> DSignature ns <$> rename sig DPragma ns p -> DPragma ns <$> rename p DBind b -> DBind <$> rename b DPatBind pat e -> DPatBind pat <$> shadowNames (namingEnv pat) (rename e) DType syn -> DType <$> rename syn DLocated d' r -> withLoc r $ DLocated <$> rename d' <*> pure r DFixity{} -> panic "Renamer" ["Unexpected fixity declaration", show d] instance Rename Newtype where rename n = do name' <- renameLoc renameType (nName n) body' <- shadowNames (nParams n) (rename (nBody n)) return Newtype { nName = name' , nParams = nParams n , nBody = body' } renameVar :: QName -> RenameM QName renameVar qn = do ro <- RenameM ask case Map.lookup qn (neExprs (roNames ro)) of Just [en] -> return (qname en) Just [] -> panic "Renamer" ["Invalid expression renaming environment"] Just syms -> do n <- located qn record (MultipleSyms n (map origin syms)) return qn Nothing -> do n <- located qn case Map.lookup qn (neTypes (roNames ro)) of -- types existed with the name of the value expected Just _ -> record (ExpectedValue n) -- the value is just missing Nothing -> record (UnboundExpr n) return qn renameType :: QName -> RenameM QName renameType qn = do ro <- RenameM ask case Map.lookup qn (neTypes (roNames ro)) of Just [tn] -> return (qname tn) Just [] -> panic "Renamer" ["Invalid type renaming environment"] Just syms -> do n <- located qn record (MultipleSyms n (map origin syms)) return qn Nothing -> do n <- located qn case Map.lookup qn (neExprs (roNames ro)) of -- values exist with the same name, so throw a different error Just _ -> record (ExpectedType n) -- no terms with the same name, so the type is just unbound Nothing -> record (UnboundType n) return qn -- | Rename a schema, assuming that none of its type variables are already in -- scope. instance Rename Schema where rename s@(Forall ps _ _ _) = shadowNames ps (renameSchema s) -- | Rename a schema, assuming that the type variables have already been brought -- into scope. renameSchema :: Schema -> RenameM Schema renameSchema (Forall ps p ty loc) = Forall ps <$> rename p <*> rename ty <*> pure loc instance Rename Prop where rename p = case p of CFin t -> CFin <$> rename t CEqual l r -> CEqual <$> rename l <*> rename r CGeq l r -> CGeq <$> rename l <*> rename r CArith t -> CArith <$> rename t CCmp t -> CCmp <$> rename t CLocated p' r -> withLoc r $ CLocated <$> rename p' <*> pure r -- here, we rename the type and then require that it produces something that -- looks like a Prop CType t -> translateProp t translateProp :: Type -> RenameM Prop translateProp ty = go =<< rnType True ty where go t = case t of TLocated t' r -> (`CLocated` r) <$> go t' TUser (QName Nothing p) [l,r] | p == mkName "==" -> pure (CEqual l r) | p == mkName ">=" -> pure (CGeq l r) | p == mkName "<=" -> pure (CGeq r l) _ -> do record (InvalidConstraint ty) return (CType t) instance Rename Type where rename = rnType False rnType :: Bool -> Type -> RenameM Type rnType isProp = go where go t = case t of TFun a b -> TFun <$> go a <*> go b TSeq n a -> TSeq <$> go n <*> go a TBit -> return t TNum _ -> return t TChar _ -> return t TInf -> return t TUser (QName Nothing n) ps | n == mkName "inf", null ps -> return TInf | n == mkName "Bit", null ps -> return TBit | n == mkName "min" -> TApp TCMin <$> traverse go ps | n == mkName "max" -> TApp TCMax <$> traverse go ps | n == mkName "lengthFromThen" -> TApp TCLenFromThen <$> traverse go ps | n == mkName "lengthFromThenTo" -> TApp TCLenFromThenTo <$> traverse go ps | n == mkName "width" -> TApp TCWidth <$> traverse go ps -- This should only happen in error, as fin constraints are constructed -- in the parser. (Cryptol.Parser.ParserUtils.mkProp) | n == mkName "fin" && isProp -> do locTy <- located t record (MalformedConstraint locTy) return t TUser qn ps -> TUser <$> renameType qn <*> traverse go ps TApp f xs -> TApp f <$> traverse go xs TRecord fs -> TRecord <$> traverse (traverse go) fs TTuple fs -> TTuple <$> traverse go fs TWild -> return t TLocated t' r -> withLoc r $ TLocated <$> go t' <*> pure r TParens t' -> TParens <$> go t' TInfix a o _ b -> do op <- renameTypeOp isProp o a' <- go a b' <- go b mkTInfix isProp a' op b' type TOp = Type -> Type -> Type mkTInfix :: Bool -> Type -> (TOp,Fixity) -> Type -> RenameM Type -- this should be one of the props, or an error, so just assume that its fixity -- is `infix 0`. mkTInfix True t@(TUser o1 [x,y]) op@(o2,f2) z = do let f1 = Fixity NonAssoc 0 case compareFixity f1 f2 of FCLeft -> return (o2 t z) FCRight -> do r <- mkTInfix True y op z return (TUser o1 [x,r]) -- Just reconstruct with the TUser part being an application. If this was -- a real error, it will have been caught by now. FCError -> return (o2 t z) -- In this case, we know the fixities of both sides. mkTInfix isProp t@(TApp o1 [x,y]) op@(o2,f2) z | Just (a1,p1) <- Map.lookup o1 tBinOpPrec = case compareFixity (Fixity a1 p1) f2 of FCLeft -> return (o2 t z) FCRight -> do r <- mkTInfix isProp y op z return (TApp o1 [x,r]) -- As the fixity table is known, and this is a case where the fixity came -- from that table, it's a real error if the fixities didn't work out. FCError -> panic "Renamer" [ "fixity problem for type operators" , show (o2 t z) ] mkTInfix isProp (TLocated t _) op z = mkTInfix isProp t op z mkTInfix _ t (op,_) z = return (op t z) -- | Rename a type operator, mapping it to a real type function. When isProp is -- True, it's assumed that the renaming is happening in the context of a Prop, -- which allows unresolved operators to propagate without an error. They will -- be resolved in the CType case for Prop. renameTypeOp :: Bool -> Located QName -> RenameM (TOp,Fixity) renameTypeOp isProp op = do let sym = unqual (thing op) props = [ mkName "==", mkName ">=", mkName "<=" ] lkp = do n <- Map.lookup (thing op) tfunNames (fAssoc,fLevel) <- Map.lookup n tBinOpPrec return (n,Fixity { .. }) case lkp of Just (p,f) -> return (\x y -> TApp p [x,y], f) Nothing | isProp && sym `elem` props -> return (\x y -> TUser (thing op) [x,y], Fixity NonAssoc 0) | otherwise -> do record (UnboundType op) return (\x y -> TUser (thing op) [x,y], defaultFixity) instance Rename Pragma where rename p = case p of PragmaNote _ -> return p PragmaProperty -> return p -- | The type renaming environment generated by a binding. bindingTypeEnv :: Bind -> NamingEnv bindingTypeEnv b = patParams `shadowing` sigParams where -- type parameters sigParams = namingEnv (bSignature b) -- pattern type parameters patParams = foldMap (foldMap qualType . tnamesP) (bParams b) qualType qn = singletonT qn (TFromParam qn) -- | Rename a binding. -- -- NOTE: this does not bind its own name into the naming context of its body. -- The assumption here is that this has been done by the enclosing environment, -- to allow for top-level renaming instance Rename Bind where rename b = do n' <- renameLoc renameVar (bName b) shadowNames (bindingTypeEnv b) $ do (patenv,pats') <- renamePats (bParams b) sig' <- traverse renameSchema (bSignature b) shadowNames patenv $ do e' <- rename (bDef b) p' <- rename (bPragmas b) return b { bName = n' , bParams = pats' , bDef = e' , bSignature = sig' , bPragmas = p' } instance Rename BindDef where rename DPrim = return DPrim rename (DExpr e) = DExpr <$> rename e -- NOTE: this only renames types within the pattern. instance Rename Pattern where rename p = case p of PVar _ -> pure p PWild -> pure p PTuple ps -> PTuple <$> rename ps PRecord nps -> PRecord <$> rename nps PList elems -> PList <$> rename elems PTyped p' t -> PTyped <$> rename p' <*> rename t PSplit l r -> PSplit <$> rename l <*> rename r PLocated p' loc -> withLoc loc $ PLocated <$> rename p' <*> pure loc instance Rename Expr where rename e = case e of EVar n -> EVar <$> renameVar n ELit _ -> return e ETuple es -> ETuple <$> rename es ERecord fs -> ERecord <$> rename fs ESel e' s -> ESel <$> rename e' <*> pure s EList es -> EList <$> rename es EFromTo s n e'-> EFromTo <$> rename s <*> rename n <*> rename e' EInfFrom a b -> EInfFrom<$> rename a <*> rename b EComp e' bs -> do bs' <- mapM renameMatch bs shadowNames (namingEnv bs') (EComp <$> rename e' <*> pure bs') EApp f x -> EApp <$> rename f <*> rename x EAppT f ti -> EAppT <$> rename f <*> rename ti EIf b t f -> EIf <$> rename b <*> rename t <*> rename f EWhere e' ds -> shadowNames ds (EWhere <$> rename e' <*> rename ds) ETyped e' ty -> ETyped <$> rename e' <*> rename ty ETypeVal ty -> ETypeVal<$> rename ty EFun ps e' -> do ps' <- rename ps shadowNames ps' (EFun ps' <$> rename e') ELocated e' r -> withLoc r $ ELocated <$> rename e' <*> pure r EParens p -> EParens <$> rename p EInfix x y _ z-> do op <- renameOp y x' <- rename x z' <- rename z mkEInfix x' op z' mkEInfix :: Expr -- ^ May contain infix expressions -> (Located QName,Fixity) -- ^ The operator to use -> Expr -- ^ Will not contain infix expressions -> RenameM Expr mkEInfix e@(EInfix x o1 f1 y) op@(o2,f2) z = case compareFixity f1 f2 of FCLeft -> return (EInfix e o2 f2 z) FCRight -> do r <- mkEInfix y op z return (EInfix x o1 f1 r) FCError -> do record (FixityError o1 o2) return (EInfix e o2 f2 z) mkEInfix (ELocated e' _) op z = mkEInfix e' op z mkEInfix e (o,f) z = return (EInfix e o f z) renameOp :: Located QName -> RenameM (Located QName,Fixity) renameOp ln = withLoc ln $ do n <- renameVar (thing ln) ro <- RenameM ask case Map.lookup n (neFixity (roNames ro)) of Just [fixity] -> return (ln { thing = n },fixity) _ -> return (ln { thing = n },defaultFixity) instance Rename TypeInst where rename ti = case ti of NamedInst nty -> NamedInst <$> rename nty PosInst ty -> PosInst <$> rename ty renameMatch :: [Match] -> RenameM [Match] renameMatch = loop where loop ms = case ms of m:rest -> do m' <- rename m (m':) <$> shadowNames m' (loop rest) [] -> return [] renamePats :: [Pattern] -> RenameM (NamingEnv,[Pattern]) renamePats = loop where loop ps = case ps of p:rest -> do p' <- rename p let pe = namingEnv p' (env',rest') <- loop rest return (pe `mappend` env', p':rest') [] -> return (mempty, []) instance Rename Match where rename m = case m of Match p e -> Match <$> rename p <*> rename e MatchLet b -> shadowNames b (MatchLet <$> rename b) instance Rename TySyn where rename (TySyn n ps ty) = shadowNames ps (TySyn <$> renameLoc renameType n <*> pure ps <*> rename ty) renameLoc :: (a -> RenameM b) -> Located a -> RenameM (Located b) renameLoc by loc = do a' <- by (thing loc) return loc { thing = a' }
beni55/cryptol
src/Cryptol/ModuleSystem/Renamer.hs
Haskell
bsd-3-clause
21,636
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Stg to C-- code generation: the binding environment -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmEnv ( CgIdInfo, litIdInfo, lneIdInfo, rhsIdInfo, mkRhsInit, idInfoToAmode, addBindC, addBindsC, bindArgsToRegs, bindToReg, rebindToReg, bindArgToReg, idToReg, getArgAmode, getNonVoidArgAmodes, getCgIdInfo, maybeLetNoEscape, ) where #include "HsVersions.h" import TyCon import StgCmmMonad import StgCmmUtils import StgCmmClosure import CLabel import BlockId import CmmExpr import CmmUtils import DynFlags import Id import MkGraph import Name import Outputable import StgSyn import UniqFM import VarEnv ------------------------------------- -- Manipulating CgIdInfo ------------------------------------- mkCgIdInfo :: Id -> LambdaFormInfo -> CmmExpr -> CgIdInfo mkCgIdInfo id lf expr = CgIdInfo { cg_id = id, cg_lf = lf , cg_loc = CmmLoc expr } litIdInfo :: DynFlags -> Id -> LambdaFormInfo -> CmmLit -> CgIdInfo litIdInfo dflags id lf lit = CgIdInfo { cg_id = id, cg_lf = lf , cg_loc = CmmLoc (addDynTag dflags (CmmLit lit) tag) } where tag = lfDynTag dflags lf lneIdInfo :: DynFlags -> Id -> [NonVoid Id] -> CgIdInfo lneIdInfo dflags id regs = CgIdInfo { cg_id = id, cg_lf = lf , cg_loc = LneLoc blk_id (map (idToReg dflags) regs) } where lf = mkLFLetNoEscape blk_id = mkBlockId (idUnique id) rhsIdInfo :: Id -> LambdaFormInfo -> FCode (CgIdInfo, LocalReg) rhsIdInfo id lf_info = do dflags <- getDynFlags reg <- newTemp (gcWord dflags) return (mkCgIdInfo id lf_info (CmmReg (CmmLocal reg)), reg) mkRhsInit :: DynFlags -> LocalReg -> LambdaFormInfo -> CmmExpr -> CmmAGraph mkRhsInit dflags reg lf_info expr = mkAssign (CmmLocal reg) (addDynTag dflags expr (lfDynTag dflags lf_info)) idInfoToAmode :: CgIdInfo -> CmmExpr -- Returns a CmmExpr for the *tagged* pointer idInfoToAmode (CgIdInfo { cg_loc = CmmLoc e }) = e idInfoToAmode cg_info = pprPanic "idInfoToAmode" (ppr (cg_id cg_info)) -- LneLoc addDynTag :: DynFlags -> CmmExpr -> DynTag -> CmmExpr -- A tag adds a byte offset to the pointer addDynTag dflags expr tag = cmmOffsetB dflags expr tag maybeLetNoEscape :: CgIdInfo -> Maybe (BlockId, [LocalReg]) maybeLetNoEscape (CgIdInfo { cg_loc = LneLoc blk_id args}) = Just (blk_id, args) maybeLetNoEscape _other = Nothing --------------------------------------------------------- -- The binding environment -- -- There are three basic routines, for adding (addBindC), -- modifying(modifyBindC) and looking up (getCgIdInfo) bindings. --------------------------------------------------------- addBindC :: CgIdInfo -> FCode () addBindC stuff_to_bind = do binds <- getBinds setBinds $ extendVarEnv binds (cg_id stuff_to_bind) stuff_to_bind addBindsC :: [CgIdInfo] -> FCode () addBindsC new_bindings = do binds <- getBinds let new_binds = foldl (\ binds info -> extendVarEnv binds (cg_id info) info) binds new_bindings setBinds new_binds getCgIdInfo :: Id -> FCode CgIdInfo getCgIdInfo id = do { dflags <- getDynFlags ; local_binds <- getBinds -- Try local bindings first ; case lookupVarEnv local_binds id of { Just info -> return info ; Nothing -> do { -- Should be imported; make up a CgIdInfo for it let name = idName id ; if isExternalName name then let ext_lbl = CmmLabel (mkClosureLabel name $ idCafInfo id) in return (litIdInfo dflags id (mkLFImported id) ext_lbl) else cgLookupPanic id -- Bug }}} cgLookupPanic :: Id -> FCode a cgLookupPanic id = do local_binds <- getBinds pprPanic "StgCmmEnv: variable not found" (vcat [ppr id, text "local binds for:", pprUFM local_binds $ \infos -> vcat [ ppr (cg_id info) | info <- infos ] ]) -------------------- getArgAmode :: NonVoid StgArg -> FCode CmmExpr getArgAmode (NonVoid (StgVarArg var)) = idInfoToAmode <$> getCgIdInfo var getArgAmode (NonVoid (StgLitArg lit)) = CmmLit <$> cgLit lit getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr] -- NB: Filters out void args, -- so the result list may be shorter than the argument list getNonVoidArgAmodes [] = return [] getNonVoidArgAmodes (arg:args) | isVoidRep (argPrimRep arg) = getNonVoidArgAmodes args | otherwise = do { amode <- getArgAmode (NonVoid arg) ; amodes <- getNonVoidArgAmodes args ; return ( amode : amodes ) } ------------------------------------------------------------------------ -- Interface functions for binding and re-binding names ------------------------------------------------------------------------ bindToReg :: NonVoid Id -> LambdaFormInfo -> FCode LocalReg -- Bind an Id to a fresh LocalReg bindToReg nvid@(NonVoid id) lf_info = do dflags <- getDynFlags let reg = idToReg dflags nvid addBindC (mkCgIdInfo id lf_info (CmmReg (CmmLocal reg))) return reg rebindToReg :: NonVoid Id -> FCode LocalReg -- Like bindToReg, but the Id is already in scope, so -- get its LF info from the envt rebindToReg nvid@(NonVoid id) = do { info <- getCgIdInfo id ; bindToReg nvid (cg_lf info) } bindArgToReg :: NonVoid Id -> FCode LocalReg bindArgToReg nvid@(NonVoid id) = bindToReg nvid (mkLFArgument id) bindArgsToRegs :: [NonVoid Id] -> FCode [LocalReg] bindArgsToRegs args = mapM bindArgToReg args idToReg :: DynFlags -> NonVoid Id -> LocalReg -- Make a register from an Id, typically a function argument, -- free variable, or case binder -- -- We re-use the Unique from the Id to make it easier to see what is going on -- -- By now the Ids should be uniquely named; else one would worry -- about accidental collision idToReg dflags (NonVoid id) = LocalReg (idUnique id) (case idPrimRep id of VoidRep -> pprPanic "idToReg" (ppr id) _ -> primRepCmmType dflags (idPrimRep id))
olsner/ghc
compiler/codeGen/StgCmmEnv.hs
Haskell
bsd-3-clause
6,443
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE Trustworthy #-} -- can't use Safe due to IsList instance {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.List.NonEmpty -- Copyright : (C) 2011-2015 Edward Kmett, -- (C) 2010 Tony Morris, Oliver Taylor, Eelis van der Weegen -- License : BSD-style (see the file LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- A 'NonEmpty' list is one which always has at least one element, but -- is otherwise identical to the traditional list type in complexity -- and in terms of API. You will almost certainly want to import this -- module @qualified@. -- -- @since 4.9.0.0 ---------------------------------------------------------------------------- module Data.List.NonEmpty ( -- * The type of non-empty streams NonEmpty(..) -- * Non-empty stream transformations , map -- :: (a -> b) -> NonEmpty a -> NonEmpty b , intersperse -- :: a -> NonEmpty a -> NonEmpty a , scanl -- :: Foldable f => (b -> a -> b) -> b -> f a -> NonEmpty b , scanr -- :: Foldable f => (a -> b -> b) -> b -> f a -> NonEmpty b , scanl1 -- :: (a -> a -> a) -> NonEmpty a -> NonEmpty a , scanr1 -- :: (a -> a -> a) -> NonEmpty a -> NonEmpty a , transpose -- :: NonEmpty (NonEmpty a) -> NonEmpty (NonEmpty a) , sortBy -- :: (a -> a -> Ordering) -> NonEmpty a -> NonEmpty a , sortWith -- :: Ord o => (a -> o) -> NonEmpty a -> NonEmpty a -- * Basic functions , length -- :: NonEmpty a -> Int , head -- :: NonEmpty a -> a , tail -- :: NonEmpty a -> [a] , last -- :: NonEmpty a -> a , init -- :: NonEmpty a -> [a] , (<|), cons -- :: a -> NonEmpty a -> NonEmpty a , uncons -- :: NonEmpty a -> (a, Maybe (NonEmpty a)) , unfoldr -- :: (a -> (b, Maybe a)) -> a -> NonEmpty b , sort -- :: NonEmpty a -> NonEmpty a , reverse -- :: NonEmpty a -> NonEmpty a , inits -- :: Foldable f => f a -> NonEmpty a , tails -- :: Foldable f => f a -> NonEmpty a -- * Building streams , iterate -- :: (a -> a) -> a -> NonEmpty a , repeat -- :: a -> NonEmpty a , cycle -- :: NonEmpty a -> NonEmpty a , unfold -- :: (a -> (b, Maybe a) -> a -> NonEmpty b , insert -- :: (Foldable f, Ord a) => a -> f a -> NonEmpty a , some1 -- :: Alternative f => f a -> f (NonEmpty a) -- * Extracting sublists , take -- :: Int -> NonEmpty a -> [a] , drop -- :: Int -> NonEmpty a -> [a] , splitAt -- :: Int -> NonEmpty a -> ([a], [a]) , takeWhile -- :: Int -> NonEmpty a -> [a] , dropWhile -- :: Int -> NonEmpty a -> [a] , span -- :: Int -> NonEmpty a -> ([a],[a]) , break -- :: Int -> NonEmpty a -> ([a],[a]) , filter -- :: (a -> Bool) -> NonEmpty a -> [a] , partition -- :: (a -> Bool) -> NonEmpty a -> ([a],[a]) , group -- :: Foldable f => Eq a => f a -> [NonEmpty a] , groupBy -- :: Foldable f => (a -> a -> Bool) -> f a -> [NonEmpty a] , groupWith -- :: (Foldable f, Eq b) => (a -> b) -> f a -> [NonEmpty a] , groupAllWith -- :: (Foldable f, Ord b) => (a -> b) -> f a -> [NonEmpty a] , group1 -- :: Eq a => NonEmpty a -> NonEmpty (NonEmpty a) , groupBy1 -- :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a) , groupWith1 -- :: (Foldable f, Eq b) => (a -> b) -> f a -> NonEmpty (NonEmpty a) , groupAllWith1 -- :: (Foldable f, Ord b) => (a -> b) -> f a -> NonEmpty (NonEmpty a) -- * Sublist predicates , isPrefixOf -- :: Foldable f => f a -> NonEmpty a -> Bool -- * \"Set\" operations , nub -- :: Eq a => NonEmpty a -> NonEmpty a , nubBy -- :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a -- * Indexing streams , (!!) -- :: NonEmpty a -> Int -> a -- * Zipping and unzipping streams , zip -- :: NonEmpty a -> NonEmpty b -> NonEmpty (a,b) , zipWith -- :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c , unzip -- :: NonEmpty (a, b) -> (NonEmpty a, NonEmpty b) -- * Converting to and from a list , fromList -- :: [a] -> NonEmpty a , toList -- :: NonEmpty a -> [a] , nonEmpty -- :: [a] -> Maybe (NonEmpty a) , xor -- :: NonEmpty a -> Bool ) where import Prelude hiding (break, cycle, drop, dropWhile, filter, foldl, foldr, head, init, iterate, last, length, map, repeat, reverse, scanl, scanl1, scanr, scanr1, span, splitAt, tail, take, takeWhile, unzip, zip, zipWith, (!!)) import qualified Prelude import Control.Applicative (Alternative, many) import Control.Monad (ap) import Control.Monad.Fix import Control.Monad.Zip (MonadZip(..)) import Data.Data (Data) import Data.Foldable hiding (length, toList) import qualified Data.Foldable as Foldable import Data.Function (on) import qualified Data.List as List import Data.Ord (comparing) import qualified GHC.Exts as Exts (IsList(..)) import GHC.Generics (Generic, Generic1) infixr 5 :|, <| -- | Non-empty (and non-strict) list type. -- -- @since 4.9.0.0 data NonEmpty a = a :| [a] deriving ( Eq, Ord, Show, Read, Data, Generic, Generic1 ) instance Exts.IsList (NonEmpty a) where type Item (NonEmpty a) = a fromList = fromList toList = toList instance MonadFix NonEmpty where mfix f = case fix (f . head) of ~(x :| _) -> x :| mfix (tail . f) instance MonadZip NonEmpty where mzip = zip mzipWith = zipWith munzip = unzip -- | Number of elements in 'NonEmpty' list. length :: NonEmpty a -> Int length (_ :| xs) = 1 + Prelude.length xs -- | Compute n-ary logic exclusive OR operation on 'NonEmpty' list. xor :: NonEmpty Bool -> Bool xor (x :| xs) = foldr xor' x xs where xor' True y = not y xor' False y = y -- | 'unfold' produces a new stream by repeatedly applying the unfolding -- function to the seed value to produce an element of type @b@ and a new -- seed value. When the unfolding function returns 'Nothing' instead of -- a new seed value, the stream ends. unfold :: (a -> (b, Maybe a)) -> a -> NonEmpty b unfold f a = case f a of (b, Nothing) -> b :| [] (b, Just c) -> b <| unfold f c -- | 'nonEmpty' efficiently turns a normal list into a 'NonEmpty' stream, -- producing 'Nothing' if the input is empty. nonEmpty :: [a] -> Maybe (NonEmpty a) nonEmpty [] = Nothing nonEmpty (a:as) = Just (a :| as) -- | 'uncons' produces the first element of the stream, and a stream of the -- remaining elements, if any. uncons :: NonEmpty a -> (a, Maybe (NonEmpty a)) uncons ~(a :| as) = (a, nonEmpty as) -- | The 'unfoldr' function is analogous to "Data.List"'s -- 'Data.List.unfoldr' operation. unfoldr :: (a -> (b, Maybe a)) -> a -> NonEmpty b unfoldr f a = case f a of (b, mc) -> b :| maybe [] go mc where go c = case f c of (d, me) -> d : maybe [] go me instance Functor NonEmpty where fmap f ~(a :| as) = f a :| fmap f as b <$ ~(_ :| as) = b :| (b <$ as) instance Applicative NonEmpty where pure a = a :| [] (<*>) = ap instance Monad NonEmpty where ~(a :| as) >>= f = b :| (bs ++ bs') where b :| bs = f a bs' = as >>= toList . f instance Traversable NonEmpty where traverse f ~(a :| as) = (:|) <$> f a <*> traverse f as instance Foldable NonEmpty where foldr f z ~(a :| as) = f a (foldr f z as) foldl f z ~(a :| as) = foldl f (f z a) as foldl1 f ~(a :| as) = foldl f a as foldMap f ~(a :| as) = f a `mappend` foldMap f as fold ~(m :| ms) = m `mappend` fold ms -- | Extract the first element of the stream. head :: NonEmpty a -> a head ~(a :| _) = a -- | Extract the possibly-empty tail of the stream. tail :: NonEmpty a -> [a] tail ~(_ :| as) = as -- | Extract the last element of the stream. last :: NonEmpty a -> a last ~(a :| as) = List.last (a : as) -- | Extract everything except the last element of the stream. init :: NonEmpty a -> [a] init ~(a :| as) = List.init (a : as) -- | Prepend an element to the stream. (<|) :: a -> NonEmpty a -> NonEmpty a a <| ~(b :| bs) = a :| b : bs -- | Synonym for '<|'. cons :: a -> NonEmpty a -> NonEmpty a cons = (<|) -- | Sort a stream. sort :: Ord a => NonEmpty a -> NonEmpty a sort = lift List.sort -- | Converts a normal list to a 'NonEmpty' stream. -- -- Raises an error if given an empty list. fromList :: [a] -> NonEmpty a fromList (a:as) = a :| as fromList [] = error "NonEmpty.fromList: empty list" -- | Convert a stream to a normal list efficiently. toList :: NonEmpty a -> [a] toList ~(a :| as) = a : as -- | Lift list operations to work on a 'NonEmpty' stream. -- -- /Beware/: If the provided function returns an empty list, -- this will raise an error. lift :: Foldable f => ([a] -> [b]) -> f a -> NonEmpty b lift f = fromList . f . Foldable.toList -- | Map a function over a 'NonEmpty' stream. map :: (a -> b) -> NonEmpty a -> NonEmpty b map f ~(a :| as) = f a :| fmap f as -- | The 'inits' function takes a stream @xs@ and returns all the -- finite prefixes of @xs@. inits :: Foldable f => f a -> NonEmpty [a] inits = fromList . List.inits . Foldable.toList -- | The 'tails' function takes a stream @xs@ and returns all the -- suffixes of @xs@. tails :: Foldable f => f a -> NonEmpty [a] tails = fromList . List.tails . Foldable.toList -- | @'insert' x xs@ inserts @x@ into the last position in @xs@ where it -- is still less than or equal to the next element. In particular, if the -- list is sorted beforehand, the result will also be sorted. insert :: (Foldable f, Ord a) => a -> f a -> NonEmpty a insert a = fromList . List.insert a . Foldable.toList -- | @'some1' x@ sequences @x@ one or more times. some1 :: Alternative f => f a -> f (NonEmpty a) some1 x = (:|) <$> x <*> many x -- | 'scanl' is similar to 'foldl', but returns a stream of successive -- reduced values from the left: -- -- > scanl f z [x1, x2, ...] == z :| [z `f` x1, (z `f` x1) `f` x2, ...] -- -- Note that -- -- > last (scanl f z xs) == foldl f z xs. scanl :: Foldable f => (b -> a -> b) -> b -> f a -> NonEmpty b scanl f z = fromList . List.scanl f z . Foldable.toList -- | 'scanr' is the right-to-left dual of 'scanl'. -- Note that -- -- > head (scanr f z xs) == foldr f z xs. scanr :: Foldable f => (a -> b -> b) -> b -> f a -> NonEmpty b scanr f z = fromList . List.scanr f z . Foldable.toList -- | 'scanl1' is a variant of 'scanl' that has no starting value argument: -- -- > scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...] scanl1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a scanl1 f ~(a :| as) = fromList (List.scanl f a as) -- | 'scanr1' is a variant of 'scanr' that has no starting value argument. scanr1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a scanr1 f ~(a :| as) = fromList (List.scanr1 f (a:as)) -- | 'intersperse x xs' alternates elements of the list with copies of @x@. -- -- > intersperse 0 (1 :| [2,3]) == 1 :| [0,2,0,3] intersperse :: a -> NonEmpty a -> NonEmpty a intersperse a ~(b :| bs) = b :| case bs of [] -> [] _ -> a : List.intersperse a bs -- | @'iterate' f x@ produces the infinite sequence -- of repeated applications of @f@ to @x@. -- -- > iterate f x = x :| [f x, f (f x), ..] iterate :: (a -> a) -> a -> NonEmpty a iterate f a = a :| List.iterate f (f a) -- | @'cycle' xs@ returns the infinite repetition of @xs@: -- -- > cycle [1,2,3] = 1 :| [2,3,1,2,3,...] cycle :: NonEmpty a -> NonEmpty a cycle = fromList . List.cycle . toList -- | 'reverse' a finite NonEmpty stream. reverse :: NonEmpty a -> NonEmpty a reverse = lift List.reverse -- | @'repeat' x@ returns a constant stream, where all elements are -- equal to @x@. repeat :: a -> NonEmpty a repeat a = a :| List.repeat a -- | @'take' n xs@ returns the first @n@ elements of @xs@. take :: Int -> NonEmpty a -> [a] take n = List.take n . toList -- | @'drop' n xs@ drops the first @n@ elements off the front of -- the sequence @xs@. drop :: Int -> NonEmpty a -> [a] drop n = List.drop n . toList -- | @'splitAt' n xs@ returns a pair consisting of the prefix of @xs@ -- of length @n@ and the remaining stream immediately following this prefix. -- -- > 'splitAt' n xs == ('take' n xs, 'drop' n xs) -- > xs == ys ++ zs where (ys, zs) = 'splitAt' n xs splitAt :: Int -> NonEmpty a -> ([a],[a]) splitAt n = List.splitAt n . toList -- | @'takeWhile' p xs@ returns the longest prefix of the stream -- @xs@ for which the predicate @p@ holds. takeWhile :: (a -> Bool) -> NonEmpty a -> [a] takeWhile p = List.takeWhile p . toList -- | @'dropWhile' p xs@ returns the suffix remaining after -- @'takeWhile' p xs@. dropWhile :: (a -> Bool) -> NonEmpty a -> [a] dropWhile p = List.dropWhile p . toList -- | @'span' p xs@ returns the longest prefix of @xs@ that satisfies -- @p@, together with the remainder of the stream. -- -- > 'span' p xs == ('takeWhile' p xs, 'dropWhile' p xs) -- > xs == ys ++ zs where (ys, zs) = 'span' p xs span :: (a -> Bool) -> NonEmpty a -> ([a], [a]) span p = List.span p . toList -- | The @'break' p@ function is equivalent to @'span' (not . p)@. break :: (a -> Bool) -> NonEmpty a -> ([a], [a]) break p = span (not . p) -- | @'filter' p xs@ removes any elements from @xs@ that do not satisfy @p@. filter :: (a -> Bool) -> NonEmpty a -> [a] filter p = List.filter p . toList -- | The 'partition' function takes a predicate @p@ and a stream -- @xs@, and returns a pair of lists. The first list corresponds to the -- elements of @xs@ for which @p@ holds; the second corresponds to the -- elements of @xs@ for which @p@ does not hold. -- -- > 'partition' p xs = ('filter' p xs, 'filter' (not . p) xs) partition :: (a -> Bool) -> NonEmpty a -> ([a], [a]) partition p = List.partition p . toList -- | The 'group' function takes a stream and returns a list of -- streams such that flattening the resulting list is equal to the -- argument. Moreover, each stream in the resulting list -- contains only equal elements. For example, in list notation: -- -- > 'group' $ 'cycle' "Mississippi" -- > = "M" : "i" : "ss" : "i" : "ss" : "i" : "pp" : "i" : "M" : "i" : ... group :: (Foldable f, Eq a) => f a -> [NonEmpty a] group = groupBy (==) -- | 'groupBy' operates like 'group', but uses the provided equality -- predicate instead of `==`. groupBy :: Foldable f => (a -> a -> Bool) -> f a -> [NonEmpty a] groupBy eq0 = go eq0 . Foldable.toList where go _ [] = [] go eq (x : xs) = (x :| ys) : groupBy eq zs where (ys, zs) = List.span (eq x) xs -- | 'groupWith' operates like 'group', but uses the provided projection when -- comparing for equality groupWith :: (Foldable f, Eq b) => (a -> b) -> f a -> [NonEmpty a] groupWith f = groupBy ((==) `on` f) -- | 'groupAllWith' operates like 'groupWith', but sorts the list -- first so that each equivalence class has, at most, one list in the -- output groupAllWith :: (Ord b) => (a -> b) -> [a] -> [NonEmpty a] groupAllWith f = groupWith f . List.sortBy (compare `on` f) -- | 'group1' operates like 'group', but uses the knowledge that its -- input is non-empty to produce guaranteed non-empty output. group1 :: Eq a => NonEmpty a -> NonEmpty (NonEmpty a) group1 = groupBy1 (==) -- | 'groupBy1' is to 'group1' as 'groupBy' is to 'group'. groupBy1 :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a) groupBy1 eq (x :| xs) = (x :| ys) :| groupBy eq zs where (ys, zs) = List.span (eq x) xs -- | 'groupWith1' is to 'group1' as 'groupWith' is to 'group' groupWith1 :: (Eq b) => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a) groupWith1 f = groupBy1 ((==) `on` f) -- | 'groupAllWith1' is to 'groupWith1' as 'groupAllWith' is to 'groupWith' groupAllWith1 :: (Ord b) => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a) groupAllWith1 f = groupWith1 f . sortWith f -- | The 'isPrefix' function returns @True@ if the first argument is -- a prefix of the second. isPrefixOf :: Eq a => [a] -> NonEmpty a -> Bool isPrefixOf [] _ = True isPrefixOf (y:ys) (x :| xs) = (y == x) && List.isPrefixOf ys xs -- | @xs !! n@ returns the element of the stream @xs@ at index -- @n@. Note that the head of the stream has index 0. -- -- /Beware/: a negative or out-of-bounds index will cause an error. (!!) :: NonEmpty a -> Int -> a (!!) ~(x :| xs) n | n == 0 = x | n > 0 = xs List.!! (n - 1) | otherwise = error "NonEmpty.!! negative argument" -- | The 'zip' function takes two streams and returns a stream of -- corresponding pairs. zip :: NonEmpty a -> NonEmpty b -> NonEmpty (a,b) zip ~(x :| xs) ~(y :| ys) = (x, y) :| List.zip xs ys -- | The 'zipWith' function generalizes 'zip'. Rather than tupling -- the elements, the elements are combined using the function -- passed as the first argument. zipWith :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c zipWith f ~(x :| xs) ~(y :| ys) = f x y :| List.zipWith f xs ys -- | The 'unzip' function is the inverse of the 'zip' function. unzip :: Functor f => f (a,b) -> (f a, f b) unzip xs = (fst <$> xs, snd <$> xs) -- | The 'nub' function removes duplicate elements from a list. In -- particular, it keeps only the first occurence of each element. -- (The name 'nub' means \'essence\'.) -- It is a special case of 'nubBy', which allows the programmer to -- supply their own inequality test. nub :: Eq a => NonEmpty a -> NonEmpty a nub = nubBy (==) -- | The 'nubBy' function behaves just like 'nub', except it uses a -- user-supplied equality predicate instead of the overloaded '==' -- function. nubBy :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a nubBy eq (a :| as) = a :| List.nubBy eq (List.filter (\b -> not (eq a b)) as) -- | 'transpose' for 'NonEmpty', behaves the same as 'Data.List.transpose' -- The rows/columns need not be the same length, in which case -- > transpose . transpose /= id transpose :: NonEmpty (NonEmpty a) -> NonEmpty (NonEmpty a) transpose = fmap fromList . fromList . List.transpose . Foldable.toList . fmap Foldable.toList -- | 'sortBy' for 'NonEmpty', behaves the same as 'Data.List.sortBy' sortBy :: (a -> a -> Ordering) -> NonEmpty a -> NonEmpty a sortBy f = lift (List.sortBy f) -- | 'sortWith' for 'NonEmpty', behaves the same as: -- -- > sortBy . comparing sortWith :: Ord o => (a -> o) -> NonEmpty a -> NonEmpty a sortWith = sortBy . comparing
da-x/ghc
libraries/base/Data/List/NonEmpty.hs
Haskell
bsd-3-clause
18,767
module Network.HTTP.UserAgent where import Control.Monad.Error import Data.ByteString.Lazy.Char8 ( ByteString ) import qualified Data.ByteString.Lazy.Char8 as BS import Network.HTTP import Network.URI import Data.Maybe ( maybe ) ----------------------------------------------------------------------------- defaultRequest :: Request defaultRequest = Request { rqURI = undefined , rqMethod = GET , rqHeaders = [] , rqBody = BS.empty } uri :: (MonadError e m, Monad m, HTTPError e) => String -> Request -> m Request uri str r = do u <- parseURI' str; return $ r { rqURI = u } headerAdderM :: Monad m => m Header -> Request -> m Request headerAdderM hm r@(Request{rqHeaders = hs}) = do h <- hm; return $ r { rqHeaders = h:hs } headerAdder :: Monad m => Header -> Request -> m Request headerAdder h r@(Request{rqHeaders = hs}) = return $ r { rqHeaders = h:hs } hExpires :: Monad m => Int -> Request -> m Request hExpires n = headerAdder (Header HdrExpires (show n)) hReferer :: (MonadError e m, HTTPError e, Monad m) => String -> Request -> m Request hReferer str = headerAdderM $ do uri <- parseURI' str return $ Header HdrReferer (show uri) exampleRequest :: (MonadError e m, Monad m, HTTPError e) => m Request exampleRequest = mkRequest [uri "http://www.google.com", hExpires 4] mkRequest :: (MonadError e m, Monad m, HTTPError e) => [Request -> m Request] -> m Request mkRequest mods = f mods defaultRequest where f [] x = return x f (m:ms) x = m x >>= f ms parseURI' :: (MonadError e m, HTTPError e) => String -> m URI parseURI' str = maybe (throwHTTPError URIErr) return $ parseURI str -- | Perform HTTP request after parsing the URI string. get :: (MonadError e m, MonadIO m, HTTPError e) => String -> m Response get uriString = mkRequest [uri uriString] >>= simpleHTTP -- | Directly get the content of the given String which is parsed as a URI. -- FIXME: Not sure this is a good name getContent :: (MonadError e m, MonadIO m, HTTPError e) => String -> m ByteString getContent uriString = get uriString >>= return . rspBody
beni55/HTTP
Network/HTTP/UserAgent.hs
Haskell
bsd-3-clause
2,287
module Options.Misc where import Types miscOptions :: [Flag] miscOptions = [ flag { flagName = "-jN" , flagDescription = "When compiling with :ghc-flag:`--make`, compile ⟨N⟩ modules in parallel." , flagType = DynamicFlag } , flag { flagName = "-fno-hi-version-check" , flagDescription = "Don't complain about ``.hi`` file mismatches" , flagType = DynamicFlag } , flag { flagName = "-fhistory-size" , flagDescription = "Set simplification history size" , flagType = DynamicFlag } , flag { flagName = "-fno-ghci-history" , flagDescription = "Do not use the load/store the GHCi command history from/to "++ "``ghci_history``." , flagType = DynamicFlag } , flag { flagName = "-fno-ghci-sandbox" , flagDescription = "Turn off the GHCi sandbox. Means computations are run in "++ "the main thread, rather than a forked thread." , flagType = DynamicFlag } , flag { flagName = "-freverse-errors" , flagDescription = "Display errors in GHC/GHCi sorted by reverse order of "++ "source code line numbers." , flagType = DynamicFlag , flagReverse = "-fno-reverse-errors" } , flag { flagName = "-flocal-ghci-history" , flagDescription = "Use current directory for the GHCi command history "++ "file ``.ghci-history``." , flagType = DynamicFlag , flagReverse = "-fno-local-ghci-history" } ]
olsner/ghc
utils/mkUserGuidePart/Options/Misc.hs
Haskell
bsd-3-clause
1,602
-- parser produced by Happy Version 1.11 module PropParser (parse) where import PropSyntax import PropSyntaxUtil import ParseMonad import Lexer import LexUtil(readInteger, readRational) import ParseUtil --import Rewrite import IOExts import Char(showLitChar) data HappyAbsSyn = HappyTerminal Token | HappyErrorToken Int | HappyAbsSyn4 (HsModuleR) | HappyAbsSyn5 (([HsImportDecl], [HsDecl])) | HappyAbsSyn7 (()) | HappyAbsSyn8 (Maybe [HsExportSpec]) | HappyAbsSyn9 ([HsExportSpec]) | HappyAbsSyn12 (HsExportSpec) | HappyAbsSyn13 ([HsName]) | HappyAbsSyn14 (HsName) | HappyAbsSyn15 ([HsImportDecl]) | HappyAbsSyn16 (HsImportDecl) | HappyAbsSyn17 (Bool) | HappyAbsSyn18 (Maybe Module) | HappyAbsSyn19 (Maybe (Bool, [HsImportSpec])) | HappyAbsSyn20 ((Bool, [HsImportSpec])) | HappyAbsSyn21 ([HsImportSpec]) | HappyAbsSyn22 (HsImportSpec) | HappyAbsSyn25 ([HsDecl]) | HappyAbsSyn26 (HsDecl) | HappyAbsSyn27 (Int) | HappyAbsSyn28 (HsAssoc) | HappyAbsSyn29 ([HsIdent]) | HappyAbsSyn37 (HsType) | HappyAbsSyn41 (([HsType],HsType)) | HappyAbsSyn42 ([HsType]) | HappyAbsSyn43 (([HsType], [HsType])) | HappyAbsSyn46 (([HsType], HsName)) | HappyAbsSyn47 ([HsConDecl HsType ]) | HappyAbsSyn48 (HsConDecl HsType) | HappyAbsSyn49 ((HsName, [HsBangType HsType])) | HappyAbsSyn51 (HsBangType HsType) | HappyAbsSyn53 ([([HsName], HsBangType HsType)]) | HappyAbsSyn54 (([HsName], HsBangType HsType)) | HappyAbsSyn66 (HsRhs HsExp) | HappyAbsSyn67 ([(SrcLoc, HsExp, HsExp)]) | HappyAbsSyn68 ((SrcLoc, HsExp, HsExp)) | HappyAbsSyn69 (HsExp) | HappyAbsSyn73 ([HsExp]) | HappyAbsSyn80 ([HsStmtAtom HsExp HsPat [HsDecl] ]) | HappyAbsSyn81 (HsStmtAtom HsExp HsPat [HsDecl]) | HappyAbsSyn82 ([HsAlt HsExp HsPat [HsDecl]]) | HappyAbsSyn84 (HsAlt HsExp HsPat [HsDecl]) | HappyAbsSyn88 ([HsStmtAtom HsExp HsPat [HsDecl]]) | HappyAbsSyn91 ([HsFieldUpdate HsExp]) | HappyAbsSyn92 (HsFieldUpdate HsExp) | HappyAbsSyn102 (HsIdent) | HappyAbsSyn115 (SrcLoc) | HappyAbsSyn119 (Module) | HappyAbsSyn126 (HsQuantifier) type HappyReduction = Int -> (Token) -> HappyState (Token) (HappyStk HappyAbsSyn -> PM(HappyAbsSyn)) -> [HappyState (Token) (HappyStk HappyAbsSyn -> PM(HappyAbsSyn))] -> HappyStk HappyAbsSyn -> PM(HappyAbsSyn) action_0, action_1, action_2, action_3, action_4, action_5, action_6, action_7, action_8, action_9, action_10, action_11, action_12, action_13, action_14, action_15, action_16, action_17, action_18, action_19, action_20, action_21, action_22, action_23, action_24, action_25, action_26, action_27, action_28, action_29, action_30, action_31, action_32, action_33, action_34, action_35, action_36, action_37, action_38, action_39, action_40, action_41, action_42, action_43, action_44, action_45, action_46, action_47, action_48, action_49, action_50, action_51, action_52, action_53, action_54, action_55, action_56, action_57, action_58, action_59, action_60, action_61, action_62, action_63, action_64, action_65, action_66, action_67, action_68, action_69, action_70, action_71, action_72, action_73, action_74, action_75, action_76, action_77, action_78, action_79, action_80, action_81, action_82, action_83, action_84, action_85, action_86, action_87, action_88, action_89, action_90, action_91, action_92, action_93, action_94, action_95, action_96, action_97, action_98, action_99, action_100, action_101, action_102, action_103, action_104, action_105, action_106, action_107, action_108, action_109, action_110, action_111, action_112, action_113, action_114, action_115, action_116, action_117, action_118, action_119, action_120, action_121, action_122, action_123, action_124, action_125, action_126, action_127, action_128, action_129, action_130, action_131, action_132, action_133, action_134, action_135, action_136, action_137, action_138, action_139, action_140, action_141, action_142, action_143, action_144, action_145, action_146, action_147, action_148, action_149, action_150, action_151, action_152, action_153, action_154, action_155, action_156, action_157, action_158, action_159, action_160, action_161, action_162, action_163, action_164, action_165, action_166, action_167, action_168, action_169, action_170, action_171, action_172, action_173, action_174, action_175, action_176, action_177, action_178, action_179, action_180, action_181, action_182, action_183, action_184, action_185, action_186, action_187, action_188, action_189, action_190, action_191, action_192, action_193, action_194, action_195, action_196, action_197, action_198, action_199, action_200, action_201, action_202, action_203, action_204, action_205, action_206, action_207, action_208, action_209, action_210, action_211, action_212, action_213, action_214, action_215, action_216, action_217, action_218, action_219, action_220, action_221, action_222, action_223, action_224, action_225, action_226, action_227, action_228, action_229, action_230, action_231, action_232, action_233, action_234, action_235, action_236, action_237, action_238, action_239, action_240, action_241, action_242, action_243, action_244, action_245, action_246, action_247, action_248, action_249, action_250, action_251, action_252, action_253, action_254, action_255, action_256, action_257, action_258, action_259, action_260, action_261, action_262, action_263, action_264, action_265, action_266, action_267, action_268, action_269, action_270, action_271, action_272, action_273, action_274, action_275, action_276, action_277, action_278, action_279, action_280, action_281, action_282, action_283, action_284, action_285, action_286, action_287, action_288, action_289, action_290, action_291, action_292, action_293, action_294, action_295, action_296, action_297, action_298, action_299, action_300, action_301, action_302, action_303, action_304, action_305, action_306, action_307, action_308, action_309, action_310, action_311, action_312, action_313, action_314, action_315, action_316, action_317, action_318, action_319, action_320, action_321, action_322, action_323, action_324, action_325, action_326, action_327, action_328, action_329, action_330, action_331, action_332, action_333, action_334, action_335, action_336, action_337, action_338, action_339, action_340, action_341, action_342, action_343, action_344, action_345, action_346, action_347, action_348, action_349, action_350, action_351, action_352, action_353, action_354, action_355, action_356, action_357, action_358, action_359, action_360, action_361, action_362, action_363, action_364, action_365, action_366, action_367, action_368, action_369, action_370, action_371, action_372, action_373, action_374, action_375, action_376, action_377, action_378, action_379, action_380, action_381, action_382, action_383, action_384, action_385, action_386, action_387, action_388, action_389, action_390, action_391, action_392, action_393, action_394, action_395, action_396, action_397, action_398, action_399, action_400, action_401, action_402, action_403, action_404, action_405, action_406, action_407, action_408, action_409, action_410, action_411, action_412, action_413, action_414, action_415, action_416, action_417, action_418, action_419, action_420, action_421, action_422, action_423, action_424, action_425, action_426, action_427, action_428, action_429, action_430, action_431, action_432, action_433, action_434, action_435, action_436, action_437, action_438, action_439, action_440, action_441, action_442, action_443, action_444, action_445, action_446, action_447, action_448, action_449, action_450, action_451, action_452, action_453, action_454, action_455, action_456, action_457, action_458, action_459, action_460, action_461, action_462, action_463, action_464, action_465, action_466, action_467, action_468, action_469, action_470, action_471, action_472, action_473, action_474, action_475, action_476, action_477, action_478, action_479, action_480, action_481, action_482, action_483, action_484, action_485, action_486, action_487, action_488, action_489, action_490, action_491, action_492, action_493, action_494, action_495, action_496, action_497, action_498, action_499, action_500, action_501, action_502, action_503, action_504, action_505, action_506, action_507, action_508, action_509, action_510, action_511, action_512, action_513, action_514, action_515, action_516, action_517, action_518, action_519, action_520, action_521, action_522, action_523, action_524, action_525, action_526, action_527, action_528, action_529, action_530, action_531, action_532 :: Int -> HappyReduction happyReduce_1, happyReduce_2, happyReduce_3, happyReduce_4, happyReduce_5, happyReduce_6, happyReduce_7, happyReduce_8, happyReduce_9, happyReduce_10, happyReduce_11, happyReduce_12, happyReduce_13, happyReduce_14, happyReduce_15, happyReduce_16, happyReduce_17, happyReduce_18, happyReduce_19, happyReduce_20, happyReduce_21, happyReduce_22, happyReduce_23, happyReduce_24, happyReduce_25, happyReduce_26, happyReduce_27, happyReduce_28, happyReduce_29, happyReduce_30, happyReduce_31, happyReduce_32, happyReduce_33, happyReduce_34, happyReduce_35, happyReduce_36, happyReduce_37, happyReduce_38, happyReduce_39, happyReduce_40, happyReduce_41, happyReduce_42, happyReduce_43, happyReduce_44, happyReduce_45, happyReduce_46, happyReduce_47, happyReduce_48, happyReduce_49, happyReduce_50, happyReduce_51, happyReduce_52, happyReduce_53, happyReduce_54, happyReduce_55, happyReduce_56, happyReduce_57, happyReduce_58, happyReduce_59, happyReduce_60, happyReduce_61, happyReduce_62, happyReduce_63, happyReduce_64, happyReduce_65, happyReduce_66, happyReduce_67, happyReduce_68, happyReduce_69, happyReduce_70, happyReduce_71, happyReduce_72, happyReduce_73, happyReduce_74, happyReduce_75, happyReduce_76, happyReduce_77, happyReduce_78, happyReduce_79, happyReduce_80, happyReduce_81, happyReduce_82, happyReduce_83, happyReduce_84, happyReduce_85, happyReduce_86, happyReduce_87, happyReduce_88, happyReduce_89, happyReduce_90, happyReduce_91, happyReduce_92, happyReduce_93, happyReduce_94, happyReduce_95, happyReduce_96, happyReduce_97, happyReduce_98, happyReduce_99, happyReduce_100, happyReduce_101, happyReduce_102, happyReduce_103, happyReduce_104, happyReduce_105, happyReduce_106, happyReduce_107, happyReduce_108, happyReduce_109, happyReduce_110, happyReduce_111, happyReduce_112, happyReduce_113, happyReduce_114, happyReduce_115, happyReduce_116, happyReduce_117, happyReduce_118, happyReduce_119, happyReduce_120, happyReduce_121, happyReduce_122, happyReduce_123, happyReduce_124, happyReduce_125, happyReduce_126, happyReduce_127, happyReduce_128, happyReduce_129, happyReduce_130, happyReduce_131, happyReduce_132, happyReduce_133, happyReduce_134, happyReduce_135, happyReduce_136, happyReduce_137, happyReduce_138, happyReduce_139, happyReduce_140, happyReduce_141, happyReduce_142, happyReduce_143, happyReduce_144, happyReduce_145, happyReduce_146, happyReduce_147, happyReduce_148, happyReduce_149, happyReduce_150, happyReduce_151, happyReduce_152, happyReduce_153, happyReduce_154, happyReduce_155, happyReduce_156, happyReduce_157, happyReduce_158, happyReduce_159, happyReduce_160, happyReduce_161, happyReduce_162, happyReduce_163, happyReduce_164, happyReduce_165, happyReduce_166, happyReduce_167, happyReduce_168, happyReduce_169, happyReduce_170, happyReduce_171, happyReduce_172, happyReduce_173, happyReduce_174, happyReduce_175, happyReduce_176, happyReduce_177, happyReduce_178, happyReduce_179, happyReduce_180, happyReduce_181, happyReduce_182, happyReduce_183, happyReduce_184, happyReduce_185, happyReduce_186, happyReduce_187, happyReduce_188, happyReduce_189, happyReduce_190, happyReduce_191, happyReduce_192, happyReduce_193, happyReduce_194, happyReduce_195, happyReduce_196, happyReduce_197, happyReduce_198, happyReduce_199, happyReduce_200, happyReduce_201, happyReduce_202, happyReduce_203, happyReduce_204, happyReduce_205, happyReduce_206, happyReduce_207, happyReduce_208, happyReduce_209, happyReduce_210, happyReduce_211, happyReduce_212, happyReduce_213, happyReduce_214, happyReduce_215, happyReduce_216, happyReduce_217, happyReduce_218, happyReduce_219, happyReduce_220, happyReduce_221, happyReduce_222, happyReduce_223, happyReduce_224, happyReduce_225, happyReduce_226, happyReduce_227, happyReduce_228, happyReduce_229, happyReduce_230, happyReduce_231, happyReduce_232, happyReduce_233, happyReduce_234, happyReduce_235, happyReduce_236, happyReduce_237, happyReduce_238, happyReduce_239, happyReduce_240, happyReduce_241, happyReduce_242, happyReduce_243, happyReduce_244, happyReduce_245, happyReduce_246, happyReduce_247, happyReduce_248, happyReduce_249, happyReduce_250, happyReduce_251, happyReduce_252, happyReduce_253, happyReduce_254, happyReduce_255, happyReduce_256, happyReduce_257, happyReduce_258, happyReduce_259, happyReduce_260, happyReduce_261, happyReduce_262, happyReduce_263, happyReduce_264, happyReduce_265, happyReduce_266, happyReduce_267, happyReduce_268, happyReduce_269, happyReduce_270, happyReduce_271, happyReduce_272, happyReduce_273, happyReduce_274, happyReduce_275, happyReduce_276, happyReduce_277, happyReduce_278, happyReduce_279, happyReduce_280, happyReduce_281, happyReduce_282, happyReduce_283, happyReduce_284, happyReduce_285, happyReduce_286, happyReduce_287, happyReduce_288, happyReduce_289, happyReduce_290, happyReduce_291, happyReduce_292, happyReduce_293, happyReduce_294, happyReduce_295 :: HappyReduction action_0 (145) = happyShift action_6 action_0 (182) = happyShift action_2 action_0 (4) = happyGoto action_3 action_0 (5) = happyGoto action_4 action_0 (118) = happyGoto action_5 action_0 _ = happyReduce_282 action_1 (182) = happyShift action_2 action_1 _ = happyFail action_2 (130) = happyShift action_73 action_2 (119) = happyGoto action_72 action_2 _ = happyFail action_3 (195) = happyAccept action_3 _ = happyFail action_4 _ = happyReduce_2 action_5 (128) = happyShift action_34 action_5 (129) = happyShift action_35 action_5 (130) = happyShift action_36 action_5 (131) = happyShift action_37 action_5 (132) = happyShift action_38 action_5 (137) = happyShift action_39 action_5 (138) = happyShift action_40 action_5 (139) = happyShift action_41 action_5 (140) = happyShift action_42 action_5 (141) = happyShift action_43 action_5 (142) = happyShift action_44 action_5 (148) = happyShift action_45 action_5 (151) = happyShift action_46 action_5 (157) = happyShift action_47 action_5 (162) = happyShift action_48 action_5 (165) = happyShift action_49 action_5 (166) = happyShift action_50 action_5 (167) = happyShift action_51 action_5 (168) = happyShift action_52 action_5 (169) = happyShift action_53 action_5 (171) = happyShift action_54 action_5 (173) = happyShift action_55 action_5 (174) = happyShift action_56 action_5 (175) = happyShift action_57 action_5 (177) = happyShift action_58 action_5 (178) = happyShift action_59 action_5 (179) = happyShift action_60 action_5 (180) = happyShift action_61 action_5 (181) = happyShift action_62 action_5 (183) = happyShift action_63 action_5 (186) = happyShift action_64 action_5 (188) = happyShift action_65 action_5 (189) = happyShift action_66 action_5 (190) = happyShift action_67 action_5 (191) = happyShift action_68 action_5 (192) = happyShift action_69 action_5 (193) = happyShift action_70 action_5 (194) = happyShift action_71 action_5 (6) = happyGoto action_8 action_5 (15) = happyGoto action_9 action_5 (16) = happyGoto action_10 action_5 (25) = happyGoto action_11 action_5 (26) = happyGoto action_12 action_5 (28) = happyGoto action_13 action_5 (30) = happyGoto action_14 action_5 (33) = happyGoto action_15 action_5 (35) = happyGoto action_16 action_5 (36) = happyGoto action_17 action_5 (64) = happyGoto action_18 action_5 (70) = happyGoto action_19 action_5 (71) = happyGoto action_20 action_5 (72) = happyGoto action_21 action_5 (74) = happyGoto action_22 action_5 (75) = happyGoto action_23 action_5 (93) = happyGoto action_24 action_5 (95) = happyGoto action_25 action_5 (97) = happyGoto action_26 action_5 (104) = happyGoto action_27 action_5 (105) = happyGoto action_28 action_5 (106) = happyGoto action_29 action_5 (108) = happyGoto action_30 action_5 (114) = happyGoto action_31 action_5 (125) = happyGoto action_32 action_5 (126) = happyGoto action_33 action_5 _ = happyReduce_8 action_6 (117) = happyGoto action_7 action_6 _ = happyReduce_281 action_7 (128) = happyShift action_34 action_7 (129) = happyShift action_35 action_7 (130) = happyShift action_36 action_7 (131) = happyShift action_37 action_7 (132) = happyShift action_38 action_7 (137) = happyShift action_39 action_7 (138) = happyShift action_40 action_7 (139) = happyShift action_41 action_7 (140) = happyShift action_42 action_7 (141) = happyShift action_43 action_7 (142) = happyShift action_44 action_7 (148) = happyShift action_45 action_7 (151) = happyShift action_46 action_7 (157) = happyShift action_47 action_7 (162) = happyShift action_48 action_7 (165) = happyShift action_49 action_7 (166) = happyShift action_50 action_7 (167) = happyShift action_51 action_7 (168) = happyShift action_52 action_7 (169) = happyShift action_53 action_7 (171) = happyShift action_54 action_7 (173) = happyShift action_55 action_7 (174) = happyShift action_56 action_7 (175) = happyShift action_57 action_7 (177) = happyShift action_58 action_7 (178) = happyShift action_59 action_7 (179) = happyShift action_60 action_7 (180) = happyShift action_61 action_7 (181) = happyShift action_62 action_7 (183) = happyShift action_63 action_7 (186) = happyShift action_64 action_7 (188) = happyShift action_65 action_7 (189) = happyShift action_66 action_7 (190) = happyShift action_67 action_7 (191) = happyShift action_68 action_7 (192) = happyShift action_69 action_7 (193) = happyShift action_70 action_7 (194) = happyShift action_71 action_7 (6) = happyGoto action_148 action_7 (15) = happyGoto action_9 action_7 (16) = happyGoto action_10 action_7 (25) = happyGoto action_11 action_7 (26) = happyGoto action_12 action_7 (28) = happyGoto action_13 action_7 (30) = happyGoto action_14 action_7 (33) = happyGoto action_15 action_7 (35) = happyGoto action_16 action_7 (36) = happyGoto action_17 action_7 (64) = happyGoto action_18 action_7 (70) = happyGoto action_19 action_7 (71) = happyGoto action_20 action_7 (72) = happyGoto action_21 action_7 (74) = happyGoto action_22 action_7 (75) = happyGoto action_23 action_7 (93) = happyGoto action_24 action_7 (95) = happyGoto action_25 action_7 (97) = happyGoto action_26 action_7 (104) = happyGoto action_27 action_7 (105) = happyGoto action_28 action_7 (106) = happyGoto action_29 action_7 (108) = happyGoto action_30 action_7 (114) = happyGoto action_31 action_7 (125) = happyGoto action_32 action_7 (126) = happyGoto action_33 action_7 _ = happyReduce_8 action_8 (1) = happyShift action_146 action_8 (147) = happyShift action_147 action_8 (116) = happyGoto action_145 action_8 _ = happyFail action_9 (144) = happyShift action_144 action_9 (7) = happyGoto action_143 action_9 _ = happyReduce_10 action_10 _ = happyReduce_30 action_11 (144) = happyShift action_142 action_11 (7) = happyGoto action_141 action_11 _ = happyReduce_10 action_12 _ = happyReduce_75 action_13 (115) = happyGoto action_140 action_13 _ = happyReduce_278 action_14 _ = happyReduce_52 action_15 _ = happyReduce_69 action_16 _ = happyReduce_74 action_17 (150) = happyShift action_139 action_17 (115) = happyGoto action_138 action_17 _ = happyReduce_278 action_18 _ = happyReduce_76 action_19 (132) = happyShift action_137 action_19 (133) = happyShift action_118 action_19 (134) = happyShift action_119 action_19 (135) = happyShift action_120 action_19 (136) = happyShift action_121 action_19 (152) = happyShift action_124 action_19 (153) = happyShift action_125 action_19 (164) = happyShift action_126 action_19 (99) = happyGoto action_109 action_19 (101) = happyGoto action_110 action_19 (103) = happyGoto action_133 action_19 (109) = happyGoto action_134 action_19 (110) = happyGoto action_113 action_19 (111) = happyGoto action_135 action_19 (112) = happyGoto action_115 action_19 (113) = happyGoto action_116 action_19 (115) = happyGoto action_136 action_19 _ = happyReduce_278 action_20 _ = happyReduce_161 action_21 (128) = happyShift action_34 action_21 (129) = happyShift action_35 action_21 (130) = happyShift action_36 action_21 (131) = happyShift action_37 action_21 (137) = happyShift action_39 action_21 (138) = happyShift action_40 action_21 (139) = happyShift action_41 action_21 (140) = happyShift action_42 action_21 (141) = happyShift action_43 action_21 (142) = happyShift action_44 action_21 (148) = happyShift action_45 action_21 (151) = happyShift action_46 action_21 (162) = happyShift action_48 action_21 (165) = happyShift action_49 action_21 (173) = happyShift action_55 action_21 (188) = happyShift action_65 action_21 (74) = happyGoto action_132 action_21 (75) = happyGoto action_23 action_21 (93) = happyGoto action_24 action_21 (95) = happyGoto action_90 action_21 (97) = happyGoto action_26 action_21 (104) = happyGoto action_27 action_21 (105) = happyGoto action_28 action_21 (106) = happyGoto action_29 action_21 (108) = happyGoto action_30 action_21 (114) = happyGoto action_31 action_21 _ = happyReduce_170 action_22 (145) = happyShift action_131 action_22 _ = happyReduce_172 action_23 _ = happyReduce_176 action_24 _ = happyReduce_178 action_25 (150) = happyReduce_82 action_25 (155) = happyReduce_82 action_25 (161) = happyShift action_130 action_25 _ = happyReduce_177 action_26 _ = happyReduce_232 action_27 _ = happyReduce_235 action_28 _ = happyReduce_253 action_29 _ = happyReduce_239 action_30 _ = happyReduce_259 action_31 _ = happyReduce_179 action_32 _ = happyReduce_77 action_33 (128) = happyShift action_34 action_33 (129) = happyShift action_35 action_33 (130) = happyShift action_36 action_33 (131) = happyShift action_37 action_33 (137) = happyShift action_39 action_33 (138) = happyShift action_40 action_33 (139) = happyShift action_41 action_33 (140) = happyShift action_42 action_33 (141) = happyShift action_43 action_33 (142) = happyShift action_44 action_33 (148) = happyShift action_45 action_33 (151) = happyShift action_46 action_33 (162) = happyShift action_48 action_33 (165) = happyShift action_49 action_33 (173) = happyShift action_55 action_33 (188) = happyShift action_65 action_33 (73) = happyGoto action_129 action_33 (74) = happyGoto action_100 action_33 (75) = happyGoto action_23 action_33 (93) = happyGoto action_24 action_33 (95) = happyGoto action_90 action_33 (97) = happyGoto action_26 action_33 (104) = happyGoto action_27 action_33 (105) = happyGoto action_28 action_33 (106) = happyGoto action_29 action_33 (108) = happyGoto action_30 action_33 (114) = happyGoto action_31 action_33 _ = happyFail action_34 _ = happyReduce_255 action_35 _ = happyReduce_254 action_36 _ = happyReduce_263 action_37 _ = happyReduce_260 action_38 (128) = happyShift action_34 action_38 (129) = happyShift action_35 action_38 (130) = happyShift action_36 action_38 (131) = happyShift action_37 action_38 (137) = happyShift action_39 action_38 (138) = happyShift action_40 action_38 (139) = happyShift action_41 action_38 (140) = happyShift action_42 action_38 (141) = happyShift action_43 action_38 (142) = happyShift action_44 action_38 (148) = happyShift action_45 action_38 (151) = happyShift action_46 action_38 (162) = happyShift action_48 action_38 (165) = happyShift action_49 action_38 (173) = happyShift action_55 action_38 (188) = happyShift action_65 action_38 (72) = happyGoto action_128 action_38 (74) = happyGoto action_22 action_38 (75) = happyGoto action_23 action_38 (93) = happyGoto action_24 action_38 (95) = happyGoto action_90 action_38 (97) = happyGoto action_26 action_38 (104) = happyGoto action_27 action_38 (105) = happyGoto action_28 action_38 (106) = happyGoto action_29 action_38 (108) = happyGoto action_30 action_38 (114) = happyGoto action_31 action_38 _ = happyFail action_39 (153) = happyShift action_127 action_39 _ = happyFail action_40 _ = happyReduce_274 action_41 _ = happyReduce_277 action_42 _ = happyReduce_275 action_43 _ = happyReduce_276 action_44 (128) = happyShift action_34 action_44 (129) = happyShift action_35 action_44 (130) = happyShift action_36 action_44 (131) = happyShift action_37 action_44 (132) = happyShift action_117 action_44 (133) = happyShift action_118 action_44 (134) = happyShift action_119 action_44 (135) = happyShift action_120 action_44 (136) = happyShift action_121 action_44 (137) = happyShift action_39 action_44 (138) = happyShift action_40 action_44 (139) = happyShift action_41 action_44 (140) = happyShift action_42 action_44 (141) = happyShift action_43 action_44 (142) = happyShift action_44 action_44 (143) = happyShift action_122 action_44 (148) = happyShift action_45 action_44 (150) = happyShift action_123 action_44 (151) = happyShift action_46 action_44 (152) = happyShift action_124 action_44 (153) = happyShift action_125 action_44 (157) = happyShift action_47 action_44 (162) = happyShift action_48 action_44 (164) = happyShift action_126 action_44 (165) = happyShift action_49 action_44 (166) = happyShift action_50 action_44 (171) = happyShift action_54 action_44 (173) = happyShift action_55 action_44 (174) = happyShift action_56 action_44 (181) = happyShift action_62 action_44 (188) = happyShift action_65 action_44 (191) = happyShift action_68 action_44 (192) = happyShift action_69 action_44 (193) = happyShift action_70 action_44 (194) = happyShift action_71 action_44 (69) = happyGoto action_105 action_44 (70) = happyGoto action_106 action_44 (71) = happyGoto action_20 action_44 (72) = happyGoto action_21 action_44 (74) = happyGoto action_22 action_44 (75) = happyGoto action_23 action_44 (76) = happyGoto action_107 action_44 (77) = happyGoto action_108 action_44 (93) = happyGoto action_24 action_44 (95) = happyGoto action_90 action_44 (97) = happyGoto action_26 action_44 (99) = happyGoto action_109 action_44 (101) = happyGoto action_110 action_44 (103) = happyGoto action_111 action_44 (104) = happyGoto action_27 action_44 (105) = happyGoto action_28 action_44 (106) = happyGoto action_29 action_44 (108) = happyGoto action_30 action_44 (109) = happyGoto action_112 action_44 (110) = happyGoto action_113 action_44 (111) = happyGoto action_114 action_44 (112) = happyGoto action_115 action_44 (113) = happyGoto action_116 action_44 (114) = happyGoto action_31 action_44 (126) = happyGoto action_33 action_44 _ = happyFail action_45 (128) = happyShift action_34 action_45 (129) = happyShift action_35 action_45 (130) = happyShift action_36 action_45 (131) = happyShift action_37 action_45 (132) = happyShift action_38 action_45 (137) = happyShift action_39 action_45 (138) = happyShift action_40 action_45 (139) = happyShift action_41 action_45 (140) = happyShift action_42 action_45 (141) = happyShift action_43 action_45 (142) = happyShift action_44 action_45 (148) = happyShift action_45 action_45 (149) = happyShift action_104 action_45 (151) = happyShift action_46 action_45 (157) = happyShift action_47 action_45 (162) = happyShift action_48 action_45 (165) = happyShift action_49 action_45 (166) = happyShift action_50 action_45 (171) = happyShift action_54 action_45 (173) = happyShift action_55 action_45 (174) = happyShift action_56 action_45 (181) = happyShift action_62 action_45 (188) = happyShift action_65 action_45 (191) = happyShift action_68 action_45 (192) = happyShift action_69 action_45 (193) = happyShift action_70 action_45 (194) = happyShift action_71 action_45 (69) = happyGoto action_101 action_45 (70) = happyGoto action_89 action_45 (71) = happyGoto action_20 action_45 (72) = happyGoto action_21 action_45 (74) = happyGoto action_22 action_45 (75) = happyGoto action_23 action_45 (78) = happyGoto action_102 action_45 (79) = happyGoto action_103 action_45 (93) = happyGoto action_24 action_45 (95) = happyGoto action_90 action_45 (97) = happyGoto action_26 action_45 (104) = happyGoto action_27 action_45 (105) = happyGoto action_28 action_45 (106) = happyGoto action_29 action_45 (108) = happyGoto action_30 action_45 (114) = happyGoto action_31 action_45 (126) = happyGoto action_33 action_45 _ = happyFail action_46 _ = happyReduce_186 action_47 (128) = happyShift action_34 action_47 (129) = happyShift action_35 action_47 (130) = happyShift action_36 action_47 (131) = happyShift action_37 action_47 (137) = happyShift action_39 action_47 (138) = happyShift action_40 action_47 (139) = happyShift action_41 action_47 (140) = happyShift action_42 action_47 (141) = happyShift action_43 action_47 (142) = happyShift action_44 action_47 (148) = happyShift action_45 action_47 (151) = happyShift action_46 action_47 (162) = happyShift action_48 action_47 (165) = happyShift action_49 action_47 (173) = happyShift action_55 action_47 (188) = happyShift action_65 action_47 (73) = happyGoto action_99 action_47 (74) = happyGoto action_100 action_47 (75) = happyGoto action_23 action_47 (93) = happyGoto action_24 action_47 (95) = happyGoto action_90 action_47 (97) = happyGoto action_26 action_47 (104) = happyGoto action_27 action_47 (105) = happyGoto action_28 action_47 (106) = happyGoto action_29 action_47 (108) = happyGoto action_30 action_47 (114) = happyGoto action_31 action_47 _ = happyFail action_48 (128) = happyShift action_34 action_48 (129) = happyShift action_35 action_48 (130) = happyShift action_36 action_48 (131) = happyShift action_37 action_48 (137) = happyShift action_39 action_48 (138) = happyShift action_40 action_48 (139) = happyShift action_41 action_48 (140) = happyShift action_42 action_48 (141) = happyShift action_43 action_48 (142) = happyShift action_44 action_48 (148) = happyShift action_45 action_48 (151) = happyShift action_46 action_48 (162) = happyShift action_48 action_48 (165) = happyShift action_49 action_48 (173) = happyShift action_55 action_48 (188) = happyShift action_65 action_48 (75) = happyGoto action_98 action_48 (93) = happyGoto action_24 action_48 (95) = happyGoto action_90 action_48 (97) = happyGoto action_26 action_48 (104) = happyGoto action_27 action_48 (105) = happyGoto action_28 action_48 (106) = happyGoto action_29 action_48 (108) = happyGoto action_30 action_48 (114) = happyGoto action_31 action_48 _ = happyFail action_49 _ = happyReduce_256 action_50 (128) = happyShift action_34 action_50 (129) = happyShift action_35 action_50 (130) = happyShift action_36 action_50 (131) = happyShift action_37 action_50 (132) = happyShift action_38 action_50 (137) = happyShift action_39 action_50 (138) = happyShift action_40 action_50 (139) = happyShift action_41 action_50 (140) = happyShift action_42 action_50 (141) = happyShift action_43 action_50 (142) = happyShift action_44 action_50 (148) = happyShift action_45 action_50 (151) = happyShift action_46 action_50 (157) = happyShift action_47 action_50 (162) = happyShift action_48 action_50 (165) = happyShift action_49 action_50 (166) = happyShift action_50 action_50 (171) = happyShift action_54 action_50 (173) = happyShift action_55 action_50 (174) = happyShift action_56 action_50 (181) = happyShift action_62 action_50 (188) = happyShift action_65 action_50 (191) = happyShift action_68 action_50 (192) = happyShift action_69 action_50 (193) = happyShift action_70 action_50 (194) = happyShift action_71 action_50 (69) = happyGoto action_97 action_50 (70) = happyGoto action_89 action_50 (71) = happyGoto action_20 action_50 (72) = happyGoto action_21 action_50 (74) = happyGoto action_22 action_50 (75) = happyGoto action_23 action_50 (93) = happyGoto action_24 action_50 (95) = happyGoto action_90 action_50 (97) = happyGoto action_26 action_50 (104) = happyGoto action_27 action_50 (105) = happyGoto action_28 action_50 (106) = happyGoto action_29 action_50 (108) = happyGoto action_30 action_50 (114) = happyGoto action_31 action_50 (126) = happyGoto action_33 action_50 _ = happyFail action_51 (115) = happyGoto action_96 action_51 _ = happyReduce_278 action_52 (115) = happyGoto action_95 action_52 _ = happyReduce_278 action_53 (115) = happyGoto action_94 action_53 _ = happyReduce_278 action_54 (145) = happyShift action_93 action_54 (88) = happyGoto action_91 action_54 (118) = happyGoto action_92 action_54 _ = happyReduce_282 action_55 _ = happyReduce_258 action_56 (128) = happyShift action_34 action_56 (129) = happyShift action_35 action_56 (130) = happyShift action_36 action_56 (131) = happyShift action_37 action_56 (132) = happyShift action_38 action_56 (137) = happyShift action_39 action_56 (138) = happyShift action_40 action_56 (139) = happyShift action_41 action_56 (140) = happyShift action_42 action_56 (141) = happyShift action_43 action_56 (142) = happyShift action_44 action_56 (148) = happyShift action_45 action_56 (151) = happyShift action_46 action_56 (157) = happyShift action_47 action_56 (162) = happyShift action_48 action_56 (165) = happyShift action_49 action_56 (166) = happyShift action_50 action_56 (171) = happyShift action_54 action_56 (173) = happyShift action_55 action_56 (174) = happyShift action_56 action_56 (181) = happyShift action_62 action_56 (188) = happyShift action_65 action_56 (191) = happyShift action_68 action_56 (192) = happyShift action_69 action_56 (193) = happyShift action_70 action_56 (194) = happyShift action_71 action_56 (69) = happyGoto action_88 action_56 (70) = happyGoto action_89 action_56 (71) = happyGoto action_20 action_56 (72) = happyGoto action_21 action_56 (74) = happyGoto action_22 action_56 (75) = happyGoto action_23 action_56 (93) = happyGoto action_24 action_56 (95) = happyGoto action_90 action_56 (97) = happyGoto action_26 action_56 (104) = happyGoto action_27 action_56 (105) = happyGoto action_28 action_56 (106) = happyGoto action_29 action_56 (108) = happyGoto action_30 action_56 (114) = happyGoto action_31 action_56 (126) = happyGoto action_33 action_56 _ = happyFail action_57 (115) = happyGoto action_87 action_57 _ = happyReduce_278 action_58 _ = happyReduce_56 action_59 _ = happyReduce_57 action_60 _ = happyReduce_58 action_61 (115) = happyGoto action_86 action_61 _ = happyReduce_278 action_62 (145) = happyShift action_85 action_62 (34) = happyGoto action_83 action_62 (118) = happyGoto action_84 action_62 _ = happyReduce_282 action_63 (115) = happyGoto action_82 action_63 _ = happyReduce_278 action_64 (130) = happyShift action_36 action_64 (44) = happyGoto action_79 action_64 (108) = happyGoto action_80 action_64 (121) = happyGoto action_81 action_64 _ = happyFail action_65 _ = happyReduce_257 action_66 (115) = happyGoto action_78 action_66 _ = happyReduce_278 action_67 (115) = happyGoto action_77 action_67 _ = happyReduce_278 action_68 _ = happyReduce_290 action_69 _ = happyReduce_291 action_70 _ = happyReduce_292 action_71 _ = happyReduce_293 action_72 (142) = happyShift action_76 action_72 (8) = happyGoto action_74 action_72 (9) = happyGoto action_75 action_72 _ = happyReduce_12 action_73 _ = happyReduce_283 action_74 (187) = happyShift action_244 action_74 _ = happyFail action_75 _ = happyReduce_11 action_76 (128) = happyShift action_34 action_76 (129) = happyShift action_35 action_76 (130) = happyShift action_36 action_76 (131) = happyShift action_200 action_76 (142) = happyShift action_241 action_76 (143) = happyShift action_242 action_76 (165) = happyShift action_49 action_76 (173) = happyShift action_55 action_76 (182) = happyShift action_243 action_76 (188) = happyShift action_65 action_76 (11) = happyGoto action_236 action_76 (12) = happyGoto action_237 action_76 (95) = happyGoto action_238 action_76 (104) = happyGoto action_27 action_76 (105) = happyGoto action_28 action_76 (107) = happyGoto action_239 action_76 (108) = happyGoto action_80 action_76 (121) = happyGoto action_198 action_76 (122) = happyGoto action_240 action_76 _ = happyFail action_77 (130) = happyShift action_36 action_77 (108) = happyGoto action_235 action_77 _ = happyFail action_78 (128) = happyShift action_34 action_78 (142) = happyShift action_157 action_78 (165) = happyShift action_49 action_78 (173) = happyShift action_55 action_78 (188) = happyShift action_65 action_78 (94) = happyGoto action_234 action_78 (105) = happyGoto action_156 action_78 _ = happyFail action_79 (115) = happyGoto action_233 action_79 _ = happyReduce_278 action_80 _ = happyReduce_285 action_81 (128) = happyShift action_34 action_81 (165) = happyShift action_49 action_81 (173) = happyShift action_55 action_81 (188) = happyShift action_65 action_81 (45) = happyGoto action_231 action_81 (105) = happyGoto action_196 action_81 (124) = happyGoto action_232 action_81 _ = happyReduce_107 action_82 (128) = happyShift action_34 action_82 (130) = happyShift action_36 action_82 (131) = happyShift action_200 action_82 (137) = happyShift action_201 action_82 (142) = happyShift action_202 action_82 (148) = happyShift action_203 action_82 (165) = happyShift action_49 action_82 (173) = happyShift action_55 action_82 (188) = happyShift action_65 action_82 (37) = happyGoto action_228 action_82 (38) = happyGoto action_192 action_82 (39) = happyGoto action_193 action_82 (40) = happyGoto action_194 action_82 (43) = happyGoto action_229 action_82 (44) = happyGoto action_206 action_82 (105) = happyGoto action_196 action_82 (107) = happyGoto action_197 action_82 (108) = happyGoto action_80 action_82 (121) = happyGoto action_230 action_82 (124) = happyGoto action_199 action_82 _ = happyFail action_83 (176) = happyShift action_227 action_83 _ = happyFail action_84 (128) = happyShift action_34 action_84 (129) = happyShift action_35 action_84 (130) = happyShift action_36 action_84 (131) = happyShift action_37 action_84 (132) = happyShift action_38 action_84 (137) = happyShift action_39 action_84 (138) = happyShift action_40 action_84 (139) = happyShift action_41 action_84 (140) = happyShift action_42 action_84 (141) = happyShift action_43 action_84 (142) = happyShift action_44 action_84 (144) = happyShift action_226 action_84 (148) = happyShift action_45 action_84 (151) = happyShift action_46 action_84 (157) = happyShift action_47 action_84 (162) = happyShift action_48 action_84 (165) = happyShift action_49 action_84 (166) = happyShift action_50 action_84 (171) = happyShift action_54 action_84 (173) = happyShift action_55 action_84 (174) = happyShift action_56 action_84 (177) = happyShift action_58 action_84 (178) = happyShift action_59 action_84 (179) = happyShift action_60 action_84 (181) = happyShift action_62 action_84 (188) = happyShift action_65 action_84 (190) = happyShift action_67 action_84 (191) = happyShift action_68 action_84 (192) = happyShift action_69 action_84 (193) = happyShift action_70 action_84 (194) = happyShift action_71 action_84 (7) = happyGoto action_222 action_84 (26) = happyGoto action_12 action_84 (28) = happyGoto action_13 action_84 (31) = happyGoto action_223 action_84 (32) = happyGoto action_224 action_84 (33) = happyGoto action_225 action_84 (35) = happyGoto action_16 action_84 (36) = happyGoto action_17 action_84 (64) = happyGoto action_18 action_84 (70) = happyGoto action_19 action_84 (71) = happyGoto action_20 action_84 (72) = happyGoto action_21 action_84 (74) = happyGoto action_22 action_84 (75) = happyGoto action_23 action_84 (93) = happyGoto action_24 action_84 (95) = happyGoto action_25 action_84 (97) = happyGoto action_26 action_84 (104) = happyGoto action_27 action_84 (105) = happyGoto action_28 action_84 (106) = happyGoto action_29 action_84 (108) = happyGoto action_30 action_84 (114) = happyGoto action_31 action_84 (125) = happyGoto action_32 action_84 (126) = happyGoto action_33 action_84 _ = happyReduce_10 action_85 (117) = happyGoto action_221 action_85 _ = happyReduce_281 action_86 (128) = happyShift action_34 action_86 (130) = happyShift action_36 action_86 (131) = happyShift action_200 action_86 (137) = happyShift action_201 action_86 (142) = happyShift action_202 action_86 (148) = happyShift action_203 action_86 (165) = happyShift action_49 action_86 (173) = happyShift action_55 action_86 (188) = happyShift action_65 action_86 (37) = happyGoto action_191 action_86 (38) = happyGoto action_192 action_86 (39) = happyGoto action_193 action_86 (40) = happyGoto action_194 action_86 (41) = happyGoto action_220 action_86 (105) = happyGoto action_196 action_86 (107) = happyGoto action_197 action_86 (108) = happyGoto action_80 action_86 (121) = happyGoto action_198 action_86 (124) = happyGoto action_199 action_86 _ = happyFail action_87 (188) = happyShift action_219 action_87 (17) = happyGoto action_218 action_87 _ = happyReduce_33 action_88 (185) = happyShift action_217 action_88 _ = happyFail action_89 (132) = happyShift action_137 action_89 (133) = happyShift action_118 action_89 (134) = happyShift action_119 action_89 (135) = happyShift action_120 action_89 (136) = happyShift action_121 action_89 (152) = happyShift action_124 action_89 (153) = happyShift action_125 action_89 (155) = happyShift action_181 action_89 (164) = happyShift action_126 action_89 (99) = happyGoto action_109 action_89 (101) = happyGoto action_110 action_89 (103) = happyGoto action_133 action_89 (109) = happyGoto action_134 action_89 (110) = happyGoto action_113 action_89 (111) = happyGoto action_135 action_89 (112) = happyGoto action_115 action_89 (113) = happyGoto action_116 action_89 _ = happyReduce_160 action_90 (161) = happyShift action_130 action_90 _ = happyReduce_177 action_91 _ = happyReduce_169 action_92 (128) = happyShift action_34 action_92 (129) = happyShift action_35 action_92 (130) = happyShift action_36 action_92 (131) = happyShift action_37 action_92 (132) = happyShift action_38 action_92 (137) = happyShift action_39 action_92 (138) = happyShift action_40 action_92 (139) = happyShift action_41 action_92 (140) = happyShift action_42 action_92 (141) = happyShift action_43 action_92 (142) = happyShift action_44 action_92 (148) = happyShift action_45 action_92 (151) = happyShift action_46 action_92 (157) = happyShift action_47 action_92 (162) = happyShift action_48 action_92 (165) = happyShift action_49 action_92 (166) = happyShift action_50 action_92 (171) = happyShift action_54 action_92 (173) = happyShift action_55 action_92 (174) = happyShift action_56 action_92 (181) = happyShift action_216 action_92 (188) = happyShift action_65 action_92 (191) = happyShift action_68 action_92 (192) = happyShift action_69 action_92 (193) = happyShift action_70 action_92 (194) = happyShift action_71 action_92 (69) = happyGoto action_211 action_92 (70) = happyGoto action_212 action_92 (71) = happyGoto action_20 action_92 (72) = happyGoto action_21 action_92 (74) = happyGoto action_22 action_92 (75) = happyGoto action_23 action_92 (81) = happyGoto action_213 action_92 (89) = happyGoto action_214 action_92 (90) = happyGoto action_215 action_92 (93) = happyGoto action_24 action_92 (95) = happyGoto action_90 action_92 (97) = happyGoto action_26 action_92 (104) = happyGoto action_27 action_92 (105) = happyGoto action_28 action_92 (106) = happyGoto action_29 action_92 (108) = happyGoto action_30 action_92 (114) = happyGoto action_31 action_92 (126) = happyGoto action_33 action_92 _ = happyFail action_93 (117) = happyGoto action_210 action_93 _ = happyReduce_281 action_94 (128) = happyShift action_34 action_94 (130) = happyShift action_36 action_94 (131) = happyShift action_200 action_94 (137) = happyShift action_201 action_94 (142) = happyShift action_202 action_94 (148) = happyShift action_203 action_94 (165) = happyShift action_49 action_94 (173) = happyShift action_55 action_94 (188) = happyShift action_65 action_94 (37) = happyGoto action_209 action_94 (38) = happyGoto action_192 action_94 (39) = happyGoto action_193 action_94 (40) = happyGoto action_194 action_94 (105) = happyGoto action_196 action_94 (107) = happyGoto action_197 action_94 (108) = happyGoto action_80 action_94 (121) = happyGoto action_198 action_94 (124) = happyGoto action_199 action_94 _ = happyFail action_95 (128) = happyShift action_34 action_95 (130) = happyShift action_36 action_95 (131) = happyShift action_200 action_95 (137) = happyShift action_201 action_95 (142) = happyShift action_202 action_95 (148) = happyShift action_203 action_95 (165) = happyShift action_49 action_95 (173) = happyShift action_55 action_95 (188) = happyShift action_65 action_95 (37) = happyGoto action_204 action_95 (38) = happyGoto action_192 action_95 (39) = happyGoto action_193 action_95 (40) = happyGoto action_194 action_95 (43) = happyGoto action_205 action_95 (44) = happyGoto action_206 action_95 (46) = happyGoto action_207 action_95 (105) = happyGoto action_196 action_95 (107) = happyGoto action_197 action_95 (108) = happyGoto action_80 action_95 (121) = happyGoto action_208 action_95 (124) = happyGoto action_199 action_95 _ = happyFail action_96 (128) = happyShift action_34 action_96 (130) = happyShift action_36 action_96 (131) = happyShift action_200 action_96 (137) = happyShift action_201 action_96 (142) = happyShift action_202 action_96 (148) = happyShift action_203 action_96 (165) = happyShift action_49 action_96 (173) = happyShift action_55 action_96 (188) = happyShift action_65 action_96 (37) = happyGoto action_191 action_96 (38) = happyGoto action_192 action_96 (39) = happyGoto action_193 action_96 (40) = happyGoto action_194 action_96 (41) = happyGoto action_195 action_96 (105) = happyGoto action_196 action_96 (107) = happyGoto action_197 action_96 (108) = happyGoto action_80 action_96 (121) = happyGoto action_198 action_96 (124) = happyGoto action_199 action_96 _ = happyFail action_97 (184) = happyShift action_190 action_97 _ = happyFail action_98 _ = happyReduce_187 action_99 (128) = happyShift action_34 action_99 (129) = happyShift action_35 action_99 (130) = happyShift action_36 action_99 (131) = happyShift action_37 action_99 (137) = happyShift action_39 action_99 (138) = happyShift action_40 action_99 (139) = happyShift action_41 action_99 (140) = happyShift action_42 action_99 (141) = happyShift action_43 action_99 (142) = happyShift action_44 action_99 (148) = happyShift action_45 action_99 (151) = happyShift action_46 action_99 (160) = happyShift action_189 action_99 (162) = happyShift action_48 action_99 (165) = happyShift action_49 action_99 (173) = happyShift action_55 action_99 (188) = happyShift action_65 action_99 (74) = happyGoto action_167 action_99 (75) = happyGoto action_23 action_99 (93) = happyGoto action_24 action_99 (95) = happyGoto action_90 action_99 (97) = happyGoto action_26 action_99 (104) = happyGoto action_27 action_99 (105) = happyGoto action_28 action_99 (106) = happyGoto action_29 action_99 (108) = happyGoto action_30 action_99 (114) = happyGoto action_31 action_99 _ = happyFail action_100 (145) = happyShift action_131 action_100 _ = happyReduce_174 action_101 (150) = happyShift action_186 action_101 (154) = happyShift action_187 action_101 (158) = happyShift action_188 action_101 _ = happyReduce_192 action_102 (149) = happyShift action_185 action_102 _ = happyFail action_103 (150) = happyShift action_184 action_103 _ = happyReduce_193 action_104 _ = happyReduce_227 action_105 (143) = happyShift action_182 action_105 (150) = happyShift action_183 action_105 _ = happyFail action_106 (132) = happyShift action_137 action_106 (133) = happyShift action_118 action_106 (134) = happyShift action_119 action_106 (135) = happyShift action_120 action_106 (136) = happyShift action_121 action_106 (152) = happyShift action_124 action_106 (153) = happyShift action_125 action_106 (155) = happyShift action_181 action_106 (164) = happyShift action_126 action_106 (99) = happyGoto action_109 action_106 (101) = happyGoto action_110 action_106 (103) = happyGoto action_180 action_106 (109) = happyGoto action_134 action_106 (110) = happyGoto action_113 action_106 (111) = happyGoto action_135 action_106 (112) = happyGoto action_115 action_106 (113) = happyGoto action_116 action_106 _ = happyReduce_160 action_107 (143) = happyShift action_178 action_107 (150) = happyShift action_179 action_107 _ = happyFail action_108 (143) = happyShift action_176 action_108 (150) = happyShift action_177 action_108 _ = happyFail action_109 _ = happyReduce_251 action_110 _ = happyReduce_252 action_111 (128) = happyShift action_34 action_111 (129) = happyShift action_35 action_111 (130) = happyShift action_36 action_111 (131) = happyShift action_37 action_111 (132) = happyShift action_38 action_111 (137) = happyShift action_39 action_111 (138) = happyShift action_40 action_111 (139) = happyShift action_41 action_111 (140) = happyShift action_42 action_111 (141) = happyShift action_43 action_111 (142) = happyShift action_44 action_111 (148) = happyShift action_45 action_111 (151) = happyShift action_46 action_111 (157) = happyShift action_47 action_111 (162) = happyShift action_48 action_111 (165) = happyShift action_49 action_111 (166) = happyShift action_50 action_111 (171) = happyShift action_54 action_111 (173) = happyShift action_55 action_111 (174) = happyShift action_56 action_111 (181) = happyShift action_62 action_111 (188) = happyShift action_65 action_111 (191) = happyShift action_68 action_111 (192) = happyShift action_69 action_111 (193) = happyShift action_70 action_111 (194) = happyShift action_71 action_111 (70) = happyGoto action_175 action_111 (71) = happyGoto action_20 action_111 (72) = happyGoto action_21 action_111 (74) = happyGoto action_22 action_111 (75) = happyGoto action_23 action_111 (93) = happyGoto action_24 action_111 (95) = happyGoto action_90 action_111 (97) = happyGoto action_26 action_111 (104) = happyGoto action_27 action_111 (105) = happyGoto action_28 action_111 (106) = happyGoto action_29 action_111 (108) = happyGoto action_30 action_111 (114) = happyGoto action_31 action_111 (126) = happyGoto action_33 action_111 _ = happyFail action_112 (143) = happyShift action_174 action_112 _ = happyReduce_247 action_113 _ = happyReduce_264 action_114 (143) = happyShift action_173 action_114 _ = happyReduce_243 action_115 _ = happyReduce_267 action_116 _ = happyReduce_268 action_117 (128) = happyShift action_34 action_117 (129) = happyShift action_35 action_117 (130) = happyShift action_36 action_117 (131) = happyShift action_37 action_117 (137) = happyShift action_39 action_117 (138) = happyShift action_40 action_117 (139) = happyShift action_41 action_117 (140) = happyShift action_42 action_117 (141) = happyShift action_43 action_117 (142) = happyShift action_44 action_117 (148) = happyShift action_45 action_117 (151) = happyShift action_46 action_117 (162) = happyShift action_48 action_117 (165) = happyShift action_49 action_117 (173) = happyShift action_55 action_117 (188) = happyShift action_65 action_117 (72) = happyGoto action_128 action_117 (74) = happyGoto action_22 action_117 (75) = happyGoto action_23 action_117 (93) = happyGoto action_24 action_117 (95) = happyGoto action_90 action_117 (97) = happyGoto action_26 action_117 (104) = happyGoto action_27 action_117 (105) = happyGoto action_28 action_117 (106) = happyGoto action_29 action_117 (108) = happyGoto action_30 action_117 (114) = happyGoto action_31 action_117 _ = happyReduce_270 action_118 _ = happyReduce_269 action_119 _ = happyReduce_266 action_120 _ = happyReduce_273 action_121 _ = happyReduce_265 action_122 _ = happyReduce_226 action_123 _ = happyReduce_189 action_124 (128) = happyShift action_34 action_124 (129) = happyShift action_35 action_124 (130) = happyShift action_36 action_124 (131) = happyShift action_37 action_124 (165) = happyShift action_49 action_124 (173) = happyShift action_55 action_124 (188) = happyShift action_65 action_124 (104) = happyGoto action_171 action_124 (105) = happyGoto action_28 action_124 (106) = happyGoto action_172 action_124 (108) = happyGoto action_30 action_124 _ = happyFail action_125 _ = happyReduce_272 action_126 _ = happyReduce_271 action_127 (142) = happyShift action_169 action_127 (148) = happyShift action_170 action_127 _ = happyFail action_128 (128) = happyShift action_34 action_128 (129) = happyShift action_35 action_128 (130) = happyShift action_36 action_128 (131) = happyShift action_37 action_128 (137) = happyShift action_39 action_128 (138) = happyShift action_40 action_128 (139) = happyShift action_41 action_128 (140) = happyShift action_42 action_128 (141) = happyShift action_43 action_128 (142) = happyShift action_44 action_128 (148) = happyShift action_45 action_128 (151) = happyShift action_46 action_128 (162) = happyShift action_48 action_128 (165) = happyShift action_49 action_128 (173) = happyShift action_55 action_128 (188) = happyShift action_65 action_128 (74) = happyGoto action_132 action_128 (75) = happyGoto action_23 action_128 (93) = happyGoto action_24 action_128 (95) = happyGoto action_90 action_128 (97) = happyGoto action_26 action_128 (104) = happyGoto action_27 action_128 (105) = happyGoto action_28 action_128 (106) = happyGoto action_29 action_128 (108) = happyGoto action_30 action_128 (114) = happyGoto action_31 action_128 _ = happyReduce_168 action_129 (128) = happyShift action_34 action_129 (129) = happyShift action_35 action_129 (130) = happyShift action_36 action_129 (131) = happyShift action_37 action_129 (137) = happyShift action_39 action_129 (138) = happyShift action_40 action_129 (139) = happyShift action_41 action_129 (140) = happyShift action_42 action_129 (141) = happyShift action_43 action_129 (142) = happyShift action_44 action_129 (148) = happyShift action_45 action_129 (151) = happyShift action_46 action_129 (153) = happyShift action_168 action_129 (162) = happyShift action_48 action_129 (165) = happyShift action_49 action_129 (173) = happyShift action_55 action_129 (188) = happyShift action_65 action_129 (74) = happyGoto action_167 action_129 (75) = happyGoto action_23 action_129 (93) = happyGoto action_24 action_129 (95) = happyGoto action_90 action_129 (97) = happyGoto action_26 action_129 (104) = happyGoto action_27 action_129 (105) = happyGoto action_28 action_129 (106) = happyGoto action_29 action_129 (108) = happyGoto action_30 action_129 (114) = happyGoto action_31 action_129 _ = happyFail action_130 (128) = happyShift action_34 action_130 (129) = happyShift action_35 action_130 (130) = happyShift action_36 action_130 (131) = happyShift action_37 action_130 (137) = happyShift action_39 action_130 (138) = happyShift action_40 action_130 (139) = happyShift action_41 action_130 (140) = happyShift action_42 action_130 (141) = happyShift action_43 action_130 (142) = happyShift action_44 action_130 (148) = happyShift action_45 action_130 (151) = happyShift action_46 action_130 (162) = happyShift action_48 action_130 (165) = happyShift action_49 action_130 (173) = happyShift action_55 action_130 (188) = happyShift action_65 action_130 (75) = happyGoto action_166 action_130 (93) = happyGoto action_24 action_130 (95) = happyGoto action_90 action_130 (97) = happyGoto action_26 action_130 (104) = happyGoto action_27 action_130 (105) = happyGoto action_28 action_130 (106) = happyGoto action_29 action_130 (108) = happyGoto action_30 action_130 (114) = happyGoto action_31 action_130 _ = happyFail action_131 (117) = happyGoto action_165 action_131 _ = happyReduce_281 action_132 (145) = happyShift action_131 action_132 _ = happyReduce_171 action_133 (128) = happyShift action_34 action_133 (129) = happyShift action_35 action_133 (130) = happyShift action_36 action_133 (131) = happyShift action_37 action_133 (132) = happyShift action_38 action_133 (137) = happyShift action_39 action_133 (138) = happyShift action_40 action_133 (139) = happyShift action_41 action_133 (140) = happyShift action_42 action_133 (141) = happyShift action_43 action_133 (142) = happyShift action_44 action_133 (148) = happyShift action_45 action_133 (151) = happyShift action_46 action_133 (157) = happyShift action_47 action_133 (162) = happyShift action_48 action_133 (165) = happyShift action_49 action_133 (166) = happyShift action_50 action_133 (171) = happyShift action_54 action_133 (173) = happyShift action_55 action_133 (174) = happyShift action_56 action_133 (181) = happyShift action_62 action_133 (188) = happyShift action_65 action_133 (191) = happyShift action_68 action_133 (192) = happyShift action_69 action_133 (193) = happyShift action_70 action_133 (194) = happyShift action_71 action_133 (71) = happyGoto action_164 action_133 (72) = happyGoto action_21 action_133 (74) = happyGoto action_22 action_133 (75) = happyGoto action_23 action_133 (93) = happyGoto action_24 action_133 (95) = happyGoto action_90 action_133 (97) = happyGoto action_26 action_133 (104) = happyGoto action_27 action_133 (105) = happyGoto action_28 action_133 (106) = happyGoto action_29 action_133 (108) = happyGoto action_30 action_133 (114) = happyGoto action_31 action_133 (126) = happyGoto action_33 action_133 _ = happyFail action_134 _ = happyReduce_247 action_135 _ = happyReduce_243 action_136 (156) = happyShift action_162 action_136 (158) = happyShift action_163 action_136 (66) = happyGoto action_159 action_136 (67) = happyGoto action_160 action_136 (68) = happyGoto action_161 action_136 _ = happyFail action_137 _ = happyReduce_270 action_138 (155) = happyShift action_158 action_138 _ = happyFail action_139 (128) = happyShift action_34 action_139 (142) = happyShift action_157 action_139 (165) = happyShift action_49 action_139 (173) = happyShift action_55 action_139 (188) = happyShift action_65 action_139 (94) = happyGoto action_155 action_139 (105) = happyGoto action_156 action_139 _ = happyFail action_140 (138) = happyShift action_154 action_140 (27) = happyGoto action_153 action_140 _ = happyReduce_54 action_141 _ = happyReduce_6 action_142 (128) = happyShift action_34 action_142 (129) = happyShift action_35 action_142 (130) = happyShift action_36 action_142 (131) = happyShift action_37 action_142 (132) = happyShift action_38 action_142 (137) = happyShift action_39 action_142 (138) = happyShift action_40 action_142 (139) = happyShift action_41 action_142 (140) = happyShift action_42 action_142 (141) = happyShift action_43 action_142 (142) = happyShift action_44 action_142 (148) = happyShift action_45 action_142 (151) = happyShift action_46 action_142 (157) = happyShift action_47 action_142 (162) = happyShift action_48 action_142 (165) = happyShift action_49 action_142 (166) = happyShift action_50 action_142 (167) = happyShift action_51 action_142 (168) = happyShift action_52 action_142 (169) = happyShift action_53 action_142 (171) = happyShift action_54 action_142 (173) = happyShift action_55 action_142 (174) = happyShift action_56 action_142 (177) = happyShift action_58 action_142 (178) = happyShift action_59 action_142 (179) = happyShift action_60 action_142 (180) = happyShift action_61 action_142 (181) = happyShift action_62 action_142 (183) = happyShift action_63 action_142 (186) = happyShift action_64 action_142 (188) = happyShift action_65 action_142 (189) = happyShift action_66 action_142 (190) = happyShift action_67 action_142 (191) = happyShift action_68 action_142 (192) = happyShift action_69 action_142 (193) = happyShift action_70 action_142 (194) = happyShift action_71 action_142 (26) = happyGoto action_12 action_142 (28) = happyGoto action_13 action_142 (30) = happyGoto action_152 action_142 (33) = happyGoto action_15 action_142 (35) = happyGoto action_16 action_142 (36) = happyGoto action_17 action_142 (64) = happyGoto action_18 action_142 (70) = happyGoto action_19 action_142 (71) = happyGoto action_20 action_142 (72) = happyGoto action_21 action_142 (74) = happyGoto action_22 action_142 (75) = happyGoto action_23 action_142 (93) = happyGoto action_24 action_142 (95) = happyGoto action_25 action_142 (97) = happyGoto action_26 action_142 (104) = happyGoto action_27 action_142 (105) = happyGoto action_28 action_142 (106) = happyGoto action_29 action_142 (108) = happyGoto action_30 action_142 (114) = happyGoto action_31 action_142 (125) = happyGoto action_32 action_142 (126) = happyGoto action_33 action_142 _ = happyReduce_9 action_143 _ = happyReduce_7 action_144 (128) = happyShift action_34 action_144 (129) = happyShift action_35 action_144 (130) = happyShift action_36 action_144 (131) = happyShift action_37 action_144 (132) = happyShift action_38 action_144 (137) = happyShift action_39 action_144 (138) = happyShift action_40 action_144 (139) = happyShift action_41 action_144 (140) = happyShift action_42 action_144 (141) = happyShift action_43 action_144 (142) = happyShift action_44 action_144 (148) = happyShift action_45 action_144 (151) = happyShift action_46 action_144 (157) = happyShift action_47 action_144 (162) = happyShift action_48 action_144 (165) = happyShift action_49 action_144 (166) = happyShift action_50 action_144 (167) = happyShift action_51 action_144 (168) = happyShift action_52 action_144 (169) = happyShift action_53 action_144 (171) = happyShift action_54 action_144 (173) = happyShift action_55 action_144 (174) = happyShift action_56 action_144 (175) = happyShift action_57 action_144 (177) = happyShift action_58 action_144 (178) = happyShift action_59 action_144 (179) = happyShift action_60 action_144 (180) = happyShift action_61 action_144 (181) = happyShift action_62 action_144 (183) = happyShift action_63 action_144 (186) = happyShift action_64 action_144 (188) = happyShift action_65 action_144 (189) = happyShift action_66 action_144 (190) = happyShift action_67 action_144 (191) = happyShift action_68 action_144 (192) = happyShift action_69 action_144 (193) = happyShift action_70 action_144 (194) = happyShift action_71 action_144 (16) = happyGoto action_150 action_144 (25) = happyGoto action_151 action_144 (26) = happyGoto action_12 action_144 (28) = happyGoto action_13 action_144 (30) = happyGoto action_14 action_144 (33) = happyGoto action_15 action_144 (35) = happyGoto action_16 action_144 (36) = happyGoto action_17 action_144 (64) = happyGoto action_18 action_144 (70) = happyGoto action_19 action_144 (71) = happyGoto action_20 action_144 (72) = happyGoto action_21 action_144 (74) = happyGoto action_22 action_144 (75) = happyGoto action_23 action_144 (93) = happyGoto action_24 action_144 (95) = happyGoto action_25 action_144 (97) = happyGoto action_26 action_144 (104) = happyGoto action_27 action_144 (105) = happyGoto action_28 action_144 (106) = happyGoto action_29 action_144 (108) = happyGoto action_30 action_144 (114) = happyGoto action_31 action_144 (125) = happyGoto action_32 action_144 (126) = happyGoto action_33 action_144 _ = happyReduce_9 action_145 _ = happyReduce_4 action_146 _ = happyReduce_280 action_147 _ = happyReduce_279 action_148 (146) = happyShift action_149 action_148 _ = happyFail action_149 _ = happyReduce_3 action_150 _ = happyReduce_29 action_151 (144) = happyShift action_142 action_151 (7) = happyGoto action_325 action_151 _ = happyReduce_10 action_152 _ = happyReduce_51 action_153 (132) = happyShift action_137 action_153 (133) = happyShift action_118 action_153 (134) = happyShift action_119 action_153 (152) = happyShift action_324 action_153 (153) = happyShift action_125 action_153 (164) = happyShift action_126 action_153 (29) = happyGoto action_318 action_153 (98) = happyGoto action_319 action_153 (100) = happyGoto action_320 action_153 (102) = happyGoto action_321 action_153 (110) = happyGoto action_322 action_153 (112) = happyGoto action_323 action_153 _ = happyFail action_154 _ = happyReduce_55 action_155 _ = happyReduce_81 action_156 _ = happyReduce_233 action_157 (132) = happyShift action_137 action_157 (133) = happyShift action_118 action_157 (153) = happyShift action_125 action_157 (164) = happyShift action_126 action_157 (112) = happyGoto action_317 action_157 _ = happyFail action_158 (128) = happyShift action_34 action_158 (130) = happyShift action_36 action_158 (131) = happyShift action_200 action_158 (137) = happyShift action_201 action_158 (142) = happyShift action_202 action_158 (148) = happyShift action_203 action_158 (165) = happyShift action_49 action_158 (173) = happyShift action_55 action_158 (188) = happyShift action_65 action_158 (37) = happyGoto action_191 action_158 (38) = happyGoto action_192 action_158 (39) = happyGoto action_193 action_158 (40) = happyGoto action_194 action_158 (41) = happyGoto action_316 action_158 (105) = happyGoto action_196 action_158 (107) = happyGoto action_197 action_158 (108) = happyGoto action_80 action_158 (121) = happyGoto action_198 action_158 (124) = happyGoto action_199 action_158 _ = happyFail action_159 (187) = happyShift action_315 action_159 (65) = happyGoto action_314 action_159 _ = happyReduce_153 action_160 (158) = happyShift action_163 action_160 (68) = happyGoto action_313 action_160 _ = happyReduce_155 action_161 _ = happyReduce_157 action_162 (128) = happyShift action_34 action_162 (129) = happyShift action_35 action_162 (130) = happyShift action_36 action_162 (131) = happyShift action_37 action_162 (132) = happyShift action_38 action_162 (137) = happyShift action_39 action_162 (138) = happyShift action_40 action_162 (139) = happyShift action_41 action_162 (140) = happyShift action_42 action_162 (141) = happyShift action_43 action_162 (142) = happyShift action_44 action_162 (148) = happyShift action_45 action_162 (151) = happyShift action_46 action_162 (157) = happyShift action_47 action_162 (162) = happyShift action_48 action_162 (165) = happyShift action_49 action_162 (166) = happyShift action_50 action_162 (171) = happyShift action_54 action_162 (173) = happyShift action_55 action_162 (174) = happyShift action_56 action_162 (181) = happyShift action_62 action_162 (188) = happyShift action_65 action_162 (191) = happyShift action_68 action_162 (192) = happyShift action_69 action_162 (193) = happyShift action_70 action_162 (194) = happyShift action_71 action_162 (69) = happyGoto action_312 action_162 (70) = happyGoto action_89 action_162 (71) = happyGoto action_20 action_162 (72) = happyGoto action_21 action_162 (74) = happyGoto action_22 action_162 (75) = happyGoto action_23 action_162 (93) = happyGoto action_24 action_162 (95) = happyGoto action_90 action_162 (97) = happyGoto action_26 action_162 (104) = happyGoto action_27 action_162 (105) = happyGoto action_28 action_162 (106) = happyGoto action_29 action_162 (108) = happyGoto action_30 action_162 (114) = happyGoto action_31 action_162 (126) = happyGoto action_33 action_162 _ = happyFail action_163 (128) = happyShift action_34 action_163 (129) = happyShift action_35 action_163 (130) = happyShift action_36 action_163 (131) = happyShift action_37 action_163 (132) = happyShift action_38 action_163 (137) = happyShift action_39 action_163 (138) = happyShift action_40 action_163 (139) = happyShift action_41 action_163 (140) = happyShift action_42 action_163 (141) = happyShift action_43 action_163 (142) = happyShift action_44 action_163 (148) = happyShift action_45 action_163 (151) = happyShift action_46 action_163 (157) = happyShift action_47 action_163 (162) = happyShift action_48 action_163 (165) = happyShift action_49 action_163 (166) = happyShift action_50 action_163 (171) = happyShift action_54 action_163 (173) = happyShift action_55 action_163 (174) = happyShift action_56 action_163 (181) = happyShift action_62 action_163 (188) = happyShift action_65 action_163 (191) = happyShift action_68 action_163 (192) = happyShift action_69 action_163 (193) = happyShift action_70 action_163 (194) = happyShift action_71 action_163 (69) = happyGoto action_311 action_163 (70) = happyGoto action_89 action_163 (71) = happyGoto action_20 action_163 (72) = happyGoto action_21 action_163 (74) = happyGoto action_22 action_163 (75) = happyGoto action_23 action_163 (93) = happyGoto action_24 action_163 (95) = happyGoto action_90 action_163 (97) = happyGoto action_26 action_163 (104) = happyGoto action_27 action_163 (105) = happyGoto action_28 action_163 (106) = happyGoto action_29 action_163 (108) = happyGoto action_30 action_163 (114) = happyGoto action_31 action_163 (126) = happyGoto action_33 action_163 _ = happyFail action_164 _ = happyReduce_162 action_165 (128) = happyShift action_34 action_165 (129) = happyShift action_35 action_165 (142) = happyShift action_241 action_165 (165) = happyShift action_49 action_165 (173) = happyShift action_55 action_165 (188) = happyShift action_65 action_165 (91) = happyGoto action_308 action_165 (92) = happyGoto action_309 action_165 (95) = happyGoto action_310 action_165 (104) = happyGoto action_27 action_165 (105) = happyGoto action_28 action_165 _ = happyFail action_166 _ = happyReduce_185 action_167 (145) = happyShift action_131 action_167 _ = happyReduce_173 action_168 (128) = happyShift action_34 action_168 (129) = happyShift action_35 action_168 (130) = happyShift action_36 action_168 (131) = happyShift action_37 action_168 (132) = happyShift action_38 action_168 (137) = happyShift action_39 action_168 (138) = happyShift action_40 action_168 (139) = happyShift action_41 action_168 (140) = happyShift action_42 action_168 (141) = happyShift action_43 action_168 (142) = happyShift action_44 action_168 (148) = happyShift action_45 action_168 (151) = happyShift action_46 action_168 (157) = happyShift action_47 action_168 (162) = happyShift action_48 action_168 (165) = happyShift action_49 action_168 (166) = happyShift action_50 action_168 (171) = happyShift action_54 action_168 (173) = happyShift action_55 action_168 (174) = happyShift action_56 action_168 (181) = happyShift action_62 action_168 (188) = happyShift action_65 action_168 (191) = happyShift action_68 action_168 (192) = happyShift action_69 action_168 (193) = happyShift action_70 action_168 (194) = happyShift action_71 action_168 (69) = happyGoto action_307 action_168 (70) = happyGoto action_89 action_168 (71) = happyGoto action_20 action_168 (72) = happyGoto action_21 action_168 (74) = happyGoto action_22 action_168 (75) = happyGoto action_23 action_168 (93) = happyGoto action_24 action_168 (95) = happyGoto action_90 action_168 (97) = happyGoto action_26 action_168 (104) = happyGoto action_27 action_168 (105) = happyGoto action_28 action_168 (106) = happyGoto action_29 action_168 (108) = happyGoto action_30 action_168 (114) = happyGoto action_31 action_168 (126) = happyGoto action_33 action_168 _ = happyFail action_169 (143) = happyShift action_306 action_169 (150) = happyShift action_123 action_169 (76) = happyGoto action_305 action_169 _ = happyFail action_170 (149) = happyShift action_304 action_170 _ = happyFail action_171 (152) = happyShift action_303 action_171 _ = happyFail action_172 (152) = happyShift action_302 action_172 _ = happyFail action_173 _ = happyReduce_236 action_174 _ = happyReduce_240 action_175 (132) = happyShift action_137 action_175 (133) = happyShift action_118 action_175 (134) = happyShift action_119 action_175 (135) = happyShift action_120 action_175 (136) = happyShift action_121 action_175 (143) = happyShift action_301 action_175 (152) = happyShift action_124 action_175 (153) = happyShift action_125 action_175 (164) = happyShift action_126 action_175 (99) = happyGoto action_109 action_175 (101) = happyGoto action_110 action_175 (103) = happyGoto action_133 action_175 (109) = happyGoto action_134 action_175 (110) = happyGoto action_113 action_175 (111) = happyGoto action_135 action_175 (112) = happyGoto action_115 action_175 (113) = happyGoto action_116 action_175 _ = happyFail action_176 _ = happyReduce_181 action_177 (128) = happyShift action_34 action_177 (129) = happyShift action_35 action_177 (130) = happyShift action_36 action_177 (131) = happyShift action_37 action_177 (132) = happyShift action_38 action_177 (137) = happyShift action_39 action_177 (138) = happyShift action_40 action_177 (139) = happyShift action_41 action_177 (140) = happyShift action_42 action_177 (141) = happyShift action_43 action_177 (142) = happyShift action_44 action_177 (148) = happyShift action_45 action_177 (151) = happyShift action_46 action_177 (157) = happyShift action_47 action_177 (162) = happyShift action_48 action_177 (165) = happyShift action_49 action_177 (166) = happyShift action_50 action_177 (171) = happyShift action_54 action_177 (173) = happyShift action_55 action_177 (174) = happyShift action_56 action_177 (181) = happyShift action_62 action_177 (188) = happyShift action_65 action_177 (191) = happyShift action_68 action_177 (192) = happyShift action_69 action_177 (193) = happyShift action_70 action_177 (194) = happyShift action_71 action_177 (69) = happyGoto action_300 action_177 (70) = happyGoto action_89 action_177 (71) = happyGoto action_20 action_177 (72) = happyGoto action_21 action_177 (74) = happyGoto action_22 action_177 (75) = happyGoto action_23 action_177 (93) = happyGoto action_24 action_177 (95) = happyGoto action_90 action_177 (97) = happyGoto action_26 action_177 (104) = happyGoto action_27 action_177 (105) = happyGoto action_28 action_177 (106) = happyGoto action_29 action_177 (108) = happyGoto action_30 action_177 (114) = happyGoto action_31 action_177 (126) = happyGoto action_33 action_177 _ = happyFail action_178 _ = happyReduce_228 action_179 _ = happyReduce_188 action_180 (128) = happyShift action_34 action_180 (129) = happyShift action_35 action_180 (130) = happyShift action_36 action_180 (131) = happyShift action_37 action_180 (132) = happyShift action_38 action_180 (137) = happyShift action_39 action_180 (138) = happyShift action_40 action_180 (139) = happyShift action_41 action_180 (140) = happyShift action_42 action_180 (141) = happyShift action_43 action_180 (142) = happyShift action_44 action_180 (143) = happyShift action_299 action_180 (148) = happyShift action_45 action_180 (151) = happyShift action_46 action_180 (157) = happyShift action_47 action_180 (162) = happyShift action_48 action_180 (165) = happyShift action_49 action_180 (166) = happyShift action_50 action_180 (171) = happyShift action_54 action_180 (173) = happyShift action_55 action_180 (174) = happyShift action_56 action_180 (181) = happyShift action_62 action_180 (188) = happyShift action_65 action_180 (191) = happyShift action_68 action_180 (192) = happyShift action_69 action_180 (193) = happyShift action_70 action_180 (194) = happyShift action_71 action_180 (71) = happyGoto action_164 action_180 (72) = happyGoto action_21 action_180 (74) = happyGoto action_22 action_180 (75) = happyGoto action_23 action_180 (93) = happyGoto action_24 action_180 (95) = happyGoto action_90 action_180 (97) = happyGoto action_26 action_180 (104) = happyGoto action_27 action_180 (105) = happyGoto action_28 action_180 (106) = happyGoto action_29 action_180 (108) = happyGoto action_30 action_180 (114) = happyGoto action_31 action_180 (126) = happyGoto action_33 action_180 _ = happyFail action_181 (115) = happyGoto action_298 action_181 _ = happyReduce_278 action_182 _ = happyReduce_180 action_183 (128) = happyShift action_34 action_183 (129) = happyShift action_35 action_183 (130) = happyShift action_36 action_183 (131) = happyShift action_37 action_183 (132) = happyShift action_38 action_183 (137) = happyShift action_39 action_183 (138) = happyShift action_40 action_183 (139) = happyShift action_41 action_183 (140) = happyShift action_42 action_183 (141) = happyShift action_43 action_183 (142) = happyShift action_44 action_183 (148) = happyShift action_45 action_183 (151) = happyShift action_46 action_183 (157) = happyShift action_47 action_183 (162) = happyShift action_48 action_183 (165) = happyShift action_49 action_183 (166) = happyShift action_50 action_183 (171) = happyShift action_54 action_183 (173) = happyShift action_55 action_183 (174) = happyShift action_56 action_183 (181) = happyShift action_62 action_183 (188) = happyShift action_65 action_183 (191) = happyShift action_68 action_183 (192) = happyShift action_69 action_183 (193) = happyShift action_70 action_183 (194) = happyShift action_71 action_183 (69) = happyGoto action_297 action_183 (70) = happyGoto action_89 action_183 (71) = happyGoto action_20 action_183 (72) = happyGoto action_21 action_183 (74) = happyGoto action_22 action_183 (75) = happyGoto action_23 action_183 (93) = happyGoto action_24 action_183 (95) = happyGoto action_90 action_183 (97) = happyGoto action_26 action_183 (104) = happyGoto action_27 action_183 (105) = happyGoto action_28 action_183 (106) = happyGoto action_29 action_183 (108) = happyGoto action_30 action_183 (114) = happyGoto action_31 action_183 (126) = happyGoto action_33 action_183 _ = happyFail action_184 (128) = happyShift action_34 action_184 (129) = happyShift action_35 action_184 (130) = happyShift action_36 action_184 (131) = happyShift action_37 action_184 (132) = happyShift action_38 action_184 (137) = happyShift action_39 action_184 (138) = happyShift action_40 action_184 (139) = happyShift action_41 action_184 (140) = happyShift action_42 action_184 (141) = happyShift action_43 action_184 (142) = happyShift action_44 action_184 (148) = happyShift action_45 action_184 (151) = happyShift action_46 action_184 (157) = happyShift action_47 action_184 (162) = happyShift action_48 action_184 (165) = happyShift action_49 action_184 (166) = happyShift action_50 action_184 (171) = happyShift action_54 action_184 (173) = happyShift action_55 action_184 (174) = happyShift action_56 action_184 (181) = happyShift action_62 action_184 (188) = happyShift action_65 action_184 (191) = happyShift action_68 action_184 (192) = happyShift action_69 action_184 (193) = happyShift action_70 action_184 (194) = happyShift action_71 action_184 (69) = happyGoto action_296 action_184 (70) = happyGoto action_89 action_184 (71) = happyGoto action_20 action_184 (72) = happyGoto action_21 action_184 (74) = happyGoto action_22 action_184 (75) = happyGoto action_23 action_184 (93) = happyGoto action_24 action_184 (95) = happyGoto action_90 action_184 (97) = happyGoto action_26 action_184 (104) = happyGoto action_27 action_184 (105) = happyGoto action_28 action_184 (106) = happyGoto action_29 action_184 (108) = happyGoto action_30 action_184 (114) = happyGoto action_31 action_184 (126) = happyGoto action_33 action_184 _ = happyFail action_185 _ = happyReduce_182 action_186 (128) = happyShift action_34 action_186 (129) = happyShift action_35 action_186 (130) = happyShift action_36 action_186 (131) = happyShift action_37 action_186 (132) = happyShift action_38 action_186 (137) = happyShift action_39 action_186 (138) = happyShift action_40 action_186 (139) = happyShift action_41 action_186 (140) = happyShift action_42 action_186 (141) = happyShift action_43 action_186 (142) = happyShift action_44 action_186 (148) = happyShift action_45 action_186 (151) = happyShift action_46 action_186 (157) = happyShift action_47 action_186 (162) = happyShift action_48 action_186 (165) = happyShift action_49 action_186 (166) = happyShift action_50 action_186 (171) = happyShift action_54 action_186 (173) = happyShift action_55 action_186 (174) = happyShift action_56 action_186 (181) = happyShift action_62 action_186 (188) = happyShift action_65 action_186 (191) = happyShift action_68 action_186 (192) = happyShift action_69 action_186 (193) = happyShift action_70 action_186 (194) = happyShift action_71 action_186 (69) = happyGoto action_295 action_186 (70) = happyGoto action_89 action_186 (71) = happyGoto action_20 action_186 (72) = happyGoto action_21 action_186 (74) = happyGoto action_22 action_186 (75) = happyGoto action_23 action_186 (93) = happyGoto action_24 action_186 (95) = happyGoto action_90 action_186 (97) = happyGoto action_26 action_186 (104) = happyGoto action_27 action_186 (105) = happyGoto action_28 action_186 (106) = happyGoto action_29 action_186 (108) = happyGoto action_30 action_186 (114) = happyGoto action_31 action_186 (126) = happyGoto action_33 action_186 _ = happyFail action_187 (128) = happyShift action_34 action_187 (129) = happyShift action_35 action_187 (130) = happyShift action_36 action_187 (131) = happyShift action_37 action_187 (132) = happyShift action_38 action_187 (137) = happyShift action_39 action_187 (138) = happyShift action_40 action_187 (139) = happyShift action_41 action_187 (140) = happyShift action_42 action_187 (141) = happyShift action_43 action_187 (142) = happyShift action_44 action_187 (148) = happyShift action_45 action_187 (151) = happyShift action_46 action_187 (157) = happyShift action_47 action_187 (162) = happyShift action_48 action_187 (165) = happyShift action_49 action_187 (166) = happyShift action_50 action_187 (171) = happyShift action_54 action_187 (173) = happyShift action_55 action_187 (174) = happyShift action_56 action_187 (181) = happyShift action_62 action_187 (188) = happyShift action_65 action_187 (191) = happyShift action_68 action_187 (192) = happyShift action_69 action_187 (193) = happyShift action_70 action_187 (194) = happyShift action_71 action_187 (69) = happyGoto action_294 action_187 (70) = happyGoto action_89 action_187 (71) = happyGoto action_20 action_187 (72) = happyGoto action_21 action_187 (74) = happyGoto action_22 action_187 (75) = happyGoto action_23 action_187 (93) = happyGoto action_24 action_187 (95) = happyGoto action_90 action_187 (97) = happyGoto action_26 action_187 (104) = happyGoto action_27 action_187 (105) = happyGoto action_28 action_187 (106) = happyGoto action_29 action_187 (108) = happyGoto action_30 action_187 (114) = happyGoto action_31 action_187 (126) = happyGoto action_33 action_187 _ = happyReduce_194 action_188 (128) = happyShift action_34 action_188 (129) = happyShift action_35 action_188 (130) = happyShift action_36 action_188 (131) = happyShift action_37 action_188 (132) = happyShift action_38 action_188 (137) = happyShift action_39 action_188 (138) = happyShift action_40 action_188 (139) = happyShift action_41 action_188 (140) = happyShift action_42 action_188 (141) = happyShift action_43 action_188 (142) = happyShift action_44 action_188 (148) = happyShift action_45 action_188 (151) = happyShift action_46 action_188 (157) = happyShift action_47 action_188 (162) = happyShift action_48 action_188 (165) = happyShift action_49 action_188 (166) = happyShift action_50 action_188 (171) = happyShift action_54 action_188 (173) = happyShift action_55 action_188 (174) = happyShift action_56 action_188 (181) = happyShift action_216 action_188 (188) = happyShift action_65 action_188 (191) = happyShift action_68 action_188 (192) = happyShift action_69 action_188 (193) = happyShift action_70 action_188 (194) = happyShift action_71 action_188 (69) = happyGoto action_291 action_188 (70) = happyGoto action_212 action_188 (71) = happyGoto action_20 action_188 (72) = happyGoto action_21 action_188 (74) = happyGoto action_22 action_188 (75) = happyGoto action_23 action_188 (80) = happyGoto action_292 action_188 (81) = happyGoto action_293 action_188 (93) = happyGoto action_24 action_188 (95) = happyGoto action_90 action_188 (97) = happyGoto action_26 action_188 (104) = happyGoto action_27 action_188 (105) = happyGoto action_28 action_188 (106) = happyGoto action_29 action_188 (108) = happyGoto action_30 action_188 (114) = happyGoto action_31 action_188 (126) = happyGoto action_33 action_188 _ = happyFail action_189 (128) = happyShift action_34 action_189 (129) = happyShift action_35 action_189 (130) = happyShift action_36 action_189 (131) = happyShift action_37 action_189 (132) = happyShift action_38 action_189 (137) = happyShift action_39 action_189 (138) = happyShift action_40 action_189 (139) = happyShift action_41 action_189 (140) = happyShift action_42 action_189 (141) = happyShift action_43 action_189 (142) = happyShift action_44 action_189 (148) = happyShift action_45 action_189 (151) = happyShift action_46 action_189 (157) = happyShift action_47 action_189 (162) = happyShift action_48 action_189 (165) = happyShift action_49 action_189 (166) = happyShift action_50 action_189 (171) = happyShift action_54 action_189 (173) = happyShift action_55 action_189 (174) = happyShift action_56 action_189 (181) = happyShift action_62 action_189 (188) = happyShift action_65 action_189 (191) = happyShift action_68 action_189 (192) = happyShift action_69 action_189 (193) = happyShift action_70 action_189 (194) = happyShift action_71 action_189 (69) = happyGoto action_290 action_189 (70) = happyGoto action_89 action_189 (71) = happyGoto action_20 action_189 (72) = happyGoto action_21 action_189 (74) = happyGoto action_22 action_189 (75) = happyGoto action_23 action_189 (93) = happyGoto action_24 action_189 (95) = happyGoto action_90 action_189 (97) = happyGoto action_26 action_189 (104) = happyGoto action_27 action_189 (105) = happyGoto action_28 action_189 (106) = happyGoto action_29 action_189 (108) = happyGoto action_30 action_189 (114) = happyGoto action_31 action_189 (126) = happyGoto action_33 action_189 _ = happyFail action_190 (145) = happyShift action_289 action_190 (82) = happyGoto action_287 action_190 (118) = happyGoto action_288 action_190 _ = happyReduce_282 action_191 (163) = happyShift action_286 action_191 _ = happyReduce_101 action_192 (128) = happyShift action_34 action_192 (130) = happyShift action_36 action_192 (131) = happyShift action_200 action_192 (137) = happyShift action_201 action_192 (142) = happyShift action_202 action_192 (148) = happyShift action_203 action_192 (160) = happyShift action_285 action_192 (165) = happyShift action_49 action_192 (173) = happyShift action_55 action_192 (188) = happyShift action_65 action_192 (39) = happyGoto action_284 action_192 (40) = happyGoto action_194 action_192 (105) = happyGoto action_196 action_192 (107) = happyGoto action_197 action_192 (108) = happyGoto action_80 action_192 (121) = happyGoto action_198 action_192 (124) = happyGoto action_199 action_192 _ = happyReduce_84 action_193 _ = happyReduce_86 action_194 _ = happyReduce_87 action_195 (187) = happyShift action_283 action_195 (58) = happyGoto action_282 action_195 _ = happyReduce_138 action_196 _ = happyReduce_288 action_197 _ = happyReduce_92 action_198 _ = happyReduce_261 action_199 _ = happyReduce_88 action_200 _ = happyReduce_262 action_201 (153) = happyShift action_281 action_201 _ = happyFail action_202 (128) = happyShift action_34 action_202 (130) = happyShift action_36 action_202 (131) = happyShift action_200 action_202 (137) = happyShift action_201 action_202 (142) = happyShift action_202 action_202 (143) = happyShift action_279 action_202 (148) = happyShift action_203 action_202 (150) = happyShift action_123 action_202 (160) = happyShift action_280 action_202 (165) = happyShift action_49 action_202 (173) = happyShift action_55 action_202 (188) = happyShift action_65 action_202 (37) = happyGoto action_276 action_202 (38) = happyGoto action_192 action_202 (39) = happyGoto action_193 action_202 (40) = happyGoto action_194 action_202 (42) = happyGoto action_277 action_202 (76) = happyGoto action_278 action_202 (105) = happyGoto action_196 action_202 (107) = happyGoto action_197 action_202 (108) = happyGoto action_80 action_202 (121) = happyGoto action_198 action_202 (124) = happyGoto action_199 action_202 _ = happyFail action_203 (128) = happyShift action_34 action_203 (130) = happyShift action_36 action_203 (131) = happyShift action_200 action_203 (137) = happyShift action_201 action_203 (142) = happyShift action_202 action_203 (148) = happyShift action_203 action_203 (149) = happyShift action_275 action_203 (165) = happyShift action_49 action_203 (173) = happyShift action_55 action_203 (188) = happyShift action_65 action_203 (37) = happyGoto action_274 action_203 (38) = happyGoto action_192 action_203 (39) = happyGoto action_193 action_203 (40) = happyGoto action_194 action_203 (105) = happyGoto action_196 action_203 (107) = happyGoto action_197 action_203 (108) = happyGoto action_80 action_203 (121) = happyGoto action_198 action_203 (124) = happyGoto action_199 action_203 _ = happyFail action_204 (163) = happyShift action_273 action_204 _ = happyFail action_205 (156) = happyShift action_272 action_205 _ = happyFail action_206 _ = happyReduce_105 action_207 _ = happyReduce_67 action_208 (128) = happyShift action_34 action_208 (130) = happyReduce_261 action_208 (131) = happyReduce_261 action_208 (137) = happyReduce_261 action_208 (142) = happyReduce_261 action_208 (148) = happyReduce_261 action_208 (156) = happyReduce_107 action_208 (160) = happyReduce_261 action_208 (163) = happyReduce_261 action_208 (165) = happyShift action_49 action_208 (173) = happyShift action_55 action_208 (188) = happyShift action_65 action_208 (45) = happyGoto action_231 action_208 (105) = happyGoto action_196 action_208 (124) = happyGoto action_232 action_208 _ = happyReduce_111 action_209 _ = happyReduce_66 action_210 (128) = happyShift action_34 action_210 (129) = happyShift action_35 action_210 (130) = happyShift action_36 action_210 (131) = happyShift action_37 action_210 (132) = happyShift action_38 action_210 (137) = happyShift action_39 action_210 (138) = happyShift action_40 action_210 (139) = happyShift action_41 action_210 (140) = happyShift action_42 action_210 (141) = happyShift action_43 action_210 (142) = happyShift action_44 action_210 (148) = happyShift action_45 action_210 (151) = happyShift action_46 action_210 (157) = happyShift action_47 action_210 (162) = happyShift action_48 action_210 (165) = happyShift action_49 action_210 (166) = happyShift action_50 action_210 (171) = happyShift action_54 action_210 (173) = happyShift action_55 action_210 (174) = happyShift action_56 action_210 (181) = happyShift action_216 action_210 (188) = happyShift action_65 action_210 (191) = happyShift action_68 action_210 (192) = happyShift action_69 action_210 (193) = happyShift action_70 action_210 (194) = happyShift action_71 action_210 (69) = happyGoto action_211 action_210 (70) = happyGoto action_212 action_210 (71) = happyGoto action_20 action_210 (72) = happyGoto action_21 action_210 (74) = happyGoto action_22 action_210 (75) = happyGoto action_23 action_210 (81) = happyGoto action_213 action_210 (89) = happyGoto action_271 action_210 (90) = happyGoto action_215 action_210 (93) = happyGoto action_24 action_210 (95) = happyGoto action_90 action_210 (97) = happyGoto action_26 action_210 (104) = happyGoto action_27 action_210 (105) = happyGoto action_28 action_210 (106) = happyGoto action_29 action_210 (108) = happyGoto action_30 action_210 (114) = happyGoto action_31 action_210 (126) = happyGoto action_33 action_210 _ = happyFail action_211 (144) = happyReduce_204 action_211 _ = happyReduce_220 action_212 (132) = happyShift action_137 action_212 (133) = happyShift action_118 action_212 (134) = happyShift action_119 action_212 (135) = happyShift action_120 action_212 (136) = happyShift action_121 action_212 (152) = happyShift action_124 action_212 (153) = happyShift action_125 action_212 (155) = happyShift action_181 action_212 (159) = happyShift action_270 action_212 (164) = happyShift action_126 action_212 (99) = happyGoto action_109 action_212 (101) = happyGoto action_110 action_212 (103) = happyGoto action_133 action_212 (109) = happyGoto action_134 action_212 (110) = happyGoto action_113 action_212 (111) = happyGoto action_135 action_212 (112) = happyGoto action_115 action_212 (113) = happyGoto action_116 action_212 _ = happyReduce_160 action_213 _ = happyReduce_222 action_214 (1) = happyShift action_146 action_214 (147) = happyShift action_147 action_214 (116) = happyGoto action_269 action_214 _ = happyFail action_215 (144) = happyShift action_268 action_215 _ = happyFail action_216 (145) = happyShift action_85 action_216 (34) = happyGoto action_267 action_216 (118) = happyGoto action_84 action_216 _ = happyReduce_282 action_217 (128) = happyShift action_34 action_217 (129) = happyShift action_35 action_217 (130) = happyShift action_36 action_217 (131) = happyShift action_37 action_217 (132) = happyShift action_38 action_217 (137) = happyShift action_39 action_217 (138) = happyShift action_40 action_217 (139) = happyShift action_41 action_217 (140) = happyShift action_42 action_217 (141) = happyShift action_43 action_217 (142) = happyShift action_44 action_217 (148) = happyShift action_45 action_217 (151) = happyShift action_46 action_217 (157) = happyShift action_47 action_217 (162) = happyShift action_48 action_217 (165) = happyShift action_49 action_217 (166) = happyShift action_50 action_217 (171) = happyShift action_54 action_217 (173) = happyShift action_55 action_217 (174) = happyShift action_56 action_217 (181) = happyShift action_62 action_217 (188) = happyShift action_65 action_217 (191) = happyShift action_68 action_217 (192) = happyShift action_69 action_217 (193) = happyShift action_70 action_217 (194) = happyShift action_71 action_217 (69) = happyGoto action_266 action_217 (70) = happyGoto action_89 action_217 (71) = happyGoto action_20 action_217 (72) = happyGoto action_21 action_217 (74) = happyGoto action_22 action_217 (75) = happyGoto action_23 action_217 (93) = happyGoto action_24 action_217 (95) = happyGoto action_90 action_217 (97) = happyGoto action_26 action_217 (104) = happyGoto action_27 action_217 (105) = happyGoto action_28 action_217 (106) = happyGoto action_29 action_217 (108) = happyGoto action_30 action_217 (114) = happyGoto action_31 action_217 (126) = happyGoto action_33 action_217 _ = happyFail action_218 (130) = happyShift action_73 action_218 (119) = happyGoto action_265 action_218 _ = happyFail action_219 _ = happyReduce_32 action_220 (187) = happyShift action_264 action_220 (62) = happyGoto action_263 action_220 _ = happyReduce_148 action_221 (128) = happyShift action_34 action_221 (129) = happyShift action_35 action_221 (130) = happyShift action_36 action_221 (131) = happyShift action_37 action_221 (132) = happyShift action_38 action_221 (137) = happyShift action_39 action_221 (138) = happyShift action_40 action_221 (139) = happyShift action_41 action_221 (140) = happyShift action_42 action_221 (141) = happyShift action_43 action_221 (142) = happyShift action_44 action_221 (144) = happyShift action_226 action_221 (148) = happyShift action_45 action_221 (151) = happyShift action_46 action_221 (157) = happyShift action_47 action_221 (162) = happyShift action_48 action_221 (165) = happyShift action_49 action_221 (166) = happyShift action_50 action_221 (171) = happyShift action_54 action_221 (173) = happyShift action_55 action_221 (174) = happyShift action_56 action_221 (177) = happyShift action_58 action_221 (178) = happyShift action_59 action_221 (179) = happyShift action_60 action_221 (181) = happyShift action_62 action_221 (188) = happyShift action_65 action_221 (190) = happyShift action_67 action_221 (191) = happyShift action_68 action_221 (192) = happyShift action_69 action_221 (193) = happyShift action_70 action_221 (194) = happyShift action_71 action_221 (7) = happyGoto action_222 action_221 (26) = happyGoto action_12 action_221 (28) = happyGoto action_13 action_221 (31) = happyGoto action_262 action_221 (32) = happyGoto action_224 action_221 (33) = happyGoto action_225 action_221 (35) = happyGoto action_16 action_221 (36) = happyGoto action_17 action_221 (64) = happyGoto action_18 action_221 (70) = happyGoto action_19 action_221 (71) = happyGoto action_20 action_221 (72) = happyGoto action_21 action_221 (74) = happyGoto action_22 action_221 (75) = happyGoto action_23 action_221 (93) = happyGoto action_24 action_221 (95) = happyGoto action_25 action_221 (97) = happyGoto action_26 action_221 (104) = happyGoto action_27 action_221 (105) = happyGoto action_28 action_221 (106) = happyGoto action_29 action_221 (108) = happyGoto action_30 action_221 (114) = happyGoto action_31 action_221 (125) = happyGoto action_32 action_221 (126) = happyGoto action_33 action_221 _ = happyReduce_10 action_222 _ = happyReduce_71 action_223 (1) = happyShift action_146 action_223 (147) = happyShift action_147 action_223 (116) = happyGoto action_261 action_223 _ = happyFail action_224 (144) = happyShift action_260 action_224 (7) = happyGoto action_259 action_224 _ = happyReduce_10 action_225 _ = happyReduce_73 action_226 _ = happyReduce_9 action_227 (128) = happyShift action_34 action_227 (129) = happyShift action_35 action_227 (130) = happyShift action_36 action_227 (131) = happyShift action_37 action_227 (132) = happyShift action_38 action_227 (137) = happyShift action_39 action_227 (138) = happyShift action_40 action_227 (139) = happyShift action_41 action_227 (140) = happyShift action_42 action_227 (141) = happyShift action_43 action_227 (142) = happyShift action_44 action_227 (148) = happyShift action_45 action_227 (151) = happyShift action_46 action_227 (157) = happyShift action_47 action_227 (162) = happyShift action_48 action_227 (165) = happyShift action_49 action_227 (166) = happyShift action_50 action_227 (171) = happyShift action_54 action_227 (173) = happyShift action_55 action_227 (174) = happyShift action_56 action_227 (181) = happyShift action_62 action_227 (188) = happyShift action_65 action_227 (191) = happyShift action_68 action_227 (192) = happyShift action_69 action_227 (193) = happyShift action_70 action_227 (194) = happyShift action_71 action_227 (69) = happyGoto action_258 action_227 (70) = happyGoto action_89 action_227 (71) = happyGoto action_20 action_227 (72) = happyGoto action_21 action_227 (74) = happyGoto action_22 action_227 (75) = happyGoto action_23 action_227 (93) = happyGoto action_24 action_227 (95) = happyGoto action_90 action_227 (97) = happyGoto action_26 action_227 (104) = happyGoto action_27 action_227 (105) = happyGoto action_28 action_227 (106) = happyGoto action_29 action_227 (108) = happyGoto action_30 action_227 (114) = happyGoto action_31 action_227 (126) = happyGoto action_33 action_227 _ = happyFail action_228 (163) = happyShift action_257 action_228 _ = happyFail action_229 (156) = happyShift action_256 action_229 _ = happyFail action_230 (128) = happyShift action_34 action_230 (156) = happyReduce_107 action_230 (165) = happyShift action_49 action_230 (173) = happyShift action_55 action_230 (188) = happyShift action_65 action_230 (45) = happyGoto action_231 action_230 (105) = happyGoto action_196 action_230 (124) = happyGoto action_232 action_230 _ = happyReduce_261 action_231 (128) = happyShift action_34 action_231 (165) = happyShift action_49 action_231 (173) = happyShift action_55 action_231 (188) = happyShift action_65 action_231 (105) = happyGoto action_196 action_231 (124) = happyGoto action_255 action_231 _ = happyReduce_106 action_232 _ = happyReduce_109 action_233 (156) = happyShift action_254 action_233 _ = happyFail action_234 (155) = happyShift action_253 action_234 _ = happyFail action_235 (128) = happyShift action_34 action_235 (165) = happyShift action_49 action_235 (173) = happyShift action_55 action_235 (188) = happyShift action_65 action_235 (105) = happyGoto action_251 action_235 (127) = happyGoto action_252 action_235 _ = happyReduce_295 action_236 (150) = happyShift action_250 action_236 (10) = happyGoto action_249 action_236 _ = happyReduce_16 action_237 _ = happyReduce_18 action_238 _ = happyReduce_19 action_239 _ = happyReduce_286 action_240 (142) = happyShift action_248 action_240 _ = happyReduce_20 action_241 (132) = happyShift action_137 action_241 (133) = happyShift action_118 action_241 (135) = happyShift action_120 action_241 (153) = happyShift action_125 action_241 (164) = happyShift action_126 action_241 (111) = happyGoto action_247 action_241 (112) = happyGoto action_115 action_241 (113) = happyGoto action_116 action_241 _ = happyFail action_242 _ = happyReduce_14 action_243 (130) = happyShift action_73 action_243 (119) = happyGoto action_246 action_243 _ = happyFail action_244 (145) = happyShift action_6 action_244 (5) = happyGoto action_245 action_244 (118) = happyGoto action_5 action_244 _ = happyReduce_282 action_245 _ = happyReduce_1 action_246 _ = happyReduce_24 action_247 (143) = happyShift action_173 action_247 _ = happyFail action_248 (128) = happyShift action_34 action_248 (129) = happyShift action_35 action_248 (130) = happyShift action_36 action_248 (131) = happyShift action_37 action_248 (142) = happyShift action_383 action_248 (143) = happyShift action_384 action_248 (154) = happyShift action_385 action_248 (165) = happyShift action_49 action_248 (173) = happyShift action_55 action_248 (188) = happyShift action_65 action_248 (13) = happyGoto action_379 action_248 (14) = happyGoto action_380 action_248 (95) = happyGoto action_381 action_248 (97) = happyGoto action_382 action_248 (104) = happyGoto action_27 action_248 (105) = happyGoto action_28 action_248 (106) = happyGoto action_29 action_248 (108) = happyGoto action_30 action_248 _ = happyFail action_249 (143) = happyShift action_378 action_249 _ = happyFail action_250 (128) = happyShift action_34 action_250 (129) = happyShift action_35 action_250 (130) = happyShift action_36 action_250 (131) = happyShift action_200 action_250 (142) = happyShift action_241 action_250 (165) = happyShift action_49 action_250 (173) = happyShift action_55 action_250 (182) = happyShift action_243 action_250 (188) = happyShift action_65 action_250 (12) = happyGoto action_377 action_250 (95) = happyGoto action_238 action_250 (104) = happyGoto action_27 action_250 (105) = happyGoto action_28 action_250 (107) = happyGoto action_239 action_250 (108) = happyGoto action_80 action_250 (121) = happyGoto action_198 action_250 (122) = happyGoto action_240 action_250 _ = happyReduce_15 action_251 (128) = happyShift action_34 action_251 (165) = happyShift action_49 action_251 (173) = happyShift action_55 action_251 (188) = happyShift action_65 action_251 (105) = happyGoto action_251 action_251 (127) = happyGoto action_376 action_251 _ = happyReduce_295 action_252 (156) = happyShift action_375 action_252 _ = happyFail action_253 (128) = happyShift action_34 action_253 (130) = happyShift action_36 action_253 (131) = happyShift action_200 action_253 (137) = happyShift action_201 action_253 (142) = happyShift action_202 action_253 (148) = happyShift action_203 action_253 (165) = happyShift action_49 action_253 (173) = happyShift action_55 action_253 (188) = happyShift action_65 action_253 (37) = happyGoto action_374 action_253 (38) = happyGoto action_192 action_253 (39) = happyGoto action_193 action_253 (40) = happyGoto action_194 action_253 (105) = happyGoto action_196 action_253 (107) = happyGoto action_197 action_253 (108) = happyGoto action_80 action_253 (121) = happyGoto action_198 action_253 (124) = happyGoto action_199 action_253 _ = happyFail action_254 (128) = happyShift action_34 action_254 (130) = happyShift action_36 action_254 (131) = happyShift action_200 action_254 (137) = happyShift action_201 action_254 (142) = happyShift action_202 action_254 (148) = happyShift action_203 action_254 (165) = happyShift action_49 action_254 (173) = happyShift action_55 action_254 (188) = happyShift action_65 action_254 (37) = happyGoto action_373 action_254 (38) = happyGoto action_192 action_254 (39) = happyGoto action_193 action_254 (40) = happyGoto action_194 action_254 (105) = happyGoto action_196 action_254 (107) = happyGoto action_197 action_254 (108) = happyGoto action_80 action_254 (121) = happyGoto action_198 action_254 (124) = happyGoto action_199 action_254 _ = happyFail action_255 _ = happyReduce_108 action_256 (48) = happyGoto action_372 action_256 (115) = happyGoto action_360 action_256 _ = happyReduce_278 action_257 (130) = happyShift action_36 action_257 (44) = happyGoto action_356 action_257 (108) = happyGoto action_80 action_257 (121) = happyGoto action_81 action_257 _ = happyFail action_258 _ = happyReduce_165 action_259 _ = happyReduce_70 action_260 (128) = happyShift action_34 action_260 (129) = happyShift action_35 action_260 (130) = happyShift action_36 action_260 (131) = happyShift action_37 action_260 (132) = happyShift action_38 action_260 (137) = happyShift action_39 action_260 (138) = happyShift action_40 action_260 (139) = happyShift action_41 action_260 (140) = happyShift action_42 action_260 (141) = happyShift action_43 action_260 (142) = happyShift action_44 action_260 (148) = happyShift action_45 action_260 (151) = happyShift action_46 action_260 (157) = happyShift action_47 action_260 (162) = happyShift action_48 action_260 (165) = happyShift action_49 action_260 (166) = happyShift action_50 action_260 (171) = happyShift action_54 action_260 (173) = happyShift action_55 action_260 (174) = happyShift action_56 action_260 (177) = happyShift action_58 action_260 (178) = happyShift action_59 action_260 (179) = happyShift action_60 action_260 (181) = happyShift action_62 action_260 (188) = happyShift action_65 action_260 (190) = happyShift action_67 action_260 (191) = happyShift action_68 action_260 (192) = happyShift action_69 action_260 (193) = happyShift action_70 action_260 (194) = happyShift action_71 action_260 (26) = happyGoto action_12 action_260 (28) = happyGoto action_13 action_260 (33) = happyGoto action_371 action_260 (35) = happyGoto action_16 action_260 (36) = happyGoto action_17 action_260 (64) = happyGoto action_18 action_260 (70) = happyGoto action_19 action_260 (71) = happyGoto action_20 action_260 (72) = happyGoto action_21 action_260 (74) = happyGoto action_22 action_260 (75) = happyGoto action_23 action_260 (93) = happyGoto action_24 action_260 (95) = happyGoto action_25 action_260 (97) = happyGoto action_26 action_260 (104) = happyGoto action_27 action_260 (105) = happyGoto action_28 action_260 (106) = happyGoto action_29 action_260 (108) = happyGoto action_30 action_260 (114) = happyGoto action_31 action_260 (125) = happyGoto action_32 action_260 (126) = happyGoto action_33 action_260 _ = happyReduce_9 action_261 _ = happyReduce_79 action_262 (146) = happyShift action_370 action_262 _ = happyFail action_263 _ = happyReduce_65 action_264 (145) = happyShift action_369 action_264 (118) = happyGoto action_368 action_264 _ = happyReduce_282 action_265 (165) = happyShift action_367 action_265 (18) = happyGoto action_366 action_265 _ = happyReduce_35 action_266 (172) = happyShift action_365 action_266 _ = happyFail action_267 (176) = happyShift action_227 action_267 _ = happyReduce_205 action_268 (128) = happyShift action_34 action_268 (129) = happyShift action_35 action_268 (130) = happyShift action_36 action_268 (131) = happyShift action_37 action_268 (132) = happyShift action_38 action_268 (137) = happyShift action_39 action_268 (138) = happyShift action_40 action_268 (139) = happyShift action_41 action_268 (140) = happyShift action_42 action_268 (141) = happyShift action_43 action_268 (142) = happyShift action_44 action_268 (148) = happyShift action_45 action_268 (151) = happyShift action_46 action_268 (157) = happyShift action_47 action_268 (162) = happyShift action_48 action_268 (165) = happyShift action_49 action_268 (166) = happyShift action_50 action_268 (171) = happyShift action_54 action_268 (173) = happyShift action_55 action_268 (174) = happyShift action_56 action_268 (181) = happyShift action_216 action_268 (188) = happyShift action_65 action_268 (191) = happyShift action_68 action_268 (192) = happyShift action_69 action_268 (193) = happyShift action_70 action_268 (194) = happyShift action_71 action_268 (69) = happyGoto action_363 action_268 (70) = happyGoto action_212 action_268 (71) = happyGoto action_20 action_268 (72) = happyGoto action_21 action_268 (74) = happyGoto action_22 action_268 (75) = happyGoto action_23 action_268 (81) = happyGoto action_364 action_268 (93) = happyGoto action_24 action_268 (95) = happyGoto action_90 action_268 (97) = happyGoto action_26 action_268 (104) = happyGoto action_27 action_268 (105) = happyGoto action_28 action_268 (106) = happyGoto action_29 action_268 (108) = happyGoto action_30 action_268 (114) = happyGoto action_31 action_268 (126) = happyGoto action_33 action_268 _ = happyFail action_269 _ = happyReduce_218 action_270 (128) = happyShift action_34 action_270 (129) = happyShift action_35 action_270 (130) = happyShift action_36 action_270 (131) = happyShift action_37 action_270 (132) = happyShift action_38 action_270 (137) = happyShift action_39 action_270 (138) = happyShift action_40 action_270 (139) = happyShift action_41 action_270 (140) = happyShift action_42 action_270 (141) = happyShift action_43 action_270 (142) = happyShift action_44 action_270 (148) = happyShift action_45 action_270 (151) = happyShift action_46 action_270 (157) = happyShift action_47 action_270 (162) = happyShift action_48 action_270 (165) = happyShift action_49 action_270 (166) = happyShift action_50 action_270 (171) = happyShift action_54 action_270 (173) = happyShift action_55 action_270 (174) = happyShift action_56 action_270 (181) = happyShift action_62 action_270 (188) = happyShift action_65 action_270 (191) = happyShift action_68 action_270 (192) = happyShift action_69 action_270 (193) = happyShift action_70 action_270 (194) = happyShift action_71 action_270 (69) = happyGoto action_362 action_270 (70) = happyGoto action_89 action_270 (71) = happyGoto action_20 action_270 (72) = happyGoto action_21 action_270 (74) = happyGoto action_22 action_270 (75) = happyGoto action_23 action_270 (93) = happyGoto action_24 action_270 (95) = happyGoto action_90 action_270 (97) = happyGoto action_26 action_270 (104) = happyGoto action_27 action_270 (105) = happyGoto action_28 action_270 (106) = happyGoto action_29 action_270 (108) = happyGoto action_30 action_270 (114) = happyGoto action_31 action_270 (126) = happyGoto action_33 action_270 _ = happyFail action_271 (146) = happyShift action_361 action_271 _ = happyFail action_272 (47) = happyGoto action_358 action_272 (48) = happyGoto action_359 action_272 (115) = happyGoto action_360 action_272 _ = happyReduce_278 action_273 (130) = happyShift action_36 action_273 (44) = happyGoto action_356 action_273 (108) = happyGoto action_80 action_273 (121) = happyGoto action_357 action_273 _ = happyFail action_274 (149) = happyShift action_355 action_274 _ = happyFail action_275 _ = happyReduce_94 action_276 (143) = happyShift action_353 action_276 (150) = happyShift action_354 action_276 _ = happyFail action_277 (143) = happyShift action_351 action_277 (150) = happyShift action_352 action_277 _ = happyFail action_278 (143) = happyShift action_350 action_278 (150) = happyShift action_179 action_278 _ = happyFail action_279 _ = happyReduce_93 action_280 (143) = happyShift action_349 action_280 _ = happyFail action_281 (142) = happyShift action_347 action_281 (148) = happyShift action_348 action_281 _ = happyFail action_282 _ = happyReduce_64 action_283 (145) = happyShift action_346 action_283 (118) = happyGoto action_345 action_283 _ = happyReduce_282 action_284 _ = happyReduce_85 action_285 (128) = happyShift action_34 action_285 (130) = happyShift action_36 action_285 (131) = happyShift action_200 action_285 (137) = happyShift action_201 action_285 (142) = happyShift action_202 action_285 (148) = happyShift action_203 action_285 (165) = happyShift action_49 action_285 (173) = happyShift action_55 action_285 (188) = happyShift action_65 action_285 (37) = happyGoto action_344 action_285 (38) = happyGoto action_192 action_285 (39) = happyGoto action_193 action_285 (40) = happyGoto action_194 action_285 (105) = happyGoto action_196 action_285 (107) = happyGoto action_197 action_285 (108) = happyGoto action_80 action_285 (121) = happyGoto action_198 action_285 (124) = happyGoto action_199 action_285 _ = happyFail action_286 (128) = happyShift action_34 action_286 (130) = happyShift action_36 action_286 (131) = happyShift action_200 action_286 (137) = happyShift action_201 action_286 (142) = happyShift action_202 action_286 (148) = happyShift action_203 action_286 (165) = happyShift action_49 action_286 (173) = happyShift action_55 action_286 (188) = happyShift action_65 action_286 (37) = happyGoto action_343 action_286 (38) = happyGoto action_192 action_286 (39) = happyGoto action_193 action_286 (40) = happyGoto action_194 action_286 (105) = happyGoto action_196 action_286 (107) = happyGoto action_197 action_286 (108) = happyGoto action_80 action_286 (121) = happyGoto action_198 action_286 (124) = happyGoto action_199 action_286 _ = happyFail action_287 _ = happyReduce_167 action_288 (128) = happyShift action_34 action_288 (129) = happyShift action_35 action_288 (130) = happyShift action_36 action_288 (131) = happyShift action_37 action_288 (132) = happyShift action_38 action_288 (137) = happyShift action_39 action_288 (138) = happyShift action_40 action_288 (139) = happyShift action_41 action_288 (140) = happyShift action_42 action_288 (141) = happyShift action_43 action_288 (142) = happyShift action_44 action_288 (148) = happyShift action_45 action_288 (151) = happyShift action_46 action_288 (157) = happyShift action_47 action_288 (162) = happyShift action_48 action_288 (165) = happyShift action_49 action_288 (166) = happyShift action_50 action_288 (171) = happyShift action_54 action_288 (173) = happyShift action_55 action_288 (174) = happyShift action_56 action_288 (181) = happyShift action_62 action_288 (188) = happyShift action_65 action_288 (191) = happyShift action_68 action_288 (192) = happyShift action_69 action_288 (193) = happyShift action_70 action_288 (194) = happyShift action_71 action_288 (70) = happyGoto action_340 action_288 (71) = happyGoto action_20 action_288 (72) = happyGoto action_21 action_288 (74) = happyGoto action_22 action_288 (75) = happyGoto action_23 action_288 (83) = happyGoto action_341 action_288 (84) = happyGoto action_342 action_288 (93) = happyGoto action_24 action_288 (95) = happyGoto action_90 action_288 (97) = happyGoto action_26 action_288 (104) = happyGoto action_27 action_288 (105) = happyGoto action_28 action_288 (106) = happyGoto action_29 action_288 (108) = happyGoto action_30 action_288 (114) = happyGoto action_31 action_288 (126) = happyGoto action_33 action_288 _ = happyFail action_289 (117) = happyGoto action_339 action_289 _ = happyReduce_281 action_290 _ = happyReduce_163 action_291 _ = happyReduce_204 action_292 (150) = happyShift action_338 action_292 _ = happyReduce_198 action_293 _ = happyReduce_202 action_294 _ = happyReduce_196 action_295 (154) = happyShift action_337 action_295 _ = happyReduce_200 action_296 _ = happyReduce_199 action_297 _ = happyReduce_191 action_298 (128) = happyShift action_34 action_298 (130) = happyShift action_36 action_298 (131) = happyShift action_200 action_298 (137) = happyShift action_201 action_298 (142) = happyShift action_202 action_298 (148) = happyShift action_203 action_298 (165) = happyShift action_49 action_298 (173) = happyShift action_55 action_298 (188) = happyShift action_65 action_298 (37) = happyGoto action_191 action_298 (38) = happyGoto action_192 action_298 (39) = happyGoto action_193 action_298 (40) = happyGoto action_194 action_298 (41) = happyGoto action_336 action_298 (105) = happyGoto action_196 action_298 (107) = happyGoto action_197 action_298 (108) = happyGoto action_80 action_298 (121) = happyGoto action_198 action_298 (124) = happyGoto action_199 action_298 _ = happyFail action_299 _ = happyReduce_183 action_300 _ = happyReduce_190 action_301 _ = happyReduce_184 action_302 _ = happyReduce_248 action_303 _ = happyReduce_244 action_304 _ = happyReduce_230 action_305 (143) = happyShift action_335 action_305 (150) = happyShift action_179 action_305 _ = happyFail action_306 _ = happyReduce_229 action_307 _ = happyReduce_164 action_308 (146) = happyShift action_333 action_308 (150) = happyShift action_334 action_308 _ = happyFail action_309 _ = happyReduce_224 action_310 (156) = happyShift action_332 action_310 _ = happyFail action_311 (115) = happyGoto action_331 action_311 _ = happyReduce_278 action_312 _ = happyReduce_154 action_313 _ = happyReduce_156 action_314 _ = happyReduce_151 action_315 (145) = happyShift action_85 action_315 (34) = happyGoto action_330 action_315 (118) = happyGoto action_84 action_315 _ = happyReduce_282 action_316 _ = happyReduce_80 action_317 (143) = happyShift action_329 action_317 _ = happyFail action_318 _ = happyReduce_53 action_319 _ = happyReduce_249 action_320 _ = happyReduce_250 action_321 (150) = happyShift action_328 action_321 _ = happyReduce_60 action_322 _ = happyReduce_245 action_323 _ = happyReduce_241 action_324 (128) = happyShift action_34 action_324 (130) = happyShift action_36 action_324 (165) = happyShift action_49 action_324 (173) = happyShift action_55 action_324 (188) = happyShift action_65 action_324 (105) = happyGoto action_326 action_324 (108) = happyGoto action_327 action_324 _ = happyFail action_325 _ = happyReduce_5 action_326 (152) = happyShift action_436 action_326 _ = happyFail action_327 (152) = happyShift action_435 action_327 _ = happyFail action_328 (132) = happyShift action_137 action_328 (133) = happyShift action_118 action_328 (134) = happyShift action_119 action_328 (152) = happyShift action_324 action_328 (153) = happyShift action_125 action_328 (164) = happyShift action_126 action_328 (29) = happyGoto action_434 action_328 (98) = happyGoto action_319 action_328 (100) = happyGoto action_320 action_328 (102) = happyGoto action_321 action_328 (110) = happyGoto action_322 action_328 (112) = happyGoto action_323 action_328 _ = happyFail action_329 _ = happyReduce_234 action_330 _ = happyReduce_152 action_331 (156) = happyShift action_433 action_331 _ = happyFail action_332 (128) = happyShift action_34 action_332 (129) = happyShift action_35 action_332 (130) = happyShift action_36 action_332 (131) = happyShift action_37 action_332 (132) = happyShift action_38 action_332 (137) = happyShift action_39 action_332 (138) = happyShift action_40 action_332 (139) = happyShift action_41 action_332 (140) = happyShift action_42 action_332 (141) = happyShift action_43 action_332 (142) = happyShift action_44 action_332 (148) = happyShift action_45 action_332 (151) = happyShift action_46 action_332 (157) = happyShift action_47 action_332 (162) = happyShift action_48 action_332 (165) = happyShift action_49 action_332 (166) = happyShift action_50 action_332 (171) = happyShift action_54 action_332 (173) = happyShift action_55 action_332 (174) = happyShift action_56 action_332 (181) = happyShift action_62 action_332 (188) = happyShift action_65 action_332 (191) = happyShift action_68 action_332 (192) = happyShift action_69 action_332 (193) = happyShift action_70 action_332 (194) = happyShift action_71 action_332 (69) = happyGoto action_432 action_332 (70) = happyGoto action_89 action_332 (71) = happyGoto action_20 action_332 (72) = happyGoto action_21 action_332 (74) = happyGoto action_22 action_332 (75) = happyGoto action_23 action_332 (93) = happyGoto action_24 action_332 (95) = happyGoto action_90 action_332 (97) = happyGoto action_26 action_332 (104) = happyGoto action_27 action_332 (105) = happyGoto action_28 action_332 (106) = happyGoto action_29 action_332 (108) = happyGoto action_30 action_332 (114) = happyGoto action_31 action_332 (126) = happyGoto action_33 action_332 _ = happyFail action_333 _ = happyReduce_175 action_334 (128) = happyShift action_34 action_334 (129) = happyShift action_35 action_334 (142) = happyShift action_241 action_334 (165) = happyShift action_49 action_334 (173) = happyShift action_55 action_334 (188) = happyShift action_65 action_334 (92) = happyGoto action_431 action_334 (95) = happyGoto action_310 action_334 (104) = happyGoto action_27 action_334 (105) = happyGoto action_28 action_334 _ = happyFail action_335 _ = happyReduce_231 action_336 _ = happyReduce_159 action_337 (128) = happyShift action_34 action_337 (129) = happyShift action_35 action_337 (130) = happyShift action_36 action_337 (131) = happyShift action_37 action_337 (132) = happyShift action_38 action_337 (137) = happyShift action_39 action_337 (138) = happyShift action_40 action_337 (139) = happyShift action_41 action_337 (140) = happyShift action_42 action_337 (141) = happyShift action_43 action_337 (142) = happyShift action_44 action_337 (148) = happyShift action_45 action_337 (151) = happyShift action_46 action_337 (157) = happyShift action_47 action_337 (162) = happyShift action_48 action_337 (165) = happyShift action_49 action_337 (166) = happyShift action_50 action_337 (171) = happyShift action_54 action_337 (173) = happyShift action_55 action_337 (174) = happyShift action_56 action_337 (181) = happyShift action_62 action_337 (188) = happyShift action_65 action_337 (191) = happyShift action_68 action_337 (192) = happyShift action_69 action_337 (193) = happyShift action_70 action_337 (194) = happyShift action_71 action_337 (69) = happyGoto action_430 action_337 (70) = happyGoto action_89 action_337 (71) = happyGoto action_20 action_337 (72) = happyGoto action_21 action_337 (74) = happyGoto action_22 action_337 (75) = happyGoto action_23 action_337 (93) = happyGoto action_24 action_337 (95) = happyGoto action_90 action_337 (97) = happyGoto action_26 action_337 (104) = happyGoto action_27 action_337 (105) = happyGoto action_28 action_337 (106) = happyGoto action_29 action_337 (108) = happyGoto action_30 action_337 (114) = happyGoto action_31 action_337 (126) = happyGoto action_33 action_337 _ = happyReduce_195 action_338 (128) = happyShift action_34 action_338 (129) = happyShift action_35 action_338 (130) = happyShift action_36 action_338 (131) = happyShift action_37 action_338 (132) = happyShift action_38 action_338 (137) = happyShift action_39 action_338 (138) = happyShift action_40 action_338 (139) = happyShift action_41 action_338 (140) = happyShift action_42 action_338 (141) = happyShift action_43 action_338 (142) = happyShift action_44 action_338 (148) = happyShift action_45 action_338 (151) = happyShift action_46 action_338 (157) = happyShift action_47 action_338 (162) = happyShift action_48 action_338 (165) = happyShift action_49 action_338 (166) = happyShift action_50 action_338 (171) = happyShift action_54 action_338 (173) = happyShift action_55 action_338 (174) = happyShift action_56 action_338 (181) = happyShift action_216 action_338 (188) = happyShift action_65 action_338 (191) = happyShift action_68 action_338 (192) = happyShift action_69 action_338 (193) = happyShift action_70 action_338 (194) = happyShift action_71 action_338 (69) = happyGoto action_291 action_338 (70) = happyGoto action_212 action_338 (71) = happyGoto action_20 action_338 (72) = happyGoto action_21 action_338 (74) = happyGoto action_22 action_338 (75) = happyGoto action_23 action_338 (81) = happyGoto action_429 action_338 (93) = happyGoto action_24 action_338 (95) = happyGoto action_90 action_338 (97) = happyGoto action_26 action_338 (104) = happyGoto action_27 action_338 (105) = happyGoto action_28 action_338 (106) = happyGoto action_29 action_338 (108) = happyGoto action_30 action_338 (114) = happyGoto action_31 action_338 (126) = happyGoto action_33 action_338 _ = happyFail action_339 (128) = happyShift action_34 action_339 (129) = happyShift action_35 action_339 (130) = happyShift action_36 action_339 (131) = happyShift action_37 action_339 (132) = happyShift action_38 action_339 (137) = happyShift action_39 action_339 (138) = happyShift action_40 action_339 (139) = happyShift action_41 action_339 (140) = happyShift action_42 action_339 (141) = happyShift action_43 action_339 (142) = happyShift action_44 action_339 (148) = happyShift action_45 action_339 (151) = happyShift action_46 action_339 (157) = happyShift action_47 action_339 (162) = happyShift action_48 action_339 (165) = happyShift action_49 action_339 (166) = happyShift action_50 action_339 (171) = happyShift action_54 action_339 (173) = happyShift action_55 action_339 (174) = happyShift action_56 action_339 (181) = happyShift action_62 action_339 (188) = happyShift action_65 action_339 (191) = happyShift action_68 action_339 (192) = happyShift action_69 action_339 (193) = happyShift action_70 action_339 (194) = happyShift action_71 action_339 (70) = happyGoto action_340 action_339 (71) = happyGoto action_20 action_339 (72) = happyGoto action_21 action_339 (74) = happyGoto action_22 action_339 (75) = happyGoto action_23 action_339 (83) = happyGoto action_428 action_339 (84) = happyGoto action_342 action_339 (93) = happyGoto action_24 action_339 (95) = happyGoto action_90 action_339 (97) = happyGoto action_26 action_339 (104) = happyGoto action_27 action_339 (105) = happyGoto action_28 action_339 (106) = happyGoto action_29 action_339 (108) = happyGoto action_30 action_339 (114) = happyGoto action_31 action_339 (126) = happyGoto action_33 action_339 _ = happyFail action_340 (132) = happyShift action_137 action_340 (133) = happyShift action_118 action_340 (134) = happyShift action_119 action_340 (135) = happyShift action_120 action_340 (136) = happyShift action_121 action_340 (152) = happyShift action_124 action_340 (153) = happyShift action_125 action_340 (164) = happyShift action_126 action_340 (99) = happyGoto action_109 action_340 (101) = happyGoto action_110 action_340 (103) = happyGoto action_133 action_340 (109) = happyGoto action_134 action_340 (110) = happyGoto action_113 action_340 (111) = happyGoto action_135 action_340 (112) = happyGoto action_115 action_340 (113) = happyGoto action_116 action_340 (115) = happyGoto action_427 action_340 _ = happyReduce_278 action_341 (144) = happyShift action_426 action_341 (7) = happyGoto action_425 action_341 _ = happyReduce_10 action_342 _ = happyReduce_209 action_343 _ = happyReduce_100 action_344 _ = happyReduce_83 action_345 (128) = happyShift action_34 action_345 (129) = happyShift action_35 action_345 (142) = happyShift action_241 action_345 (144) = happyShift action_226 action_345 (165) = happyShift action_49 action_345 (173) = happyShift action_55 action_345 (188) = happyShift action_65 action_345 (7) = happyGoto action_420 action_345 (35) = happyGoto action_421 action_345 (36) = happyGoto action_17 action_345 (59) = happyGoto action_422 action_345 (60) = happyGoto action_423 action_345 (95) = happyGoto action_424 action_345 (104) = happyGoto action_27 action_345 (105) = happyGoto action_28 action_345 _ = happyReduce_10 action_346 (117) = happyGoto action_419 action_346 _ = happyReduce_281 action_347 (143) = happyShift action_418 action_347 (150) = happyShift action_123 action_347 (76) = happyGoto action_417 action_347 _ = happyFail action_348 (149) = happyShift action_416 action_348 _ = happyFail action_349 _ = happyReduce_95 action_350 _ = happyReduce_96 action_351 _ = happyReduce_89 action_352 (128) = happyShift action_34 action_352 (130) = happyShift action_36 action_352 (131) = happyShift action_200 action_352 (137) = happyShift action_201 action_352 (142) = happyShift action_202 action_352 (148) = happyShift action_203 action_352 (165) = happyShift action_49 action_352 (173) = happyShift action_55 action_352 (188) = happyShift action_65 action_352 (37) = happyGoto action_415 action_352 (38) = happyGoto action_192 action_352 (39) = happyGoto action_193 action_352 (40) = happyGoto action_194 action_352 (105) = happyGoto action_196 action_352 (107) = happyGoto action_197 action_352 (108) = happyGoto action_80 action_352 (121) = happyGoto action_198 action_352 (124) = happyGoto action_199 action_352 _ = happyFail action_353 _ = happyReduce_91 action_354 (128) = happyShift action_34 action_354 (130) = happyShift action_36 action_354 (131) = happyShift action_200 action_354 (137) = happyShift action_201 action_354 (142) = happyShift action_202 action_354 (148) = happyShift action_203 action_354 (165) = happyShift action_49 action_354 (173) = happyShift action_55 action_354 (188) = happyShift action_65 action_354 (37) = happyGoto action_414 action_354 (38) = happyGoto action_192 action_354 (39) = happyGoto action_193 action_354 (40) = happyGoto action_194 action_354 (105) = happyGoto action_196 action_354 (107) = happyGoto action_197 action_354 (108) = happyGoto action_80 action_354 (121) = happyGoto action_198 action_354 (124) = happyGoto action_199 action_354 _ = happyFail action_355 _ = happyReduce_90 action_356 _ = happyReduce_104 action_357 (128) = happyShift action_34 action_357 (156) = happyReduce_107 action_357 (165) = happyShift action_49 action_357 (173) = happyShift action_55 action_357 (188) = happyShift action_65 action_357 (45) = happyGoto action_231 action_357 (105) = happyGoto action_196 action_357 (124) = happyGoto action_232 action_357 _ = happyReduce_110 action_358 (158) = happyShift action_413 action_358 (170) = happyShift action_392 action_358 (56) = happyGoto action_412 action_358 _ = happyReduce_130 action_359 _ = happyReduce_113 action_360 (128) = happyShift action_34 action_360 (130) = happyShift action_36 action_360 (131) = happyShift action_200 action_360 (137) = happyShift action_201 action_360 (142) = happyShift action_410 action_360 (148) = happyShift action_203 action_360 (164) = happyShift action_411 action_360 (165) = happyShift action_49 action_360 (173) = happyShift action_55 action_360 (188) = happyShift action_65 action_360 (38) = happyGoto action_404 action_360 (39) = happyGoto action_193 action_360 (40) = happyGoto action_194 action_360 (49) = happyGoto action_405 action_360 (50) = happyGoto action_406 action_360 (52) = happyGoto action_407 action_360 (96) = happyGoto action_408 action_360 (105) = happyGoto action_196 action_360 (107) = happyGoto action_197 action_360 (108) = happyGoto action_409 action_360 (121) = happyGoto action_198 action_360 (124) = happyGoto action_199 action_360 _ = happyFail action_361 _ = happyReduce_217 action_362 _ = happyReduce_203 action_363 (144) = happyReduce_204 action_363 _ = happyReduce_219 action_364 _ = happyReduce_221 action_365 (128) = happyShift action_34 action_365 (129) = happyShift action_35 action_365 (130) = happyShift action_36 action_365 (131) = happyShift action_37 action_365 (132) = happyShift action_38 action_365 (137) = happyShift action_39 action_365 (138) = happyShift action_40 action_365 (139) = happyShift action_41 action_365 (140) = happyShift action_42 action_365 (141) = happyShift action_43 action_365 (142) = happyShift action_44 action_365 (148) = happyShift action_45 action_365 (151) = happyShift action_46 action_365 (157) = happyShift action_47 action_365 (162) = happyShift action_48 action_365 (165) = happyShift action_49 action_365 (166) = happyShift action_50 action_365 (171) = happyShift action_54 action_365 (173) = happyShift action_55 action_365 (174) = happyShift action_56 action_365 (181) = happyShift action_62 action_365 (188) = happyShift action_65 action_365 (191) = happyShift action_68 action_365 (192) = happyShift action_69 action_365 (193) = happyShift action_70 action_365 (194) = happyShift action_71 action_365 (69) = happyGoto action_403 action_365 (70) = happyGoto action_89 action_365 (71) = happyGoto action_20 action_365 (72) = happyGoto action_21 action_365 (74) = happyGoto action_22 action_365 (75) = happyGoto action_23 action_365 (93) = happyGoto action_24 action_365 (95) = happyGoto action_90 action_365 (97) = happyGoto action_26 action_365 (104) = happyGoto action_27 action_365 (105) = happyGoto action_28 action_365 (106) = happyGoto action_29 action_365 (108) = happyGoto action_30 action_365 (114) = happyGoto action_31 action_365 (126) = happyGoto action_33 action_365 _ = happyFail action_366 (142) = happyShift action_401 action_366 (173) = happyShift action_402 action_366 (19) = happyGoto action_399 action_366 (20) = happyGoto action_400 action_366 _ = happyReduce_37 action_367 (130) = happyShift action_73 action_367 (119) = happyGoto action_398 action_367 _ = happyFail action_368 (128) = happyShift action_34 action_368 (129) = happyShift action_35 action_368 (130) = happyShift action_36 action_368 (131) = happyShift action_37 action_368 (132) = happyShift action_38 action_368 (137) = happyShift action_39 action_368 (138) = happyShift action_40 action_368 (139) = happyShift action_41 action_368 (140) = happyShift action_42 action_368 (141) = happyShift action_43 action_368 (142) = happyShift action_44 action_368 (144) = happyShift action_226 action_368 (148) = happyShift action_45 action_368 (151) = happyShift action_46 action_368 (157) = happyShift action_47 action_368 (162) = happyShift action_48 action_368 (165) = happyShift action_49 action_368 (166) = happyShift action_50 action_368 (171) = happyShift action_54 action_368 (173) = happyShift action_55 action_368 (174) = happyShift action_56 action_368 (181) = happyShift action_62 action_368 (188) = happyShift action_65 action_368 (191) = happyShift action_68 action_368 (192) = happyShift action_69 action_368 (193) = happyShift action_70 action_368 (194) = happyShift action_71 action_368 (7) = happyGoto action_394 action_368 (61) = happyGoto action_395 action_368 (63) = happyGoto action_396 action_368 (64) = happyGoto action_397 action_368 (70) = happyGoto action_19 action_368 (71) = happyGoto action_20 action_368 (72) = happyGoto action_21 action_368 (74) = happyGoto action_22 action_368 (75) = happyGoto action_23 action_368 (93) = happyGoto action_24 action_368 (95) = happyGoto action_90 action_368 (97) = happyGoto action_26 action_368 (104) = happyGoto action_27 action_368 (105) = happyGoto action_28 action_368 (106) = happyGoto action_29 action_368 (108) = happyGoto action_30 action_368 (114) = happyGoto action_31 action_368 (126) = happyGoto action_33 action_368 _ = happyReduce_10 action_369 (117) = happyGoto action_393 action_369 _ = happyReduce_281 action_370 _ = happyReduce_78 action_371 _ = happyReduce_72 action_372 (170) = happyShift action_392 action_372 (56) = happyGoto action_391 action_372 _ = happyReduce_130 action_373 _ = happyReduce_61 action_374 _ = happyReduce_68 action_375 (128) = happyShift action_34 action_375 (129) = happyShift action_35 action_375 (130) = happyShift action_36 action_375 (131) = happyShift action_37 action_375 (132) = happyShift action_38 action_375 (137) = happyShift action_39 action_375 (138) = happyShift action_40 action_375 (139) = happyShift action_41 action_375 (140) = happyShift action_42 action_375 (141) = happyShift action_43 action_375 (142) = happyShift action_44 action_375 (148) = happyShift action_45 action_375 (151) = happyShift action_46 action_375 (157) = happyShift action_47 action_375 (162) = happyShift action_48 action_375 (165) = happyShift action_49 action_375 (166) = happyShift action_50 action_375 (171) = happyShift action_54 action_375 (173) = happyShift action_55 action_375 (174) = happyShift action_56 action_375 (181) = happyShift action_62 action_375 (188) = happyShift action_65 action_375 (191) = happyShift action_68 action_375 (192) = happyShift action_69 action_375 (193) = happyShift action_70 action_375 (194) = happyShift action_71 action_375 (69) = happyGoto action_390 action_375 (70) = happyGoto action_89 action_375 (71) = happyGoto action_20 action_375 (72) = happyGoto action_21 action_375 (74) = happyGoto action_22 action_375 (75) = happyGoto action_23 action_375 (93) = happyGoto action_24 action_375 (95) = happyGoto action_90 action_375 (97) = happyGoto action_26 action_375 (104) = happyGoto action_27 action_375 (105) = happyGoto action_28 action_375 (106) = happyGoto action_29 action_375 (108) = happyGoto action_30 action_375 (114) = happyGoto action_31 action_375 (126) = happyGoto action_33 action_375 _ = happyFail action_376 _ = happyReduce_294 action_377 _ = happyReduce_17 action_378 _ = happyReduce_13 action_379 (143) = happyShift action_388 action_379 (150) = happyShift action_389 action_379 _ = happyFail action_380 _ = happyReduce_26 action_381 _ = happyReduce_27 action_382 _ = happyReduce_28 action_383 (132) = happyShift action_137 action_383 (133) = happyShift action_118 action_383 (134) = happyShift action_119 action_383 (135) = happyShift action_120 action_383 (136) = happyShift action_121 action_383 (153) = happyShift action_125 action_383 (164) = happyShift action_126 action_383 (109) = happyGoto action_387 action_383 (110) = happyGoto action_113 action_383 (111) = happyGoto action_247 action_383 (112) = happyGoto action_115 action_383 (113) = happyGoto action_116 action_383 _ = happyFail action_384 _ = happyReduce_22 action_385 (143) = happyShift action_386 action_385 _ = happyFail action_386 _ = happyReduce_21 action_387 (143) = happyShift action_174 action_387 _ = happyFail action_388 _ = happyReduce_23 action_389 (128) = happyShift action_34 action_389 (129) = happyShift action_35 action_389 (130) = happyShift action_36 action_389 (131) = happyShift action_37 action_389 (142) = happyShift action_383 action_389 (165) = happyShift action_49 action_389 (173) = happyShift action_55 action_389 (188) = happyShift action_65 action_389 (14) = happyGoto action_474 action_389 (95) = happyGoto action_381 action_389 (97) = happyGoto action_382 action_389 (104) = happyGoto action_27 action_389 (105) = happyGoto action_28 action_389 (106) = happyGoto action_29 action_389 (108) = happyGoto action_30 action_389 _ = happyFail action_390 _ = happyReduce_289 action_391 _ = happyReduce_63 action_392 (130) = happyShift action_36 action_392 (131) = happyShift action_200 action_392 (142) = happyShift action_473 action_392 (107) = happyGoto action_471 action_392 (108) = happyGoto action_80 action_392 (121) = happyGoto action_198 action_392 (123) = happyGoto action_472 action_392 _ = happyFail action_393 (128) = happyShift action_34 action_393 (129) = happyShift action_35 action_393 (130) = happyShift action_36 action_393 (131) = happyShift action_37 action_393 (132) = happyShift action_38 action_393 (137) = happyShift action_39 action_393 (138) = happyShift action_40 action_393 (139) = happyShift action_41 action_393 (140) = happyShift action_42 action_393 (141) = happyShift action_43 action_393 (142) = happyShift action_44 action_393 (144) = happyShift action_226 action_393 (148) = happyShift action_45 action_393 (151) = happyShift action_46 action_393 (157) = happyShift action_47 action_393 (162) = happyShift action_48 action_393 (165) = happyShift action_49 action_393 (166) = happyShift action_50 action_393 (171) = happyShift action_54 action_393 (173) = happyShift action_55 action_393 (174) = happyShift action_56 action_393 (181) = happyShift action_62 action_393 (188) = happyShift action_65 action_393 (191) = happyShift action_68 action_393 (192) = happyShift action_69 action_393 (193) = happyShift action_70 action_393 (194) = happyShift action_71 action_393 (7) = happyGoto action_394 action_393 (61) = happyGoto action_395 action_393 (63) = happyGoto action_470 action_393 (64) = happyGoto action_397 action_393 (70) = happyGoto action_19 action_393 (71) = happyGoto action_20 action_393 (72) = happyGoto action_21 action_393 (74) = happyGoto action_22 action_393 (75) = happyGoto action_23 action_393 (93) = happyGoto action_24 action_393 (95) = happyGoto action_90 action_393 (97) = happyGoto action_26 action_393 (104) = happyGoto action_27 action_393 (105) = happyGoto action_28 action_393 (106) = happyGoto action_29 action_393 (108) = happyGoto action_30 action_393 (114) = happyGoto action_31 action_393 (126) = happyGoto action_33 action_393 _ = happyReduce_10 action_394 _ = happyReduce_150 action_395 (144) = happyShift action_469 action_395 (7) = happyGoto action_468 action_395 _ = happyReduce_10 action_396 (1) = happyShift action_146 action_396 (147) = happyShift action_147 action_396 (116) = happyGoto action_467 action_396 _ = happyFail action_397 _ = happyReduce_145 action_398 _ = happyReduce_34 action_399 _ = happyReduce_31 action_400 _ = happyReduce_36 action_401 (128) = happyShift action_34 action_401 (130) = happyShift action_36 action_401 (142) = happyShift action_157 action_401 (165) = happyShift action_49 action_401 (173) = happyShift action_55 action_401 (188) = happyShift action_65 action_401 (21) = happyGoto action_462 action_401 (22) = happyGoto action_463 action_401 (94) = happyGoto action_464 action_401 (105) = happyGoto action_156 action_401 (108) = happyGoto action_465 action_401 (120) = happyGoto action_466 action_401 _ = happyFail action_402 (142) = happyShift action_461 action_402 _ = happyFail action_403 _ = happyReduce_166 action_404 (128) = happyShift action_34 action_404 (130) = happyShift action_36 action_404 (131) = happyShift action_200 action_404 (134) = happyReduce_123 action_404 (137) = happyShift action_201 action_404 (142) = happyShift action_202 action_404 (148) = happyShift action_203 action_404 (152) = happyReduce_123 action_404 (164) = happyShift action_460 action_404 (165) = happyShift action_49 action_404 (173) = happyShift action_55 action_404 (188) = happyShift action_65 action_404 (39) = happyGoto action_284 action_404 (40) = happyGoto action_194 action_404 (105) = happyGoto action_196 action_404 (107) = happyGoto action_197 action_404 (108) = happyGoto action_80 action_404 (121) = happyGoto action_198 action_404 (124) = happyGoto action_199 action_404 _ = happyReduce_117 action_405 _ = happyReduce_114 action_406 (128) = happyShift action_34 action_406 (130) = happyShift action_36 action_406 (131) = happyShift action_200 action_406 (137) = happyShift action_201 action_406 (142) = happyShift action_202 action_406 (148) = happyShift action_203 action_406 (164) = happyShift action_459 action_406 (165) = happyShift action_49 action_406 (173) = happyShift action_55 action_406 (188) = happyShift action_65 action_406 (39) = happyGoto action_457 action_406 (40) = happyGoto action_194 action_406 (51) = happyGoto action_458 action_406 (105) = happyGoto action_196 action_406 (107) = happyGoto action_197 action_406 (108) = happyGoto action_80 action_406 (121) = happyGoto action_198 action_406 (124) = happyGoto action_199 action_406 _ = happyReduce_118 action_407 (134) = happyShift action_119 action_407 (152) = happyShift action_456 action_407 (100) = happyGoto action_455 action_407 (110) = happyGoto action_322 action_407 _ = happyFail action_408 (145) = happyShift action_454 action_408 _ = happyFail action_409 (145) = happyReduce_237 action_409 _ = happyReduce_285 action_410 (128) = happyShift action_34 action_410 (130) = happyShift action_36 action_410 (131) = happyShift action_200 action_410 (134) = happyShift action_119 action_410 (137) = happyShift action_201 action_410 (142) = happyShift action_202 action_410 (143) = happyShift action_279 action_410 (148) = happyShift action_203 action_410 (150) = happyShift action_123 action_410 (160) = happyShift action_280 action_410 (165) = happyShift action_49 action_410 (173) = happyShift action_55 action_410 (188) = happyShift action_65 action_410 (37) = happyGoto action_276 action_410 (38) = happyGoto action_192 action_410 (39) = happyGoto action_193 action_410 (40) = happyGoto action_194 action_410 (42) = happyGoto action_277 action_410 (76) = happyGoto action_278 action_410 (105) = happyGoto action_196 action_410 (107) = happyGoto action_197 action_410 (108) = happyGoto action_80 action_410 (110) = happyGoto action_453 action_410 (121) = happyGoto action_198 action_410 (124) = happyGoto action_199 action_410 _ = happyFail action_411 (128) = happyShift action_34 action_411 (130) = happyShift action_36 action_411 (131) = happyShift action_200 action_411 (137) = happyShift action_201 action_411 (142) = happyShift action_202 action_411 (148) = happyShift action_203 action_411 (165) = happyShift action_49 action_411 (173) = happyShift action_55 action_411 (188) = happyShift action_65 action_411 (39) = happyGoto action_452 action_411 (40) = happyGoto action_194 action_411 (105) = happyGoto action_196 action_411 (107) = happyGoto action_197 action_411 (108) = happyGoto action_80 action_411 (121) = happyGoto action_198 action_411 (124) = happyGoto action_199 action_411 _ = happyFail action_412 _ = happyReduce_62 action_413 (48) = happyGoto action_451 action_413 (115) = happyGoto action_360 action_413 _ = happyReduce_278 action_414 _ = happyReduce_103 action_415 _ = happyReduce_102 action_416 _ = happyReduce_98 action_417 (143) = happyShift action_450 action_417 (150) = happyShift action_179 action_417 _ = happyFail action_418 _ = happyReduce_97 action_419 (128) = happyShift action_34 action_419 (129) = happyShift action_35 action_419 (142) = happyShift action_241 action_419 (144) = happyShift action_226 action_419 (165) = happyShift action_49 action_419 (173) = happyShift action_55 action_419 (188) = happyShift action_65 action_419 (7) = happyGoto action_420 action_419 (35) = happyGoto action_421 action_419 (36) = happyGoto action_17 action_419 (59) = happyGoto action_449 action_419 (60) = happyGoto action_423 action_419 (95) = happyGoto action_424 action_419 (104) = happyGoto action_27 action_419 (105) = happyGoto action_28 action_419 _ = happyReduce_10 action_420 _ = happyReduce_141 action_421 _ = happyReduce_143 action_422 (1) = happyShift action_146 action_422 (147) = happyShift action_147 action_422 (116) = happyGoto action_448 action_422 _ = happyFail action_423 (144) = happyShift action_447 action_423 (7) = happyGoto action_446 action_423 _ = happyReduce_10 action_424 _ = happyReduce_82 action_425 (1) = happyShift action_146 action_425 (147) = happyShift action_147 action_425 (116) = happyGoto action_445 action_425 _ = happyFail action_426 (128) = happyShift action_34 action_426 (129) = happyShift action_35 action_426 (130) = happyShift action_36 action_426 (131) = happyShift action_37 action_426 (132) = happyShift action_38 action_426 (137) = happyShift action_39 action_426 (138) = happyShift action_40 action_426 (139) = happyShift action_41 action_426 (140) = happyShift action_42 action_426 (141) = happyShift action_43 action_426 (142) = happyShift action_44 action_426 (148) = happyShift action_45 action_426 (151) = happyShift action_46 action_426 (157) = happyShift action_47 action_426 (162) = happyShift action_48 action_426 (165) = happyShift action_49 action_426 (166) = happyShift action_50 action_426 (171) = happyShift action_54 action_426 (173) = happyShift action_55 action_426 (174) = happyShift action_56 action_426 (181) = happyShift action_62 action_426 (188) = happyShift action_65 action_426 (191) = happyShift action_68 action_426 (192) = happyShift action_69 action_426 (193) = happyShift action_70 action_426 (194) = happyShift action_71 action_426 (70) = happyGoto action_340 action_426 (71) = happyGoto action_20 action_426 (72) = happyGoto action_21 action_426 (74) = happyGoto action_22 action_426 (75) = happyGoto action_23 action_426 (84) = happyGoto action_444 action_426 (93) = happyGoto action_24 action_426 (95) = happyGoto action_90 action_426 (97) = happyGoto action_26 action_426 (104) = happyGoto action_27 action_426 (105) = happyGoto action_28 action_426 (106) = happyGoto action_29 action_426 (108) = happyGoto action_30 action_426 (114) = happyGoto action_31 action_426 (126) = happyGoto action_33 action_426 _ = happyReduce_9 action_427 (158) = happyShift action_442 action_427 (160) = happyShift action_443 action_427 (85) = happyGoto action_439 action_427 (86) = happyGoto action_440 action_427 (87) = happyGoto action_441 action_427 _ = happyFail action_428 (144) = happyShift action_426 action_428 (7) = happyGoto action_438 action_428 _ = happyReduce_10 action_429 _ = happyReduce_201 action_430 _ = happyReduce_197 action_431 _ = happyReduce_223 action_432 _ = happyReduce_225 action_433 (128) = happyShift action_34 action_433 (129) = happyShift action_35 action_433 (130) = happyShift action_36 action_433 (131) = happyShift action_37 action_433 (132) = happyShift action_38 action_433 (137) = happyShift action_39 action_433 (138) = happyShift action_40 action_433 (139) = happyShift action_41 action_433 (140) = happyShift action_42 action_433 (141) = happyShift action_43 action_433 (142) = happyShift action_44 action_433 (148) = happyShift action_45 action_433 (151) = happyShift action_46 action_433 (157) = happyShift action_47 action_433 (162) = happyShift action_48 action_433 (165) = happyShift action_49 action_433 (166) = happyShift action_50 action_433 (171) = happyShift action_54 action_433 (173) = happyShift action_55 action_433 (174) = happyShift action_56 action_433 (181) = happyShift action_62 action_433 (188) = happyShift action_65 action_433 (191) = happyShift action_68 action_433 (192) = happyShift action_69 action_433 (193) = happyShift action_70 action_433 (194) = happyShift action_71 action_433 (69) = happyGoto action_437 action_433 (70) = happyGoto action_89 action_433 (71) = happyGoto action_20 action_433 (72) = happyGoto action_21 action_433 (74) = happyGoto action_22 action_433 (75) = happyGoto action_23 action_433 (93) = happyGoto action_24 action_433 (95) = happyGoto action_90 action_433 (97) = happyGoto action_26 action_433 (104) = happyGoto action_27 action_433 (105) = happyGoto action_28 action_433 (106) = happyGoto action_29 action_433 (108) = happyGoto action_30 action_433 (114) = happyGoto action_31 action_433 (126) = happyGoto action_33 action_433 _ = happyFail action_434 _ = happyReduce_59 action_435 _ = happyReduce_246 action_436 _ = happyReduce_242 action_437 _ = happyReduce_158 action_438 (146) = happyShift action_497 action_438 _ = happyFail action_439 (187) = happyShift action_496 action_439 _ = happyReduce_210 action_440 (158) = happyShift action_442 action_440 (87) = happyGoto action_495 action_440 _ = happyReduce_213 action_441 _ = happyReduce_215 action_442 (115) = happyGoto action_494 action_442 _ = happyReduce_278 action_443 (128) = happyShift action_34 action_443 (129) = happyShift action_35 action_443 (130) = happyShift action_36 action_443 (131) = happyShift action_37 action_443 (132) = happyShift action_38 action_443 (137) = happyShift action_39 action_443 (138) = happyShift action_40 action_443 (139) = happyShift action_41 action_443 (140) = happyShift action_42 action_443 (141) = happyShift action_43 action_443 (142) = happyShift action_44 action_443 (148) = happyShift action_45 action_443 (151) = happyShift action_46 action_443 (157) = happyShift action_47 action_443 (162) = happyShift action_48 action_443 (165) = happyShift action_49 action_443 (166) = happyShift action_50 action_443 (171) = happyShift action_54 action_443 (173) = happyShift action_55 action_443 (174) = happyShift action_56 action_443 (181) = happyShift action_62 action_443 (188) = happyShift action_65 action_443 (191) = happyShift action_68 action_443 (192) = happyShift action_69 action_443 (193) = happyShift action_70 action_443 (194) = happyShift action_71 action_443 (69) = happyGoto action_493 action_443 (70) = happyGoto action_89 action_443 (71) = happyGoto action_20 action_443 (72) = happyGoto action_21 action_443 (74) = happyGoto action_22 action_443 (75) = happyGoto action_23 action_443 (93) = happyGoto action_24 action_443 (95) = happyGoto action_90 action_443 (97) = happyGoto action_26 action_443 (104) = happyGoto action_27 action_443 (105) = happyGoto action_28 action_443 (106) = happyGoto action_29 action_443 (108) = happyGoto action_30 action_443 (114) = happyGoto action_31 action_443 (126) = happyGoto action_33 action_443 _ = happyFail action_444 _ = happyReduce_208 action_445 _ = happyReduce_207 action_446 _ = happyReduce_140 action_447 (128) = happyShift action_34 action_447 (129) = happyShift action_35 action_447 (130) = happyShift action_36 action_447 (131) = happyShift action_37 action_447 (132) = happyShift action_38 action_447 (137) = happyShift action_39 action_447 (138) = happyShift action_40 action_447 (139) = happyShift action_41 action_447 (140) = happyShift action_42 action_447 (141) = happyShift action_43 action_447 (142) = happyShift action_44 action_447 (148) = happyShift action_45 action_447 (151) = happyShift action_46 action_447 (157) = happyShift action_47 action_447 (162) = happyShift action_48 action_447 (165) = happyShift action_49 action_447 (166) = happyShift action_50 action_447 (171) = happyShift action_54 action_447 (173) = happyShift action_55 action_447 (174) = happyShift action_56 action_447 (181) = happyShift action_62 action_447 (188) = happyShift action_65 action_447 (191) = happyShift action_68 action_447 (192) = happyShift action_69 action_447 (193) = happyShift action_70 action_447 (194) = happyShift action_71 action_447 (35) = happyGoto action_491 action_447 (36) = happyGoto action_17 action_447 (61) = happyGoto action_492 action_447 (64) = happyGoto action_397 action_447 (70) = happyGoto action_19 action_447 (71) = happyGoto action_20 action_447 (72) = happyGoto action_21 action_447 (74) = happyGoto action_22 action_447 (75) = happyGoto action_23 action_447 (93) = happyGoto action_24 action_447 (95) = happyGoto action_25 action_447 (97) = happyGoto action_26 action_447 (104) = happyGoto action_27 action_447 (105) = happyGoto action_28 action_447 (106) = happyGoto action_29 action_447 (108) = happyGoto action_30 action_447 (114) = happyGoto action_31 action_447 (126) = happyGoto action_33 action_447 _ = happyReduce_9 action_448 _ = happyReduce_137 action_449 (146) = happyShift action_490 action_449 _ = happyFail action_450 _ = happyReduce_99 action_451 _ = happyReduce_112 action_452 _ = happyReduce_124 action_453 (143) = happyShift action_489 action_453 _ = happyFail action_454 (117) = happyGoto action_488 action_454 _ = happyReduce_281 action_455 (128) = happyShift action_34 action_455 (130) = happyShift action_36 action_455 (131) = happyShift action_200 action_455 (137) = happyShift action_201 action_455 (142) = happyShift action_202 action_455 (148) = happyShift action_203 action_455 (164) = happyShift action_411 action_455 (165) = happyShift action_49 action_455 (173) = happyShift action_55 action_455 (188) = happyShift action_65 action_455 (38) = happyGoto action_486 action_455 (39) = happyGoto action_193 action_455 (40) = happyGoto action_194 action_455 (52) = happyGoto action_487 action_455 (105) = happyGoto action_196 action_455 (107) = happyGoto action_197 action_455 (108) = happyGoto action_80 action_455 (121) = happyGoto action_198 action_455 (124) = happyGoto action_199 action_455 _ = happyFail action_456 (130) = happyShift action_36 action_456 (108) = happyGoto action_327 action_456 _ = happyFail action_457 _ = happyReduce_121 action_458 _ = happyReduce_120 action_459 (128) = happyShift action_34 action_459 (130) = happyShift action_36 action_459 (131) = happyShift action_200 action_459 (137) = happyShift action_201 action_459 (142) = happyShift action_202 action_459 (148) = happyShift action_203 action_459 (165) = happyShift action_49 action_459 (173) = happyShift action_55 action_459 (188) = happyShift action_65 action_459 (39) = happyGoto action_485 action_459 (40) = happyGoto action_194 action_459 (105) = happyGoto action_196 action_459 (107) = happyGoto action_197 action_459 (108) = happyGoto action_80 action_459 (121) = happyGoto action_198 action_459 (124) = happyGoto action_199 action_459 _ = happyFail action_460 (128) = happyShift action_34 action_460 (130) = happyShift action_36 action_460 (131) = happyShift action_200 action_460 (137) = happyShift action_201 action_460 (142) = happyShift action_202 action_460 (148) = happyShift action_203 action_460 (165) = happyShift action_49 action_460 (173) = happyShift action_55 action_460 (188) = happyShift action_65 action_460 (39) = happyGoto action_484 action_460 (40) = happyGoto action_194 action_460 (105) = happyGoto action_196 action_460 (107) = happyGoto action_197 action_460 (108) = happyGoto action_80 action_460 (121) = happyGoto action_198 action_460 (124) = happyGoto action_199 action_460 _ = happyFail action_461 (128) = happyShift action_34 action_461 (130) = happyShift action_36 action_461 (142) = happyShift action_157 action_461 (165) = happyShift action_49 action_461 (173) = happyShift action_55 action_461 (188) = happyShift action_65 action_461 (21) = happyGoto action_483 action_461 (22) = happyGoto action_463 action_461 (94) = happyGoto action_464 action_461 (105) = happyGoto action_156 action_461 (108) = happyGoto action_465 action_461 (120) = happyGoto action_466 action_461 _ = happyFail action_462 (150) = happyShift action_482 action_462 (10) = happyGoto action_481 action_462 _ = happyReduce_16 action_463 _ = happyReduce_41 action_464 _ = happyReduce_42 action_465 _ = happyReduce_284 action_466 (142) = happyShift action_480 action_466 _ = happyReduce_43 action_467 _ = happyReduce_147 action_468 _ = happyReduce_149 action_469 (128) = happyShift action_34 action_469 (129) = happyShift action_35 action_469 (130) = happyShift action_36 action_469 (131) = happyShift action_37 action_469 (132) = happyShift action_38 action_469 (137) = happyShift action_39 action_469 (138) = happyShift action_40 action_469 (139) = happyShift action_41 action_469 (140) = happyShift action_42 action_469 (141) = happyShift action_43 action_469 (142) = happyShift action_44 action_469 (148) = happyShift action_45 action_469 (151) = happyShift action_46 action_469 (157) = happyShift action_47 action_469 (162) = happyShift action_48 action_469 (165) = happyShift action_49 action_469 (166) = happyShift action_50 action_469 (171) = happyShift action_54 action_469 (173) = happyShift action_55 action_469 (174) = happyShift action_56 action_469 (181) = happyShift action_62 action_469 (188) = happyShift action_65 action_469 (191) = happyShift action_68 action_469 (192) = happyShift action_69 action_469 (193) = happyShift action_70 action_469 (194) = happyShift action_71 action_469 (64) = happyGoto action_479 action_469 (70) = happyGoto action_19 action_469 (71) = happyGoto action_20 action_469 (72) = happyGoto action_21 action_469 (74) = happyGoto action_22 action_469 (75) = happyGoto action_23 action_469 (93) = happyGoto action_24 action_469 (95) = happyGoto action_90 action_469 (97) = happyGoto action_26 action_469 (104) = happyGoto action_27 action_469 (105) = happyGoto action_28 action_469 (106) = happyGoto action_29 action_469 (108) = happyGoto action_30 action_469 (114) = happyGoto action_31 action_469 (126) = happyGoto action_33 action_469 _ = happyReduce_9 action_470 (146) = happyShift action_478 action_470 _ = happyFail action_471 _ = happyReduce_287 action_472 _ = happyReduce_131 action_473 (130) = happyShift action_36 action_473 (131) = happyShift action_200 action_473 (143) = happyShift action_477 action_473 (57) = happyGoto action_475 action_473 (107) = happyGoto action_471 action_473 (108) = happyGoto action_80 action_473 (121) = happyGoto action_198 action_473 (123) = happyGoto action_476 action_473 _ = happyFail action_474 _ = happyReduce_25 action_475 (143) = happyShift action_515 action_475 (150) = happyShift action_516 action_475 _ = happyFail action_476 _ = happyReduce_135 action_477 _ = happyReduce_132 action_478 _ = happyReduce_146 action_479 _ = happyReduce_144 action_480 (128) = happyShift action_34 action_480 (130) = happyShift action_36 action_480 (142) = happyShift action_512 action_480 (143) = happyShift action_513 action_480 (154) = happyShift action_514 action_480 (165) = happyShift action_49 action_480 (173) = happyShift action_55 action_480 (188) = happyShift action_65 action_480 (23) = happyGoto action_507 action_480 (24) = happyGoto action_508 action_480 (94) = happyGoto action_509 action_480 (96) = happyGoto action_510 action_480 (105) = happyGoto action_156 action_480 (108) = happyGoto action_511 action_480 _ = happyFail action_481 (143) = happyShift action_506 action_481 _ = happyFail action_482 (128) = happyShift action_34 action_482 (130) = happyShift action_36 action_482 (142) = happyShift action_157 action_482 (165) = happyShift action_49 action_482 (173) = happyShift action_55 action_482 (188) = happyShift action_65 action_482 (22) = happyGoto action_505 action_482 (94) = happyGoto action_464 action_482 (105) = happyGoto action_156 action_482 (108) = happyGoto action_465 action_482 (120) = happyGoto action_466 action_482 _ = happyReduce_15 action_483 (150) = happyShift action_482 action_483 (10) = happyGoto action_504 action_483 _ = happyReduce_16 action_484 _ = happyReduce_119 action_485 _ = happyReduce_122 action_486 (128) = happyShift action_34 action_486 (130) = happyShift action_36 action_486 (131) = happyShift action_200 action_486 (137) = happyShift action_201 action_486 (142) = happyShift action_202 action_486 (148) = happyShift action_203 action_486 (165) = happyShift action_49 action_486 (173) = happyShift action_55 action_486 (188) = happyShift action_65 action_486 (39) = happyGoto action_284 action_486 (40) = happyGoto action_194 action_486 (105) = happyGoto action_196 action_486 (107) = happyGoto action_197 action_486 (108) = happyGoto action_80 action_486 (121) = happyGoto action_198 action_486 (124) = happyGoto action_199 action_486 _ = happyReduce_123 action_487 _ = happyReduce_115 action_488 (128) = happyShift action_34 action_488 (129) = happyShift action_35 action_488 (142) = happyShift action_241 action_488 (165) = happyShift action_49 action_488 (173) = happyShift action_55 action_488 (188) = happyShift action_65 action_488 (36) = happyGoto action_501 action_488 (53) = happyGoto action_502 action_488 (54) = happyGoto action_503 action_488 (95) = happyGoto action_424 action_488 (104) = happyGoto action_27 action_488 (105) = happyGoto action_28 action_488 _ = happyFail action_489 _ = happyReduce_238 action_490 _ = happyReduce_136 action_491 _ = happyReduce_142 action_492 (144) = happyShift action_469 action_492 (7) = happyGoto action_500 action_492 _ = happyReduce_10 action_493 _ = happyReduce_212 action_494 (128) = happyShift action_34 action_494 (129) = happyShift action_35 action_494 (130) = happyShift action_36 action_494 (131) = happyShift action_37 action_494 (132) = happyShift action_38 action_494 (137) = happyShift action_39 action_494 (138) = happyShift action_40 action_494 (139) = happyShift action_41 action_494 (140) = happyShift action_42 action_494 (141) = happyShift action_43 action_494 (142) = happyShift action_44 action_494 (148) = happyShift action_45 action_494 (151) = happyShift action_46 action_494 (157) = happyShift action_47 action_494 (162) = happyShift action_48 action_494 (165) = happyShift action_49 action_494 (166) = happyShift action_50 action_494 (171) = happyShift action_54 action_494 (173) = happyShift action_55 action_494 (174) = happyShift action_56 action_494 (181) = happyShift action_62 action_494 (188) = happyShift action_65 action_494 (191) = happyShift action_68 action_494 (192) = happyShift action_69 action_494 (193) = happyShift action_70 action_494 (194) = happyShift action_71 action_494 (69) = happyGoto action_499 action_494 (70) = happyGoto action_89 action_494 (71) = happyGoto action_20 action_494 (72) = happyGoto action_21 action_494 (74) = happyGoto action_22 action_494 (75) = happyGoto action_23 action_494 (93) = happyGoto action_24 action_494 (95) = happyGoto action_90 action_494 (97) = happyGoto action_26 action_494 (104) = happyGoto action_27 action_494 (105) = happyGoto action_28 action_494 (106) = happyGoto action_29 action_494 (108) = happyGoto action_30 action_494 (114) = happyGoto action_31 action_494 (126) = happyGoto action_33 action_494 _ = happyFail action_495 _ = happyReduce_214 action_496 (145) = happyShift action_85 action_496 (34) = happyGoto action_498 action_496 (118) = happyGoto action_84 action_496 _ = happyReduce_282 action_497 _ = happyReduce_206 action_498 _ = happyReduce_211 action_499 (160) = happyShift action_525 action_499 _ = happyFail action_500 _ = happyReduce_139 action_501 (150) = happyShift action_139 action_501 (155) = happyShift action_524 action_501 _ = happyFail action_502 (146) = happyShift action_522 action_502 (150) = happyShift action_523 action_502 _ = happyFail action_503 _ = happyReduce_126 action_504 (143) = happyShift action_521 action_504 _ = happyFail action_505 _ = happyReduce_40 action_506 _ = happyReduce_38 action_507 (143) = happyShift action_519 action_507 (150) = happyShift action_520 action_507 _ = happyFail action_508 _ = happyReduce_48 action_509 _ = happyReduce_49 action_510 _ = happyReduce_50 action_511 _ = happyReduce_237 action_512 (132) = happyShift action_137 action_512 (133) = happyShift action_118 action_512 (134) = happyShift action_119 action_512 (153) = happyShift action_125 action_512 (164) = happyShift action_126 action_512 (110) = happyGoto action_453 action_512 (112) = happyGoto action_317 action_512 _ = happyFail action_513 _ = happyReduce_45 action_514 (143) = happyShift action_518 action_514 _ = happyFail action_515 _ = happyReduce_133 action_516 (130) = happyShift action_36 action_516 (131) = happyShift action_200 action_516 (107) = happyGoto action_471 action_516 (108) = happyGoto action_80 action_516 (121) = happyGoto action_198 action_516 (123) = happyGoto action_517 action_516 _ = happyFail action_517 _ = happyReduce_134 action_518 _ = happyReduce_44 action_519 _ = happyReduce_46 action_520 (128) = happyShift action_34 action_520 (130) = happyShift action_36 action_520 (142) = happyShift action_512 action_520 (165) = happyShift action_49 action_520 (173) = happyShift action_55 action_520 (188) = happyShift action_65 action_520 (24) = happyGoto action_531 action_520 (94) = happyGoto action_509 action_520 (96) = happyGoto action_510 action_520 (105) = happyGoto action_156 action_520 (108) = happyGoto action_511 action_520 _ = happyFail action_521 _ = happyReduce_39 action_522 _ = happyReduce_116 action_523 (128) = happyShift action_34 action_523 (129) = happyShift action_35 action_523 (142) = happyShift action_241 action_523 (165) = happyShift action_49 action_523 (173) = happyShift action_55 action_523 (188) = happyShift action_65 action_523 (36) = happyGoto action_501 action_523 (54) = happyGoto action_530 action_523 (95) = happyGoto action_424 action_523 (104) = happyGoto action_27 action_523 (105) = happyGoto action_28 action_523 _ = happyFail action_524 (128) = happyShift action_34 action_524 (130) = happyShift action_36 action_524 (131) = happyShift action_200 action_524 (137) = happyShift action_201 action_524 (142) = happyShift action_202 action_524 (148) = happyShift action_203 action_524 (164) = happyShift action_529 action_524 (165) = happyShift action_49 action_524 (173) = happyShift action_55 action_524 (188) = happyShift action_65 action_524 (37) = happyGoto action_527 action_524 (38) = happyGoto action_192 action_524 (39) = happyGoto action_193 action_524 (40) = happyGoto action_194 action_524 (55) = happyGoto action_528 action_524 (105) = happyGoto action_196 action_524 (107) = happyGoto action_197 action_524 (108) = happyGoto action_80 action_524 (121) = happyGoto action_198 action_524 (124) = happyGoto action_199 action_524 _ = happyFail action_525 (128) = happyShift action_34 action_525 (129) = happyShift action_35 action_525 (130) = happyShift action_36 action_525 (131) = happyShift action_37 action_525 (132) = happyShift action_38 action_525 (137) = happyShift action_39 action_525 (138) = happyShift action_40 action_525 (139) = happyShift action_41 action_525 (140) = happyShift action_42 action_525 (141) = happyShift action_43 action_525 (142) = happyShift action_44 action_525 (148) = happyShift action_45 action_525 (151) = happyShift action_46 action_525 (157) = happyShift action_47 action_525 (162) = happyShift action_48 action_525 (165) = happyShift action_49 action_525 (166) = happyShift action_50 action_525 (171) = happyShift action_54 action_525 (173) = happyShift action_55 action_525 (174) = happyShift action_56 action_525 (181) = happyShift action_62 action_525 (188) = happyShift action_65 action_525 (191) = happyShift action_68 action_525 (192) = happyShift action_69 action_525 (193) = happyShift action_70 action_525 (194) = happyShift action_71 action_525 (69) = happyGoto action_526 action_525 (70) = happyGoto action_89 action_525 (71) = happyGoto action_20 action_525 (72) = happyGoto action_21 action_525 (74) = happyGoto action_22 action_525 (75) = happyGoto action_23 action_525 (93) = happyGoto action_24 action_525 (95) = happyGoto action_90 action_525 (97) = happyGoto action_26 action_525 (104) = happyGoto action_27 action_525 (105) = happyGoto action_28 action_525 (106) = happyGoto action_29 action_525 (108) = happyGoto action_30 action_525 (114) = happyGoto action_31 action_525 (126) = happyGoto action_33 action_525 _ = happyFail action_526 _ = happyReduce_216 action_527 _ = happyReduce_128 action_528 _ = happyReduce_127 action_529 (128) = happyShift action_34 action_529 (130) = happyShift action_36 action_529 (131) = happyShift action_200 action_529 (137) = happyShift action_201 action_529 (142) = happyShift action_202 action_529 (148) = happyShift action_203 action_529 (165) = happyShift action_49 action_529 (173) = happyShift action_55 action_529 (188) = happyShift action_65 action_529 (39) = happyGoto action_532 action_529 (40) = happyGoto action_194 action_529 (105) = happyGoto action_196 action_529 (107) = happyGoto action_197 action_529 (108) = happyGoto action_80 action_529 (121) = happyGoto action_198 action_529 (124) = happyGoto action_199 action_529 _ = happyFail action_530 _ = happyReduce_125 action_531 _ = happyReduce_47 action_532 _ = happyReduce_129 happyReduce_1 = happyReduce 5 4 happyReduction_1 happyReduction_1 ((HappyAbsSyn5 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn8 happy_var_3) `HappyStk` (HappyAbsSyn119 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn4 (hsModule happy_var_2 happy_var_3 happy_var_5 ) `HappyStk` happyRest happyReduce_2 = happySpecReduce_1 4 happyReduction_2 happyReduction_2 (HappyAbsSyn5 happy_var_1) = HappyAbsSyn4 (hsModule main_mod Nothing happy_var_1 ) happyReduction_2 _ = notHappyAtAll happyReduce_3 = happyReduce 4 5 happyReduction_3 happyReduction_3 (_ `HappyStk` (HappyAbsSyn5 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn5 (happy_var_3 ) `HappyStk` happyRest happyReduce_4 = happySpecReduce_3 5 happyReduction_4 happyReduction_4 _ (HappyAbsSyn5 happy_var_2) _ = HappyAbsSyn5 (happy_var_2 ) happyReduction_4 _ _ _ = notHappyAtAll happyReduce_5 = happyReduce 4 6 happyReduction_5 happyReduction_5 (_ `HappyStk` (HappyAbsSyn25 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn15 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn5 ((happy_var_1, happy_var_3) ) `HappyStk` happyRest happyReduce_6 = happySpecReduce_2 6 happyReduction_6 happyReduction_6 _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn5 (([], happy_var_1) ) happyReduction_6 _ _ = notHappyAtAll happyReduce_7 = happySpecReduce_2 6 happyReduction_7 happyReduction_7 _ (HappyAbsSyn15 happy_var_1) = HappyAbsSyn5 ((happy_var_1, []) ) happyReduction_7 _ _ = notHappyAtAll happyReduce_8 = happySpecReduce_0 6 happyReduction_8 happyReduction_8 = HappyAbsSyn5 (([], []) ) happyReduce_9 = happySpecReduce_1 7 happyReduction_9 happyReduction_9 _ = HappyAbsSyn7 (() ) happyReduce_10 = happySpecReduce_0 7 happyReduction_10 happyReduction_10 = HappyAbsSyn7 (() ) happyReduce_11 = happySpecReduce_1 8 happyReduction_11 happyReduction_11 (HappyAbsSyn9 happy_var_1) = HappyAbsSyn8 (Just happy_var_1 ) happyReduction_11 _ = notHappyAtAll happyReduce_12 = happySpecReduce_0 8 happyReduction_12 happyReduction_12 = HappyAbsSyn8 (Nothing ) happyReduce_13 = happyReduce 4 9 happyReduction_13 happyReduction_13 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn9 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn9 (reverse happy_var_2 ) `HappyStk` happyRest happyReduce_14 = happySpecReduce_2 9 happyReduction_14 happyReduction_14 _ _ = HappyAbsSyn9 ([] ) happyReduce_15 = happySpecReduce_1 10 happyReduction_15 happyReduction_15 _ = HappyAbsSyn7 (() ) happyReduce_16 = happySpecReduce_0 10 happyReduction_16 happyReduction_16 = HappyAbsSyn7 (() ) happyReduce_17 = happySpecReduce_3 11 happyReduction_17 happyReduction_17 (HappyAbsSyn12 happy_var_3) _ (HappyAbsSyn9 happy_var_1) = HappyAbsSyn9 (happy_var_3 : happy_var_1 ) happyReduction_17 _ _ _ = notHappyAtAll happyReduce_18 = happySpecReduce_1 11 happyReduction_18 happyReduction_18 (HappyAbsSyn12 happy_var_1) = HappyAbsSyn9 ([happy_var_1] ) happyReduction_18 _ = notHappyAtAll happyReduce_19 = happySpecReduce_1 12 happyReduction_19 happyReduction_19 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn12 (HsEVar happy_var_1 ) happyReduction_19 _ = notHappyAtAll happyReduce_20 = happySpecReduce_1 12 happyReduction_20 happyReduction_20 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn12 (HsEAbs happy_var_1 ) happyReduction_20 _ = notHappyAtAll happyReduce_21 = happyReduce 4 12 happyReduction_21 happyReduction_21 (_ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn12 (HsEThingAll happy_var_1 ) `HappyStk` happyRest happyReduce_22 = happySpecReduce_3 12 happyReduction_22 happyReduction_22 _ _ (HappyAbsSyn14 happy_var_1) = HappyAbsSyn12 (HsEThingWith happy_var_1 [] ) happyReduction_22 _ _ _ = notHappyAtAll happyReduce_23 = happyReduce 4 12 happyReduction_23 happyReduction_23 (_ `HappyStk` (HappyAbsSyn13 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn12 (HsEThingWith happy_var_1 (reverse happy_var_3) ) `HappyStk` happyRest happyReduce_24 = happySpecReduce_2 12 happyReduction_24 happyReduction_24 (HappyAbsSyn119 happy_var_2) _ = HappyAbsSyn12 (HsEModuleContents happy_var_2 ) happyReduction_24 _ _ = notHappyAtAll happyReduce_25 = happySpecReduce_3 13 happyReduction_25 happyReduction_25 (HappyAbsSyn14 happy_var_3) _ (HappyAbsSyn13 happy_var_1) = HappyAbsSyn13 (happy_var_3 : happy_var_1 ) happyReduction_25 _ _ _ = notHappyAtAll happyReduce_26 = happySpecReduce_1 13 happyReduction_26 happyReduction_26 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn13 ([happy_var_1] ) happyReduction_26 _ = notHappyAtAll happyReduce_27 = happySpecReduce_1 14 happyReduction_27 happyReduction_27 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_27 _ = notHappyAtAll happyReduce_28 = happySpecReduce_1 14 happyReduction_28 happyReduction_28 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_28 _ = notHappyAtAll happyReduce_29 = happySpecReduce_3 15 happyReduction_29 happyReduction_29 (HappyAbsSyn16 happy_var_3) _ (HappyAbsSyn15 happy_var_1) = HappyAbsSyn15 (happy_var_3 : happy_var_1 ) happyReduction_29 _ _ _ = notHappyAtAll happyReduce_30 = happySpecReduce_1 15 happyReduction_30 happyReduction_30 (HappyAbsSyn16 happy_var_1) = HappyAbsSyn15 ([happy_var_1] ) happyReduction_30 _ = notHappyAtAll happyReduce_31 = happyReduce 6 16 happyReduction_31 happyReduction_31 ((HappyAbsSyn19 happy_var_6) `HappyStk` (HappyAbsSyn18 happy_var_5) `HappyStk` (HappyAbsSyn119 happy_var_4) `HappyStk` (HappyAbsSyn17 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn16 (HsImportDecl happy_var_2 happy_var_4 happy_var_3 happy_var_5 happy_var_6 ) `HappyStk` happyRest happyReduce_32 = happySpecReduce_1 17 happyReduction_32 happyReduction_32 _ = HappyAbsSyn17 (True ) happyReduce_33 = happySpecReduce_0 17 happyReduction_33 happyReduction_33 = HappyAbsSyn17 (False ) happyReduce_34 = happySpecReduce_2 18 happyReduction_34 happyReduction_34 (HappyAbsSyn119 happy_var_2) _ = HappyAbsSyn18 (Just happy_var_2 ) happyReduction_34 _ _ = notHappyAtAll happyReduce_35 = happySpecReduce_0 18 happyReduction_35 happyReduction_35 = HappyAbsSyn18 (Nothing ) happyReduce_36 = happySpecReduce_1 19 happyReduction_36 happyReduction_36 (HappyAbsSyn20 happy_var_1) = HappyAbsSyn19 (Just happy_var_1 ) happyReduction_36 _ = notHappyAtAll happyReduce_37 = happySpecReduce_0 19 happyReduction_37 happyReduction_37 = HappyAbsSyn19 (Nothing ) happyReduce_38 = happyReduce 4 20 happyReduction_38 happyReduction_38 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn21 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn20 ((False, reverse happy_var_2) ) `HappyStk` happyRest happyReduce_39 = happyReduce 5 20 happyReduction_39 happyReduction_39 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn21 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn20 ((True, reverse happy_var_3) ) `HappyStk` happyRest happyReduce_40 = happySpecReduce_3 21 happyReduction_40 happyReduction_40 (HappyAbsSyn22 happy_var_3) _ (HappyAbsSyn21 happy_var_1) = HappyAbsSyn21 (happy_var_3 : happy_var_1 ) happyReduction_40 _ _ _ = notHappyAtAll happyReduce_41 = happySpecReduce_1 21 happyReduction_41 happyReduction_41 (HappyAbsSyn22 happy_var_1) = HappyAbsSyn21 ([happy_var_1] ) happyReduction_41 _ = notHappyAtAll happyReduce_42 = happySpecReduce_1 22 happyReduction_42 happyReduction_42 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn22 (HsIVar happy_var_1 ) happyReduction_42 _ = notHappyAtAll happyReduce_43 = happySpecReduce_1 22 happyReduction_43 happyReduction_43 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn22 (HsIAbs happy_var_1 ) happyReduction_43 _ = notHappyAtAll happyReduce_44 = happyReduce 4 22 happyReduction_44 happyReduction_44 (_ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn22 (HsIThingAll happy_var_1 ) `HappyStk` happyRest happyReduce_45 = happySpecReduce_3 22 happyReduction_45 happyReduction_45 _ _ (HappyAbsSyn14 happy_var_1) = HappyAbsSyn22 (HsIThingWith happy_var_1 [] ) happyReduction_45 _ _ _ = notHappyAtAll happyReduce_46 = happyReduce 4 22 happyReduction_46 happyReduction_46 (_ `HappyStk` (HappyAbsSyn13 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn22 (HsIThingWith happy_var_1 (reverse happy_var_3) ) `HappyStk` happyRest happyReduce_47 = happySpecReduce_3 23 happyReduction_47 happyReduction_47 (HappyAbsSyn14 happy_var_3) _ (HappyAbsSyn13 happy_var_1) = HappyAbsSyn13 (happy_var_3 : happy_var_1 ) happyReduction_47 _ _ _ = notHappyAtAll happyReduce_48 = happySpecReduce_1 23 happyReduction_48 happyReduction_48 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn13 ([happy_var_1] ) happyReduction_48 _ = notHappyAtAll happyReduce_49 = happySpecReduce_1 24 happyReduction_49 happyReduction_49 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_49 _ = notHappyAtAll happyReduce_50 = happySpecReduce_1 24 happyReduction_50 happyReduction_50 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_50 _ = notHappyAtAll happyReduce_51 = happySpecReduce_3 25 happyReduction_51 happyReduction_51 (HappyAbsSyn26 happy_var_3) _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (funCons happy_var_3 happy_var_1 ) happyReduction_51 _ _ _ = notHappyAtAll happyReduce_52 = happySpecReduce_1 25 happyReduction_52 happyReduction_52 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn25 ([happy_var_1] ) happyReduction_52 _ = notHappyAtAll happyReduce_53 = happyReduce 4 26 happyReduction_53 happyReduction_53 ((HappyAbsSyn29 happy_var_4) `HappyStk` (HappyAbsSyn27 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` (HappyAbsSyn28 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn26 (hsInfixDecl happy_var_2 (HsFixity happy_var_1 happy_var_3) happy_var_4 ) `HappyStk` happyRest happyReduce_54 = happySpecReduce_0 27 happyReduction_54 happyReduction_54 = HappyAbsSyn27 (9 ) happyReduce_55 = happySpecReduce_1 27 happyReduction_55 happyReduction_55 (HappyTerminal (IntTok happy_var_1)) = HappyAbsSyn27 (fromInteger (readInteger happy_var_1) ) happyReduction_55 _ = notHappyAtAll happyReduce_56 = happySpecReduce_1 28 happyReduction_56 happyReduction_56 _ = HappyAbsSyn28 (HsAssocNone ) happyReduce_57 = happySpecReduce_1 28 happyReduction_57 happyReduction_57 _ = HappyAbsSyn28 (HsAssocLeft ) happyReduce_58 = happySpecReduce_1 28 happyReduction_58 happyReduction_58 _ = HappyAbsSyn28 (HsAssocRight ) happyReduce_59 = happySpecReduce_3 29 happyReduction_59 happyReduction_59 (HappyAbsSyn29 happy_var_3) _ (HappyAbsSyn102 happy_var_1) = HappyAbsSyn29 (happy_var_1 : happy_var_3 ) happyReduction_59 _ _ _ = notHappyAtAll happyReduce_60 = happySpecReduce_1 29 happyReduction_60 happyReduction_60 (HappyAbsSyn102 happy_var_1) = HappyAbsSyn29 ([happy_var_1] ) happyReduction_60 _ = notHappyAtAll happyReduce_61 = happyReduce 5 30 happyReduction_61 happyReduction_61 ((HappyAbsSyn37 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn115 happy_var_3) `HappyStk` (HappyAbsSyn42 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsTypeDecl happy_var_3 happy_var_2 happy_var_5 ) `HappyStk` happyRest happyReduce_62 = happyReduce 6 30 happyReduction_62 happyReduction_62 ((HappyAbsSyn13 happy_var_6) `HappyStk` (HappyAbsSyn47 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn43 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsDataDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) (reverse happy_var_5) happy_var_6 ) `HappyStk` happyRest happyReduce_63 = happyReduce 6 30 happyReduction_63 happyReduction_63 ((HappyAbsSyn13 happy_var_6) `HappyStk` (HappyAbsSyn48 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn43 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsNewTypeDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) happy_var_5 happy_var_6 ) `HappyStk` happyRest happyReduce_64 = happyReduce 4 30 happyReduction_64 happyReduction_64 ((HappyAbsSyn25 happy_var_4) `HappyStk` (HappyAbsSyn41 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsClassDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) [] happy_var_4 ) `HappyStk` happyRest happyReduce_65 = happyReduce 4 30 happyReduction_65 happyReduction_65 ((HappyAbsSyn25 happy_var_4) `HappyStk` (HappyAbsSyn41 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsInstDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) happy_var_4 ) `HappyStk` happyRest happyReduce_66 = happySpecReduce_3 30 happyReduction_66 happyReduction_66 (HappyAbsSyn37 happy_var_3) (HappyAbsSyn115 happy_var_2) _ = HappyAbsSyn26 (hsDefaultDecl happy_var_2 happy_var_3 ) happyReduction_66 _ _ _ = notHappyAtAll happyReduce_67 = happySpecReduce_3 30 happyReduction_67 happyReduction_67 (HappyAbsSyn46 happy_var_3) (HappyAbsSyn115 happy_var_2) _ = HappyAbsSyn26 (hsPrimitiveTypeDecl happy_var_2 (fst happy_var_3) (snd happy_var_3) ) happyReduction_67 _ _ _ = notHappyAtAll happyReduce_68 = happyReduce 5 30 happyReduction_68 happyReduction_68 ((HappyAbsSyn37 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsPrimitiveBind happy_var_2 happy_var_3 happy_var_5 ) `HappyStk` happyRest happyReduce_69 = happySpecReduce_1 30 happyReduction_69 happyReduction_69 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn26 (happy_var_1 ) happyReduction_69 _ = notHappyAtAll happyReduce_70 = happySpecReduce_2 31 happyReduction_70 happyReduction_70 _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (reverse happy_var_1 ) happyReduction_70 _ _ = notHappyAtAll happyReduce_71 = happySpecReduce_1 31 happyReduction_71 happyReduction_71 _ = HappyAbsSyn25 ([] ) happyReduce_72 = happySpecReduce_3 32 happyReduction_72 happyReduction_72 (HappyAbsSyn26 happy_var_3) _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (funCons happy_var_3 happy_var_1 ) happyReduction_72 _ _ _ = notHappyAtAll happyReduce_73 = happySpecReduce_1 32 happyReduction_73 happyReduction_73 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn25 ([happy_var_1] ) happyReduction_73 _ = notHappyAtAll happyReduce_74 = happySpecReduce_1 33 happyReduction_74 happyReduction_74 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn26 (happy_var_1 ) happyReduction_74 _ = notHappyAtAll happyReduce_75 = happySpecReduce_1 33 happyReduction_75 happyReduction_75 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn26 (happy_var_1 ) happyReduction_75 _ = notHappyAtAll happyReduce_76 = happySpecReduce_1 33 happyReduction_76 happyReduction_76 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn26 (happy_var_1 ) happyReduction_76 _ = notHappyAtAll happyReduce_77 = happySpecReduce_1 33 happyReduction_77 happyReduction_77 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn26 (happy_var_1 ) happyReduction_77 _ = notHappyAtAll happyReduce_78 = happyReduce 4 34 happyReduction_78 happyReduction_78 (_ `HappyStk` (HappyAbsSyn25 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn25 (happy_var_3 ) `HappyStk` happyRest happyReduce_79 = happySpecReduce_3 34 happyReduction_79 happyReduction_79 _ (HappyAbsSyn25 happy_var_2) _ = HappyAbsSyn25 (happy_var_2 ) happyReduction_79 _ _ _ = notHappyAtAll happyReduce_80 = happyReduce 4 35 happyReduction_80 happyReduction_80 ((HappyAbsSyn41 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` (HappyAbsSyn13 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn26 (hsTypeSig happy_var_2 (reverse happy_var_1) (fst happy_var_4) (snd happy_var_4) ) `HappyStk` happyRest happyReduce_81 = happySpecReduce_3 36 happyReduction_81 happyReduction_81 (HappyAbsSyn14 happy_var_3) _ (HappyAbsSyn13 happy_var_1) = HappyAbsSyn13 (happy_var_3 : happy_var_1 ) happyReduction_81 _ _ _ = notHappyAtAll happyReduce_82 = happyMonadReduce 1 36 happyReduction_82 happyReduction_82 ((HappyAbsSyn14 happy_var_1) `HappyStk` happyRest) = happyThen ( case happy_var_1 of Qual _ _ -> parseError "bad qvar in vars." _ -> return [happy_var_1] ) (\r -> happyReturn (HappyAbsSyn13 r)) happyReduce_83 = happySpecReduce_3 37 happyReduction_83 happyReduction_83 (HappyAbsSyn37 happy_var_3) _ (HappyAbsSyn37 happy_var_1) = HappyAbsSyn37 (hsTyFun happy_var_1 happy_var_3 ) happyReduction_83 _ _ _ = notHappyAtAll happyReduce_84 = happySpecReduce_1 37 happyReduction_84 happyReduction_84 (HappyAbsSyn37 happy_var_1) = HappyAbsSyn37 (happy_var_1 ) happyReduction_84 _ = notHappyAtAll happyReduce_85 = happySpecReduce_2 38 happyReduction_85 happyReduction_85 (HappyAbsSyn37 happy_var_2) (HappyAbsSyn37 happy_var_1) = HappyAbsSyn37 (hsTyApp happy_var_1 happy_var_2 ) happyReduction_85 _ _ = notHappyAtAll happyReduce_86 = happySpecReduce_1 38 happyReduction_86 happyReduction_86 (HappyAbsSyn37 happy_var_1) = HappyAbsSyn37 (happy_var_1 ) happyReduction_86 _ = notHappyAtAll happyReduce_87 = happySpecReduce_1 39 happyReduction_87 happyReduction_87 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn37 (hsTyCon happy_var_1 ) happyReduction_87 _ = notHappyAtAll happyReduce_88 = happySpecReduce_1 39 happyReduction_88 happyReduction_88 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn37 (hsTyVar happy_var_1 ) happyReduction_88 _ = notHappyAtAll happyReduce_89 = happySpecReduce_3 39 happyReduction_89 happyReduction_89 _ (HappyAbsSyn42 happy_var_2) _ = HappyAbsSyn37 (hsTyTuple (reverse happy_var_2) ) happyReduction_89 _ _ _ = notHappyAtAll happyReduce_90 = happySpecReduce_3 39 happyReduction_90 happyReduction_90 _ (HappyAbsSyn37 happy_var_2) _ = HappyAbsSyn37 (hsTyApp list_tycon happy_var_2 ) happyReduction_90 _ _ _ = notHappyAtAll happyReduce_91 = happySpecReduce_3 39 happyReduction_91 happyReduction_91 _ (HappyAbsSyn37 happy_var_2) _ = HappyAbsSyn37 (happy_var_2 ) happyReduction_91 _ _ _ = notHappyAtAll happyReduce_92 = happySpecReduce_1 40 happyReduction_92 happyReduction_92 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_92 _ = notHappyAtAll happyReduce_93 = happySpecReduce_2 40 happyReduction_93 happyReduction_93 _ _ = HappyAbsSyn14 (unit_tycon_name ) happyReduce_94 = happySpecReduce_2 40 happyReduction_94 happyReduction_94 _ _ = HappyAbsSyn14 (list_tycon_name ) happyReduce_95 = happySpecReduce_3 40 happyReduction_95 happyReduction_95 _ _ _ = HappyAbsSyn14 (fun_tycon_name ) happyReduce_96 = happySpecReduce_3 40 happyReduction_96 happyReduction_96 _ (HappyAbsSyn27 happy_var_2) _ = HappyAbsSyn14 (tuple_tycon_name happy_var_2 ) happyReduction_96 _ _ _ = notHappyAtAll happyReduce_97 = happyReduce 4 40 happyReduction_97 happyReduction_97 (_ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyTerminal (QModId happy_var_1)) `HappyStk` happyRest) = HappyAbsSyn14 (qualify happy_var_1 "()" ) `HappyStk` happyRest happyReduce_98 = happyReduce 4 40 happyReduction_98 happyReduction_98 (_ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyTerminal (QModId happy_var_1)) `HappyStk` happyRest) = HappyAbsSyn14 (qualify happy_var_1 "[]" ) `HappyStk` happyRest happyReduce_99 = happyReduce 5 40 happyReduction_99 happyReduction_99 (_ `HappyStk` (HappyAbsSyn27 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyTerminal (QModId happy_var_1)) `HappyStk` happyRest) = HappyAbsSyn14 (qualify happy_var_1 (tuple happy_var_4) ) `HappyStk` happyRest happyReduce_100 = happySpecReduce_3 41 happyReduction_100 happyReduction_100 (HappyAbsSyn37 happy_var_3) _ (HappyAbsSyn37 happy_var_1) = HappyAbsSyn41 ((reverse (tupleTypeToContext happy_var_1), happy_var_3) ) happyReduction_100 _ _ _ = notHappyAtAll happyReduce_101 = happySpecReduce_1 41 happyReduction_101 happyReduction_101 (HappyAbsSyn37 happy_var_1) = HappyAbsSyn41 (([], happy_var_1) ) happyReduction_101 _ = notHappyAtAll happyReduce_102 = happySpecReduce_3 42 happyReduction_102 happyReduction_102 (HappyAbsSyn37 happy_var_3) _ (HappyAbsSyn42 happy_var_1) = HappyAbsSyn42 (happy_var_3 : happy_var_1 ) happyReduction_102 _ _ _ = notHappyAtAll happyReduce_103 = happySpecReduce_3 42 happyReduction_103 happyReduction_103 (HappyAbsSyn37 happy_var_3) _ (HappyAbsSyn37 happy_var_1) = HappyAbsSyn42 ([happy_var_3, happy_var_1] ) happyReduction_103 _ _ _ = notHappyAtAll happyReduce_104 = happySpecReduce_3 43 happyReduction_104 happyReduction_104 (HappyAbsSyn42 happy_var_3) _ (HappyAbsSyn37 happy_var_1) = HappyAbsSyn43 ((reverse (tupleTypeToContext happy_var_1), happy_var_3) ) happyReduction_104 _ _ _ = notHappyAtAll happyReduce_105 = happySpecReduce_1 43 happyReduction_105 happyReduction_105 (HappyAbsSyn42 happy_var_1) = HappyAbsSyn43 (([], happy_var_1) ) happyReduction_105 _ = notHappyAtAll happyReduce_106 = happySpecReduce_2 44 happyReduction_106 happyReduction_106 (HappyAbsSyn42 happy_var_2) (HappyAbsSyn14 happy_var_1) = HappyAbsSyn42 (hsTyCon happy_var_1 : (reverse happy_var_2) ) happyReduction_106 _ _ = notHappyAtAll happyReduce_107 = happySpecReduce_1 44 happyReduction_107 happyReduction_107 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn42 ([hsTyCon happy_var_1] ) happyReduction_107 _ = notHappyAtAll happyReduce_108 = happySpecReduce_2 45 happyReduction_108 happyReduction_108 (HappyAbsSyn14 happy_var_2) (HappyAbsSyn42 happy_var_1) = HappyAbsSyn42 ((hsTyVar happy_var_2) : happy_var_1 ) happyReduction_108 _ _ = notHappyAtAll happyReduce_109 = happySpecReduce_1 45 happyReduction_109 happyReduction_109 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn42 ([hsTyVar happy_var_1] ) happyReduction_109 _ = notHappyAtAll happyReduce_110 = happySpecReduce_3 46 happyReduction_110 happyReduction_110 (HappyAbsSyn14 happy_var_3) _ (HappyAbsSyn37 happy_var_1) = HappyAbsSyn46 ((reverse (tupleTypeToContext happy_var_1), happy_var_3) ) happyReduction_110 _ _ _ = notHappyAtAll happyReduce_111 = happySpecReduce_1 46 happyReduction_111 happyReduction_111 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn46 (([], happy_var_1) ) happyReduction_111 _ = notHappyAtAll happyReduce_112 = happySpecReduce_3 47 happyReduction_112 happyReduction_112 (HappyAbsSyn48 happy_var_3) _ (HappyAbsSyn47 happy_var_1) = HappyAbsSyn47 (happy_var_3 : happy_var_1 ) happyReduction_112 _ _ _ = notHappyAtAll happyReduce_113 = happySpecReduce_1 47 happyReduction_113 happyReduction_113 (HappyAbsSyn48 happy_var_1) = HappyAbsSyn47 ([happy_var_1] ) happyReduction_113 _ = notHappyAtAll happyReduce_114 = happySpecReduce_2 48 happyReduction_114 happyReduction_114 (HappyAbsSyn49 happy_var_2) (HappyAbsSyn115 happy_var_1) = HappyAbsSyn48 (HsConDecl happy_var_1 (fst happy_var_2) (snd happy_var_2) ) happyReduction_114 _ _ = notHappyAtAll happyReduce_115 = happyReduce 4 48 happyReduction_115 happyReduction_115 ((HappyAbsSyn51 happy_var_4) `HappyStk` (HappyAbsSyn14 happy_var_3) `HappyStk` (HappyAbsSyn51 happy_var_2) `HappyStk` (HappyAbsSyn115 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn48 (HsConDecl happy_var_1 happy_var_3 [happy_var_2, happy_var_4] ) `HappyStk` happyRest happyReduce_116 = happyReduce 6 48 happyReduction_116 happyReduction_116 (_ `HappyStk` (HappyAbsSyn53 happy_var_5) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn14 happy_var_2) `HappyStk` (HappyAbsSyn115 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn48 (HsRecDecl happy_var_1 happy_var_2 (reverse happy_var_5) ) `HappyStk` happyRest happyReduce_117 = happyMonadReduce 1 49 happyReduction_117 happyReduction_117 ((HappyAbsSyn37 happy_var_1) `HappyStk` happyRest) = happyThen ( do { (c, ts) <- splitTyConApp happy_var_1 ; return (c, map HsUnBangedType ts) } ) (\r -> happyReturn (HappyAbsSyn49 r)) happyReduce_118 = happySpecReduce_1 49 happyReduction_118 happyReduction_118 (HappyAbsSyn49 happy_var_1) = HappyAbsSyn49 (happy_var_1 ) happyReduction_118 _ = notHappyAtAll happyReduce_119 = happyMonadReduce 3 50 happyReduction_119 happyReduction_119 ((HappyAbsSyn37 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn37 happy_var_1) `HappyStk` happyRest) = happyThen ( do { (c, ts) <- splitTyConApp happy_var_1 ; return (c, map HsUnBangedType ts ++ [HsBangedType happy_var_3]) } ) (\r -> happyReturn (HappyAbsSyn49 r)) happyReduce_120 = happySpecReduce_2 50 happyReduction_120 happyReduction_120 (HappyAbsSyn51 happy_var_2) (HappyAbsSyn49 happy_var_1) = HappyAbsSyn49 ((fst happy_var_1, snd happy_var_1 ++ [happy_var_2] ) ) happyReduction_120 _ _ = notHappyAtAll happyReduce_121 = happySpecReduce_1 51 happyReduction_121 happyReduction_121 (HappyAbsSyn37 happy_var_1) = HappyAbsSyn51 (HsUnBangedType happy_var_1 ) happyReduction_121 _ = notHappyAtAll happyReduce_122 = happySpecReduce_2 51 happyReduction_122 happyReduction_122 (HappyAbsSyn37 happy_var_2) _ = HappyAbsSyn51 (HsBangedType happy_var_2 ) happyReduction_122 _ _ = notHappyAtAll happyReduce_123 = happySpecReduce_1 52 happyReduction_123 happyReduction_123 (HappyAbsSyn37 happy_var_1) = HappyAbsSyn51 (HsUnBangedType happy_var_1 ) happyReduction_123 _ = notHappyAtAll happyReduce_124 = happySpecReduce_2 52 happyReduction_124 happyReduction_124 (HappyAbsSyn37 happy_var_2) _ = HappyAbsSyn51 (HsBangedType happy_var_2 ) happyReduction_124 _ _ = notHappyAtAll happyReduce_125 = happySpecReduce_3 53 happyReduction_125 happyReduction_125 (HappyAbsSyn54 happy_var_3) _ (HappyAbsSyn53 happy_var_1) = HappyAbsSyn53 (happy_var_3 : happy_var_1 ) happyReduction_125 _ _ _ = notHappyAtAll happyReduce_126 = happySpecReduce_1 53 happyReduction_126 happyReduction_126 (HappyAbsSyn54 happy_var_1) = HappyAbsSyn53 ([happy_var_1] ) happyReduction_126 _ = notHappyAtAll happyReduce_127 = happySpecReduce_3 54 happyReduction_127 happyReduction_127 (HappyAbsSyn51 happy_var_3) _ (HappyAbsSyn13 happy_var_1) = HappyAbsSyn54 ((reverse happy_var_1, happy_var_3) ) happyReduction_127 _ _ _ = notHappyAtAll happyReduce_128 = happySpecReduce_1 55 happyReduction_128 happyReduction_128 (HappyAbsSyn37 happy_var_1) = HappyAbsSyn51 (HsUnBangedType happy_var_1 ) happyReduction_128 _ = notHappyAtAll happyReduce_129 = happySpecReduce_2 55 happyReduction_129 happyReduction_129 (HappyAbsSyn37 happy_var_2) _ = HappyAbsSyn51 (HsBangedType happy_var_2 ) happyReduction_129 _ _ = notHappyAtAll happyReduce_130 = happySpecReduce_0 56 happyReduction_130 happyReduction_130 = HappyAbsSyn13 ([] ) happyReduce_131 = happySpecReduce_2 56 happyReduction_131 happyReduction_131 (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn13 ([happy_var_2] ) happyReduction_131 _ _ = notHappyAtAll happyReduce_132 = happySpecReduce_3 56 happyReduction_132 happyReduction_132 _ _ _ = HappyAbsSyn13 ([] ) happyReduce_133 = happyReduce 4 56 happyReduction_133 happyReduction_133 (_ `HappyStk` (HappyAbsSyn13 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn13 (reverse happy_var_3 ) `HappyStk` happyRest happyReduce_134 = happySpecReduce_3 57 happyReduction_134 happyReduction_134 (HappyAbsSyn14 happy_var_3) _ (HappyAbsSyn13 happy_var_1) = HappyAbsSyn13 (happy_var_3 : happy_var_1 ) happyReduction_134 _ _ _ = notHappyAtAll happyReduce_135 = happySpecReduce_1 57 happyReduction_135 happyReduction_135 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn13 ([happy_var_1] ) happyReduction_135 _ = notHappyAtAll happyReduce_136 = happyReduce 5 58 happyReduction_136 happyReduction_136 (_ `HappyStk` (HappyAbsSyn25 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn25 (happy_var_4 ) `HappyStk` happyRest happyReduce_137 = happyReduce 4 58 happyReduction_137 happyReduction_137 (_ `HappyStk` (HappyAbsSyn25 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn25 (happy_var_3 ) `HappyStk` happyRest happyReduce_138 = happySpecReduce_0 58 happyReduction_138 happyReduction_138 = HappyAbsSyn25 ([] ) happyReduce_139 = happyReduce 4 59 happyReduction_139 happyReduction_139 (_ `HappyStk` (HappyAbsSyn25 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn25 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn25 (reverse happy_var_1 ++ reverse happy_var_3 ) `HappyStk` happyRest happyReduce_140 = happySpecReduce_2 59 happyReduction_140 happyReduction_140 _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (reverse happy_var_1 ) happyReduction_140 _ _ = notHappyAtAll happyReduce_141 = happySpecReduce_1 59 happyReduction_141 happyReduction_141 _ = HappyAbsSyn25 ([] ) happyReduce_142 = happySpecReduce_3 60 happyReduction_142 happyReduction_142 (HappyAbsSyn26 happy_var_3) _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (funCons happy_var_3 happy_var_1 ) happyReduction_142 _ _ _ = notHappyAtAll happyReduce_143 = happySpecReduce_1 60 happyReduction_143 happyReduction_143 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn25 ([happy_var_1] ) happyReduction_143 _ = notHappyAtAll happyReduce_144 = happySpecReduce_3 61 happyReduction_144 happyReduction_144 (HappyAbsSyn26 happy_var_3) _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (funCons happy_var_3 happy_var_1 ) happyReduction_144 _ _ _ = notHappyAtAll happyReduce_145 = happySpecReduce_1 61 happyReduction_145 happyReduction_145 (HappyAbsSyn26 happy_var_1) = HappyAbsSyn25 ([happy_var_1] ) happyReduction_145 _ = notHappyAtAll happyReduce_146 = happyReduce 5 62 happyReduction_146 happyReduction_146 (_ `HappyStk` (HappyAbsSyn25 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn25 (happy_var_4 ) `HappyStk` happyRest happyReduce_147 = happyReduce 4 62 happyReduction_147 happyReduction_147 (_ `HappyStk` (HappyAbsSyn25 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn25 (happy_var_3 ) `HappyStk` happyRest happyReduce_148 = happySpecReduce_0 62 happyReduction_148 happyReduction_148 = HappyAbsSyn25 ([] ) happyReduce_149 = happySpecReduce_2 63 happyReduction_149 happyReduction_149 _ (HappyAbsSyn25 happy_var_1) = HappyAbsSyn25 (reverse happy_var_1 ) happyReduction_149 _ _ = notHappyAtAll happyReduce_150 = happySpecReduce_1 63 happyReduction_150 happyReduction_150 _ = HappyAbsSyn25 ([] ) happyReduce_151 = happyMonadReduce 4 64 happyReduction_151 happyReduction_151 ((HappyAbsSyn25 happy_var_4) `HappyStk` (HappyAbsSyn66 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = happyThen ( if isPatternExp happy_var_1 then mkValDef happy_var_1 happy_var_2 happy_var_3 happy_var_4 else mkFunDef happy_var_1 happy_var_2 happy_var_3 happy_var_4 ) (\r -> happyReturn (HappyAbsSyn26 r)) happyReduce_152 = happySpecReduce_2 65 happyReduction_152 happyReduction_152 (HappyAbsSyn25 happy_var_2) _ = HappyAbsSyn25 (happy_var_2 ) happyReduction_152 _ _ = notHappyAtAll happyReduce_153 = happySpecReduce_0 65 happyReduction_153 happyReduction_153 = HappyAbsSyn25 ([] ) happyReduce_154 = happySpecReduce_2 66 happyReduction_154 happyReduction_154 (HappyAbsSyn69 happy_var_2) _ = HappyAbsSyn66 (HsBody happy_var_2 ) happyReduction_154 _ _ = notHappyAtAll happyReduce_155 = happySpecReduce_1 66 happyReduction_155 happyReduction_155 (HappyAbsSyn67 happy_var_1) = HappyAbsSyn66 (HsGuard (reverse happy_var_1) ) happyReduction_155 _ = notHappyAtAll happyReduce_156 = happySpecReduce_2 67 happyReduction_156 happyReduction_156 (HappyAbsSyn68 happy_var_2) (HappyAbsSyn67 happy_var_1) = HappyAbsSyn67 (happy_var_2 : happy_var_1 ) happyReduction_156 _ _ = notHappyAtAll happyReduce_157 = happySpecReduce_1 67 happyReduction_157 happyReduction_157 (HappyAbsSyn68 happy_var_1) = HappyAbsSyn67 ([happy_var_1] ) happyReduction_157 _ = notHappyAtAll happyReduce_158 = happyReduce 5 68 happyReduction_158 happyReduction_158 ((HappyAbsSyn69 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn115 happy_var_3) `HappyStk` (HappyAbsSyn69 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn68 ((happy_var_3, happy_var_2, happy_var_5) ) `HappyStk` happyRest happyReduce_159 = happyReduce 4 69 happyReduction_159 happyReduction_159 ((HappyAbsSyn41 happy_var_4) `HappyStk` (HappyAbsSyn115 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn69 (hsExpTypeSig happy_var_3 happy_var_1 (fst happy_var_4) (snd happy_var_4) ) `HappyStk` happyRest happyReduce_160 = happySpecReduce_1 69 happyReduction_160 happyReduction_160 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_160 _ = notHappyAtAll happyReduce_161 = happySpecReduce_1 70 happyReduction_161 happyReduction_161 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_161 _ = notHappyAtAll happyReduce_162 = happySpecReduce_3 70 happyReduction_162 happyReduction_162 (HappyAbsSyn69 happy_var_3) (HappyAbsSyn102 happy_var_2) (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (hsInfixApp happy_var_1 happy_var_2 happy_var_3 ) happyReduction_162 _ _ _ = notHappyAtAll happyReduce_163 = happyMonadReduce 4 71 happyReduction_163 happyReduction_163 ((HappyAbsSyn69 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn73 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = happyThen ( do { ps <- mapM expToPat happy_var_2 ; return (hsLambda (reverse ps) happy_var_4) } ) (\r -> happyReturn (HappyAbsSyn69 r)) happyReduce_164 = happyMonadReduce 4 71 happyReduction_164 happyReduction_164 ((HappyAbsSyn69 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn73 happy_var_2) `HappyStk` (HappyAbsSyn126 happy_var_1) `HappyStk` happyRest) = happyThen ( do { ps <- mapM expToPat happy_var_2 ; return (mkQuant happy_var_1 (reverse ps) happy_var_4) } ) (\r -> happyReturn (HappyAbsSyn69 r)) happyReduce_165 = happyReduce 4 71 happyReduction_165 happyReduction_165 ((HappyAbsSyn69 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn25 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn69 (hsLet happy_var_2 happy_var_4 ) `HappyStk` happyRest happyReduce_166 = happyReduce 6 71 happyReduction_166 happyReduction_166 ((HappyAbsSyn69 happy_var_6) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn69 (hsIf happy_var_2 happy_var_4 happy_var_6 ) `HappyStk` happyRest happyReduce_167 = happyReduce 4 71 happyReduction_167 happyReduction_167 ((HappyAbsSyn82 happy_var_4) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn69 (hsCase happy_var_2 happy_var_4 ) `HappyStk` happyRest happyReduce_168 = happySpecReduce_2 71 happyReduction_168 happyReduction_168 (HappyAbsSyn69 happy_var_2) _ = HappyAbsSyn69 (hsNegApp happy_var_2 ) happyReduction_168 _ _ = notHappyAtAll happyReduce_169 = happySpecReduce_2 71 happyReduction_169 happyReduction_169 (HappyAbsSyn88 happy_var_2) _ = HappyAbsSyn69 (hsDo (atoms2Stmt happy_var_2) ) happyReduction_169 _ _ = notHappyAtAll happyReduce_170 = happySpecReduce_1 71 happyReduction_170 happyReduction_170 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_170 _ = notHappyAtAll happyReduce_171 = happySpecReduce_2 72 happyReduction_171 happyReduction_171 (HappyAbsSyn69 happy_var_2) (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (hsApp happy_var_1 happy_var_2 ) happyReduction_171 _ _ = notHappyAtAll happyReduce_172 = happySpecReduce_1 72 happyReduction_172 happyReduction_172 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_172 _ = notHappyAtAll happyReduce_173 = happySpecReduce_2 73 happyReduction_173 happyReduction_173 (HappyAbsSyn69 happy_var_2) (HappyAbsSyn73 happy_var_1) = HappyAbsSyn73 (happy_var_2 : happy_var_1 ) happyReduction_173 _ _ = notHappyAtAll happyReduce_174 = happySpecReduce_1 73 happyReduction_174 happyReduction_174 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn73 ([happy_var_1] ) happyReduction_174 _ = notHappyAtAll happyReduce_175 = happyReduce 5 74 happyReduction_175 happyReduction_175 (_ `HappyStk` (HappyAbsSyn91 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn69 (mkRecord happy_var_1 (reverse happy_var_4) ) `HappyStk` happyRest happyReduce_176 = happySpecReduce_1 74 happyReduction_176 happyReduction_176 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_176 _ = notHappyAtAll happyReduce_177 = happySpecReduce_1 75 happyReduction_177 happyReduction_177 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn69 (hsEVar (happy_var_1 :: HsName) ) happyReduction_177 _ = notHappyAtAll happyReduce_178 = happySpecReduce_1 75 happyReduction_178 happyReduction_178 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_178 _ = notHappyAtAll happyReduce_179 = happySpecReduce_1 75 happyReduction_179 happyReduction_179 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (happy_var_1 ) happyReduction_179 _ = notHappyAtAll happyReduce_180 = happySpecReduce_3 75 happyReduction_180 happyReduction_180 _ (HappyAbsSyn69 happy_var_2) _ = HappyAbsSyn69 (hsParen happy_var_2 ) happyReduction_180 _ _ _ = notHappyAtAll happyReduce_181 = happySpecReduce_3 75 happyReduction_181 happyReduction_181 _ (HappyAbsSyn73 happy_var_2) _ = HappyAbsSyn69 (hsTuple (reverse happy_var_2) ) happyReduction_181 _ _ _ = notHappyAtAll happyReduce_182 = happySpecReduce_3 75 happyReduction_182 happyReduction_182 _ (HappyAbsSyn69 happy_var_2) _ = HappyAbsSyn69 (happy_var_2 ) happyReduction_182 _ _ _ = notHappyAtAll happyReduce_183 = happyReduce 4 75 happyReduction_183 happyReduction_183 (_ `HappyStk` (HappyAbsSyn102 happy_var_3) `HappyStk` (HappyAbsSyn69 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn69 (hsLeftSection happy_var_2 happy_var_3 ) `HappyStk` happyRest happyReduce_184 = happyReduce 4 75 happyReduction_184 happyReduction_184 (_ `HappyStk` (HappyAbsSyn69 happy_var_3) `HappyStk` (HappyAbsSyn102 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn69 (hsRightSection happy_var_2 happy_var_3 ) `HappyStk` happyRest happyReduce_185 = happySpecReduce_3 75 happyReduction_185 happyReduction_185 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn14 happy_var_1) = HappyAbsSyn69 (hsAsPat happy_var_1 happy_var_3 ) happyReduction_185 _ _ _ = notHappyAtAll happyReduce_186 = happySpecReduce_1 75 happyReduction_186 happyReduction_186 _ = HappyAbsSyn69 (hsWildCard ) happyReduce_187 = happySpecReduce_2 75 happyReduction_187 happyReduction_187 (HappyAbsSyn69 happy_var_2) _ = HappyAbsSyn69 (hsIrrPat happy_var_2 ) happyReduction_187 _ _ = notHappyAtAll happyReduce_188 = happySpecReduce_2 76 happyReduction_188 happyReduction_188 _ (HappyAbsSyn27 happy_var_1) = HappyAbsSyn27 (happy_var_1 + 1 ) happyReduction_188 _ _ = notHappyAtAll happyReduce_189 = happySpecReduce_1 76 happyReduction_189 happyReduction_189 _ = HappyAbsSyn27 (1 ) happyReduce_190 = happySpecReduce_3 77 happyReduction_190 happyReduction_190 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn73 happy_var_1) = HappyAbsSyn73 (happy_var_3 : happy_var_1 ) happyReduction_190 _ _ _ = notHappyAtAll happyReduce_191 = happySpecReduce_3 77 happyReduction_191 happyReduction_191 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn69 happy_var_1) = HappyAbsSyn73 ([happy_var_3, happy_var_1] ) happyReduction_191 _ _ _ = notHappyAtAll happyReduce_192 = happySpecReduce_1 78 happyReduction_192 happyReduction_192 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (hsList [happy_var_1] ) happyReduction_192 _ = notHappyAtAll happyReduce_193 = happySpecReduce_1 78 happyReduction_193 happyReduction_193 (HappyAbsSyn73 happy_var_1) = HappyAbsSyn69 (hsList (reverse happy_var_1) ) happyReduction_193 _ = notHappyAtAll happyReduce_194 = happySpecReduce_2 78 happyReduction_194 happyReduction_194 _ (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (hsEnumFrom happy_var_1 ) happyReduction_194 _ _ = notHappyAtAll happyReduce_195 = happyReduce 4 78 happyReduction_195 happyReduction_195 (_ `HappyStk` (HappyAbsSyn69 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn69 (hsEnumFromThen happy_var_1 happy_var_3 ) `HappyStk` happyRest happyReduce_196 = happySpecReduce_3 78 happyReduction_196 happyReduction_196 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (hsEnumFromTo happy_var_1 happy_var_3 ) happyReduction_196 _ _ _ = notHappyAtAll happyReduce_197 = happyReduce 5 78 happyReduction_197 happyReduction_197 ((HappyAbsSyn69 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = HappyAbsSyn69 (hsEnumFromThenTo happy_var_1 happy_var_3 happy_var_5 ) `HappyStk` happyRest happyReduce_198 = happySpecReduce_3 78 happyReduction_198 happyReduction_198 (HappyAbsSyn80 happy_var_3) _ (HappyAbsSyn69 happy_var_1) = HappyAbsSyn69 (hsListComp (atoms2Stmt (reverse happy_var_3 ++ [HsQualifierAtom happy_var_1])) ) happyReduction_198 _ _ _ = notHappyAtAll happyReduce_199 = happySpecReduce_3 79 happyReduction_199 happyReduction_199 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn73 happy_var_1) = HappyAbsSyn73 (happy_var_3 : happy_var_1 ) happyReduction_199 _ _ _ = notHappyAtAll happyReduce_200 = happySpecReduce_3 79 happyReduction_200 happyReduction_200 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn69 happy_var_1) = HappyAbsSyn73 ([happy_var_3,happy_var_1] ) happyReduction_200 _ _ _ = notHappyAtAll happyReduce_201 = happySpecReduce_3 80 happyReduction_201 happyReduction_201 (HappyAbsSyn81 happy_var_3) _ (HappyAbsSyn80 happy_var_1) = HappyAbsSyn80 (happy_var_3 : happy_var_1 ) happyReduction_201 _ _ _ = notHappyAtAll happyReduce_202 = happySpecReduce_1 80 happyReduction_202 happyReduction_202 (HappyAbsSyn81 happy_var_1) = HappyAbsSyn80 ([happy_var_1] ) happyReduction_202 _ = notHappyAtAll happyReduce_203 = happyMonadReduce 3 81 happyReduction_203 happyReduction_203 ((HappyAbsSyn69 happy_var_3) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = happyThen ( do { p <- expToPat happy_var_1 ; return (HsGeneratorAtom p happy_var_3) } ) (\r -> happyReturn (HappyAbsSyn81 r)) happyReduce_204 = happySpecReduce_1 81 happyReduction_204 happyReduction_204 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn81 (HsQualifierAtom happy_var_1 ) happyReduction_204 _ = notHappyAtAll happyReduce_205 = happySpecReduce_2 81 happyReduction_205 happyReduction_205 (HappyAbsSyn25 happy_var_2) _ = HappyAbsSyn81 (HsLetStmtAtom happy_var_2 ) happyReduction_205 _ _ = notHappyAtAll happyReduce_206 = happyReduce 5 82 happyReduction_206 happyReduction_206 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn82 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn82 (reverse happy_var_3 ) `HappyStk` happyRest happyReduce_207 = happyReduce 4 82 happyReduction_207 happyReduction_207 (_ `HappyStk` _ `HappyStk` (HappyAbsSyn82 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn82 (reverse happy_var_2 ) `HappyStk` happyRest happyReduce_208 = happySpecReduce_3 83 happyReduction_208 happyReduction_208 (HappyAbsSyn84 happy_var_3) _ (HappyAbsSyn82 happy_var_1) = HappyAbsSyn82 (happy_var_3 : happy_var_1 ) happyReduction_208 _ _ _ = notHappyAtAll happyReduce_209 = happySpecReduce_1 83 happyReduction_209 happyReduction_209 (HappyAbsSyn84 happy_var_1) = HappyAbsSyn82 ([happy_var_1] ) happyReduction_209 _ = notHappyAtAll happyReduce_210 = happyMonadReduce 3 84 happyReduction_210 happyReduction_210 ((HappyAbsSyn66 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = happyThen ( do { p <- expToPat happy_var_1 ; return (HsAlt happy_var_2 p happy_var_3 []) } ) (\r -> happyReturn (HappyAbsSyn84 r)) happyReduce_211 = happyMonadReduce 5 84 happyReduction_211 happyReduction_211 ((HappyAbsSyn25 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn66 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` (HappyAbsSyn69 happy_var_1) `HappyStk` happyRest) = happyThen ( do { p <- expToPat happy_var_1 ; return (HsAlt happy_var_2 p happy_var_3 happy_var_5) } ) (\r -> happyReturn (HappyAbsSyn84 r)) happyReduce_212 = happySpecReduce_2 85 happyReduction_212 happyReduction_212 (HappyAbsSyn69 happy_var_2) _ = HappyAbsSyn66 (HsBody happy_var_2 ) happyReduction_212 _ _ = notHappyAtAll happyReduce_213 = happySpecReduce_1 85 happyReduction_213 happyReduction_213 (HappyAbsSyn67 happy_var_1) = HappyAbsSyn66 (HsGuard (reverse happy_var_1) ) happyReduction_213 _ = notHappyAtAll happyReduce_214 = happySpecReduce_2 86 happyReduction_214 happyReduction_214 (HappyAbsSyn68 happy_var_2) (HappyAbsSyn67 happy_var_1) = HappyAbsSyn67 (happy_var_2 : happy_var_1 ) happyReduction_214 _ _ = notHappyAtAll happyReduce_215 = happySpecReduce_1 86 happyReduction_215 happyReduction_215 (HappyAbsSyn68 happy_var_1) = HappyAbsSyn67 ([happy_var_1] ) happyReduction_215 _ = notHappyAtAll happyReduce_216 = happyReduce 5 87 happyReduction_216 happyReduction_216 ((HappyAbsSyn69 happy_var_5) `HappyStk` _ `HappyStk` (HappyAbsSyn69 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn68 ((happy_var_2, happy_var_3, happy_var_5) ) `HappyStk` happyRest happyReduce_217 = happyReduce 4 88 happyReduction_217 happyReduction_217 (_ `HappyStk` (HappyAbsSyn88 happy_var_3) `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn88 (happy_var_3 ) `HappyStk` happyRest happyReduce_218 = happySpecReduce_3 88 happyReduction_218 happyReduction_218 _ (HappyAbsSyn88 happy_var_2) _ = HappyAbsSyn88 (happy_var_2 ) happyReduction_218 _ _ _ = notHappyAtAll happyReduce_219 = happySpecReduce_3 89 happyReduction_219 happyReduction_219 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn88 happy_var_1) = HappyAbsSyn88 (reverse (HsQualifierAtom happy_var_3 : happy_var_1) ) happyReduction_219 _ _ _ = notHappyAtAll happyReduce_220 = happySpecReduce_1 89 happyReduction_220 happyReduction_220 (HappyAbsSyn69 happy_var_1) = HappyAbsSyn88 ([HsQualifierAtom happy_var_1] ) happyReduction_220 _ = notHappyAtAll happyReduce_221 = happySpecReduce_3 90 happyReduction_221 happyReduction_221 (HappyAbsSyn81 happy_var_3) _ (HappyAbsSyn88 happy_var_1) = HappyAbsSyn88 (happy_var_3 : happy_var_1 ) happyReduction_221 _ _ _ = notHappyAtAll happyReduce_222 = happySpecReduce_1 90 happyReduction_222 happyReduction_222 (HappyAbsSyn81 happy_var_1) = HappyAbsSyn88 ([happy_var_1] ) happyReduction_222 _ = notHappyAtAll happyReduce_223 = happySpecReduce_3 91 happyReduction_223 happyReduction_223 (HappyAbsSyn92 happy_var_3) _ (HappyAbsSyn91 happy_var_1) = HappyAbsSyn91 (happy_var_3 : happy_var_1 ) happyReduction_223 _ _ _ = notHappyAtAll happyReduce_224 = happySpecReduce_1 91 happyReduction_224 happyReduction_224 (HappyAbsSyn92 happy_var_1) = HappyAbsSyn91 ([happy_var_1] ) happyReduction_224 _ = notHappyAtAll happyReduce_225 = happySpecReduce_3 92 happyReduction_225 happyReduction_225 (HappyAbsSyn69 happy_var_3) _ (HappyAbsSyn14 happy_var_1) = HappyAbsSyn92 (HsFieldUpdate happy_var_1 (happy_var_3) ) happyReduction_225 _ _ _ = notHappyAtAll happyReduce_226 = happySpecReduce_2 93 happyReduction_226 happyReduction_226 _ _ = HappyAbsSyn69 (hsECon (qualify "Prelude" "()") ) happyReduce_227 = happySpecReduce_2 93 happyReduction_227 happyReduction_227 _ _ = HappyAbsSyn69 (hsList [] ) happyReduce_228 = happySpecReduce_3 93 happyReduction_228 happyReduction_228 _ (HappyAbsSyn27 happy_var_2) _ = HappyAbsSyn69 (hsECon (qualify "Prelude" (tuple happy_var_2)) ) happyReduction_228 _ _ _ = notHappyAtAll happyReduce_229 = happyReduce 4 93 happyReduction_229 happyReduction_229 (_ `HappyStk` _ `HappyStk` _ `HappyStk` (HappyTerminal (QModId happy_var_1)) `HappyStk` happyRest) = HappyAbsSyn69 (hsECon (qualify happy_var_1 "()") ) `HappyStk` happyRest happyReduce_230 = happyReduce 4 93 happyReduction_230 happyReduction_230 (_ `HappyStk` _ `HappyStk` _ `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn69 (hsList [] ) `HappyStk` happyRest happyReduce_231 = happyReduce 5 93 happyReduction_231 happyReduction_231 (_ `HappyStk` (HappyAbsSyn27 happy_var_4) `HappyStk` _ `HappyStk` _ `HappyStk` (HappyTerminal (QModId happy_var_1)) `HappyStk` happyRest) = HappyAbsSyn69 (hsECon (qualify happy_var_1 (tuple happy_var_4)) ) `HappyStk` happyRest happyReduce_232 = happySpecReduce_1 93 happyReduction_232 happyReduction_232 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn69 (hsECon happy_var_1 ) happyReduction_232 _ = notHappyAtAll happyReduce_233 = happySpecReduce_1 94 happyReduction_233 happyReduction_233 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_233 _ = notHappyAtAll happyReduce_234 = happySpecReduce_3 94 happyReduction_234 happyReduction_234 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_234 _ _ _ = notHappyAtAll happyReduce_235 = happySpecReduce_1 95 happyReduction_235 happyReduction_235 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_235 _ = notHappyAtAll happyReduce_236 = happySpecReduce_3 95 happyReduction_236 happyReduction_236 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_236 _ _ _ = notHappyAtAll happyReduce_237 = happySpecReduce_1 96 happyReduction_237 happyReduction_237 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_237 _ = notHappyAtAll happyReduce_238 = happySpecReduce_3 96 happyReduction_238 happyReduction_238 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_238 _ _ _ = notHappyAtAll happyReduce_239 = happySpecReduce_1 97 happyReduction_239 happyReduction_239 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_239 _ = notHappyAtAll happyReduce_240 = happySpecReduce_3 97 happyReduction_240 happyReduction_240 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_240 _ _ _ = notHappyAtAll happyReduce_241 = happySpecReduce_1 98 happyReduction_241 happyReduction_241 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_241 _ = notHappyAtAll happyReduce_242 = happySpecReduce_3 98 happyReduction_242 happyReduction_242 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_242 _ _ _ = notHappyAtAll happyReduce_243 = happySpecReduce_1 99 happyReduction_243 happyReduction_243 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_243 _ = notHappyAtAll happyReduce_244 = happySpecReduce_3 99 happyReduction_244 happyReduction_244 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_244 _ _ _ = notHappyAtAll happyReduce_245 = happySpecReduce_1 100 happyReduction_245 happyReduction_245 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_245 _ = notHappyAtAll happyReduce_246 = happySpecReduce_3 100 happyReduction_246 happyReduction_246 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_246 _ _ _ = notHappyAtAll happyReduce_247 = happySpecReduce_1 101 happyReduction_247 happyReduction_247 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_247 _ = notHappyAtAll happyReduce_248 = happySpecReduce_3 101 happyReduction_248 happyReduction_248 _ (HappyAbsSyn14 happy_var_2) _ = HappyAbsSyn14 (happy_var_2 ) happyReduction_248 _ _ _ = notHappyAtAll happyReduce_249 = happySpecReduce_1 102 happyReduction_249 happyReduction_249 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn102 (hsVar happy_var_1 ) happyReduction_249 _ = notHappyAtAll happyReduce_250 = happySpecReduce_1 102 happyReduction_250 happyReduction_250 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn102 (hsCon happy_var_1 ) happyReduction_250 _ = notHappyAtAll happyReduce_251 = happySpecReduce_1 103 happyReduction_251 happyReduction_251 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn102 (hsVar happy_var_1 ) happyReduction_251 _ = notHappyAtAll happyReduce_252 = happySpecReduce_1 103 happyReduction_252 happyReduction_252 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn102 (hsCon happy_var_1 ) happyReduction_252 _ = notHappyAtAll happyReduce_253 = happySpecReduce_1 104 happyReduction_253 happyReduction_253 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_253 _ = notHappyAtAll happyReduce_254 = happySpecReduce_1 104 happyReduction_254 happyReduction_254 (HappyTerminal (QVarId happy_var_1)) = HappyAbsSyn14 (uncurry (Qual . Module) happy_var_1 ) happyReduction_254 _ = notHappyAtAll happyReduce_255 = happySpecReduce_1 105 happyReduction_255 happyReduction_255 (HappyTerminal (VarId happy_var_1)) = HappyAbsSyn14 (UnQual happy_var_1 ) happyReduction_255 _ = notHappyAtAll happyReduce_256 = happySpecReduce_1 105 happyReduction_256 happyReduction_256 _ = HappyAbsSyn14 (as_name ) happyReduce_257 = happySpecReduce_1 105 happyReduction_257 happyReduction_257 _ = HappyAbsSyn14 (qualified_name ) happyReduce_258 = happySpecReduce_1 105 happyReduction_258 happyReduction_258 _ = HappyAbsSyn14 (hiding_name ) happyReduce_259 = happySpecReduce_1 106 happyReduction_259 happyReduction_259 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_259 _ = notHappyAtAll happyReduce_260 = happySpecReduce_1 106 happyReduction_260 happyReduction_260 (HappyTerminal (QConId happy_var_1)) = HappyAbsSyn14 (uncurry (Qual . Module) happy_var_1 ) happyReduction_260 _ = notHappyAtAll happyReduce_261 = happySpecReduce_1 107 happyReduction_261 happyReduction_261 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_261 _ = notHappyAtAll happyReduce_262 = happySpecReduce_1 107 happyReduction_262 happyReduction_262 (HappyTerminal (QConId happy_var_1)) = HappyAbsSyn14 (uncurry (Qual . Module) happy_var_1 ) happyReduction_262 _ = notHappyAtAll happyReduce_263 = happySpecReduce_1 108 happyReduction_263 happyReduction_263 (HappyTerminal (ConId happy_var_1)) = HappyAbsSyn14 (UnQual happy_var_1 ) happyReduction_263 _ = notHappyAtAll happyReduce_264 = happySpecReduce_1 109 happyReduction_264 happyReduction_264 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_264 _ = notHappyAtAll happyReduce_265 = happySpecReduce_1 109 happyReduction_265 happyReduction_265 (HappyTerminal (QConSym happy_var_1)) = HappyAbsSyn14 (uncurry (Qual . Module) happy_var_1 ) happyReduction_265 _ = notHappyAtAll happyReduce_266 = happySpecReduce_1 110 happyReduction_266 happyReduction_266 (HappyTerminal (ConSym happy_var_1)) = HappyAbsSyn14 (UnQual happy_var_1 ) happyReduction_266 _ = notHappyAtAll happyReduce_267 = happySpecReduce_1 111 happyReduction_267 happyReduction_267 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_267 _ = notHappyAtAll happyReduce_268 = happySpecReduce_1 111 happyReduction_268 happyReduction_268 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_268 _ = notHappyAtAll happyReduce_269 = happySpecReduce_1 112 happyReduction_269 happyReduction_269 (HappyTerminal (VarSym happy_var_1)) = HappyAbsSyn14 (UnQual happy_var_1 ) happyReduction_269 _ = notHappyAtAll happyReduce_270 = happySpecReduce_1 112 happyReduction_270 happyReduction_270 _ = HappyAbsSyn14 (minus_name ) happyReduce_271 = happySpecReduce_1 112 happyReduction_271 happyReduction_271 _ = HappyAbsSyn14 (pling_name ) happyReduce_272 = happySpecReduce_1 112 happyReduction_272 happyReduction_272 _ = HappyAbsSyn14 (period_name ) happyReduce_273 = happySpecReduce_1 113 happyReduction_273 happyReduction_273 (HappyTerminal (QVarSym happy_var_1)) = HappyAbsSyn14 (uncurry (Qual . Module) happy_var_1 ) happyReduction_273 _ = notHappyAtAll happyReduce_274 = happySpecReduce_1 114 happyReduction_274 happyReduction_274 (HappyTerminal (IntTok happy_var_1)) = HappyAbsSyn69 (hsLit (HsInt (readInteger happy_var_1)) ) happyReduction_274 _ = notHappyAtAll happyReduce_275 = happySpecReduce_1 114 happyReduction_275 happyReduction_275 (HappyTerminal (Character happy_var_1)) = HappyAbsSyn69 (hsLit (HsChar happy_var_1) ) happyReduction_275 _ = notHappyAtAll happyReduce_276 = happySpecReduce_1 114 happyReduction_276 happyReduction_276 (HappyTerminal (StringTok happy_var_1)) = HappyAbsSyn69 (hsLit (HsString happy_var_1) ) happyReduction_276 _ = notHappyAtAll happyReduce_277 = happySpecReduce_1 114 happyReduction_277 happyReduction_277 (HappyTerminal (FloatTok happy_var_1)) = HappyAbsSyn69 (hsLit (HsFrac (readRational happy_var_1)) ) happyReduction_277 _ = notHappyAtAll happyReduce_278 = happyMonadReduce 0 115 happyReduction_278 happyReduction_278 (happyRest) = happyThen ( getSrcLoc ) (\r -> happyReturn (HappyAbsSyn115 r)) happyReduce_279 = happySpecReduce_1 116 happyReduction_279 happyReduction_279 _ = HappyAbsSyn7 (() ) happyReduce_280 = happyMonadReduce 1 116 happyReduction_280 happyReduction_280 (_ `HappyStk` happyRest) = happyThen ( popContext ) (\r -> happyReturn (HappyAbsSyn7 r)) happyReduce_281 = happyMonadReduce 0 117 happyReduction_281 happyReduction_281 (happyRest) = happyThen ( pushContext NoLayout ) (\r -> happyReturn (HappyAbsSyn7 r)) happyReduce_282 = happyMonadReduce 0 118 happyReduction_282 happyReduction_282 (happyRest) = happyThen ( do { SrcLoc _ _ c <- getSrcLoc ; pushContext (Layout c) } ) (\r -> happyReturn (HappyAbsSyn7 r)) happyReduce_283 = happySpecReduce_1 119 happyReduction_283 happyReduction_283 (HappyTerminal (ConId happy_var_1)) = HappyAbsSyn119 (Module happy_var_1 ) happyReduction_283 _ = notHappyAtAll happyReduce_284 = happySpecReduce_1 120 happyReduction_284 happyReduction_284 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_284 _ = notHappyAtAll happyReduce_285 = happySpecReduce_1 121 happyReduction_285 happyReduction_285 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_285 _ = notHappyAtAll happyReduce_286 = happySpecReduce_1 122 happyReduction_286 happyReduction_286 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_286 _ = notHappyAtAll happyReduce_287 = happySpecReduce_1 123 happyReduction_287 happyReduction_287 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_287 _ = notHappyAtAll happyReduce_288 = happySpecReduce_1 124 happyReduction_288 happyReduction_288 (HappyAbsSyn14 happy_var_1) = HappyAbsSyn14 (happy_var_1 ) happyReduction_288 _ = notHappyAtAll happyReduce_289 = happyReduce 6 125 happyReduction_289 happyReduction_289 ((HappyAbsSyn69 happy_var_6) `HappyStk` _ `HappyStk` (HappyAbsSyn13 happy_var_4) `HappyStk` (HappyAbsSyn14 happy_var_3) `HappyStk` (HappyAbsSyn115 happy_var_2) `HappyStk` _ `HappyStk` happyRest) = HappyAbsSyn26 (hsProperty happy_var_2 happy_var_3 happy_var_4 happy_var_6 ) `HappyStk` happyRest happyReduce_290 = happySpecReduce_1 126 happyReduction_290 happyReduction_290 _ = HappyAbsSyn126 (hsPropForall ) happyReduce_291 = happySpecReduce_1 126 happyReduction_291 happyReduction_291 _ = HappyAbsSyn126 (hsPropExists ) happyReduce_292 = happySpecReduce_1 126 happyReduction_292 happyReduction_292 _ = HappyAbsSyn126 (hsPropForallDefined ) happyReduce_293 = happySpecReduce_1 126 happyReduction_293 happyReduction_293 _ = HappyAbsSyn126 (hsPropExistsUnique ) happyReduce_294 = happySpecReduce_2 127 happyReduction_294 happyReduction_294 (HappyAbsSyn13 happy_var_2) (HappyAbsSyn14 happy_var_1) = HappyAbsSyn13 (happy_var_1 : happy_var_2 ) happyReduction_294 _ _ = notHappyAtAll happyReduce_295 = happySpecReduce_0 127 happyReduction_295 happyReduction_295 = HappyAbsSyn13 ([] ) happyNewToken action sts stk = lexer(\tk -> let cont i = action i i tk (HappyState action) sts stk in case tk of { EOF -> action 195 195 (error "reading EOF!") (HappyState action) sts stk; VarId happy_dollar_dollar -> cont 128; QVarId happy_dollar_dollar -> cont 129; ConId happy_dollar_dollar -> cont 130; QConId happy_dollar_dollar -> cont 131; VarSym "-" -> cont 132; VarSym happy_dollar_dollar -> cont 133; ConSym happy_dollar_dollar -> cont 134; QVarSym happy_dollar_dollar -> cont 135; QConSym happy_dollar_dollar -> cont 136; QModId happy_dollar_dollar -> cont 137; IntTok happy_dollar_dollar -> cont 138; FloatTok happy_dollar_dollar -> cont 139; Character happy_dollar_dollar -> cont 140; StringTok happy_dollar_dollar -> cont 141; LeftParen -> cont 142; RightParen -> cont 143; SemiColon -> cont 144; LeftCurly -> cont 145; RightCurly -> cont 146; VRightCurly -> cont 147; LeftSquare -> cont 148; RightSquare -> cont 149; Comma -> cont 150; Underscore -> cont 151; BackQuote -> cont 152; Period -> cont 153; DotDot -> cont 154; DoubleColon -> cont 155; Equals -> cont 156; Backslash -> cont 157; Bar -> cont 158; LeftArrow -> cont 159; RightArrow -> cont 160; At -> cont 161; Tilde -> cont 162; DoubleArrow -> cont 163; Exclamation -> cont 164; KW_As -> cont 165; KW_Case -> cont 166; KW_Class -> cont 167; KW_Data -> cont 168; KW_Default -> cont 169; KW_Deriving -> cont 170; KW_Do -> cont 171; KW_Else -> cont 172; KW_Hiding -> cont 173; KW_If -> cont 174; KW_Import -> cont 175; KW_In -> cont 176; KW_Infix -> cont 177; KW_InfixL -> cont 178; KW_InfixR -> cont 179; KW_Instance -> cont 180; KW_Let -> cont 181; KW_Module -> cont 182; KW_NewType -> cont 183; KW_Of -> cont 184; KW_Then -> cont 185; KW_Type -> cont 186; KW_Where -> cont 187; KW_Qualified -> cont 188; KW_Primitive -> cont 189; KW_Property -> cont 190; KW_QAll -> cont 191; KW_QExists -> cont 192; KW_QAllDef -> cont 193; KW_QExistsU -> cont 194; }) happyThen :: PM a -> (a -> PM b) -> PM b happyThen = (thenPM) happyReturn = (returnPM) happyThen1 = happyThen happyReturn1 = happyReturn parse = happyThen (happyParse action_0) (\x -> case x of {HappyAbsSyn4 z -> happyReturn z; _other -> notHappyAtAll }) happyError = parseError "parse error" {-# LINE 1 "GenericTemplate.hs" #-} {-# LINE 1 "GenericTemplate.hs" #-} -- $Id: PropParser.hs,v 1.10 2001/11/06 06:33:37 hallgren Exp $ {-# LINE 15 "GenericTemplate.hs" #-} infixr 9 `HappyStk` data HappyStk a = HappyStk a (HappyStk a) ----------------------------------------------------------------------------- -- starting the parse happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll ----------------------------------------------------------------------------- -- Accepting the parse happyAccept j tk st sts (HappyStk ans _) = (happyReturn1 ans) ----------------------------------------------------------------------------- -- Arrays only: do the next action {-# LINE 138 "GenericTemplate.hs" #-} ----------------------------------------------------------------------------- -- HappyState data type (not arrays) newtype HappyState b c = HappyState (Int -> -- token number Int -> -- token number (yes, again) b -> -- token semantic value HappyState b c -> -- current state [HappyState b c] -> -- state stack c) ----------------------------------------------------------------------------- -- Shifting a token happyShift new_state (1) tk st sts stk@(x `HappyStk` _) = let i = (case x of { HappyErrorToken (i) -> i }) in -- trace "shifting the error token" $ new_state i i tk (HappyState (new_state)) ((st):(sts)) (stk) happyShift new_state i tk st sts stk = happyNewToken new_state ((st):(sts)) ((HappyTerminal (tk))`HappyStk`stk) -- happyReduce is specialised for the common cases. happySpecReduce_0 i fn (1) tk st sts stk = happyFail (1) tk st sts stk happySpecReduce_0 nt fn j tk st@((HappyState (action))) sts stk = action nt j tk st ((st):(sts)) (fn `HappyStk` stk) happySpecReduce_1 i fn (1) tk st sts stk = happyFail (1) tk st sts stk happySpecReduce_1 nt fn j tk _ sts@(((st@(HappyState (action))):(_))) (v1`HappyStk`stk') = action nt j tk st sts (fn v1 `HappyStk` stk') happySpecReduce_2 i fn (1) tk st sts stk = happyFail (1) tk st sts stk happySpecReduce_2 nt fn j tk _ ((_):(sts@(((st@(HappyState (action))):(_))))) (v1`HappyStk`v2`HappyStk`stk') = action nt j tk st sts (fn v1 v2 `HappyStk` stk') happySpecReduce_3 i fn (1) tk st sts stk = happyFail (1) tk st sts stk happySpecReduce_3 nt fn j tk _ ((_):(((_):(sts@(((st@(HappyState (action))):(_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk') = action nt j tk st sts (fn v1 v2 v3 `HappyStk` stk') happyReduce k i fn (1) tk st sts stk = happyFail (1) tk st sts stk happyReduce k nt fn j tk st sts stk = action nt j tk st1 sts1 (fn stk) where sts1@(((st1@(HappyState (action))):(_))) = happyDrop k ((st):(sts)) happyMonadReduce k nt fn (1) tk st sts stk = happyFail (1) tk st sts stk happyMonadReduce k nt fn j tk st sts stk = happyThen1 (fn stk) (\r -> action nt j tk st1 sts1 (r `HappyStk` drop_stk)) where sts1@(((st1@(HappyState (action))):(_))) = happyDrop k ((st):(sts)) drop_stk = happyDropStk k stk happyDrop (0) l = l happyDrop n ((_):(t)) = happyDrop (n - ((1) :: Int)) t happyDropStk (0) l = l happyDropStk n (x `HappyStk` xs) = happyDropStk (n - ((1)::Int)) xs ----------------------------------------------------------------------------- -- Moving to a new state after a reduction happyGoto action j tk st = action j j tk (HappyState action) ----------------------------------------------------------------------------- -- Error recovery ((1) is the error token) -- parse error if we are in recovery and we fail again happyFail (1) tk old_st _ stk = -- trace "failing" $ happyError {- We don't need state discarding for our restricted implementation of "error". In fact, it can cause some bogus parses, so I've disabled it for now --SDM -- discard a state happyFail (1) tk old_st (((HappyState (action))):(sts)) (saved_tok `HappyStk` _ `HappyStk` stk) = -- trace ("discarding state, depth " ++ show (length stk)) $ action (1) (1) tk (HappyState (action)) sts ((saved_tok`HappyStk`stk)) -} -- Enter error recovery: generate an error token, -- save the old token and carry on. happyFail i tk (HappyState (action)) sts stk = -- trace "entering error recovery" $ action (1) (1) tk (HappyState (action)) sts ( (HappyErrorToken (i)) `HappyStk` stk) -- Internal happy errors: notHappyAtAll = error "Internal Happy error\n" ----------------------------------------------------------------------------- -- Hack to get the typechecker to accept our action functions ----------------------------------------------------------------------------- -- Don't inline any functions from the template. GHC has a nasty habit -- of deciding to inline happyGoto everywhere, which increases the size of -- the generated parser quite a bit. {-# NOINLINE happyShift #-} {-# NOINLINE happySpecReduce_0 #-} {-# NOINLINE happySpecReduce_1 #-} {-# NOINLINE happySpecReduce_2 #-} {-# NOINLINE happySpecReduce_3 #-} {-# NOINLINE happyReduce #-} {-# NOINLINE happyMonadReduce #-} {-# NOINLINE happyGoto #-} {-# NOINLINE happyFail #-} -- end of Happy Template.
forste/haReFork
tools/property/parse/extras/PropParser.hs
Haskell
bsd-3-clause
240,488
module Main where import Test.Hspec import SpecHelper import Spec main :: IO () main = resetDb >> hspec spec
Drooids/postgrest
test/Main.hs
Haskell
mit
111
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Char -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : stable -- Portability : portable -- -- The Char type and associated operations. -- ----------------------------------------------------------------------------- module Data.Char ( Char -- * Character classification -- | Unicode characters are divided into letters, numbers, marks, -- punctuation, symbols, separators (including spaces) and others -- (including control characters). , isControl, isSpace , isLower, isUpper, isAlpha, isAlphaNum, isPrint , isDigit, isOctDigit, isHexDigit , isLetter, isMark, isNumber, isPunctuation, isSymbol, isSeparator -- ** Subranges , isAscii, isLatin1 , isAsciiUpper, isAsciiLower -- ** Unicode general categories , GeneralCategory(..), generalCategory -- * Case conversion , toUpper, toLower, toTitle -- * Single digit characters , digitToInt , intToDigit -- * Numeric representations , ord , chr -- * String representations , showLitChar , lexLitChar , readLitChar ) where import GHC.Base import GHC.Arr (Ix) import GHC.Char import GHC.Real (fromIntegral) import GHC.Show import GHC.Read (Read, readLitChar, lexLitChar) import GHC.Unicode import GHC.Num import GHC.Enum -- $setup -- Allow the use of Prelude in doctests. -- >>> import Prelude -- | Convert a single digit 'Char' to the corresponding 'Int'. This -- function fails unless its argument satisfies 'isHexDigit', but -- recognises both upper- and lower-case hexadecimal digits (that -- is, @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@). -- -- ==== __Examples__ -- -- Characters @\'0\'@ through @\'9\'@ are converted properly to -- @0..9@: -- -- >>> map digitToInt ['0'..'9'] -- [0,1,2,3,4,5,6,7,8,9] -- -- Both upper- and lower-case @\'A\'@ through @\'F\'@ are converted -- as well, to @10..15@. -- -- >>> map digitToInt ['a'..'f'] -- [10,11,12,13,14,15] -- >>> map digitToInt ['A'..'F'] -- [10,11,12,13,14,15] -- -- Anything else throws an exception: -- -- >>> digitToInt 'G' -- *** Exception: Char.digitToInt: not a digit 'G' -- >>> digitToInt '♥' -- *** Exception: Char.digitToInt: not a digit '\9829' -- digitToInt :: Char -> Int digitToInt c | (fromIntegral dec::Word) <= 9 = dec | (fromIntegral hexl::Word) <= 5 = hexl + 10 | (fromIntegral hexu::Word) <= 5 = hexu + 10 | otherwise = error ("Char.digitToInt: not a digit " ++ show c) -- sigh where dec = ord c - ord '0' hexl = ord c - ord 'a' hexu = ord c - ord 'A' -- | Unicode General Categories (column 2 of the UnicodeData table) in -- the order they are listed in the Unicode standard (the Unicode -- Character Database, in particular). -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> :t OtherLetter -- OtherLetter :: GeneralCategory -- -- 'Eq' instance: -- -- >>> UppercaseLetter == UppercaseLetter -- True -- >>> UppercaseLetter == LowercaseLetter -- False -- -- 'Ord' instance: -- -- >>> NonSpacingMark <= MathSymbol -- True -- -- 'Enum' instance: -- -- >>> enumFromTo ModifierLetter SpacingCombiningMark -- [ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark] -- -- 'Read' instance: -- -- >>> read "DashPunctuation" :: GeneralCategory -- DashPunctuation -- >>> read "17" :: GeneralCategory -- *** Exception: Prelude.read: no parse -- -- 'Show' instance: -- -- >>> show EnclosingMark -- "EnclosingMark" -- -- 'Bounded' instance: -- -- >>> minBound :: GeneralCategory -- UppercaseLetter -- >>> maxBound :: GeneralCategory -- NotAssigned -- -- 'Ix' instance: -- -- >>> import Data.Ix ( index ) -- >>> index (OtherLetter,Control) FinalQuote -- 12 -- >>> index (OtherLetter,Control) Format -- *** Exception: Error in array index -- data GeneralCategory = UppercaseLetter -- ^ Lu: Letter, Uppercase | LowercaseLetter -- ^ Ll: Letter, Lowercase | TitlecaseLetter -- ^ Lt: Letter, Titlecase | ModifierLetter -- ^ Lm: Letter, Modifier | OtherLetter -- ^ Lo: Letter, Other | NonSpacingMark -- ^ Mn: Mark, Non-Spacing | SpacingCombiningMark -- ^ Mc: Mark, Spacing Combining | EnclosingMark -- ^ Me: Mark, Enclosing | DecimalNumber -- ^ Nd: Number, Decimal | LetterNumber -- ^ Nl: Number, Letter | OtherNumber -- ^ No: Number, Other | ConnectorPunctuation -- ^ Pc: Punctuation, Connector | DashPunctuation -- ^ Pd: Punctuation, Dash | OpenPunctuation -- ^ Ps: Punctuation, Open | ClosePunctuation -- ^ Pe: Punctuation, Close | InitialQuote -- ^ Pi: Punctuation, Initial quote | FinalQuote -- ^ Pf: Punctuation, Final quote | OtherPunctuation -- ^ Po: Punctuation, Other | MathSymbol -- ^ Sm: Symbol, Math | CurrencySymbol -- ^ Sc: Symbol, Currency | ModifierSymbol -- ^ Sk: Symbol, Modifier | OtherSymbol -- ^ So: Symbol, Other | Space -- ^ Zs: Separator, Space | LineSeparator -- ^ Zl: Separator, Line | ParagraphSeparator -- ^ Zp: Separator, Paragraph | Control -- ^ Cc: Other, Control | Format -- ^ Cf: Other, Format | Surrogate -- ^ Cs: Other, Surrogate | PrivateUse -- ^ Co: Other, Private Use | NotAssigned -- ^ Cn: Other, Not Assigned deriving (Eq, Ord, Enum, Read, Show, Bounded, Ix) -- | The Unicode general category of the character. This relies on the -- 'Enum' instance of 'GeneralCategory', which must remain in the -- same order as the categories are presented in the Unicode -- standard. -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> generalCategory 'a' -- LowercaseLetter -- >>> generalCategory 'A' -- UppercaseLetter -- >>> generalCategory '0' -- DecimalNumber -- >>> generalCategory '%' -- OtherPunctuation -- >>> generalCategory '♥' -- OtherSymbol -- >>> generalCategory '\31' -- Control -- >>> generalCategory ' ' -- Space -- generalCategory :: Char -> GeneralCategory generalCategory c = toEnum $ fromIntegral $ wgencat $ fromIntegral $ ord c -- derived character classifiers -- | Selects alphabetic Unicode characters (lower-case, upper-case and -- title-case letters, plus letters of caseless scripts and -- modifiers letters). This function is equivalent to -- 'Data.Char.isAlpha'. -- -- This function returns 'True' if its argument has one of the -- following 'GeneralCategory's, or 'False' otherwise: -- -- * 'UppercaseLetter' -- * 'LowercaseLetter' -- * 'TitlecaseLetter' -- * 'ModifierLetter' -- * 'OtherLetter' -- -- These classes are defined in the -- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>, -- part of the Unicode standard. The same document defines what is -- and is not a \"Letter\". -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isLetter 'a' -- True -- >>> isLetter 'A' -- True -- >>> isLetter '0' -- False -- >>> isLetter '%' -- False -- >>> isLetter '♥' -- False -- >>> isLetter '\31' -- False -- -- Ensure that 'isLetter' and 'isAlpha' are equivalent. -- -- >>> let chars = [(chr 0)..] -- >>> let letters = map isLetter chars -- >>> let alphas = map isAlpha chars -- >>> letters == alphas -- True -- isLetter :: Char -> Bool isLetter c = case generalCategory c of UppercaseLetter -> True LowercaseLetter -> True TitlecaseLetter -> True ModifierLetter -> True OtherLetter -> True _ -> False -- | Selects Unicode mark characters, for example accents and the -- like, which combine with preceding characters. -- -- This function returns 'True' if its argument has one of the -- following 'GeneralCategory's, or 'False' otherwise: -- -- * 'NonSpacingMark' -- * 'SpacingCombiningMark' -- * 'EnclosingMark' -- -- These classes are defined in the -- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>, -- part of the Unicode standard. The same document defines what is -- and is not a \"Mark\". -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isMark 'a' -- False -- >>> isMark '0' -- False -- -- Combining marks such as accent characters usually need to follow -- another character before they become printable: -- -- >>> map isMark "ò" -- [False,True] -- -- Puns are not necessarily supported: -- -- >>> isMark '✓' -- False -- isMark :: Char -> Bool isMark c = case generalCategory c of NonSpacingMark -> True SpacingCombiningMark -> True EnclosingMark -> True _ -> False -- | Selects Unicode numeric characters, including digits from various -- scripts, Roman numerals, et cetera. -- -- This function returns 'True' if its argument has one of the -- following 'GeneralCategory's, or 'False' otherwise: -- -- * 'DecimalNumber' -- * 'LetterNumber' -- * 'OtherNumber' -- -- These classes are defined in the -- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>, -- part of the Unicode standard. The same document defines what is -- and is not a \"Number\". -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isNumber 'a' -- False -- >>> isNumber '%' -- False -- >>> isNumber '3' -- True -- -- ASCII @\'0\'@ through @\'9\'@ are all numbers: -- -- >>> and $ map isNumber ['0'..'9'] -- True -- -- Unicode Roman numerals are \"numbers\" as well: -- -- >>> isNumber 'Ⅸ' -- True -- isNumber :: Char -> Bool isNumber c = case generalCategory c of DecimalNumber -> True LetterNumber -> True OtherNumber -> True _ -> False -- | Selects Unicode punctuation characters, including various kinds -- of connectors, brackets and quotes. -- -- This function returns 'True' if its argument has one of the -- following 'GeneralCategory's, or 'False' otherwise: -- -- * 'ConnectorPunctuation' -- * 'DashPunctuation' -- * 'OpenPunctuation' -- * 'ClosePunctuation' -- * 'InitialQuote' -- * 'FinalQuote' -- * 'OtherPunctuation' -- -- These classes are defined in the -- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>, -- part of the Unicode standard. The same document defines what is -- and is not a \"Punctuation\". -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isPunctuation 'a' -- False -- >>> isPunctuation '7' -- False -- >>> isPunctuation '♥' -- False -- >>> isPunctuation '"' -- True -- >>> isPunctuation '?' -- True -- >>> isPunctuation '—' -- True -- isPunctuation :: Char -> Bool isPunctuation c = case generalCategory c of ConnectorPunctuation -> True DashPunctuation -> True OpenPunctuation -> True ClosePunctuation -> True InitialQuote -> True FinalQuote -> True OtherPunctuation -> True _ -> False -- | Selects Unicode symbol characters, including mathematical and -- currency symbols. -- -- This function returns 'True' if its argument has one of the -- following 'GeneralCategory's, or 'False' otherwise: -- -- * 'MathSymbol' -- * 'CurrencySymbol' -- * 'ModifierSymbol' -- * 'OtherSymbol' -- -- These classes are defined in the -- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>, -- part of the Unicode standard. The same document defines what is -- and is not a \"Symbol\". -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isSymbol 'a' -- False -- >>> isSymbol '6' -- False -- >>> isSymbol '=' -- True -- -- The definition of \"math symbol\" may be a little -- counter-intuitive depending on one's background: -- -- >>> isSymbol '+' -- True -- >>> isSymbol '-' -- False -- isSymbol :: Char -> Bool isSymbol c = case generalCategory c of MathSymbol -> True CurrencySymbol -> True ModifierSymbol -> True OtherSymbol -> True _ -> False -- | Selects Unicode space and separator characters. -- -- This function returns 'True' if its argument has one of the -- following 'GeneralCategory's, or 'False' otherwise: -- -- * 'Space' -- * 'LineSeparator' -- * 'ParagraphSeparator' -- -- These classes are defined in the -- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>, -- part of the Unicode standard. The same document defines what is -- and is not a \"Separator\". -- -- ==== __Examples__ -- -- Basic usage: -- -- >>> isSeparator 'a' -- False -- >>> isSeparator '6' -- False -- >>> isSeparator ' ' -- True -- -- Warning: newlines and tab characters are not considered -- separators. -- -- >>> isSeparator '\n' -- False -- >>> isSeparator '\t' -- False -- -- But some more exotic characters are (like HTML's @&nbsp;@): -- -- >>> isSeparator '\160' -- True -- isSeparator :: Char -> Bool isSeparator c = case generalCategory c of Space -> True LineSeparator -> True ParagraphSeparator -> True _ -> False
beni55/haste-compiler
libraries/ghc-7.10/base/Data/Char.hs
Haskell
bsd-3-clause
13,652
{-# LANGUAGE TemplateHaskell, GADTs #-} module T4188 where import Language.Haskell.TH import System.IO class C a where {} data T1 a where MkT1 :: a -> b -> T1 a data T2 a where MkT2 :: (C a, C b) => a -> b -> T2 a data T3 x where MkT3 :: (C x, C y) => x -> y -> T3 (x,y) $(do { dec1 <- reify ''T1 ; runIO (putStrLn (pprint dec1)) ; dec2 <- reify ''T2 ; runIO (putStrLn (pprint dec2)) ; dec3 <- reify ''T3 ; runIO (putStrLn (pprint dec3)) ; runIO (hFlush stdout) ; return [] })
oldmanmike/ghc
testsuite/tests/th/T4188.hs
Haskell
bsd-3-clause
525
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module DFS where import Prelude hiding (pred) import Data.List ((\\), sort) import GraphClass class (Node n, Ord n) => DFSNode n instance (Node n, Ord n) => DFSNode n dfs :: (Graph g n, DFSNode n) => (n -> Bool) -> g -> n -> [n] dfs pred graph begin = reverse $ dfs' [begin] [begin] where dfs' (x:xs) visited | pred x = visited | otherwise = case unvisitedNodes x visited of [] -> dfs' xs visited (v:_) -> dfs' (v:x:xs) (v:visited) dfs' [] visited = visited unvisitedNodes x visited = sort (adjacentNodes graph x \\ visited) dfsTraverse :: (Graph g n, DFSNode n) => g -> n -> [n] dfsTraverse graph begin = dfs (const False) graph begin dfsSearch :: (Graph g n, DFSNode n) => g -> n -> n -> [n] dfsSearch graph begin end = dfs (== end) graph begin
shouya/thinking-dumps
graph/DFS.hs
Haskell
mit
929
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module IHaskell.Display.Widgets.Selection.SelectMultiple ( -- * The SelectMultiple Widget SelectMultiple -- * Constructor , mkSelectMultiple ) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (void) import Data.Aeson import Data.IORef (newIORef) import qualified Data.Scientific as Sci import qualified Data.Vector as V import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common import IHaskell.Display.Widgets.Layout.LayoutWidget import IHaskell.Display.Widgets.Style.DescriptionStyle -- | A 'SelectMultiple' represents a SelectMultiple widget from IPython.html.widgets. type SelectMultiple = IPythonWidget 'SelectMultipleType -- | Create a new SelectMultiple widget mkSelectMultiple :: IO SelectMultiple mkSelectMultiple = do -- Default properties, with a random uuid wid <- U.random layout <- mkLayout dstyle <- mkDescriptionStyle let multipleSelectionAttrs = defaultMultipleSelectionWidget "SelectMultipleView" "SelectMultipleModel" layout $ StyleWidget dstyle selectMultipleAttrs = (Rows =:: Just 5) :& RNil widgetState = WidgetState $ multipleSelectionAttrs <+> selectMultipleAttrs stateIO <- newIORef widgetState let widget = IPythonWidget wid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellWidget SelectMultiple where getCommUUID = uuid comm widget val _ = case nestedObjectLookup val ["state", "index"] of Just (Array indices) -> do let indicesList = map (\(Number x) -> Sci.coefficient x) $ V.toList indices void $ setField' widget Indices indicesList triggerSelection widget _ -> pure ()
gibiansky/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Selection/SelectMultiple.hs
Haskell
mit
2,254
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.YarnServerResourceManagerServiceProtos.RefreshUserToGroupsMappingsResponseProto (RefreshUserToGroupsMappingsResponseProto(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data RefreshUserToGroupsMappingsResponseProto = RefreshUserToGroupsMappingsResponseProto{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable RefreshUserToGroupsMappingsResponseProto where mergeAppend RefreshUserToGroupsMappingsResponseProto RefreshUserToGroupsMappingsResponseProto = RefreshUserToGroupsMappingsResponseProto instance P'.Default RefreshUserToGroupsMappingsResponseProto where defaultValue = RefreshUserToGroupsMappingsResponseProto instance P'.Wire RefreshUserToGroupsMappingsResponseProto where wireSize ft' self'@(RefreshUserToGroupsMappingsResponseProto) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(RefreshUserToGroupsMappingsResponseProto) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> RefreshUserToGroupsMappingsResponseProto) RefreshUserToGroupsMappingsResponseProto where getVal m' f' = f' m' instance P'.GPB RefreshUserToGroupsMappingsResponseProto instance P'.ReflectDescriptor RefreshUserToGroupsMappingsResponseProto where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.yarn.RefreshUserToGroupsMappingsResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"YarnServerResourceManagerServiceProtos\"], baseName = MName \"RefreshUserToGroupsMappingsResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"YarnServerResourceManagerServiceProtos\",\"RefreshUserToGroupsMappingsResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType RefreshUserToGroupsMappingsResponseProto where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg RefreshUserToGroupsMappingsResponseProto where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/YarnServerResourceManagerServiceProtos/RefreshUserToGroupsMappingsResponseProto.hs
Haskell
mit
3,338
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.PopStateEvent (js_getState, getState, PopStateEvent, castToPopStateEvent, gTypePopStateEvent) 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 (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) 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.Enums foreign import javascript unsafe "$1[\"state\"]" js_getState :: JSRef PopStateEvent -> IO (JSRef a) -- | <https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent.state Mozilla PopStateEvent.state documentation> getState :: (MonadIO m) => PopStateEvent -> m (JSRef a) getState self = liftIO (js_getState (unPopStateEvent self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/PopStateEvent.hs
Haskell
mit
1,315
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.String.TextArea ( -- * The TextArea Widget TextArea, -- * Constructor mkTextArea) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.IORef (newIORef) import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'TextArea' represents a Textarea widget from IPython.html.widgets. type TextArea = IPythonWidget TextAreaType -- | Create a new TextArea widget mkTextArea :: IO TextArea mkTextArea = do -- Default properties, with a random uuid uuid <- U.random let strAttrs = defaultStringWidget "TextareaView" "TextareaModel" wgtAttrs = (ChangeHandler =:: return ()) :& RNil widgetState = WidgetState $ strAttrs <+> wgtAttrs stateIO <- newIORef widgetState let widget = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellDisplay TextArea where display b = do widgetSendView b return $ Display [] instance IHaskellWidget TextArea where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "sync_data" :: Text key2 = "value" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (String value) = HM.lookup key2 dict2 setField' widget StringValue value triggerChange widget
sumitsahrawat/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/String/TextArea.hs
Haskell
mit
1,883
{-# htermination foldM :: (a -> b -> [] a) -> a -> [b] -> [] a #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_foldM_1.hs
Haskell
mit
81
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} {-# OPTIONS_GHC -Wall #-} -- | Common web page input elements, often with bootstrap scaffolding. module Web.Rep.Html.Input ( Input (..), InputType (..), ) where import Data.Text (split) import Lucid import Lucid.Base import NumHask.Prelude hiding (for_) import Web.Rep.Html -- | something that might exist on a web page and be a front-end input to computations. data Input a = Input { -- | underlying value inputVal :: a, -- | label suggestion inputLabel :: Maybe Text, -- | name//key//id of the Input inputId :: Text, -- | type of html input inputType :: InputType } deriving (Eq, Show, Generic) -- | Various types of web page inputs, encapsulating practical bootstrap class functionality data InputType = Slider [Attribute] | TextBox | TextBox' | TextArea Int | ColorPicker | ChooseFile | Dropdown [Text] | DropdownMultiple [Text] Char | DropdownSum [Text] | Datalist [Text] Text | Checkbox Bool | Toggle Bool (Maybe Text) | Button deriving (Eq, Show, Generic) instance (ToHtml a) => ToHtml (Input a) where toHtml (Input v l i (Slider satts)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ ( [ type_ "range", class__ " form-control-range form-control-sm custom-range jsbClassEventChange", id_ i, value_ (pack $ show $ toHtml v) ] <> satts ) ) toHtml (Input v l i TextBox) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "text", class__ "form-control form-control-sm jsbClassEventInput", id_ i, value_ (pack $ show $ toHtmlRaw v) ] ) toHtml (Input v l i TextBox') = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "text", class__ "form-control form-control-sm jsbClassEventFocusout", id_ i, value_ (pack $ show $ toHtmlRaw v) ] ) toHtml (Input v l i (TextArea rows)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with textarea_ [ rows_ (pack $ show rows), class__ "form-control form-control-sm jsbClassEventInput", id_ i ] (toHtmlRaw v) ) toHtml (Input v l i ColorPicker) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "color", class__ "form-control form-control-sm jsbClassEventInput", id_ i, value_ (pack $ show $ toHtml v) ] ) toHtml (Input _ l i ChooseFile) = with div_ [class__ "form-group-sm"] (maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l) <> input_ [ type_ "file", class__ "form-control-file form-control-sm jsbClassEventChooseFile", id_ i ] toHtml (Input v l i (Dropdown opts)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with select_ [ class__ "form-control form-control-sm jsbClassEventInput", id_ i ] opts' ) where opts' = mconcat $ ( \o -> with option_ ( bool [] [selected_ "selected"] (toText (toHtml o) == toText (toHtml v)) ) (toHtml o) ) <$> opts toHtml (Input vs l i (DropdownMultiple opts sep)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with select_ [ class__ "form-control form-control-sm jsbClassEventChangeMultiple", multiple_ "multiple", id_ i ] opts' ) where opts' = mconcat $ ( \o -> with option_ ( bool [] [selected_ "selected"] (any (\v -> toText (toHtml o) == toText (toHtml v)) (Data.Text.split (== sep) (toText (toHtml vs)))) ) (toHtml o) ) <$> opts toHtml (Input v l i (DropdownSum opts)) = with div_ [class__ "form-group-sm sumtype-group"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with select_ [ class__ "form-control form-control-sm jsbClassEventInput jsbClassEventShowSum", id_ i ] opts' ) where opts' = mconcat $ ( \o -> with option_ (bool [] [selected_ "selected"] (toText (toHtml o) == toText (toHtml v))) (toHtml o) ) <$> opts toHtml (Input v l i (Datalist opts listId)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "text", class__ "form-control form-control-sm jsbClassEventInput", id_ i, list_ listId -- the datalist concept in html assumes initial state is a null -- and doesn't present the list if it has a value alreadyx -- , value_ (show $ toHtml v) ] <> with datalist_ [id_ listId] ( mconcat $ ( \o -> with option_ ( bool [] [selected_ "selected"] (toText (toHtml o) == toText (toHtml v)) ) (toHtml o) ) <$> opts ) ) -- FIXME: How can you refactor to eliminate this polymorphic wart? toHtml (Input _ l i (Checkbox checked)) = with div_ [class__ "form-check form-check-sm"] ( input_ ( [ type_ "checkbox", class__ "form-check-input jsbClassEventCheckbox", id_ i ] <> bool [] [checked_] checked ) <> maybe mempty (with label_ [for_ i, class__ "form-check-label mb-0"] . toHtml) l ) toHtml (Input _ l i (Toggle pushed lab)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ ( [ type_ "button", class__ "btn btn-primary btn-sm jsbClassEventToggle", data_ "toggle" "button", id_ i, makeAttribute "aria-pressed" (bool "false" "true" pushed) ] <> maybe [] (\l' -> [value_ l']) lab <> bool [] [checked_] pushed ) ) toHtml (Input _ l i Button) = with div_ [class__ "form-group-sm"] ( input_ [ type_ "button", id_ i, class__ "btn btn-primary btn-sm jsbClassEventButton", value_ (fromMaybe "button" l) ] ) toHtmlRaw = toHtml
tonyday567/lucid-page
src/Web/Rep/Html/Input.hs
Haskell
mit
7,932
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.DataCue (js_newDataCue, newDataCue, js_newDataCue', newDataCue', js_setData, setData, js_getData, getData, js_setValue, setValue, js_getValue, getValue, js_getType, getType, DataCue, castToDataCue, gTypeDataCue) 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 foreign import javascript unsafe "new window[\"WebKitDataCue\"]()" js_newDataCue :: IO DataCue -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue Mozilla WebKitDataCue documentation> newDataCue :: (MonadIO m) => m DataCue newDataCue = liftIO (js_newDataCue) foreign import javascript unsafe "new window[\"WebKitDataCue\"]($1,\n$2, $3, $4)" js_newDataCue' :: Double -> Double -> JSVal -> JSString -> IO DataCue -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue Mozilla WebKitDataCue documentation> newDataCue' :: (MonadIO m, ToJSString type') => Double -> Double -> JSVal -> type' -> m DataCue newDataCue' startTime endTime value type' = liftIO (js_newDataCue' startTime endTime value (toJSString type')) foreign import javascript unsafe "$1[\"data\"] = $2;" js_setData :: DataCue -> Nullable ArrayBuffer -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.data Mozilla WebKitDataCue.data documentation> setData :: (MonadIO m, IsArrayBuffer val) => DataCue -> Maybe val -> m () setData self val = liftIO (js_setData (self) (maybeToNullable (fmap toArrayBuffer val))) foreign import javascript unsafe "$1[\"data\"]" js_getData :: DataCue -> IO (Nullable ArrayBuffer) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.data Mozilla WebKitDataCue.data documentation> getData :: (MonadIO m) => DataCue -> m (Maybe ArrayBuffer) getData self = liftIO (nullableToMaybe <$> (js_getData (self))) foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue :: DataCue -> JSVal -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.value Mozilla WebKitDataCue.value documentation> setValue :: (MonadIO m) => DataCue -> JSVal -> m () setValue self val = liftIO (js_setValue (self) val) foreign import javascript unsafe "$1[\"value\"]" js_getValue :: DataCue -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.value Mozilla WebKitDataCue.value documentation> getValue :: (MonadIO m) => DataCue -> m JSVal getValue self = liftIO (js_getValue (self)) foreign import javascript unsafe "$1[\"type\"]" js_getType :: DataCue -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.type Mozilla WebKitDataCue.type documentation> getType :: (MonadIO m, FromJSString result) => DataCue -> m result getType self = liftIO (fromJSString <$> (js_getType (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/DataCue.hs
Haskell
mit
3,658
{-# htermination (absRatio :: Ratio MyInt -> Ratio MyInt) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; data Ratio a = CnPc a a; primNegInt :: MyInt -> MyInt; primNegInt (Pos x) = Neg x; primNegInt (Neg x) = Pos x; negateMyInt :: MyInt -> MyInt negateMyInt = primNegInt; absReal0 x MyTrue = negateMyInt x; otherwise :: MyBool; otherwise = MyTrue; absReal1 x MyTrue = x; absReal1 x MyFalse = absReal0 x otherwise; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; compareMyInt :: MyInt -> MyInt -> Ordering compareMyInt = primCmpInt; esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsOrdering :: Ordering -> Ordering -> MyBool fsEsOrdering x y = not (esEsOrdering x y); gtEsMyInt :: MyInt -> MyInt -> MyBool gtEsMyInt x y = fsEsOrdering (compareMyInt x y) LT; absReal2 x = absReal1 x (gtEsMyInt x (fromIntMyInt (Pos Zero))); absReal x = absReal2 x; absMyInt :: MyInt -> MyInt absMyInt = absReal; absRatio :: Ratio MyInt -> Ratio MyInt absRatio (CnPc x y) = CnPc (absMyInt x) y;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/abs_1.hs
Haskell
mit
2,053
{-# LANGUAGE InstanceSigs #-} module RealWorld where import Control.Applicative import Control.Monad import Control.Monad.Reader import Control.Monad.State import Control.Monad.Writer import Data.Functor import Data.Monoid import Data.Maybe import System.Random -- All monads are applicatives, and all applicatives are functors. -- Not all functors are applicatives and not all applicatives are monads. {- The Reader Functor fmap :: (a -> b) -> (r -> a) -> (r -> b) f g instance Functor ((->) r) where fmap f g = f . g or fmap = (.) -} newtype Mystery r a = Mystery { solve :: r -> a } instance Functor (Mystery r) where fmap f m = Mystery $ f . solve m -- or fmap f (Mystery ra) = Mystery $ f . ra -- Note - fmap f x = pure f <*> x instance Applicative (Mystery r) where pure :: a -> Mystery r a pure a = Mystery $ \ r -> a -- or Mystery . const (<*>) :: Mystery r (a -> b) -> Mystery r a -> Mystery r b Mystery rab <*> Mystery ra = Mystery $ \r -> rab r (ra r) -- Note - fmap f xs = xs >>= return . f instance Monad (Mystery r) where return :: a -> Mystery r a return = pure (>>=) :: Mystery r a -> (a -> Mystery r b) -> Mystery r b Mystery ra >>= aRb = Mystery $ \r -> solve (aRb (ra r)) r {- The Reader Monad newtype Reader r a = Reader { runReader :: r -> a } ask :: MonadReader r m => m r -} circA :: Reader Int Int circA = do mpI <- ask return (mpI * 10 * 10) cylA :: Reader Int Int cylA = do mpI <- ask return (mpI * 10 * 10 * 20) addCAndCl :: Reader Int Int addCAndCl = do cA <- circA lA <- cylA return (cA + lA) -------------------- bookWorm :: Reader Int Int bookWorm = do val <- ask return $ (+) 1 val -- bookWorm' :: Reader Int Int bookWorm' = fmap (1 +) ask bookWorm'' :: Reader Int Int bookWorm'' = (1 +) <$> ask -- (10 +) . (runReader ask) $ 10 -- f . g {- Writer Monad data Writer w a = Writer {runWriter :: (a, w)} -} half :: Int -> Writer String Int half x = do tell ("I just halved " ++ show x ++ "! ") return (x `div` 2) ho = runWriter $ half 200 >>= half >>= half fib :: Int -> Int -> Writer String Int fib a b = do tell ( "Adding " ++ show a ++ " to " ++ show b ++ ". ") return (a+ b) main = do let a = runWriter $ fib 10 20 >>= fib 30 >>= fib 40 print (fst a) -- State Monad -- Write as well as read -- s == state , a == result state -> (result, modified state) -- data State s a = State {runState :: s -> (a, s)} -- return a = State $ \s -> (a,s) greeter :: State String String greeter = do name <- get put "Pandey" return ("Hello " ++ name ++ "!") gee = runState greeter "Alok" newtype Distaste s a = Distaste { runDistaste :: s -> (a, s) } -- Functor instance Functor (Distaste s) where fmap :: (a -> b) -> Distaste s a -> Distaste s b fmap f (Distaste g) = Distaste $ \ s -> mapp f (g s) where mapp f (x, y) = (f x, y) -- instance Applicative (Distaste s) where pure a = Distaste (\s -> (a,s)) mf <*> xs = Distaste $ \s0 -> let (f, s1) = runDistaste mf s0 (x, s2) = runDistaste xs s1 in (f x, s2) -- instance Monad (Distaste s) where return a = Distaste (\s -> (a,s)) Distaste mf >>= mg = Distaste (\s -> let (r,s1) = mf s Distaste c2 = mg r in c2 s1) -- State eg fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = "FizzBuzz" | n`mod`5 == 0 = "Fizz" | n`mod`3 == 0 = "Buzz" | otherwise = show n addResult :: Integer -> State [String] () addResult n = do xs <- get let result = fizzBuzz n put (result : xs) fizzbuzzList :: [Integer] -> [String] fizzbuzzList list = execState (mapM_ addResult list) [] train :: IO () train = mapM_ putStrLn $ reverse $ fizzbuzzList [1..10] foo :: Int -> State [String] () foo n = do st <- get let b | n > 5 = "High" | n < 5 = "Low" | otherwise = "Equal" put (b : st) bar :: Int -> State [String] () bar n = do st <- get let b | n > 5 = "High" | n < 5 = "Low" | otherwise = "Equal" put ([b]) -- goo :: String -> State [String] () goo n = do st <- get let b | n == "Max" = "High" | otherwise = "Equal" put (b : st) -- execState (mapM_ breeze [2,7,11,3,5]) [] -- ["Equal","Low","High","High","Low"] -- runState (mapM_ breeze [2,7,11,3,5]) []-- -- evalState :: State s a -> s -> a -- ((),["Equal","Low","High","High","Low"]) -- -- :t sequenceA $ fmap breeze [3,6] (mapM == traverse) -- also -- execState (sequenceA $ concat $ (:) <$> [foo 2] <*> [[foo 8]] ) [] -- as -- instance Traversable [] where -- traverse f = List.foldr cons_f (pure []) -- where cons_f x ys = (:) <$> f x <*> ys -- traverse f = sequenceA . fmap f sequenceAholla us = foldr (\u v -> (:) <$> u <*> v) (pure []) us -- sequenceAholla ([ Just 2, Just 3, Just 4]) --- Just [2,3,4] mytraverse f = foldr cons_f (pure []) where cons_f x ys = (:) <$> f x <*> ys more :: State () [Int] more = traverse pure [1..4] showMore = print (evalState more ()) sure :: State () [String] sure = traverse pure ["al", "kl"] predictor :: Int -> State [String] Int predictor n = do st <- get let b | mod n 2 == 0 = "even" | mod n 2 == 1 = "odd" | otherwise = "Whoa" put (b : st) return (n + 1) -- return (n+1) -- runState (traverse predictor [1..10]) [] ---- ([2,3,4,5,6,7,8,9,10,11],["even","odd","even","odd","even","odd","even","odd","even","odd"]) -- make return n -- runState (predictor 1 >>= predictor >>= predictor) [] ---- (4,["odd","even","odd"]) -- incrementor :: Int -> State [Maybe Int] (Maybe Int) -- incrementor n = do -- st <- get -- put $ Just n : st -- let old = case st of -- [] -> Just (n + 1) -- xs -> case head xs of -- (Just x) -> if x + 1 == n then Nothing else Just (n + 1) -- Nothing -> Nothing -- return old incrementor :: Int -> State [Maybe Int] () incrementor n = do st <- get case st of [] -> put $ Just (n + 1) : st xs -> if summation xs + 1 > n then put $ Nothing : st else put $ Just (n + 1) : st where summation = sum . catMaybes {-- Also using fold incrementor :: [Int] -> Int -> [Int] incrementor st n = if null st || n >= sum st + 1 then n + 1 : st else st res = reverse $ foldl' incrementor mempty [1,2,4,5] --} boo = do let scanMap f = scanr ((:) . f) [] print $ scanMap (\x -> x + 1) [1..5]
alokpndy/haskell-learn
src/monads/monadThree.hs
Haskell
mit
6,949
module Physics.Scenes.FourBoxesTwoStatic where import Linear.Epsilon import Linear.V2 import Physics.Constraint import Physics.Contact import Physics.External import Physics.Geometry import Physics.Object import Physics.World import Physics.Scenes.Scene boxA :: (Fractional a, Eq a) => PhysicalObj a boxA = PhysicalObj { _physObjVel = V2 1 0 , _physObjRotVel = 0 , _physObjPos = V2 (-5) 0 , _physObjRotPos = 0 , _physObjHull = rectangleHull 4 4 , _physObjInvMass = toInvMass2 (2, 1) } boxB :: (Fractional a, Eq a) => PhysicalObj a boxB = PhysicalObj { _physObjVel = V2 (-4) 0 , _physObjRotVel = 0 , _physObjPos = V2 5 2 , _physObjRotPos = 0 , _physObjHull = rectangleHull 2 2 , _physObjInvMass = toInvMass2 (1, 0.5) } boxC :: (Fractional a, Eq a) => PhysicalObj a boxC = PhysicalObj { _physObjVel = V2 0 0 , _physObjRotVel = 0 , _physObjPos = V2 0 (-6) , _physObjRotPos = 0 , _physObjHull = rectangleHull 18 1 , _physObjInvMass = toInvMass2 (0, 0) } boxD :: (Fractional a, Eq a) => PhysicalObj a boxD = PhysicalObj { _physObjVel = V2 0 0 , _physObjRotVel = 0 , _physObjPos = V2 (-5) (-4) , _physObjRotPos = 0 , _physObjHull = rectangleHull 0.4 3 , _physObjInvMass = toInvMass2 (1, 0) } boxA' :: (Fractional a, Eq a) => WorldObj a boxA' = WorldObj boxA 0.2 boxB' :: (Fractional a, Eq a) => WorldObj a boxB' = WorldObj boxB 0.2 boxC' :: (Fractional a, Eq a) => WorldObj a boxC' = WorldObj boxC 0.2 boxD' :: (Fractional a, Eq a) => WorldObj a boxD' = WorldObj boxD 0.2 world :: (Fractional a, Eq a) => World (WorldObj a) world = fromList [boxA', boxB', boxC', boxD'] externals :: (Physical n a, Epsilon n, Floating n, Ord n) => [External n a] externals = [constantAccel (V2 0 (-2))] contactBehavior :: (Floating a) => ContactBehavior a contactBehavior = ContactBehavior 0.01 0.02 scene :: (Physical a p, Epsilon a, Floating a, Ord a, Eq a) => Scene a p scene = Scene world externals contactBehavior
ublubu/shapes-demo
src/Physics/Scenes/FourBoxesTwoStatic.hs
Haskell
mit
2,289
module Spear.Sys.Store.ID ( ID , IDStore , emptyIDStore , newID , freeID ) where import Data.Vector.Unboxed as U import Control.Monad.State -- test import Text.Printf -- test type ID = Int data IDStore = IDStore { assigned :: Vector Bool -- ^ A bit array indicating used IDs. , last :: Int -- ^ The greatest ID assigned so far. } deriving Show -- | Create an empty ID store. emptyIDStore :: IDStore emptyIDStore = IDStore U.empty (-1) -- | Request an ID from the ID store. newID :: IDStore -> (ID, IDStore) newID store@(IDStore assigned last) = if last == U.length assigned - 1 then case findIndex (==False) assigned of Just i -> assign i store Nothing -> newID $ IDStore (assigned U.++ U.replicate (max 1 last + 1) False) last else assign (last+1) store -- Assign the given ID in the ID store. assign :: ID -> IDStore -> (ID, IDStore) assign i (IDStore assigned last) = let assigned' = assigned // [(i,True)] in (i, IDStore assigned' (max last i)) -- | Free the given ID from the ID store. freeID :: ID -> IDStore -> IDStore freeID i (IDStore assigned last) = let assigned' = assigned // [(i,False)] in if i == last then case findLastIndex (==True) assigned' of Just j -> IDStore assigned' j Nothing -> IDStore assigned' 0 else IDStore assigned' last findLastIndex :: Unbox a => (a -> Bool) -> Vector a -> Maybe Int findLastIndex p v = findLastIndex' p v Nothing 0 where findLastIndex' p v current i = if i >= U.length v then current else if p $ v U.! i then let x = Just i in x `seq` findLastIndex' p v x (i+1) else findLastIndex' p v current (i+1) -- test test :: IO () test = evalStateT test' emptyIDStore test' :: StateT IDStore IO () test' = do x <- request y <- request z <- request w <- request free y request free w request a <- request free a request return () request :: StateT IDStore IO ID request = do store <- get let (i, store') = newID store put store' lift $ printf "ID requested, got %d; %s\n" i (show store') return i free :: ID -> StateT IDStore IO () free i = do store <- get let store' = freeID i store put store' lift $ printf "ID %d freed; %s\n" i (show store')
jeannekamikaze/Spear
Spear/Sys/Store/ID.hs
Haskell
mit
2,492
module SuperUserSpark.Check.TestUtils where import TestImport import SuperUserSpark.Bake.Gen () import SuperUserSpark.Bake.Types import SuperUserSpark.Check.Gen () import SuperUserSpark.Check.Internal import SuperUserSpark.Check.Types import SuperUserSpark.CoreTypes import SuperUserSpark.Diagnose.Types -- * Test utils for checkDeployment shouldBeImpossible' :: DiagnosedDeployment -> Expectation shouldBeImpossible' dd = checkDeployment dd `shouldSatisfy` impossibleDeployment shouldBeImpossibleDeployment :: [CheckResult] -> Expectation shouldBeImpossibleDeployment dd = bestResult dd `shouldSatisfy` impossibleDeployment -- * Test utils for checkSingle isDirty :: CheckResult -> Bool isDirty Dirty{} = True isDirty _ = False isReady :: CheckResult -> Bool isReady (Ready _) = True isReady _ = False isDone :: CheckResult -> Bool isDone AlreadyDone = True isDone _ = False isImpossible :: CheckResult -> Bool isImpossible (Impossible _) = True isImpossible _ = False shouldBeDirty :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> CleanupInstruction -> Expectation shouldBeDirty src dst kind eci = case checkSingle src dst kind of Dirty _ ins ci -> do ci `shouldBe` eci let tp = dropTrailingPathSeparator . toFilePath let checkCopyDeployment isrc idst expectation = do tp isrc `shouldBe` toPath (diagnosedFilePath src) tp idst `shouldBe` toPath (diagnosedFilePath dst) expectation `shouldBe` kind case ins of CopyFile isrc idst -> checkCopyDeployment isrc idst CopyDeployment CopyDir isrc idst -> checkCopyDeployment isrc idst CopyDeployment LinkFile isrc idst -> checkCopyDeployment isrc idst LinkDeployment LinkDir isrc idst -> checkCopyDeployment isrc idst LinkDeployment t -> expectationFailure $ unlines [ "checkSingle" , show src , show dst , show kind , "should be dirty but is" , show t ] shouldBeReady :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> Expectation shouldBeReady src dst kind = checkSingle src dst kind `shouldSatisfy` isReady shouldBeDone :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> Expectation shouldBeDone src dst kind = checkSingle src dst kind `shouldSatisfy` isDone shouldBeImpossible :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> Expectation shouldBeImpossible src dst kind = checkSingle src dst kind `shouldSatisfy` isImpossible validWith :: Diagnostics -> Gen DiagnosedFp validWith d = D <$> genValid <*> pure d <*> genValid
NorfairKing/super-user-spark
test/SuperUserSpark/Check/TestUtils.hs
Haskell
mit
2,802
{-# OPTIONS_GHC -fno-warn-orphans #-} module Graphics.Urho3D.Math.Color( Color(..) , rgb , rgba , HasRComp(..) , HasGComp(..) , HasBComp(..) , HasAComp(..) , colorContext ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import Graphics.Urho3D.Creatable import Graphics.Urho3D.Math.Internal.Color import Graphics.Urho3D.Monad import Data.Monoid import Foreign import Text.RawString.QQ import Control.Lens C.context (C.cppCtx <> colorCntx) C.include "<Urho3D/Math/Color.h>" C.using "namespace Urho3D" colorContext :: C.Context colorContext = colorCntx C.verbatim [r| template <class T> class Traits { public: struct AlignmentFinder { char a; T b; }; enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)}; }; |] -- | Helper to use default alpha rgb :: Float -> Float -> Float -> Color rgb rc gc bc = Color rc gc bc 1 -- | Helpwer for Color rgba :: Float -> Float -> Float -> Float -> Color rgba = Color instance Storable Color where sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(Color) } |] alignment _ = fromIntegral $ [C.pure| int { (int)Traits<Color>::AlignmentOf } |] peek ptr = do vr <- realToFrac <$> [C.exp| float { $(Color* ptr)->r_ } |] vg <- realToFrac <$> [C.exp| float { $(Color* ptr)->g_ } |] vb <- realToFrac <$> [C.exp| float { $(Color* ptr)->b_ } |] va <- realToFrac <$> [C.exp| float { $(Color* ptr)->a_ } |] return $ Color vr vg vb va poke ptr (Color vr vg vb va) = [C.block| void { $(Color* ptr)->r_ = $(float vr'); $(Color* ptr)->g_ = $(float vg'); $(Color* ptr)->b_ = $(float vb'); $(Color* ptr)->a_ = $(float va'); } |] where vr' = realToFrac vr vg' = realToFrac vg vb' = realToFrac vb va' = realToFrac va instance Num Color where c1 + c2 = Color (c1^.rComp + c2^.rComp) (c1^.gComp + c2^.gComp) (c1^.bComp + c2^.bComp) (c1^.aComp + c2^.aComp) c1 - c2 = Color (c1^.rComp - c2^.rComp) (c1^.gComp - c2^.gComp) (c1^.bComp - c2^.bComp) (c1^.aComp - c2^.aComp) c1 * c2 = Color (c1^.rComp * c2^.rComp) (c1^.gComp * c2^.gComp) (c1^.bComp * c2^.bComp) (c1^.aComp * c2^.aComp) abs c = Color (abs $ c^.rComp) (abs $ c^.gComp) (abs $ c^.bComp) (abs $ c^.aComp) signum c = Color (signum $ c^.rComp) (signum $ c^.gComp) (signum $ c^.bComp) (signum $ c^.aComp) fromInteger i = Color (fromIntegral i) (fromIntegral i) (fromIntegral i) 1 instance Creatable (Ptr Color) where type CreationOptions (Ptr Color) = Color newObject = liftIO . new deleteObject = liftIO . free
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Math/Color.hs
Haskell
mit
2,586
module Analys where import Tree import Data.List kLimited :: AttainTree -> Chip kLimited (AttainTree (Marking mark) _ subTr) = let curMax = maximum mark subTrMax = case subTr of Tree pairs -> if null pairs then Num 0 else maximum $ map (kLimited . snd) pairs Degenerate -> Num 0 in max curMax subTrMax -- Сеть сохраняема, если количество фишек во всех переходах одинаково isSelfLife :: AttainTree -> Bool isSelfLife tree@(AttainTree (Marking mark) _ _) = let withoutOmega = notElem Omega findCount = sum . map (\(Num i) -> i) isSelfLife' count (AttainTree (Marking m) _ subTr) = withoutOmega m && count == findCount m && case subTr of Degenerate -> True Tree pairs -> all (isSelfLife' count . snd) pairs in withoutOmega mark && isSelfLife' (findCount mark) tree -- Переход потенциально жив, если его можно запустить isTransferPotentiallyAlife :: AttainTree -> TransferNum -> Bool isTransferPotentiallyAlife (AttainTree _ _ (Tree pairs)) t = let (curTranses, subTrees) = unzip pairs in elem t curTranses || any (`isTransferPotentiallyAlife` t) subTrees isTransferPotentiallyAlife (AttainTree _ _ Degenerate) _ = False -- Переход жив, если он разрешен в каждой разрешенной маркировке isTransferAlife :: AttainTree -> TransferNum -> Bool isTransferAlife (AttainTree _ _ Degenerate) _ = True isTransferAlife (AttainTree _ _ (Tree pairs)) t = let (curTranses, subTrees) = unzip pairs in elem t curTranses && all (`isTransferAlife` t) subTrees -- Переход устойчив, если из каждой маркировки, -- В которую мы по нему пришли, -- Его можно снова запустить -- Не будет работать, если маркировка -- помечена как уже существующая, и, при этом, -- достигли мы её не с помощью этого перехода -- (тогда переход может оказаться нестабильным) -- !!!!!!!!!! неправильно isTransferStable :: AttainTree -> TransferNum -> Bool isTransferStable (AttainTree _ _ Degenerate) _ = True isTransferStable (AttainTree _ _ (Tree pairs)) t = let branch = filter ((== t) . fst) pairs --Найдем наш переход is = not $ null branch isExist (AttainTree _ _ (Tree ps)) = elem t $ map fst ps isExist (AttainTree _ _ Degenerate) = True isStillStable (AttainTree _ _ tree) = case tree of Degenerate -> True (Tree ps) -> all (isExist . snd) ps -- all of snd ps has t -- elem t $ map fst ps in all ((`isTransferStable` t) . snd) pairs && (not is || all (isStillStable . snd) branch) analys :: Petri -> AttainTree -> [String] analys petri tree = let kLimit = "\"limited\": " ++ case kLimited tree of Omega -> "false," Num i -> "К = " ++ show i safety = "\"safe\": " ++ case kLimited tree of Num 1 -> "true," _ -> "false," selfLife = "\"save\": " ++ if isSelfLife tree then "true," else "false," transfsNum = [1..length petri] potVitalityTransfers = zip transfsNum (map (isTransferPotentiallyAlife tree) transfsNum) potentVitality = "\"transfers_potential_aliveness\": [" ++ init (concatMap (\(n, is) -> if is then "\"t" ++ show n ++ "\"" ++ "," else show "") potVitalityTransfers) ++ "]," vitalityTransfers = zip transfsNum (map (isTransferAlife tree) transfsNum) vitalityTrans = "\"transfers_aliveness\": [" ++ intercalate ", " (map ((\n -> "\"t" ++ show n) . fst) (filter snd vitalityTransfers)) ++ "]," webVitality = "\"net_aliveness\": " ++ if all snd vitalityTransfers then "true," else "false," transferStability = zip transfsNum (map (isTransferStable tree) transfsNum) pTransStable = "\"transfers_stability\": [" ++ intercalate ", " (map ((\n -> "\"t" ++ show n) . fst) (filter snd transferStability)) ++ "]," pWebStable = "\"net_stability\": " ++ if all snd transferStability then "true" else "false" in [kLimit, safety, selfLife, potentVitality, vitalityTrans, webVitality, pTransStable, pWebStable] growAndGetInfo :: Petri -> [Int] -> String growAndGetInfo transfers mark = let petriMark = Marking [Num i | i <- mark] tree = findTree transfers petriMark settings = analys transfers tree in "{\"tree\": {" ++ show tree ++ "}" ++ ", " ++ concat settings ++ "}"
NickolayStorm/PetriNet
Analys.hs
Haskell
mit
5,468
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TupleSections #-} -- |CSP example for "bring items to the other shore"-type of problems: -- Items i1,...,in are on one side of the shore and there's a boat -- with limited passenger size. The aim is to transport all items -- to the other side without leaving certain conflicting items -- (e.g. a wolf and a sheep) unattended (e.g without a farmer). module Algorithms.SimpleCSP.Examples.Wolf where import Algorithms.SimpleCSP import Prelude.Unicode import Control.Monad import Data.List import Data.List.Unicode -- |Position of a boat. data Boat = West | East deriving (Eq, Show, Read, Enum, Ord) -- |Objects on the shore. data Object = Wolf | Goat | Cabbage | Fire | Stick | Farmer deriving (Eq, Show, Read, Enum, Ord) type Objects = ([Object], [Object]) type GameState = (Objects, Boat) -- |Nondeterminisitically moves between 1 and n items via boat to the other side, -- always, taking the Farmer. nextMove :: GameMove Int GameState nextMove boatSize x = case x of ((w,e),West) → liftM (,East) (transport w e) ((w,e),East) → liftM (\(e',w') → ((w',e'),West)) (transport e w) where transport from to = do passengers ← chooseBetween 1 boatSize from let from' = from \\ (Farmer:passengers) to' = nub $ Farmer:passengers ++ to return (from', to') -- |Returns true iff all items have arrived on the eastern side. goalState :: Int → GameState → Bool goalState _ (([],_),East) = True goalState _ _ = False -- |Solves the simple problem of a 2-passenger boat and -- a farmer, a wolf, a goat, and a cabbage. problem1 :: [Plan GameState] problem1 = doPlan nextMove goalState constraints1 boatSize1 begin1 -- |Solves the more complex version: a 3-passenger boat, -- and a farmer, a wolf, a goat, a cabbage, a fire and a stick. problem2 :: [Plan GameState] problem2 = doPlan nextMove goalState constraints2 boatSize2 begin2 boatSize1 :: Int boatSize1 = 1 boatSize2 :: Int boatSize2 = 2 begin1 :: GameState begin1 = (([Wolf, Goat, Cabbage, Farmer], []), West) begin2 :: GameState begin2 = (([Wolf, Goat, Cabbage, Stick, Fire, Farmer], []), West) wolfGoatNotAlone :: Constraint Int GameState wolfGoatNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Wolf ∈ set ∧ Goat ∈ set ∧ Farmer ∉ set = False | otherwise = True cabbageGoatNotAlone :: Constraint Int GameState cabbageGoatNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Goat ∈ set ∧ Cabbage ∈ set ∧ Farmer ∉ set = False | otherwise = True fireStickNotAlone :: Constraint Int GameState fireStickNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Fire ∈ set ∧ Stick ∈ set ∧ Farmer ∉ set = False | otherwise = True wolfStickNotAlone :: Constraint Int GameState wolfStickNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Wolf ∈ set ∧ Stick ∈ set ∧ Farmer ∉ set = False | otherwise = True farmerWithBoat :: Constraint Int GameState farmerWithBoat _ ((w,_),West) = Farmer ∈ w farmerWithBoat _ ((_,e),East) = Farmer ∈ e constraints1 :: Constraint Int GameState constraints1 = constraints [wolfGoatNotAlone, cabbageGoatNotAlone, farmerWithBoat] constraints2 :: Constraint Int GameState constraints2 = constraints [wolfGoatNotAlone, cabbageGoatNotAlone, fireStickNotAlone, wolfStickNotAlone, farmerWithBoat] -- |Prints a plan to the console. printPlan :: Plan GameState → IO () printPlan p = void $ foldM1 printStep $ reverse p where printStep :: GameState -> GameState -> IO GameState printStep (prev, b1) (cur,b2) = do let dir = case (b1,b2) of (East,West) → putStr " <== " _ → putStr " ==> " w = putStr $ show $ fst prev e = putStr $ show $ snd prev movement = putStr $ show $ fst prev ∆ fst cur sequence_ [w,dir,movement,dir,e, putStrLn ""] return (cur,b2)
ombocomp/CSP
Algorithms/SimpleCSP/Examples/Wolf.hs
Haskell
mit
4,449
{-# LANGUAGE TemplateHaskell , LambdaCase , RankNTypes #-} module AppDefs where import Control.Lens import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.Either import Control.Concurrent.STM.TQueue import qualified Graphics.UI.GLFW as GLFW import qualified Graphics.Rendering.OpenGL as GL import GLFWHelpers import FrameBuffer import QuadRendering import qualified BoundedSequence as BS import Experiment -- Some definitions and utilities split out from the App module data AppState = AppState { _asCurTick :: !Double , _asLastEscPress :: !Double , _asFrameTimes :: !(BS.BoundedSequence Double) , _asFrameIdx :: !Int , _asVSync :: !Bool , _asExperiment :: !AnyExperiment , _asExperimentDesc :: !String } data AppEnv = AppEnv { _aeWindow :: !GLFW.Window , _aeGLFWEventsQueue :: !(TQueue GLFWEvent) , _aeFontTexture :: !GL.TextureObject , _aeFB :: !FrameBuffer , _aeQR :: !QuadRenderer , _aeExperiments :: ![AnyWithExperiment] } makeLenses ''AppState makeLenses ''AppEnv -- Our application runs in a reader / state / either / IO transformer stack data ExpResult = ExpNext | ExpPrev | ExpExit deriving (Show, Eq, Enum) type AppT m = EitherT ExpResult (StateT AppState (ReaderT AppEnv m)) type AppIO = AppT IO -- Run a computation in the State monad with the current experiment as its state. Store the -- final state back into ours. Note that we can't write this with the 'zoom' combinator -- from lens as we can't define a lens for an existential type runExperimentState :: (forall e m. (Experiment e, MonadIO m, MonadState e m) => m a) -> AppIO a runExperimentState f = use asExperiment >>= \case (AnyExperiment e) -> do (r, e') <- liftIO . flip runStateT e $ f asExperiment .= AnyExperiment e' return r
blitzcode/rust-exp
hs-src/AppDefs.hs
Haskell
mit
2,210
-- import Control.Monad import Control.Exception import System.Directory (doesFileExist) import System.Environment import System.Exit import qualified Data.Text as T import qualified Data.List as List -- iff :: Bool -> a -> a -> a iff True x _ = x iff False _ y = y -- strings_join :: String -> [String] -> String strings_join delim [] = "" strings_join delim (x:[]) = x strings_join delim (x:xs) = x ++ delim ++ (strings_join delim xs) -- texts_uniq :: [T.Text] -> [T.Text] texts_uniq [] = [] texts_uniq (x:xs) = let xs_uniq = (texts_uniq xs) in iff (x `elem` xs_uniq) (xs_uniq) ([x] ++ xs_uniq) -- getEnvOrEmpty :: String -> IO String getEnvOrEmpty name = getEnv name `catch` -- "(e :: IOException)" is for hinting exception type (\e -> let _ = (e :: IOException) in return "") -- find_exe_paths :: String -> IO [String] find_exe_paths prog = do -- 8f1kRCu env_pathext <- getEnvOrEmpty "PATHEXT" -- 4fpQ2RB iff (env_pathext == "") -- then -- 9dqlPRg (return []) -- else (do -- 6qhHTHF -- Split into a list of extensions let ext_s = T.splitOn (T.pack ";") (T.pack env_pathext) -- 2pGJrMW -- Strip let ext_s_2 = map T.strip ext_s -- 2gqeHHl -- Remove empty let ext_s_3 = filter (\x -> x /= (T.pack "")) ext_s_2 -- 2zdGM8W -- Convert to lowercase let ext_s_4 = map T.toLower ext_s_3 -- 2fT8aRB -- Uniquify let ext_s_5 = texts_uniq ext_s_4 -- 4ysaQVN env_path <- getEnvOrEmpty "PATH" -- 5gGwKZL let dir_path_s = iff (env_path == "") -- then -- 7bVmOKe -- Go ahead with "dir_path_s" being empty [] -- else -- 6mPI0lg -- Split into a list of paths (T.splitOn (T.pack ";") (T.pack env_path)) -- 5rT49zI -- Insert empty dir path to the beginning. -- -- Empty dir handles the case that "prog" is a path, either -- relative or absolute. See code 7rO7NIN. let dir_path_s2 = [T.pack ""] ++ dir_path_s -- 2klTv20 -- Uniquify let dir_path_s3 = texts_uniq dir_path_s2 -- 9gTU1rI -- Check if "prog" ends with one of the file extension in -- "ext_s_5". -- -- "ext_s_5" are all in lowercase, ensured at 2zdGM8W. let prog_lc = T.toLower (T.pack prog) let prog_has_ext = any (`T.isSuffixOf` prog_lc) ext_s_5 -- 6bFwhbv exe_path_s <- liftM List.concat ( (`mapM` dir_path_s3) (\dir_path -> do -- 7rO7NIN -- Synthesize a path let path = iff (dir_path == T.pack "") (T.pack prog) (T.concat [ dir_path ,(T.pack "\\") ,(T.pack prog) ]) -- "exe_path" is used at 4bm0d25. -- Its value being empty string means file not exist. exe_path <- -- 6kZa5cq -- If "prog" ends with executable file extension iff prog_has_ext -- then (do file_exists <- (doesFileExist (T.unpack path)) -- 3whKebE iff file_exists -- then -- 2ffmxRF (return path) -- else (return (T.pack "")) ) -- else (return (T.pack "")) -- 2sJhhEV -- Assume user has omitted the file extension exe_path_s <- liftM List.concat ( (`mapM` ext_s_5) (\ext -> do -- 6k9X6GP -- Synthesize a path with one of the file -- extensions in PATHEXT let path_2 = (T.concat [path, ext]) file_exists_2 <- (doesFileExist (T.unpack path_2)) -- 6kabzQg iff file_exists_2 -- then -- 7dui4cD (return [path_2]) -- else (return []) ) ) -- 4bm0d25 iff (exe_path == (T.pack "")) -- then (return exe_path_s) -- then (return ([exe_path] ++ exe_path_s)) -- ) ) -- 8swW6Av -- Uniquify let exe_path_s2 = texts_uniq exe_path_s -- Convert from Text to String let exe_path_s3 = map T.unpack exe_path_s2 -- 7y3JlnS return exe_path_s3 ) -- 4zKrqsC -- Program entry main = do -- arg_s <- getArgs -- let arg_cnt = length arg_s -- 9mlJlKg -- If not exactly one command argument is given iff (arg_cnt /= 1) -- then (do -- 7rOUXFo -- Print program usage let usage = strings_join "\n" [ "Usage: aoikwinwhich PROG", "", "#/ PROG can be either name or path", "aoikwinwhich notepad.exe", "aoikwinwhich C:\\Windows\\notepad.exe", "", "#/ PROG can be either absolute or relative", "aoikwinwhich C:\\Windows\\notepad.exe", "aoikwinwhich Windows\\notepad.exe", "", "#/ PROG can be either with or without extension", "aoikwinwhich notepad.exe", "aoikwinwhich notepad", "aoikwinwhich C:\\Windows\\notepad.exe", "aoikwinwhich C:\\Windows\\notepad\n" ] putStr usage -- 3nqHnP7 exitWith (ExitFailure 1) ) -- else (do -- 9m5B08H -- Get executable name or path let prog = head arg_s -- 8ulvPXM -- Find executable paths exe_path_s <- find_exe_paths prog -- 5fWrcaF -- If has found none iff (length exe_path_s == 0) -- then (do -- 3uswpx0 exitWith (ExitFailure 2) ) -- else -- If has found some (do -- 9xPCWuS -- Print to stdout putStrLn (strings_join "\n" exe_path_s) -- 4s1yY1b exitWith (ExitSuccess) ) )
AoiKuiyuyou/AoikWinWhich-Haskell
src/aoikwinwhich/aoikwinwhich.hs
Haskell
mit
8,400
addStuff :: Int -> Int addStuff = do a <- (*2) b <- (+10) return (a+b) addStuff1 = (*2) >>= \a -> (+10) >>= \b -> return (a+b) {- (*2) >>= \a -> (+10) >>= \b -> return (a+b) == \w -> (\a -> (+10) >>= \b -> return (a+b)) (w*2) w == \w -> ((+10) >>= \b -> return (w*2+b)) w == \w -> (\w' -> (\b->return (w*2+b)) (w'+10) w') w == \w -> (\w' -> (return (w*2 +(w'+10))) w') w == \w -> (\w' -> (\_ -> (w*2+(w'+10))) w') w == \w -> (\w' -> (w*2+ (w'+10)) ) w == \w -> (w*2 + (w+10)) -} {- a <- (*2) return (1+a) (*2) >>= \a -> return (1+a) == (*2) >>= \a -> (\_ -> (1+a)) == \w -> (\a -> (\_ -> (1+a))) (w*2) w == \w -> (\_ -> (1+w*2)) w == \w -> 1 + 2*w -} -- > addStuff 3 -- 19 -- > addStuff1 3 -- 19 {- h >>= f = \w -> f (h w) w f = (\a -> (+10) >>= \b -> return (a+b)) f (h w) = (+10) >>= \b -> return ((h w) +b) (\w' -> (\b->return ((h w) + b)) (h' w') ) w (\w' -> return ((h w) + (h' w')) w' ) w return ((h w) + (h' w)) w = (h w) + (h' w) -}
egaburov/funstuff
Haskell/monads/monad1.hs
Haskell
apache-2.0
1,029
data List a = Nil | Cons a (List a) len xs = len' 0 xs len' acc xs = case xs of Nil -> acc Cons _ t -> len' (acc+1) t safe queen diag xs = case xs of Nil -> True Cons q t -> queen /= q && queen /= q + diag && queen /= q - diag && safe queen (diag + 1) t appendSafe k soln solns = if (k <= 0) then solns else if safe k 1 soln then appendSafe (k-1) soln (Cons (Cons k soln) solns) else appendSafe (k-1) soln solns extend n acc solns = case solns of Nil -> acc Cons soln rest -> extend n (appendSafe n soln acc) rest find_solutions n k = if k == 0 then Cons Nil Nil else extend n Nil (find_solutions n (k-1)) -- fst_solution n = head (find_solutions n n) queens n = len (find_solutions n n) main = print (queens 13)
lpeterse/koka
test/medium/nqueens.hs
Haskell
apache-2.0
874
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE BangPatterns #-} module Haskell.Decode.Operations where import Data.Int (Int32,Int16) import qualified Prelude as P import Prelude hiding (Num(..),Ord(..)) import Data.Monoid (Monoid(..),(<>)) type family Signum d :: * class (Eq d,Monoid (Signum d)) => Operations d where signum :: d -> Signum d abs :: d -> d negate :: d -> d zero :: d (<) :: d -> d -> Bool threeFourths :: d -> d (+) :: d -> d -> d (-) :: d -> d -> d (*) :: Signum d -> d -> d min a b = if a < b then a else b type instance Signum Double = SignumDouble newtype SignumDouble = SignumDouble Double instance Monoid SignumDouble where mempty = SignumDouble 1 mappend (SignumDouble x) (SignumDouble y) = SignumDouble (x P.* y) instance Operations Double where signum d = SignumDouble (P.signum d) abs = P.abs negate = P.negate zero = 0 (<) = (P.<) threeFourths = ((3 / 4) P.*) (+) = (P.+) (-) = (P.-) SignumDouble s * d = s P.* d type instance Signum Int = SignumInt newtype SignumInt = SignumInt Int instance Monoid SignumInt where mempty = SignumInt 1 mappend (SignumInt x) (SignumInt y) = SignumInt (x P.* y) instance Operations Int where signum i = SignumInt (P.signum i) -- surprisingly: P.abs minBound == minBound !! abs i = if i == minBound then maxBound else P.abs i -- surprisingly: P.negate minBound == minBound !! negate i = if i == minBound then maxBound else P.negate i zero = 0 (<) = (P.<) threeFourths i = let !half = i `div` 2 in half P.+ (half `div` 2) -- avoids overflows x + y = if x P.> 0 && y P.> 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.< 0 && z P.>= 0 then minBound else z where z = x P.+ y -- avoids overflows x - y = if x P.> 0 && y P.< 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.> 0 && z P.>= 0 then minBound else z where z = x P.- y SignumInt s * d = s P.* d type instance Signum Int32 = SignumInt32 newtype SignumInt32 = SignumInt32 Int32 instance Monoid SignumInt32 where mempty = SignumInt32 1 mappend (SignumInt32 x) (SignumInt32 y) = SignumInt32 (x P.* y) instance Operations Int32 where signum i = SignumInt32 (P.signum i) -- surprisingly: P.abs minBound == minBound !! abs i = if i == minBound then maxBound else P.abs i -- surprisingly: P.negate minBound == minBound !! negate i = if i == minBound then maxBound else P.negate i zero = 0 (<) = (P.<) threeFourths i = let !half = i `div` 2 in half P.+ (half `div` 2) -- avoids overflows x + y = if x P.> 0 && y P.> 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.< 0 && z P.>= 0 then minBound else z where z = x P.+ y -- avoids overflows x - y = if x P.> 0 && y P.< 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.> 0 && z P.>= 0 then minBound else z where z = x P.- y SignumInt32 s * d = s P.* d type instance Signum Int16 = SignumInt16 newtype SignumInt16 = SignumInt16 Int16 instance Monoid SignumInt16 where mempty = SignumInt16 1 mappend (SignumInt16 x) (SignumInt16 y) = SignumInt16 (x P.* y) instance Operations Int16 where signum i = SignumInt16 (P.signum i) -- surprisingly: P.abs minBound == minBound !! abs i = if i == minBound then maxBound else P.abs i -- surprisingly: P.negate minBound == minBound !! negate i = if i == minBound then maxBound else P.negate i zero = 0 (<) = (P.<) threeFourths i = let !half = i `div` 2 in half P.+ (half `div` 2) -- avoids overflows x + y = if x P.> 0 && y P.> 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.< 0 && z P.>= 0 then minBound else z where z = x P.+ y -- avoids overflows x - y = if x P.> 0 && y P.< 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.> 0 && z P.>= 0 then minBound else z where z = x P.- y SignumInt16 s * d = s P.* d {-# INLINE min_dagger #-} min_dagger :: Operations d => d -> d -> d min_dagger x y = (signum x <> signum y) * min (abs x) (abs y) -- INVARIANT all values in this data-structure are non-negative data MD a = ZeroMD | OneMD a | TwoMD a a -- INVARIANT all arguments non-negative minMD ZeroMD x = OneMD x minMD (OneMD a) x | x < a = TwoMD x a | otherwise = TwoMD a x minMD (TwoMD a b) x | x < a = TwoMD x a | x < b = TwoMD a x | otherwise = TwoMD a b {-# INLINE minMD #-}
ku-fpg/ldpc
src/LDPC/Decode/Operations.hs
Haskell
bsd-2-clause
4,590
module CLasH.Utils.Pretty (prettyShow, pprString, pprStringDebug, zEncodeString) where -- Standard imports import qualified Data.Map as Map import Text.PrettyPrint.HughesPJClass import Data.Char import Numeric -- GHC API import qualified CoreSyn import Outputable ( showSDoc, showSDocDebug, ppr, Outputable, OutputableBndr) -- VHDL Imports import qualified Language.VHDL.Ppr as Ppr import qualified Language.VHDL.AST as AST import qualified Language.VHDL.AST.Ppr -- Local imports import CLasH.VHDL.VHDLTypes import CLasH.Utils.Core.CoreShow -- | A version of the default pPrintList method, which uses a custom function -- f instead of pPrint to print elements. printList :: (a -> Doc) -> [a] -> Doc printList f = brackets . fsep . punctuate comma . map f {- instance Pretty FuncData where pPrint (FuncData flatfunc entity arch) = text "Flattened: " $$ nest 15 (ppffunc flatfunc) $+$ text "Entity" $$ nest 15 (ppent entity) $+$ pparch arch where ppffunc (Just f) = pPrint f ppffunc Nothing = text "Nothing" ppent (Just e) = pPrint e ppent Nothing = text "Nothing" pparch Nothing = text "VHDL architecture not present" pparch (Just _) = text "VHDL architecture present" -} instance Pretty Entity where pPrint (Entity id args res decl) = text "Entity: " $$ nest 10 (pPrint id) $+$ text "Args: " $$ nest 10 (pPrint args) $+$ text "Result: " $$ nest 10 (pPrint res) $+$ text "Declaration not shown" instance (OutputableBndr b, Show b) => Pretty (CoreSyn.Bind b) where pPrint (CoreSyn.NonRec b expr) = text "NonRec: " $$ nest 10 (prettyBind (b, expr)) pPrint (CoreSyn.Rec binds) = text "Rec: " $$ nest 10 (vcat $ map (prettyBind) binds) instance (OutputableBndr b, Show b) => Pretty (CoreSyn.Expr b) where pPrint = text . show instance Pretty AST.VHDLId where pPrint id = Ppr.ppr id instance Pretty AST.VHDLName where pPrint name = Ppr.ppr name prettyBind :: (Show b, Show e) => (b, e) -> Doc prettyBind (b, expr) = text b' <> text " = " <> text expr' where b' = show b expr' = show expr instance (Pretty k, Pretty v) => Pretty (Map.Map k v) where pPrint = vcat . map ppentry . Map.toList where ppentry (k, v) = pPrint k <> text " : " $$ nest 15 (pPrint v) -- Convenience method for turning an Outputable into a string pprString :: (Outputable x) => x -> String pprString = showSDoc . ppr pprStringDebug :: (Outputable x) => x -> String pprStringDebug = showSDocDebug . ppr type UserString = String -- As the user typed it type EncodedString = String -- Encoded form zEncodeString :: UserString -> EncodedString zEncodeString cs = case maybe_tuple cs of Just n -> n ++ (go cs) -- Tuples go to Z2T etc Nothing -> go cs where go [] = [] go (c:cs) = encode_digit_ch c ++ go' cs go' [] = [] go' (c:cs) = encode_ch c ++ go' cs maybe_tuple :: UserString -> Maybe EncodedString maybe_tuple "(# #)" = Just("Z1H") maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H") _ -> Nothing maybe_tuple "()" = Just("Z0T") maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of (n, ')' : _) -> Just ('Z' : shows (n+1) "T") _ -> Nothing maybe_tuple _ = Nothing count_commas :: Int -> String -> (Int, String) count_commas n (',' : cs) = count_commas (n+1) cs count_commas n cs = (n,cs) encode_digit_ch :: Char -> EncodedString encode_digit_ch c | c >= '0' && c <= '9' = encode_as_unicode_char c encode_digit_ch c | otherwise = encode_ch c encode_ch :: Char -> EncodedString encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" -- Variables encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '%' = "zv" encode_ch c = encode_as_unicode_char c encode_as_unicode_char :: Char -> EncodedString encode_as_unicode_char c = 'z' : if isDigit (head hex_str) then hex_str else '0':hex_str where hex_str = showHex (ord c) "U" unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar c = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
christiaanb/clash
clash/CLasH/Utils/Pretty.hs
Haskell
bsd-3-clause
5,175
{-# LANGUAGE RankNTypes, ScopedTypeVariables, GADTs, EmptyDataDecls, PatternGuards, TypeFamilies, MultiParamTypeClasses #-} module Compiler.Hoopl.Dataflow ( DataflowLattice(..), JoinFun, OldFact(..), NewFact(..), Fact, mkFactBase , ChangeFlag(..), changeIf , FwdPass(..), FwdTransfer, mkFTransfer, mkFTransfer3, getFTransfer3 -- * Respecting Fuel -- $fuel , FwdRewrite, mkFRewrite, mkFRewrite3, getFRewrite3, noFwdRewrite , wrapFR, wrapFR2 , BwdPass(..), BwdTransfer, mkBTransfer, mkBTransfer3, getBTransfer3 , wrapBR, wrapBR2 , BwdRewrite, mkBRewrite, mkBRewrite3, getBRewrite3, noBwdRewrite , analyzeAndRewriteFwd, analyzeAndRewriteBwd ) where import Control.Monad import Data.Maybe import Compiler.Hoopl.Checkpoint import Compiler.Hoopl.Collections import Compiler.Hoopl.Fuel import Compiler.Hoopl.Graph hiding (Graph) -- hiding so we can redefine -- and include definition in paper import qualified Compiler.Hoopl.GraphUtil as U import Compiler.Hoopl.Label import Compiler.Hoopl.Util ----------------------------------------------------------------------------- -- DataflowLattice ----------------------------------------------------------------------------- data DataflowLattice a = DataflowLattice { fact_name :: String -- Documentation , fact_bot :: a -- Lattice bottom element , fact_join :: JoinFun a -- Lattice join plus change flag -- (changes iff result > old fact) } -- ^ A transfer function might want to use the logging flag -- to control debugging, as in for example, it updates just one element -- in a big finite map. We don't want Hoopl to show the whole fact, -- and only the transfer function knows exactly what changed. type JoinFun a = Label -> OldFact a -> NewFact a -> (ChangeFlag, a) -- the label argument is for debugging purposes only newtype OldFact a = OldFact a newtype NewFact a = NewFact a data ChangeFlag = NoChange | SomeChange deriving (Eq, Ord) changeIf :: Bool -> ChangeFlag changeIf changed = if changed then SomeChange else NoChange -- | 'mkFactBase' creates a 'FactBase' from a list of ('Label', fact) -- pairs. If the same label appears more than once, the relevant facts -- are joined. mkFactBase :: forall f. DataflowLattice f -> [(Label, f)] -> FactBase f mkFactBase lattice = foldl add mapEmpty where add :: FactBase f -> (Label, f) -> FactBase f add map (lbl, f) = mapInsert lbl newFact map where newFact = case mapLookup lbl map of Nothing -> f Just f' -> snd $ join lbl (OldFact f') (NewFact f) join = fact_join lattice ----------------------------------------------------------------------------- -- Analyze and rewrite forward: the interface ----------------------------------------------------------------------------- data FwdPass m n f = FwdPass { fp_lattice :: DataflowLattice f , fp_transfer :: FwdTransfer n f , fp_rewrite :: FwdRewrite m n f } newtype FwdTransfer n f = FwdTransfer3 { getFTransfer3 :: ( n C O -> f -> f , n O O -> f -> f , n O C -> f -> FactBase f ) } newtype FwdRewrite m n f -- see Note [Respects Fuel] = FwdRewrite3 { getFRewrite3 :: ( n C O -> f -> m (Maybe (Graph n C O, FwdRewrite m n f)) , n O O -> f -> m (Maybe (Graph n O O, FwdRewrite m n f)) , n O C -> f -> m (Maybe (Graph n O C, FwdRewrite m n f)) ) } wrapFR :: (forall e x. (n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f ))) -> (n' e x -> f' -> m' (Maybe (Graph n' e x, FwdRewrite m' n' f'))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> FwdRewrite m n f -> FwdRewrite m' n' f' -- see Note [Respects Fuel] wrapFR wrap (FwdRewrite3 (f, m, l)) = FwdRewrite3 (wrap f, wrap m, wrap l) wrapFR2 :: (forall e x . (n1 e x -> f1 -> m1 (Maybe (Graph n1 e x, FwdRewrite m1 n1 f1))) -> (n2 e x -> f2 -> m2 (Maybe (Graph n2 e x, FwdRewrite m2 n2 f2))) -> (n3 e x -> f3 -> m3 (Maybe (Graph n3 e x, FwdRewrite m3 n3 f3))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> FwdRewrite m1 n1 f1 -> FwdRewrite m2 n2 f2 -> FwdRewrite m3 n3 f3 -- see Note [Respects Fuel] wrapFR2 wrap2 (FwdRewrite3 (f1, m1, l1)) (FwdRewrite3 (f2, m2, l2)) = FwdRewrite3 (wrap2 f1 f2, wrap2 m1 m2, wrap2 l1 l2) mkFTransfer3 :: (n C O -> f -> f) -> (n O O -> f -> f) -> (n O C -> f -> FactBase f) -> FwdTransfer n f mkFTransfer3 f m l = FwdTransfer3 (f, m, l) mkFTransfer :: (forall e x . n e x -> f -> Fact x f) -> FwdTransfer n f mkFTransfer f = FwdTransfer3 (f, f, f) -- | Functions passed to 'mkFRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite3' respects fuel. mkFRewrite3 :: forall m n f. FuelMonad m => (n C O -> f -> m (Maybe (Graph n C O))) -> (n O O -> f -> m (Maybe (Graph n O O))) -> (n O C -> f -> m (Maybe (Graph n O C))) -> FwdRewrite m n f mkFRewrite3 f m l = FwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> m (Maybe a)) -> t -> t1 -> m (Maybe (a, FwdRewrite m n f)) lift rw node fact = liftM (liftM asRew) (withFuel =<< rw node fact) asRew :: forall t. t -> (t, FwdRewrite m n f) asRew g = (g, noFwdRewrite) noFwdRewrite :: Monad m => FwdRewrite m n f noFwdRewrite = FwdRewrite3 (noRewrite, noRewrite, noRewrite) noRewrite :: Monad m => a -> b -> m (Maybe c) noRewrite _ _ = return Nothing -- | Functions passed to 'mkFRewrite' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite' respects fuel. mkFRewrite :: FuelMonad m => (forall e x . n e x -> f -> m (Maybe (Graph n e x))) -> FwdRewrite m n f mkFRewrite f = mkFRewrite3 f f f type family Fact x f :: * type instance Fact C f = FactBase f type instance Fact O f = f -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeAndRewriteFwd :: forall m n f e x entries. (CheckpointMonad m, NonLocal n, LabelsPtr entries) => FwdPass m n f -> MaybeC e entries -> Graph n e x -> Fact e f -> m (Graph n e x, FactBase f, MaybeO x f) analyzeAndRewriteFwd pass entries g f = do (rg, fout) <- arfGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedExitFact g' fout) distinguishedExitFact :: forall n e x f . Graph n e x -> Fact x f -> MaybeO x f distinguishedExitFact g f = maybe g where maybe :: Graph n e x -> MaybeO x f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany _ _ x) = case x of NothingO -> NothingO JustO _ -> JustO f ---------------------------------------------------------------- -- Forward Implementation ---------------------------------------------------------------- type Entries e = MaybeC e [Label] arfGraph :: forall m n f e x . (NonLocal n, CheckpointMonad m) => FwdPass m n f -> Entries e -> Graph n e x -> Fact e f -> m (DG f n e x, Fact x f) arfGraph pass entries = graph where {- nested type synonyms would be so lovely here type ARF thing = forall e x . thing e x -> f -> m (DG f n e x, Fact x f) type ARFX thing = forall e x . thing e x -> Fact e f -> m (DG f n e x, Fact x f) -} graph :: Graph n e x -> Fact e f -> m (DG f n e x, Fact x f) -- @ start block.tex -2 block :: forall e x . Block n e x -> f -> m (DG f n e x, Fact x f) -- @ end block.tex -- @ start node.tex -4 node :: forall e x . (ShapeLifter e x) => n e x -> f -> m (DG f n e x, Fact x f) -- @ end node.tex -- @ start bodyfun.tex body :: [Label] -> LabelMap (Block n C C) -> Fact C f -> m (DG f n C C, Fact C f) -- @ end bodyfun.tex -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' -- @ start cat.tex -2 cat :: forall e a x f1 f2 f3. (f1 -> m (DG f n e a, f2)) -> (f2 -> m (DG f n a x, f3)) -> (f1 -> m (DG f n e x, f3)) -- @ end cat.tex graph GNil = \f -> return (dgnil, f) graph (GUnit blk) = block blk graph (GMany e bdy x) = (e `ebcat` bdy) `cat` exit x where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact e f -> m (DG f n e C, Fact C f) exit :: MaybeO x (Block n C O) -> Fact C f -> m (DG f n C x, Fact x f) exit (JustO blk) = arfx block blk exit NothingO = \fb -> return (dgnilC, fb) ebcat entry bdy = c entries entry where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact e f -> m (DG f n e C, Fact C f) c NothingC (JustO entry) = block entry `cat` body (successors entry) bdy c (JustC entries) NothingO = body entries bdy c _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks -- @ start block.tex -2 block (BFirst n) = node n block (BMiddle n) = node n block (BLast n) = node n block (BCat b1 b2) = block b1 `cat` block b2 -- @ end block.tex block (BHead h n) = block h `cat` node n block (BTail n t) = node n `cat` block t block (BClosed h t)= block h `cat` block t -- @ start node.tex -4 node n f = do { grw <- frewrite pass n f ; case grw of Nothing -> return ( singletonDG f n , ftransfer pass n f ) Just (g, rw) -> let pass' = pass { fp_rewrite = rw } f' = fwdEntryFact n f in arfGraph pass' (fwdEntryLabel n) g f' } -- @ end node.tex -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} -- @ start cat.tex -2 cat ft1 ft2 f = do { (g1,f1) <- ft1 f ; (g2,f2) <- ft2 f1 ; return (g1 `dgSplice` g2, f2) } -- @ end cat.tex arfx :: forall thing x . NonLocal thing => (thing C x -> f -> m (DG f n C x, Fact x f)) -> (thing C x -> Fact C f -> m (DG f n C x, Fact x f)) arfx arf thing fb = arf thing $ fromJust $ lookupFact (entryLabel thing) $ joinInFacts lattice fb where lattice = fp_lattice pass -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' -- @ start bodyfun.tex body entries blockmap init_fbase = fixpoint Fwd lattice do_block blocks init_fbase where blocks = forwardBlockList entries blockmap lattice = fp_lattice pass do_block :: forall x. Block n C x -> FactBase f -> m (DG f n C x, Fact x f) do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- @ end bodyfun.tex -- Join all the incoming facts with bottom. -- We know the results _shouldn't change_, but the transfer -- functions might, for example, generate some debugging traces. joinInFacts :: DataflowLattice f -> FactBase f -> FactBase f joinInFacts (lattice @ DataflowLattice {fact_bot = bot, fact_join = fj}) fb = mkFactBase lattice $ map botJoin $ mapToList fb where botJoin (l, f) = (l, snd $ fj l (OldFact bot) (NewFact f)) forwardBlockList :: (NonLocal n, LabelsPtr entry) => entry -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for forward analysis, -- along with the list of Labels it may depend on for facts. forwardBlockList entries blks = postorder_dfs_from blks entries ----------------------------------------------------------------------------- -- Backward analysis and rewriting: the interface ----------------------------------------------------------------------------- data BwdPass m n f = BwdPass { bp_lattice :: DataflowLattice f , bp_transfer :: BwdTransfer n f , bp_rewrite :: BwdRewrite m n f } newtype BwdTransfer n f = BwdTransfer3 { getBTransfer3 :: ( n C O -> f -> f , n O O -> f -> f , n O C -> FactBase f -> f ) } newtype BwdRewrite m n f = BwdRewrite3 { getBRewrite3 :: ( n C O -> f -> m (Maybe (Graph n C O, BwdRewrite m n f)) , n O O -> f -> m (Maybe (Graph n O O, BwdRewrite m n f)) , n O C -> FactBase f -> m (Maybe (Graph n O C, BwdRewrite m n f)) ) } wrapBR :: (forall e x . Shape x -> (n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f ))) -> (n' e x -> Fact x f' -> m' (Maybe (Graph n' e x, BwdRewrite m' n' f'))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> BwdRewrite m n f -> BwdRewrite m' n' f' -- see Note [Respects Fuel] wrapBR wrap (BwdRewrite3 (f, m, l)) = BwdRewrite3 (wrap Open f, wrap Open m, wrap Closed l) wrapBR2 :: (forall e x . Shape x -> (n1 e x -> Fact x f1 -> m1 (Maybe (Graph n1 e x, BwdRewrite m1 n1 f1))) -> (n2 e x -> Fact x f2 -> m2 (Maybe (Graph n2 e x, BwdRewrite m2 n2 f2))) -> (n3 e x -> Fact x f3 -> m3 (Maybe (Graph n3 e x, BwdRewrite m3 n3 f3)))) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> BwdRewrite m1 n1 f1 -> BwdRewrite m2 n2 f2 -> BwdRewrite m3 n3 f3 -- see Note [Respects Fuel] wrapBR2 wrap2 (BwdRewrite3 (f1, m1, l1)) (BwdRewrite3 (f2, m2, l2)) = BwdRewrite3 (wrap2 Open f1 f2, wrap2 Open m1 m2, wrap2 Closed l1 l2) mkBTransfer3 :: (n C O -> f -> f) -> (n O O -> f -> f) -> (n O C -> FactBase f -> f) -> BwdTransfer n f mkBTransfer3 f m l = BwdTransfer3 (f, m, l) mkBTransfer :: (forall e x . n e x -> Fact x f -> f) -> BwdTransfer n f mkBTransfer f = BwdTransfer3 (f, f, f) -- | Functions passed to 'mkBRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkBRewrite3' respects fuel. mkBRewrite3 :: forall m n f. FuelMonad m => (n C O -> f -> m (Maybe (Graph n C O))) -> (n O O -> f -> m (Maybe (Graph n O O))) -> (n O C -> FactBase f -> m (Maybe (Graph n O C))) -> BwdRewrite m n f mkBRewrite3 f m l = BwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> m (Maybe a)) -> t -> t1 -> m (Maybe (a, BwdRewrite m n f)) lift rw node fact = liftM (liftM asRew) (withFuel =<< rw node fact) asRew :: t -> (t, BwdRewrite m n f) asRew g = (g, noBwdRewrite) noBwdRewrite :: Monad m => BwdRewrite m n f noBwdRewrite = BwdRewrite3 (noRewrite, noRewrite, noRewrite) -- | Functions passed to 'mkBRewrite' should not be aware of the fuel supply. -- The result returned by 'mkBRewrite' respects fuel. mkBRewrite :: FuelMonad m => (forall e x . n e x -> Fact x f -> m (Maybe (Graph n e x))) -> BwdRewrite m n f mkBRewrite f = mkBRewrite3 f f f ----------------------------------------------------------------------------- -- Backward implementation ----------------------------------------------------------------------------- arbGraph :: forall m n f e x . (NonLocal n, CheckpointMonad m) => BwdPass m n f -> Entries e -> Graph n e x -> Fact x f -> m (DG f n e x, Fact e f) arbGraph pass entries = graph where {- nested type synonyms would be so lovely here type ARB thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, f) type ARBX thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, Fact e f) -} graph :: Graph n e x -> Fact x f -> m (DG f n e x, Fact e f) block :: forall e x . Block n e x -> Fact x f -> m (DG f n e x, f) node :: forall e x . (ShapeLifter e x) => n e x -> Fact x f -> m (DG f n e x, f) body :: [Label] -> Body n -> Fact C f -> m (DG f n C C, Fact C f) cat :: forall e a x info info' info''. (info' -> m (DG f n e a, info'')) -> (info -> m (DG f n a x, info')) -> (info -> m (DG f n e x, info'')) graph GNil = \f -> return (dgnil, f) graph (GUnit blk) = block blk graph (GMany e bdy x) = (e `ebcat` bdy) `cat` exit x where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact C f -> m (DG f n e C, Fact e f) exit :: MaybeO x (Block n C O) -> Fact x f -> m (DG f n C x, Fact C f) exit (JustO blk) = arbx block blk exit NothingO = \fb -> return (dgnilC, fb) ebcat entry bdy = c entries entry where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact C f -> m (DG f n e C, Fact e f) c NothingC (JustO entry) = block entry `cat` body (successors entry) bdy c (JustC entries) NothingO = body entries bdy c _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block (BFirst n) = node n block (BMiddle n) = node n block (BLast n) = node n block (BCat b1 b2) = block b1 `cat` block b2 block (BHead h n) = block h `cat` node n block (BTail n t) = node n `cat` block t block (BClosed h t)= block h `cat` block t node n f = do { bwdres <- brewrite pass n f ; case bwdres of Nothing -> return (singletonDG entry_f n, entry_f) where entry_f = btransfer pass n f Just (g, rw) -> do { let pass' = pass { bp_rewrite = rw } ; (g, f) <- arbGraph pass' (fwdEntryLabel n) g f ; return (g, bwdEntryFact (bp_lattice pass) n f)} } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g2,f2) <- ft2 f ; (g1,f1) <- ft1 f2 ; return (g1 `dgSplice` g2, f1) } arbx :: forall thing x . NonLocal thing => (thing C x -> Fact x f -> m (DG f n C x, f)) -> (thing C x -> Fact x f -> m (DG f n C x, Fact C f)) arbx arb thing f = do { (rg, f) <- arb thing f ; let fb = joinInFacts (bp_lattice pass) $ mapSingleton (entryLabel thing) f ; return (rg, fb) } -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Bwd (bp_lattice pass) do_block blocks init_fbase where blocks = backwardBlockList entries blockmap do_block :: forall x. Block n C x -> Fact x f -> m (DG f n C x, LabelMap f) do_block b f = do (g, f) <- block b f return (g, mapSingleton (entryLabel b) f) backwardBlockList :: (LabelsPtr entries, NonLocal n) => entries -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for backward analysis, -- along with the list of Labels it may depend on for facts. backwardBlockList entries body = reverse $ forwardBlockList entries body {- The forward and backward cases are not dual. In the forward case, the entry points are known, and one simply traverses the body blocks from those points. In the backward case, something is known about the exit points, but this information is essentially useless, because we don't actually have a dual graph (that is, one with edges reversed) to compute with. (Even if we did have a dual graph, it would not avail us---a backward analysis must include reachable blocks that don't reach the exit, as in a procedure that loops forever and has side effects.) -} -- | if the graph being analyzed is open at the exit, I don't -- quite understand the implications of possible other exits analyzeAndRewriteBwd :: (CheckpointMonad m, NonLocal n, LabelsPtr entries) => BwdPass m n f -> MaybeC e entries -> Graph n e x -> Fact x f -> m (Graph n e x, FactBase f, MaybeO e f) analyzeAndRewriteBwd pass entries g f = do (rg, fout) <- arbGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedEntryFact g' fout) distinguishedEntryFact :: forall n e x f . Graph n e x -> Fact e f -> MaybeO e f distinguishedEntryFact g f = maybe g where maybe :: Graph n e x -> MaybeO e f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany e _ _) = case e of NothingO -> NothingO JustO _ -> JustO f ----------------------------------------------------------------------------- -- fixpoint: finding fixed points ----------------------------------------------------------------------------- -- @ start txfb.tex data TxFactBase n f = TxFB { tfb_fbase :: FactBase (ChangeFlag, f) -- We could technically use DG f n C C to handle this, but -- using a LabelMap makes it a bit clearer. , tfb_rg :: LabelMap (DG f n C C) , tfb_cha :: ChangeFlag , tfb_lbls :: LabelSet } -- @ end txfb.tex -- See Note [TxFactBase invariants] -- @ start update.tex -- Fold function, which folds over new facts and integrates them with an -- existing FactBase, keeping track of whether or not another sweep is -- necessary. updateFact :: DataflowLattice f -> LabelSet -- labels that have already been processed -> Label -- label fact is associated with -> f -- new fact to merge in -- fst is global change flag -> (ChangeFlag, FactBase (ChangeFlag, f)) -> (ChangeFlag, FactBase (ChangeFlag, f)) -- See Note [TxFactBase change flag] updateFact lat lbls lbl new_fact (cha, fbase) -- No change to fact | NoChange <- local_change = (cha, fbase) -- Change to fact, and it's for a block we've already processed. | lbl `setMember` lbls = (SomeChange, new_fbase) -- Change to fact, but it's for a block pending processing. | otherwise = (cha, new_fbase) where (init_change, old_fact) = fromMaybe (SomeChange, fact_bot lat) (lookupFact lbl fbase) (join_change, res_fact) = fact_join lat lbl (OldFact old_fact) (NewFact new_fact) -- If we've never seen this block before, it needs to be processed. -- Otherwise, it only needs to be reprocessed if its fact changed. local_change | SomeChange <- init_change = SomeChange | otherwise = join_change new_fbase = mapInsert lbl (local_change, res_fact) fbase -- @ end update.tex {- -- this doesn't work because it can't be implemented class Monad m => FixpointMonad m where observeChangedFactBase :: m (Maybe (FactBase f)) -> Maybe (FactBase f) -} -- @ start fptype.tex data Direction = Fwd | Bwd fixpoint :: forall m n f. (CheckpointMonad m, NonLocal n) => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> m (DG f n C C, Fact C f)) -> [Block n C C] -- topologically sorted list of blocks to process -> (Fact C f -> m (DG f n C C, Fact C f)) -- @ end fptype.tex -- @ start fpimp.tex fixpoint direction lat do_block blocks init_fbase = do { -- Always begin by sweeping all blocks let init_fbase_with_flags = mapMap (\x -> (SomeChange, x)) init_fbase ; tx_fb <- loop init_fbase_with_flags mapEmpty ; return (mapFold dgSplice dgnilC (tfb_rg tx_fb), map (fst . fst) tagged_blocks `mapDeleteList` mapMap snd (tfb_fbase tx_fb) ) } -- The successors of the Graph are the the Labels -- for which we have facts and which are *not* in -- the blocks of the graph where tagged_blocks = map tag blocks is_fwd = case direction of { Fwd -> True; Bwd -> False } tag :: NonLocal t => t C C -> ((Label, t C C), [Label]) tag b = ((entryLabel b, b), if is_fwd then [entryLabel b] else successors b) -- 'tag' adds the in-labels of the block; -- see Note [TxFactBase invariants] -- A list of tagged blocks: -- [(block label, block), [entry or successor block labels]] tx_blocks :: [((Label, Block n C C), [Label])] -> TxFactBase n f -> m (TxFactBase n f) tx_blocks [] tx_fb = return tx_fb tx_blocks (((lbl,blk), in_lbls):bs) tx_fb = tx_block lbl blk in_lbls tx_fb >>= tx_blocks bs -- "in_lbls" == Labels the block may -- _depend_ upon for facts tx_block :: Label -> Block n C C -> [Label] -> TxFactBase n f -> m (TxFactBase n f) tx_block lbl blk in_lbls tx_fb@(TxFB { tfb_fbase = fbase, tfb_lbls = lbls , tfb_rg = blkMap , tfb_cha = cha }) | is_fwd && not (lbl `mapMember` fbase) = return (tx_fb {tfb_lbls = lbls'}) -- Note [Unreachable blocks] -- Don't bother processing a node if nothing affecting -- it has changed. | Just (NoChange, _) <- lookupFact lbl fbase = {-# SCC "fixpoint-shortcut" #-} return (tx_fb {tfb_lbls = lbls'}) | otherwise = {-# SCC "fixpoint-tx_block" #-} do { (rg, out_facts) <- do_block blk (mapMap snd fbase) -- XXX ugh, allocation -- Update rg for current node ; let blkMap' = mapInsert lbl rg blkMap -- Update fbase for current node ; let fbase' = case mapLookup lbl fbase of Nothing -> fbase Just (_, f) -> mapInsert lbl (NoChange, f) fbase -- Merge out_facts with fbase, and determine if -- another sweep is required. ; let (cha', fbase'') = mapFoldWithKey (updateFact lat lbls') -- combining function (cha, fbase') -- fold base out_facts -- map to fold over ; return $ TxFB { tfb_lbls = lbls' , tfb_fbase = fbase'' , tfb_rg = blkMap' , tfb_cha = cha' } } where lbls' = lbls `setUnion` setFromList in_lbls loop :: FactBase (ChangeFlag, f) -> LabelMap (DG f n C C) -> m (TxFactBase n f) loop fbase rgbase = {-# SCC "fixpoint-loop" #-} do { s <- checkpoint ; let init_tx :: TxFactBase n f init_tx = TxFB { tfb_fbase = fbase , tfb_cha = NoChange , tfb_rg = rgbase , tfb_lbls = setEmpty } ; tx_fb <- tx_blocks tagged_blocks init_tx ; case tfb_cha tx_fb of NoChange -> return tx_fb SomeChange -> do { restart s ; loop (tfb_fbase tx_fb) (tfb_rg tx_fb) } } -- @ end fpimp.tex {- Note [TxFactBase invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The TxFactBase is used only during a fixpoint iteration (or "sweep"), and accumulates facts (and the transformed code) during the fixpoint iteration. * tfb_fbase increases monotonically, across all sweeps * At the beginning of each sweep tfb_cha = NoChange tfb_lbls = {} * During each sweep we process each block in turn. Processing a block is done thus: 1. Read from tfb_fbase the facts for its entry label (forward) or successors labels (backward) 2. Transform those facts into new facts for its successors (forward) or entry label (backward) 3. Augment tfb_fbase with that info We call the labels read in step (1) the "in-labels" of the sweep * The field tfb_lbls is the set of in-labels of all blocks that have been processed so far this sweep, including the block that is currently being processed. tfb_lbls is initialised to {}. It is a subset of the Labels of the *original* (not transformed) blocks. * The tfb_cha field is set to SomeChange iff we decide we need to perform another iteration of the fixpoint loop. It is initialsed to NoChange. Specifically, we set tfb_cha to SomeChange in step (3) iff (a) The fact in tfb_fbase for a block L changes (b) L is in tfb_lbls Reason: until a label enters the in-labels its accumuated fact in tfb_fbase has not been read, hence cannot affect the outcome Note [Unreachable blocks] ~~~~~~~~~~~~~~~~~~~~~~~~~ A block that is not in the domain of tfb_fbase is "currently unreachable". A currently-unreachable block is not even analyzed. Reason: consider constant prop and this graph, with entry point L1: L1: x:=3; goto L4 L2: x:=4; goto L4 L4: if x>3 goto L2 else goto L5 Here L2 is actually unreachable, but if we process it with bottom input fact, we'll propagate (x=4) to L4, and nuke the otherwise-good rewriting of L4. * If a currently-unreachable block is not analyzed, then its rewritten graph will not be accumulated in tfb_rg. And that is good: unreachable blocks simply do not appear in the output. * Note that clients must be careful to provide a fact (even if bottom) for each entry point. Otherwise useful blocks may be garbage collected. * Note that updateFact must set the change-flag if a label goes from not-in-fbase to in-fbase, even if its fact is bottom. In effect the real fact lattice is UNR bottom the points above bottom * Even if the fact is going from UNR to bottom, we still call the client's fact_join function because it might give the client some useful debugging information. * All of this only applies for *forward* fixpoints. For the backward case we must treat every block as reachable; it might finish with a 'return', and therefore have no successors, for example. -} ----------------------------------------------------------------------------- -- DG: an internal data type for 'decorated graphs' -- TOTALLY internal to Hoopl; each block is decorated with a fact ----------------------------------------------------------------------------- -- @ start dg.tex type Graph = Graph' Block type DG f = Graph' (DBlock f) data DBlock f n e x = DBlock f (Block n e x) -- ^ block decorated with fact -- @ end dg.tex instance NonLocal n => NonLocal (DBlock f n) where entryLabel (DBlock _ b) = entryLabel b successors (DBlock _ b) = successors b --- constructors dgnil :: DG f n O O dgnilC :: DG f n C C dgSplice :: NonLocal n => DG f n e a -> DG f n a x -> DG f n e x ---- observers type GraphWithFacts n f e x = (Graph n e x, FactBase f) -- A Graph together with the facts for that graph -- The domains of the two maps should be identical normalizeGraph :: forall n f e x . NonLocal n => DG f n e x -> GraphWithFacts n f e x normalizeGraph g = (graphMapBlocks dropFact g, facts g) where dropFact :: DBlock t t1 t2 t3 -> Block t1 t2 t3 dropFact (DBlock _ b) = b facts :: DG f n e x -> FactBase f facts GNil = noFacts facts (GUnit _) = noFacts facts (GMany _ body exit) = bodyFacts body `mapUnion` exitFacts exit exitFacts :: MaybeO x (DBlock f n C O) -> FactBase f exitFacts NothingO = noFacts exitFacts (JustO (DBlock f b)) = mapSingleton (entryLabel b) f bodyFacts :: LabelMap (DBlock f n C C) -> FactBase f bodyFacts body = mapFold f noFacts body where f :: forall t a x. (NonLocal t) => DBlock a t C x -> LabelMap a -> LabelMap a f (DBlock f b) fb = mapInsert (entryLabel b) f fb --- implementation of the constructors (boring) dgnil = GNil dgnilC = GMany NothingO emptyBody NothingO dgSplice = U.splice fzCat where fzCat :: DBlock f n e O -> DBlock t n O x -> DBlock f n e x fzCat (DBlock f b1) (DBlock _ b2) = DBlock f (b1 `U.cat` b2) ---------------------------------------------------------------- -- Utilities ---------------------------------------------------------------- -- Lifting based on shape: -- - from nodes to blocks -- - from facts to fact-like things -- Lowering back: -- - from fact-like things to facts -- Note that the latter two functions depend only on the entry shape. -- @ start node.tex class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x fwdEntryFact :: NonLocal n => n e x -> f -> Fact e f fwdEntryLabel :: NonLocal n => n e x -> MaybeC e [Label] ftransfer :: FwdPass m n f -> n e x -> f -> Fact x f frewrite :: FwdPass m n f -> n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f)) -- @ end node.tex bwdEntryFact :: NonLocal n => DataflowLattice f -> n e x -> Fact e f -> f btransfer :: BwdPass m n f -> n e x -> Fact x f -> f brewrite :: BwdPass m n f -> n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f)) instance ShapeLifter C O where singletonDG f = gUnitCO . DBlock f . BFirst fwdEntryFact n f = mapSingleton (entryLabel n) f bwdEntryFact lat n fb = getFact lat (entryLabel n) fb ftransfer (FwdPass {fp_transfer = FwdTransfer3 (ft, _, _)}) n f = ft n f btransfer (BwdPass {bp_transfer = BwdTransfer3 (bt, _, _)}) n f = bt n f frewrite (FwdPass {fp_rewrite = FwdRewrite3 (fr, _, _)}) n f = fr n f brewrite (BwdPass {bp_rewrite = BwdRewrite3 (br, _, _)}) n f = br n f fwdEntryLabel n = JustC [entryLabel n] instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdPass {fp_transfer = FwdTransfer3 (_, ft, _)}) n f = ft n f btransfer (BwdPass {bp_transfer = BwdTransfer3 (_, bt, _)}) n f = bt n f frewrite (FwdPass {fp_rewrite = FwdRewrite3 (_, fr, _)}) n f = fr n f brewrite (BwdPass {bp_rewrite = BwdRewrite3 (_, br, _)}) n f = br n f fwdEntryLabel _ = NothingC instance ShapeLifter O C where singletonDG f = gUnitOC . DBlock f . BLast fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdPass {fp_transfer = FwdTransfer3 (_, _, ft)}) n f = ft n f btransfer (BwdPass {bp_transfer = BwdTransfer3 (_, _, bt)}) n f = bt n f frewrite (FwdPass {fp_rewrite = FwdRewrite3 (_, _, fr)}) n f = fr n f brewrite (BwdPass {bp_rewrite = BwdRewrite3 (_, _, br)}) n f = br n f fwdEntryLabel _ = NothingC -- Fact lookup: the fact `orelse` bottom getFact :: DataflowLattice f -> Label -> FactBase f -> f getFact lat l fb = case lookupFact l fb of Just f -> f Nothing -> fact_bot lat {- Note [Respects fuel] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} -- $fuel -- A value of type 'FwdRewrite' or 'BwdRewrite' /respects fuel/ if -- any function contained within the value satisfies the following properties: -- -- * When fuel is exhausted, it always returns 'Nothing'. -- -- * When it returns @Just g rw@, it consumes /exactly/ one unit -- of fuel, and new rewrite 'rw' also respects fuel. -- -- Provided that functions passed to 'mkFRewrite', 'mkFRewrite3', -- 'mkBRewrite', and 'mkBRewrite3' are not aware of the fuel supply, -- the results respect fuel. -- -- It is an /unchecked/ run-time error for the argument passed to 'wrapFR', -- 'wrapFR2', 'wrapBR', or 'warpBR2' to return a function that does not respect fuel.
ezyang/hoopl
src/Compiler/Hoopl/Dataflow.hs
Haskell
bsd-3-clause
36,430
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Distance.FR.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Distance.Types import Duckling.Locale import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale FR Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (simple Kilometre 3) [ "3 kilomètres" , "3 kilometres" , "3 km" , "3km" , "3k" ] , examples (simple Kilometre 3.0) [ "3,0 km" ] , examples (simple Mile 8) [ "8 miles" ] , examples (simple Metre 9) [ "9 metres" , "9m" ] , examples (simple Centimetre 2) [ "2cm" , "2 centimetres" ] ]
facebookincubator/duckling
Duckling/Distance/FR/Corpus.hs
Haskell
bsd-3-clause
1,102
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Duckling.Volume.Types where import Control.DeepSeq import Data.Aeson import Data.Hashable import Data.Text (Text) import qualified Data.Text as Text import GHC.Generics import Prelude import Duckling.Resolve (Resolve (..)) data Unit = Gallon | Hectolitre | Litre | Millilitre deriving (Eq, Generic, Hashable, Ord, Show, NFData) instance ToJSON Unit where toJSON = String . Text.toLower . Text.pack . show data VolumeData = VolumeData { unit :: Maybe Unit , value :: Double } deriving (Eq, Generic, Hashable, Ord, Show, NFData) instance Resolve VolumeData where type ResolvedValue VolumeData = VolumeValue resolve _ VolumeData {unit = Nothing} = Nothing resolve _ VolumeData {unit = Just unit, value} = Just VolumeValue {vValue = value, vUnit = unit} data VolumeValue = VolumeValue { vUnit :: Unit , vValue :: Double } deriving (Eq, Ord, Show) instance ToJSON VolumeValue where toJSON (VolumeValue unit value) = object [ "type" .= ("value" :: Text) , "value" .= value , "unit" .= unit ]
rfranek/duckling
Duckling/Volume/Types.hs
Haskell
bsd-3-clause
1,557
module Lib ( paletteThem ) where import Codec.Picture import System.Directory import Control.Monad import Data.List import qualified Data.ByteString.Lazy as B import System.Info dirSep :: String dirSep = if os == "linux" then "/" else "\\" isImage :: FilePath -> Bool isImage p = any (`isSuffixOf` p) formats where formats = [".jpg", ".jpeg", ".png", ".gif"] paletteThem :: FilePath -> FilePath -> IO () paletteThem paletteFile imgDir = do dynimg <- readImage paletteFile let palette = fmap convertRGB8 dynimg files <- getDirectoryContents imgDir let imgs = filter isImage files either putStrLn (\x -> mapM_ (paletteIt imgDir x) imgs) palette mkPalOpt :: Palette -> PaletteOptions mkPalOpt p = PaletteOptions { paletteCreationMethod = MedianMeanCut, enableImageDithering = True, paletteColorCount = imageWidth p } reorderPalette :: Palette -> Palette -> Palette reorderPalette p p' = let pl = [pixelAt p x 0 | x <- [0.. imageWidth p - 1]] pl' = [pixelAt p' x 0 | x <- [0.. imageWidth p - 1]] perm = bestPerm pl' pl in generateImage (\x _ -> perm !! x) (imageWidth p) (imageHeight p) bestPerm :: [PixelRGB8] -> [PixelRGB8] -> [PixelRGB8] bestPerm _ [] = [] bestPerm [] _ = [] bestPerm (x:xs) l = let best = minimumBy (comparePerm x) l comparePerm x p1 p2 = compare (distance x p1) (distance x p2) l' = filter (/= best) l in best : bestPerm xs l distance :: PixelRGB8 -> PixelRGB8 -> Int distance (PixelRGB8 r1 g1 b1) (PixelRGB8 r2 g2 b2) = abs $ (fromIntegral r2 - fromIntegral r1) * (fromIntegral g2 - fromIntegral g1) * (fromIntegral b2 - fromIntegral b1) paletteIt :: FilePath -> Palette -> FilePath -> IO () paletteIt dir pal file = do dynimg <- readImage $ dir ++ dirSep ++ file putStrLn $ "treating : " ++ file createDirectoryIfMissing True (dir ++ dirSep ++ "res") let img = paletteItAnnexe pal =<< dynimg either putStrLn (writePng (dir ++ dirSep ++ "res" ++ dirSep ++ file ++ ".png")) img putStrLn "done" paletteItAnnexe :: Palette -> DynamicImage -> Either String (Image PixelRGBA8) paletteItAnnexe p img = let img' = convertRGBA8 img appendAlpha a = generateImage (\x y -> let (PixelRGB8 r g b) = pixelAt a x y (PixelRGBA8 _ _ _ alp) = pixelAt img' x y in PixelRGBA8 r g b alp) (imageWidth a) (imageHeight a) palOpt = mkPalOpt p (pImg, p2) = palettize palOpt (pixelMap (\(PixelRGBA8 r g b _ ) -> PixelRGB8 r g b) img') p3 = reorderPalette p p2 in do gifByte <- encodeGifImageWithPalette pImg p3 gif <- decodeImage $ B.toStrict gifByte let rgb = convertRGB8 gif return $ appendAlpha rgb
CharlesHD/Palettize
src/Lib.hs
Haskell
bsd-3-clause
3,099
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Distribution.Solver.Modular.Tree ( FailReason(..) , POption(..) , Tree(..) , TreeF(..) , Weight , ana , cata , dchoices , inn , innM , para , trav , zeroOrOneChoices ) where import Control.Monad hiding (mapM, sequence) import Data.Foldable import Data.Traversable import Prelude hiding (foldr, mapM, sequence) import Distribution.Solver.Modular.Degree import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.PSQ (PSQ) import Distribution.Solver.Modular.Version import Distribution.Solver.Modular.WeightedPSQ (WeightedPSQ) import qualified Distribution.Solver.Modular.WeightedPSQ as W import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.PackagePath type Weight = Double -- | Type of the search tree. Inlining the choice nodes for now. Weights on -- package, flag, and stanza choices control the traversal order. -- TODO: The weight type should be changed from [Double] to Double to avoid -- giving too much weight to preferences that are applied later. data Tree a = -- | Choose a version for a package (or choose to link) PChoice QPN a (WeightedPSQ [Weight] POption (Tree a)) -- | Choose a value for a flag -- -- The Bool indicates whether it's manual. | FChoice QFN a WeakOrTrivial Bool (WeightedPSQ [Weight] Bool (Tree a)) -- | Choose whether or not to enable a stanza | SChoice QSN a WeakOrTrivial (WeightedPSQ [Weight] Bool (Tree a)) -- | Choose which choice to make next -- -- Invariants: -- -- * PSQ should never be empty -- * For each choice we additionally record the 'QGoalReason' why we are -- introducing that goal into tree. Note that most of the time we are -- working with @Tree QGoalReason@; in that case, we must have the -- invariant that the 'QGoalReason' cached in the 'PChoice', 'FChoice' -- or 'SChoice' directly below a 'GoalChoice' node must equal the reason -- recorded on that 'GoalChoice' node. | GoalChoice (PSQ (Goal QPN) (Tree a)) -- | We're done -- we found a solution! | Done RevDepMap -- | We failed to find a solution in this path through the tree | Fail (ConflictSet QPN) FailReason deriving (Eq, Show, Functor) -- | A package option is a package instance with an optional linking annotation -- -- The modular solver has a number of package goals to solve for, and can only -- pick a single package version for a single goal. In order to allow to -- install multiple versions of the same package as part of a single solution -- the solver uses qualified goals. For example, @0.P@ and @1.P@ might both -- be qualified goals for @P@, allowing to pick a difference version of package -- @P@ for @0.P@ and @1.P@. -- -- Linking is an essential part of this story. In addition to picking a specific -- version for @1.P@, the solver can also decide to link @1.P@ to @0.P@ (or -- vice versa). It means that @1.P@ and @0.P@ really must be the very same package -- (and hence must have the same build time configuration, and their -- dependencies must also be the exact same). -- -- See <http://www.well-typed.com/blog/2015/03/qualified-goals/> for details. data POption = POption I (Maybe PackagePath) deriving (Eq, Show) data FailReason = InconsistentInitialConstraints | Conflicting [Dep QPN] | CannotInstall | CannotReinstall | Shadowed | Broken | GlobalConstraintVersion VR ConstraintSource | GlobalConstraintInstalled ConstraintSource | GlobalConstraintSource ConstraintSource | GlobalConstraintFlag ConstraintSource | ManualFlag | MalformedFlagChoice QFN | MalformedStanzaChoice QSN | EmptyGoalChoice | Backjump | MultipleInstances | DependenciesNotLinked String | CyclicDependencies deriving (Eq, Show) -- | Functor for the tree type. data TreeF a b = PChoiceF QPN a (WeightedPSQ [Weight] POption b) | FChoiceF QFN a WeakOrTrivial Bool (WeightedPSQ [Weight] Bool b) | SChoiceF QSN a WeakOrTrivial (WeightedPSQ [Weight] Bool b) | GoalChoiceF (PSQ (Goal QPN) b) | DoneF RevDepMap | FailF (ConflictSet QPN) FailReason deriving (Functor, Foldable, Traversable) out :: Tree a -> TreeF a (Tree a) out (PChoice p i ts) = PChoiceF p i ts out (FChoice p i b m ts) = FChoiceF p i b m ts out (SChoice p i b ts) = SChoiceF p i b ts out (GoalChoice ts) = GoalChoiceF ts out (Done x ) = DoneF x out (Fail c x ) = FailF c x inn :: TreeF a (Tree a) -> Tree a inn (PChoiceF p i ts) = PChoice p i ts inn (FChoiceF p i b m ts) = FChoice p i b m ts inn (SChoiceF p i b ts) = SChoice p i b ts inn (GoalChoiceF ts) = GoalChoice ts inn (DoneF x ) = Done x inn (FailF c x ) = Fail c x innM :: Monad m => TreeF a (m (Tree a)) -> m (Tree a) innM (PChoiceF p i ts) = liftM (PChoice p i ) (sequence ts) innM (FChoiceF p i b m ts) = liftM (FChoice p i b m) (sequence ts) innM (SChoiceF p i b ts) = liftM (SChoice p i b ) (sequence ts) innM (GoalChoiceF ts) = liftM (GoalChoice ) (sequence ts) innM (DoneF x ) = return $ Done x innM (FailF c x ) = return $ Fail c x -- | Determines whether a tree is active, i.e., isn't a failure node. active :: Tree a -> Bool active (Fail _ _) = False active _ = True -- | Approximates the number of active choices that are available in a node. -- Note that we count goal choices as having one choice, always. dchoices :: Tree a -> Degree dchoices (PChoice _ _ ts) = W.degree (W.filter active ts) dchoices (FChoice _ _ _ _ ts) = W.degree (W.filter active ts) dchoices (SChoice _ _ _ ts) = W.degree (W.filter active ts) dchoices (GoalChoice _ ) = ZeroOrOne dchoices (Done _ ) = ZeroOrOne dchoices (Fail _ _ ) = ZeroOrOne -- | Variant of 'dchoices' that traverses fewer children. zeroOrOneChoices :: Tree a -> Bool zeroOrOneChoices (PChoice _ _ ts) = W.isZeroOrOne (W.filter active ts) zeroOrOneChoices (FChoice _ _ _ _ ts) = W.isZeroOrOne (W.filter active ts) zeroOrOneChoices (SChoice _ _ _ ts) = W.isZeroOrOne (W.filter active ts) zeroOrOneChoices (GoalChoice _ ) = True zeroOrOneChoices (Done _ ) = True zeroOrOneChoices (Fail _ _ ) = True -- | Catamorphism on trees. cata :: (TreeF a b -> b) -> Tree a -> b cata phi x = (phi . fmap (cata phi) . out) x trav :: (TreeF a (Tree b) -> TreeF b (Tree b)) -> Tree a -> Tree b trav psi x = cata (inn . psi) x -- | Paramorphism on trees. para :: (TreeF a (b, Tree a) -> b) -> Tree a -> b para phi = phi . fmap (\ x -> (para phi x, x)) . out -- | Anamorphism on trees. ana :: (b -> TreeF a b) -> b -> Tree a ana psi = inn . fmap (ana psi) . psi
sopvop/cabal
cabal-install/Distribution/Solver/Modular/Tree.hs
Haskell
bsd-3-clause
7,333
{-# LANGUAGE RecordWildCards #-} module Main where import Control.Monad import Pipes import Pipes.Serial import Data.Serialize import qualified Data.ByteString.Char8 as B import qualified HXStream.Native as HX import qualified Pipes.Prelude as P import LDrive.Types.Adc import LDrive.Types.Encoder import LDrive.Types.Svm import LDrive.Types.CurrentControl import LDrive.Client.Pipes -- lp import MVC import qualified MVC.Prelude as MVC import Graphics.Liveplot msgDes :: Serialize a => B.ByteString -> IO (Maybe a) msgDes msg = do case runGetState get msg 0 of Left e -> putStrLn ("deserialize error: " ++ e) >> return (Nothing) Right (r, _) -> do return (Just r) des :: Proxy () (HX.Tag, B.ByteString) () (SensorReading GLfloat) IO b des = forever $ do (tag, msg) <- await case tag of 69 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield $ fromEncoder x 65 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield $ fromAdc x 83 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield $ fromSVM x 67 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> do liftIO $ print x mapM_ yield $ fromCC x _ -> return () des' :: (Eq a, Serialize t1, Foldable t, Foldable t2) => t2 (a, t1 -> t y) -> Proxy () (a, B.ByteString) () y IO b des' mappings = forever $ do (tag, msg) <- await mapM_ (handle tag msg) mappings where handle tag msg (tag', handler) | tag == tag' = do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield (handler x) handle _ _ _ = return () --data HXDes a = HXDes a Int --des'' = des' [(69, fromEncoder), (65, fromAdc)] --des'' = des' [ -- (69, toReading :: Encoder -> [SensorReading GLfloat]) -- (65, toReading :: Adc -> [SensorReading GLfloat]) -- ] scaleRange :: Fractional a => (a, a) -> (a, a) -> a -> a scaleRange (fromLow, fromHigh) (toLow, toHigh) x = (x - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow normRange :: Fractional a => (a, a) -> a -> a normRange from = scaleRange from (-1, 1) graphRange :: Fractional a => (a, a) -> a -> a graphRange from = scaleRange from (0, 1) -- utility pipes for liveplot normalize :: (Fractional b, Monad m) => (b, b) -> Pipe b b m r normalize from = P.map (graphRange from) dbg :: (Show a) => Pipe a a IO () dbg = P.tee (P.map (show) >-> P.stdoutLn) main :: IO () main = do let port = "/dev/ttyUSB0" s <- openSerial port defaultSerialSettings { commSpeed = CS115200 } runLiveplot $ myplot (hxserial s >-> des >-> dbg) myplot :: Producer a IO () -> Managed (View (Either (SensorReading GLfloat) GLApp), Controller (Either a Event)) myplot pipe = do let sc = (9, 2) inits = [ lineGraph "pll_pos" sc (0, 0) , lineGraph "pll_vel" sc (1, 0) , lineGraph "phase" sc (2, 0) , lineGraph "vbus" sc (3, 0) , lineGraph "phase_b" sc (4, 0) , lineGraph "phase_c" sc (5, 0) , lineGraph "svm_a" sc (6, 0) , lineGraph "svm_b" sc (7, 0) , lineGraph "svm_c" sc (8, 0) , lineGraph "alpha" sc (0, 1) , lineGraph "beta" sc (1, 1) , lineGraph "d" sc (2, 1) , lineGraph "q" sc (3, 1) , lineGraph "q_in" sc (4, 1) , lineGraph "q_err" sc (5, 1) , lineGraph "mod_d" sc (6, 1) , lineGraph "mod_q" sc (7, 1) , lineGraph "current_i_q" sc (8, 1) ] (v, c) <- ogl inits dat <- MVC.producer (bounded 1) (pipe) return (v, fmap Left (dat) <> fmap Right c) fromEncoder :: Encoder -> [SensorReading GLfloat] fromEncoder Encoder{..} = [ Reading "pll_vel" $ gr' 2000000 pll_vel , Reading "pll_pos" $ gr' 100000 pll_pos , Reading "phase" $ gr' 10 phase ] fromAdc :: Adc -> [SensorReading GLfloat] fromAdc Adc{..} = [ Reading "vbus" $ gr' 25 vbus , Reading "phase_b" $ gr' 0.15 (phase_b) , Reading "phase_c" $ gr' 0.15 (phase_c) ] fromSVM :: Svm -> [SensorReading GLfloat] fromSVM Svm{..} = [ Reading "svm_a" $ gr' 1 svm_a , Reading "svm_b" $ gr' 1 (svm_b) , Reading "svm_c" $ gr' 1 (svm_c) ] fromCC :: CurrentControl -> [SensorReading GLfloat] fromCC CurrentControl{..} = [ Reading "alpha" $ gr' 1 alpha , Reading "beta" $ gr' 1 beta , Reading "d" $ gr' 1 d , Reading "q" $ gr' 1 q , Reading "d_in" $ gr' 1 d_in , Reading "q_in" $ gr' 1 q_in , Reading "d_err" $ gr' 1 d_err , Reading "q_err" $ gr' 1 q_err , Reading "v_d" $ gr' 1 v_d , Reading "v_q" $ gr' 1 v_q , Reading "mod_d" $ gr' 1 mod_d , Reading "mod_q" $ gr' 1 mod_q , Reading "current_i_q" $ gr' 10 current_i_q ] gr' :: GLfloat -> Float -> GLfloat gr' x = (graphRange (-x, x) :: Float -> GLfloat) gR :: (GLfloat, GLfloat) -> Float -> GLfloat gR (x1, x2) = (graphRange (x1, x2) :: Float -> GLfloat) class ToReading a where toReading :: a -> [SensorReading GLfloat] instance ToReading Encoder where toReading = fromEncoder instance ToReading Adc where toReading = fromAdc
sorki/odrive
client/app/Main.hs
Haskell
bsd-3-clause
5,189
triple x = tripleItYo x where tripleItYo :: Integer -> Integer tripleItYo y = y * 3
dhaneshkk/haskell-programming
localType.hs
Haskell
bsd-3-clause
94
{-# LANGUAGE OverloadedStrings #-} module Filesystem ( isXmlFile , isDotFile , isDirectory , isRegularFile , isSymbolicLink , isBlockDevice , isCharacterDevice , isNamedPipe , isSocket , isValidFile , getAllFilesInDir , getAllFilesOfType , chdir ) where import Data.ByteString.Char8 (ByteString, pack, unpack) import HPath import HPath.IO import System.Posix.ByteString.FilePath import System.Posix.Directory.ByteString import System.Posix.Directory.Traversals import System.Posix.FilePath --import System.Posix.Files hiding (isSymbolicLink, isRegularFile) import qualified System.Posix.Files as F chdir :: RawFilePath -> IO () chdir = changeWorkingDirectory cmpFileType :: RawFilePath -> FileType -> IO Bool cmpFileType fp ft = do f <- parseAbs fp fmap (ft ==) (getFileType f) isXmlFile :: RawFilePath -> Bool isXmlFile fp = hasExtension fp && takeExtension fp == extension where extension = pack ".xml" isDotFile :: RawFilePath -> IO Bool isDotFile fp = return $ hiddenFile fp isDirectory :: RawFilePath -> IO Bool isDirectory fp = cmpFileType fp Directory isRegularFile :: RawFilePath -> IO Bool isRegularFile fp = cmpFileType fp RegularFile isSymbolicLink :: RawFilePath -> IO Bool isSymbolicLink fp = cmpFileType fp SymbolicLink isBlockDevice :: RawFilePath -> IO Bool isBlockDevice fp = cmpFileType fp BlockDevice isCharacterDevice :: RawFilePath -> IO Bool isCharacterDevice fp = cmpFileType fp CharacterDevice isNamedPipe :: RawFilePath -> IO Bool isNamedPipe fp = cmpFileType fp NamedPipe isSocket :: RawFilePath -> IO Bool isSocket fp = cmpFileType fp Socket isValidFile :: RawFilePath -> Bool -> IO Bool isValidFile fp allowSymLink = do fileStatus <- F.getFileStatus (unpack fp) let regularFile = F.isRegularFile fileStatus let symbolicLink = F.isSymbolicLink fileStatus return (regularFile || (symbolicLink && allowSymLink)) getAllFilesInDir :: RawFilePath -> Bool -> IO [RawFilePath] getAllFilesInDir fp followLinks = traverseDirectory flt [] fp where flt acc f = do valid <- isValidFile f followLinks if valid then return (f:acc) else return (acc) getAllFilesOfType :: RawFilePath -> ByteString -> Bool -> IO [RawFilePath] getAllFilesOfType fp typ followLinks = traverseDirectory flt [] fp where flt acc f = do valid <- isValidFile f followLinks let validType = hasExtension f && takeExtension f == typ if valid && validType then return (f:acc) else return (acc)
dxtr/hagento
src/Filesystem.hs
Haskell
bsd-3-clause
2,695
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoMonoPatBinds #-} import Types import Data.Iso import Language.JsonGrammar import Prelude hiding (id, (.), head, either) import Control.Category import Data.Aeson (Object) import Test.Framework (Test, defaultMain) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertEqual) person = $(deriveIsos ''Person) (male, female) = $(deriveIsos ''Gender) coords = $(deriveIsos ''Coords) instance Json Person where grammar = person . object ( prop "naam" . prop "geslacht" . prop "leeftijd" . coordsProps ) instance Json Gender where grammar = male . litJson "man" <> female . litJson "vrouw" coordsProps :: Iso (Object :- t) (Object :- Coords :- t) coordsProps = duck coords . prop "lat" . prop "lng" anna :: Person anna = Person "Anna" Female 36 (Coords 53.0163038 5.1993053) main :: IO () main = defaultMain [personTest] personTest :: Test personTest = testCase "Person" (assertEqual "" anna anna') where Just anna' = fromJson annaJson Just annaJson = toJson anna
MedeaMelana/JsonGrammar
tests/Tests.hs
Haskell
bsd-3-clause
1,130
{-# LANGUAGE BangPatterns , RankNTypes, GADTs, DataKinds #-} module Numerical.HBLAS.BLAS.Internal.Level1( AsumFun ,AxpyFun ,CopyFun ,NoScalarDotFun ,ScalarDotFun ,ComplexDotFun ,Nrm2Fun ,RotFun ,RotgFun ,RotmFun ,RotmgFun ,ScalFun ,SwapFun ,IamaxFun --,IaminFun ,asumAbstraction ,axpyAbstraction ,copyAbstraction ,noScalarDotAbstraction ,scalarDotAbstraction ,complexDotAbstraction ,norm2Abstraction ,rotAbstraction ,rotgAbstraction ,rotmAbstraction ,rotmgAbstraction ,scalAbstraction ,swapAbstraction ,iamaxAbstraction --,iaminAbstraction ) where import Numerical.HBLAS.Constants import Numerical.HBLAS.UtilsFFI import Numerical.HBLAS.BLAS.FFI.Level1 import Numerical.HBLAS.BLAS.Internal.Utility import Numerical.HBLAS.MatrixTypes import Control.Monad.Primitive import qualified Data.Vector.Storable.Mutable as SM import Foreign.C.Types import Foreign.Ptr type AsumFun el s m res = Int -> MDenseVector s Direct el -> m res type AxpyFun el s m = Int -> el -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type CopyFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type NoScalarDotFun el s m res = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> m res type ScalarDotFun el s m res = Int -> el -> MDenseVector s Direct el -> MDenseVector s Direct el -> m res type ComplexDotFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> MValue (PrimState m) el -> m() type Nrm2Fun el s m res = Int -> MDenseVector s Direct el -> m res type RotFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> el -> el -> m() type RotgFun el s m = MValue (PrimState m) el -> MValue (PrimState m) el -> MValue (PrimState m) el -> MValue (PrimState m) el -> m() type RotmFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type RotmgFun el s m = MValue (PrimState m) el -> MValue (PrimState m) el -> MValue (PrimState m) el -> el -> MDenseVector s Direct el -> m() type ScalFun scale el s m = Int -> scale -> MDenseVector s Direct el -> m() type SwapFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type IamaxFun el s m = Int -> MDenseVector s Direct el -> m Int --type IaminFun el s m = Int -> MDenseVector s Direct el -> Int -> m Int {-# NOINLINE asumAbstraction #-} asumAbstraction:: (SM.Storable el, PrimMonad m) => String -> AsumFunFFI el res -> AsumFunFFI el res -> AsumFun el (PrimState m) m res asumAbstraction asumName asumSafeFFI asumUnsafeFFI = asum where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= 2 * (fromIntegral n) -- for complex vector, 2n additions are needed asum n (MutableDenseVector _ dim stride buff) | isVectorBadWithNIncrement dim n stride = error $! vectorBadInfo asumName "source matrix" dim n stride | otherwise = unsafeWithPrim buff $ \ptr -> do unsafePrimToPrim $! (if shouldCallFast n then asumUnsafeFFI else asumSafeFFI) (fromIntegral n) ptr (fromIntegral stride) {-# NOINLINE axpyAbstraction #-} axpyAbstraction :: (SM.Storable el, PrimMonad m) => String -> AxpyFunFFI scale el -> AxpyFunFFI scale el -> (el -> (scale -> m()) -> m()) -> AxpyFun el (PrimState m) m axpyAbstraction axpyName axpySafeFFI axpyUnsafeFFI constHandler = axpy where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= 2 * (fromIntegral n) -- n for a*x, and n for +y axpy n alpha (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo axpyName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo axpyName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> constHandler alpha $ \alphaPtr -> do unsafePrimToPrim $! (if shouldCallFast n then axpyUnsafeFFI else axpySafeFFI) (fromIntegral n) alphaPtr ap (fromIntegral astride) bp (fromIntegral bstride) {-# NOINLINE copyAbstraction #-} copyAbstraction :: (SM.Storable el, PrimMonad m) => String -> CopyFunFFI el -> CopyFunFFI el -> CopyFun el (PrimState m) m copyAbstraction copyName copySafeFFI copyUnsafeFFI = copy where shouldCallFast :: Bool shouldCallFast = True -- TODO:(yjj) to confirm no flops are needed in copy copy n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo copyName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo copyName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> do unsafePrimToPrim $! (if shouldCallFast then copyUnsafeFFI else copySafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) {-# NOINLINE noScalarDotAbstraction #-} noScalarDotAbstraction :: (SM.Storable el, PrimMonad m) => String -> NoScalarDotFunFFI el res -> NoScalarDotFunFFI el res -> NoScalarDotFun el (PrimState m) m res noScalarDotAbstraction dotName dotSafeFFI dotUnsafeFFI = dot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n dot n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo dotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo dotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> do unsafePrimToPrim $! (if shouldCallFast n then dotUnsafeFFI else dotSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) {-# NOINLINE scalarDotAbstraction #-} scalarDotAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> SdsdotFortranFunFFI el res -> SdsdotFortranFunFFI el res -> (CInt -> (Ptr CInt -> m res) -> m res) -> (el -> (Ptr el -> m res) -> m res) -> ScalarDotFun el (PrimState m) m res scalarDotAbstraction dotName dotSafeFFI dotUnsafeFFI intConstHandler scaleConstHandler = dot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n dot n sb (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo dotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo dotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> intConstHandler (fromIntegral n) $ \nPtr -> intConstHandler (fromIntegral astride) $ \incaPtr -> intConstHandler (fromIntegral bstride) $ \incbPtr -> scaleConstHandler sb $ \sbPtr -> do unsafePrimToPrim $! (if shouldCallFast n then dotUnsafeFFI else dotSafeFFI) nPtr sbPtr ap incaPtr bp incbPtr {-# NOINLINE complexDotAbstraction #-} complexDotAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> ComplexDotFunFFI el -> ComplexDotFunFFI el -> ComplexDotFun el (PrimState m) m complexDotAbstraction dotName dotSafeFFI dotUnsafeFFI = dot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n dot n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) (MutableValue resbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo dotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo dotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> unsafeWithPrim resbuff $ \resPtr -> do unsafePrimToPrim $! (if shouldCallFast n then dotUnsafeFFI else dotSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) resPtr {-# NOINLINE norm2Abstraction #-} norm2Abstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> Nrm2FunFFI el res -> Nrm2FunFFI el res -> Nrm2Fun el (PrimState m) m res norm2Abstraction norm2Name norm2SafeFFI norm2UnsafeFFI = norm2 where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- not sure, maybe for complex is 2n norm2 n (MutableDenseVector _ dim stride buff) | isVectorBadWithNIncrement dim n stride = error $! vectorBadInfo norm2Name "input matrix" dim n stride | otherwise = unsafeWithPrim buff $ \p -> do unsafePrimToPrim $! (if shouldCallFast n then norm2UnsafeFFI else norm2SafeFFI) (fromIntegral n) p (fromIntegral stride) {-# NOINLINE rotAbstraction #-} rotAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotFunFFI el -> RotFunFFI el -> RotFun el (PrimState m) m rotAbstraction rotName rotSafeFFI rotUnsafeFFI = rot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n rot n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) c s | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo rotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo rotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> do unsafePrimToPrim $! (if shouldCallFast n then rotUnsafeFFI else rotSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) c s {-# NOINLINE rotgAbstraction #-} rotgAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotgFunFFI el -> RotgFunFFI el -> RotgFun el (PrimState m) m rotgAbstraction rotgName rotgSafeFFI rotgUnsafeFFI = rotg where shouldCallFast :: Bool shouldCallFast = True -- not sure, seems O(1) rotg (MutableValue aptr) (MutableValue bptr) (MutableValue cptr) (MutableValue sptr) = unsafeWithPrim aptr $ \ap -> unsafeWithPrim bptr $ \bp -> unsafeWithPrim cptr $ \cp -> unsafeWithPrim sptr $ \sp -> do unsafePrimToPrim $! (if shouldCallFast then rotgUnsafeFFI else rotgSafeFFI) ap bp cp sp {-# NOINLINE rotmAbstraction #-} rotmAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotmFunFFI el -> RotmFunFFI el -> RotmFun el (PrimState m) m rotmAbstraction rotmName rotmSafeFFI rotmUnsafeFFI = rotm where shouldCallFast :: Bool shouldCallFast = True -- O(1) rotm n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) (MutableDenseVector _ pdim _ pbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo rotmName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo rotmName "second matrix" bdim n bstride | pdim /= 5 = error $! rotmName ++ " param dimension is not 5" | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> unsafeWithPrim pbuff $ \pp -> do unsafePrimToPrim $! (if shouldCallFast then rotmUnsafeFFI else rotmSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) pp {-# NOINLINE rotmgAbstraction #-} rotmgAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotmgFunFFI el -> RotmgFunFFI el -> RotmgFun el (PrimState m) m rotmgAbstraction rotmgName rotmgSafeFFI rotmgUnsafeFFI = rotmg where shouldCallFast :: Bool shouldCallFast = True -- O(1) rotmg (MutableValue d1) (MutableValue d2) (MutableValue x1) y1 (MutableDenseVector _ pdim _ pbuff) | pdim /= 5 = error $! rotmgName ++ " param dimension is not 5" | otherwise = unsafeWithPrim d1 $ \d1p -> unsafeWithPrim d2 $ \d2p -> unsafeWithPrim x1 $ \x1p -> unsafeWithPrim pbuff $ \pp -> do unsafePrimToPrim $! (if shouldCallFast then rotmgUnsafeFFI else rotmgSafeFFI) d1p d2p x1p y1 pp {-# NOINLINE scalAbstraction #-} scalAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> ScalFunFFI scale el -> ScalFunFFI scale el -> (scaleplain -> (scale -> m()) -> m()) -> ScalFun scaleplain el (PrimState m) m scalAbstraction scalName scalSafeFFI scalUnsafeFFI constHandler = scal where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n scal n alpha (MutableDenseVector _ xdim stride xbuff) | isVectorBadWithNIncrement xdim n stride = error $! vectorBadInfo scalName "vector" xdim n stride | otherwise = unsafeWithPrim xbuff $ \xptr -> constHandler alpha $ \alphaPtr -> do unsafePrimToPrim $! (if shouldCallFast n then scalUnsafeFFI else scalSafeFFI) (fromIntegral n) alphaPtr xptr (fromIntegral stride) {-# NOINLINE swapAbstraction #-} swapAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> SwapFunFFI el -> SwapFunFFI el -> SwapFun el (PrimState m) m swapAbstraction swapName swapSafeFFI swapUnsafeFFI = swap where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- no computation? only n times memory access? swap n (MutableDenseVector _ xdim xstride xbuff) (MutableDenseVector _ ydim ystride ybuff) | isVectorBadWithNIncrement xdim n xstride = error $! vectorBadInfo swapName "vector x" xdim n xstride | isVectorBadWithNIncrement ydim n ystride = error $! vectorBadInfo swapName "vector y" ydim n ystride | otherwise = unsafeWithPrim xbuff $ \xptr -> unsafeWithPrim ybuff $ \yptr -> do unsafePrimToPrim $! (if shouldCallFast n then swapUnsafeFFI else swapSafeFFI) (fromIntegral n) xptr (fromIntegral xstride) yptr (fromIntegral ystride) {-# NOINLINE iamaxAbstraction #-} iamaxAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> IamaxFunFFI el -> IamaxFunFFI el -> IamaxFun el (PrimState m) m iamaxAbstraction iamaxName iamaxSafeFFI iamaxUnsafeFFI = iamax where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- n times comparison iamax n (MutableDenseVector _ xdim xstride xbuff) | isVectorBadWithNIncrement xdim n xstride = error $! vectorBadInfo iamaxName "target vector" xdim n xstride | otherwise = unsafeWithPrim xbuff $ \xptr -> do unsafePrimToPrim $! (if shouldCallFast n then iamaxUnsafeFFI else iamaxSafeFFI) (fromIntegral n) xptr (fromIntegral xstride) {- {-# NOINLINE iaminAbstraction #-} iaminAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> IaminFunFFI el -> IaminFunFFI el -> IaminFun el (PrimState m) m iaminAbstraction iaminName iaminSafeFFI iaminUnsafeFFI = iamin where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- n times comparison iamin n (MutableDenseVector _ xdim _ xbuff) xincx | isVectorBadWithNIncrement xdim n xincx = error $! vectorBadInfo iaminName "target vector" xdim n xincx | otherwise = unsafeWithPrim xbuff $ \xptr -> do unsafePrimToPrim $! (if shouldCallFast n then iaminUnsafeFFI else iaminSafeFFI) (fromIntegral n) xptr (fromIntegral xincx) -}
yangjueji/hblas
src/Numerical/HBLAS/BLAS/Internal/Level1.hs
Haskell
bsd-3-clause
15,741
import Data.ByteString (ByteString) import Control.Monad (replicateM) import Data.List (unfoldr) -- From the 'entropy' package - for non-determinstic random bits. -- These values come from -- - RDRAND (when on an x86-64 system with said instruction and using new enough compilers) -- - /dev/urandom (when on a nix system) -- - Windows crypt-api (obvious) import System.Entropy -- From the DRBG package -- The CtrDRBG will use NIST SP800-90 + AES-CTR + a seed you provide to -- produce cryptographically strong random values. import Crypto.Random.DRBG -- To throw exceptions instead of get 'Either' results. import Crypto.Classes.Exceptions as X -- Obtain N blocks of 1MB random values based on the given seed -- (Seed must be 32 bytes or larger) pseudoRandom :: ByteString -> Int -> [ByteString] pseudoRandom seed n = let g = X.newGen seed :: CtrDRBG in unfoldr (\(gen,cnt) -> if cnt == 0 then Nothing else let (rand,newGen) = X.genBytes (2^20) gen in Just (rand, (newGen,cnt-1))) (g,n) realRandom :: Int -> IO [ByteString] realRandom n = replicateM n (getEntropy (2^20))
GaloisInc/hacrypto
src/Haskell/rand.hs
Haskell
bsd-3-clause
1,219
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.TextureStorageMultisample -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.TextureStorageMultisample ( -- * Extension Support glGetARBTextureStorageMultisample, gl_ARB_texture_storage_multisample, -- * Functions glTexStorage2DMultisample, glTexStorage3DMultisample ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/TextureStorageMultisample.hs
Haskell
bsd-3-clause
700
module ErrMsg ( LogReader , setLogger , handleErrMsg ) where import Bag import Control.Applicative import Data.IORef import Data.Maybe import DynFlags import ErrUtils import GHC import qualified Gap import HscTypes import Outputable ---------------------------------------------------------------- type LogReader = IO [String] ---------------------------------------------------------------- setLogger :: Bool -> DynFlags -> IO (DynFlags, LogReader) setLogger False df = return (newdf, undefined) where newdf = df { log_action = \_ _ _ _ -> return () } setLogger True df = do ref <- newIORef [] :: IO (IORef [String]) let newdf = df { log_action = appendLog ref } return (newdf, reverse <$> readIORef ref) where appendLog ref _ src stl msg = modifyIORef ref (\ls -> ppMsg src msg stl : ls) ---------------------------------------------------------------- handleErrMsg :: SourceError -> Ghc [String] handleErrMsg = return . errBagToStrList . srcErrorMessages errBagToStrList :: Bag ErrMsg -> [String] errBagToStrList = map ppErrMsg . reverse . bagToList ---------------------------------------------------------------- ppErrMsg :: ErrMsg -> String ppErrMsg err = ppMsg spn msg defaultUserStyle ++ ext where spn = head (errMsgSpans err) msg = errMsgShortDoc err ext = showMsg (errMsgExtraInfo err) defaultUserStyle ppMsg :: SrcSpan -> Message -> PprStyle -> String ppMsg spn msg stl = fromMaybe def $ do (line,col,_,_) <- Gap.getSrcSpan spn file <- Gap.getSrcFile spn return $ file ++ ":" ++ show line ++ ":" ++ show col ++ ":" ++ cts ++ "\0" where def = "ghc-mod:0:0:Probably mutual module import occurred\0" cts = showMsg msg stl ---------------------------------------------------------------- showMsg :: SDoc -> PprStyle -> String showMsg d stl = map toNull $ Gap.renderMsg d stl where toNull '\n' = '\0' toNull x = x
johntyree/ghc-mod
ErrMsg.hs
Haskell
bsd-3-clause
1,919
{- EEL -- Extensible Experimental Language by Lukáš Kuklínek, 2013 -} module Main.REPL(repl) where import Parser.Parser import Parser.State import Parser.Dump import Parser.Core import Sema.Term import Sema.Infer import Backend.Emit import System.IO import Control.Applicative import Text.Parsec import Data.Char import qualified Data.Map as M -- | REPL + welcome message repl ste = do hSetBuffering stdout NoBuffering putStrLn "Welcome to the EEL interactive interpreter!" putStrLn "Type :? for help" prompt 1 repl' 1 ste -- | Read-Eval-Print Loop: quick, dirty, and ugly repl' n ste = do let quit = return (Right ste) let continue ste' = prompt (succ n) >> repl' (succ n) ste' let continue' = continue ste end <- hIsEOF stdin if end then quit else do lineIn <- getLine case reverse . dropWhile isSpace . reverse $ lineIn of "" -> continue' ":q" -> quit ":quit" -> quit ":exit" -> quit ":?" -> help >> continue' ":h" -> help >> continue' ":help" -> help >> continue' ':':'t':' ':str -> do withParse n ste pinfer str $ \term -> do case termType term of Left err -> printErr err Right ty -> putStrLn (show term ++ ": " ++ show ty) continue' ':':'g':' ':str -> withParse n ste pinfer str (putStrLn . genTerm) >> continue' ':':'d':' ':str -> do withParse n ste pinfer str $ \term -> putStrLn (dumpTerm term) continue' ':':'i':' ':str -> do case M.lookup (Symbol str) (pSymTable ste) of Nothing -> printErrStr ("Could not find symbol: '" ++ str ++ "'") Just fd -> case fd of FDUser term -> putStrLn (dumpTerm term) FDBuiltIn _ -> putStrLn "<builtin>" continue' ":x" -> continue (ste { pStack = initStack}) ":ls" -> printFuncs ste >> continue' ":l" -> printFuncs ste >> continue' ":s" -> stackDump ste >> continue' ':':str -> printErrStr ("Unknown command: " ++ show str) >> continue' line -> do ste'' <- case runParser (onLine n >> coreTopParser) ste "<interactive>" line of Left err -> printErr err >> return ste Right ste' -> case semaCheck Nothing ste' of Right _ -> (putStrLn $ show $ pStack ste') >> return ste' Left errs -> (putStrLn $ show errs) >> return ste continue ste'' -- print stack contents stackDump ste = let stk = pStack ste in putStrLn (show stk) >> putStrLn ("Type: " ++ show (stackInfer stk)) prompt n = putStr (zeroPad 3 (show (n :: Int)) ++ "> ") zeroPad n = reverse . take n . (++ repeat '0') . reverse pinfer = infer <$> coreTermParser printErr s = printErrStr (show s) printErrStr s = hPutStrLn stderr ("ERROR: " ++ s) withParse n ste parser str action = case runParser (onLine n >> coreSkipParser >> parser) ste "<interactive>" str of Left err -> printErr err Right term -> action term onLine n = fmap (flip setSourceLine n) getPosition >>= setPosition help = putStr helpMsg helpMsg = unlines [ " Available commands:", " :? show this help message", " :q quit", " :t EXPR print type of an expression", " :d EXPR dump AST of an expression", " :g EXPR generate LLVM code for EXPR", " :i NAME dump AST of an user-defined function", " :x clear the stack", " :s show current stack", " :l list of defined functions" ]
iljakuklic/eel-proto
src/Main/REPL.hs
Haskell
bsd-3-clause
3,935
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} module RoundTripSpec (spec) where import Test.Hspec import Bound import Data.Aeson import Data.Default import Data.Map.Strict (fromList) import qualified Data.HashSet as HS import qualified Data.Vector as V import Pact.Types.RowData import Pact.Types.Runtime import Pact.Types.PactValue spec :: Spec spec = do describe "JSONRoundtrips" $ do describe "testJSONPersist" testJSONPersist describe "testJSONColumns "testJSONColumns describe "testJSONModules" testJSONModules describe "testUnification" testUnification rt :: (FromJSON a,ToJSON a,Show a,Eq a) => String -> a -> Spec rt n p = it ("roundtrips " ++ n) $ do decode (encode p) `shouldBe` Just p testJSONPersist :: Spec testJSONPersist = do rt "integer" (PLiteral (LInteger 123)) rt "decimal" (PLiteral (LDecimal 123.34857)) rt "bool" (PLiteral (LBool False)) rt "string" (PLiteral (LString "hello")) rt "time" (PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))) rt "keyset" (PGuard (GKeySet $ mkKeySet [PublicKey "askjh",PublicKey "dfgh"] "predfun")) rt "modref" (PModRef (ModRef "foo.bar" (Just ["baz", "bof.quux"]) def)) rt "list" (PList (V.fromList [PLiteral (LInteger 123), PLiteral (LBool False), PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))])) rt "object" (PObject (ObjectMap (fromList [("A",PLiteral (LInteger 123)), ("B",PLiteral (LBool False))]))) testJSONColumns :: Spec testJSONColumns = do rt "object" obj it "roundtrips as rowdata" $ do decode @RowData (encode obj) `shouldBe` Just (RowData RDV0 (pactValueToRowData <$> obj)) where uguard = GUser $ UserGuard (Name (BareName "a" def)) [PLiteral (LInteger 123)] pguard = GPact $ PactGuard (PactId "123") "456" ksguard = GKeySet $ mkKeySet [PublicKey "askjh",PublicKey "dfgh"] "predfun" ksrguard = GKeySetRef $ KeySetName "beepboop" mguard = GModule $ ModuleGuard (ModuleName "beep" Nothing) "boop" obj = ObjectMap $ fromList [("A", PLiteral (LInteger 123)) ,("B", PLiteral (LBool False)) ,("C", PLiteral (LString "hello")) ,("D", PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))) ,("E", PGuard uguard) ,("F", PModRef (ModRef "foo.bar" (Just ["baz", "bof.quux"]) def)) ,("G", PObject (ObjectMap (fromList [("A",PLiteral (LInteger 123))]))) ,("H", PList (V.fromList [PLiteral (LInteger 123), PLiteral (LBool False), PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))])) ,("I", PGuard pguard) ,("J", PGuard ksguard) ,("K", PGuard ksrguard) ,("L", PGuard mguard)] testJSONModules :: Spec testJSONModules = rt "module" tmod where tmod = TModule (MDModule (Module "foo" (Governance (Right (tStr "hi"))) def "" (ModuleHash pactInitialHash) HS.empty [] [])) (abstract (const (Just ())) (toTList TyAny def [tlet1])) def tlet1 = TBinding [] (abstract (\b -> if b == na then Just 0 else Nothing) (toTList TyAny def [(TVar na def),tlet2])) -- bound var + let BindLet def tlet2 = TBinding [] (abstract (\b -> if b == nb then Just 0 else Nothing) (toTList TyAny def [(TVar na def),(TVar nb def)])) -- free var + bound var BindLet def na = Name $ BareName "a" def nb = Name $ BareName "b" def testUnification :: Spec testUnification = do it "mod spec unifies with a module with greater coverage" $ (modRef [ifaceA], modRef [ifaceA,ifaceB]) `shouldSatisfy` (uncurry canUnifyWith) it "mod spec unifies with a module with same coverage" $ (modRef [ifaceA,ifaceB], modRef [ifaceA,ifaceB]) `shouldSatisfy` (uncurry canUnifyWith) it "mod spec does not unify with a module with less coverage" $ (modRef [ifaceA,ifaceB], modRef [ifaceA]) `shouldSatisfy` (not . uncurry canUnifyWith) it "mod spec does not unify with a module with different coverage" $ (modRef [ifaceB], modRef [ifaceA]) `shouldSatisfy` (not . uncurry canUnifyWith) -- TODO: add other cases, TyList and TySchema being important candidates where ifaceA = "ifaceA" ifaceB = "ifaceB" modRef :: [ModuleName] -> Type (Term ()) modRef is = modRefTy (ModRef "a" (Just is) def)
kadena-io/pact
tests/RoundTripSpec.hs
Haskell
bsd-3-clause
4,328
main = putStrLn "Dummy fixpoint.native"
gridaphobe/liquid-fixpoint
src/Ocaml.hs
Haskell
bsd-3-clause
40
module Main where import Trombone.Server main :: IO () main = runWithArgs
johanneshilden/principle
Main.hs
Haskell
bsd-3-clause
77
module Foundation where import Prelude import Yesod import Yesod.Static import Yesod.Auth import Yesod.Auth.BrowserId import Yesod.Default.Config import Yesod.Default.Util (addStaticContentExternal) import Network.HTTP.Client.Conduit (Manager, HasHttpManager (getHttpManager)) import qualified Settings import Settings.Development (development) import qualified Database.Persist import Database.Persist.Sql (SqlPersistT) import Settings.StaticFiles import Settings (widgetFile, Extra (..)) import Model import Text.Jasmine (minifym) import Text.Hamlet (hamletFile) import Yesod.Core.Types (Logger) -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { settings :: AppConfig DefaultEnv Extra , getStatic :: Static -- ^ Settings for static file serving. , connPool :: Database.Persist.PersistConfigPool Settings.PersistConf -- ^ Database connection pool. , httpManager :: Manager , persistConfig :: Settings.PersistConf , appLogger :: Logger } instance HasHttpManager App where getHttpManager = httpManager -- Set up i18n messages. See the message folder. mkMessage "App" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where approot = ApprootMaster $ appRoot . settings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 -- timeout in minutes "config/client_session_key.aes" defaultLayout widget = do master <- getYesod mmsg <- getMessage -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do $(combineStylesheets 'StaticR [ css_normalize_css , css_bootstrap_css ]) $(widgetFile "default-layout") giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticRoot setting in Settings.hs urlRenderOverride y (StaticR s) = Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s urlRenderOverride _ _ = Nothing -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authenitcation. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized -- Default to Authorized for now. isAuthorized _ _ = return Authorized -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent = addStaticContentExternal minifym genFileName Settings.staticDir (StaticR . flip StaticRoute []) where -- Generate a unique filename based on the content itself genFileName lbs | development = "autogen-" ++ base64md5 lbs | otherwise = base64md5 lbs -- Place Javascript at bottom of the body tag so the rest of the page loads first jsLoader _ = BottomOfBody -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog _ _source level = development || level == LevelWarn || level == LevelError makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlPersistT runDB = defaultRunDB persistConfig connPool instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner connPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = HomeR -- Where to send a user after logout logoutDest _ = HomeR getAuthId creds = runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Just uid Nothing -> do fmap Just $ insert User { userIdent = credsIdent creds , userPassword = Nothing } -- You can add other plugins like BrowserID, email or OAuth here authPlugins _ = [authBrowserId def] authHttpManager = httpManager -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- | Get the 'Extra' value, used to hold data from the settings.yml file. getExtra :: Handler Extra getExtra = fmap (appExtra . settings) getYesod -- Note: previous versions of the scaffolding included a deliver function to -- send emails. Unfortunately, there are too many different options for us to -- give a reasonable default. Instead, the information is available on the -- wiki: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email
Laquendi/memopad
Foundation.hs
Haskell
mit
6,292
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module Module2_Types where import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, seq, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import qualified Control.Applicative as Applicative (ZipList(..)) import Control.Applicative ( (<*>) ) import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as Exception import qualified Control.Monad as Monad ( liftM, ap, when ) import qualified Data.ByteString.Lazy as BS import Data.Functor ( (<$>) ) import qualified Data.Hashable as Hashable import qualified Data.Int as Int import qualified Data.Maybe as Maybe (catMaybes) import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) ) import qualified Test.QuickCheck as QuickCheck ( elements ) import qualified Thrift import qualified Thrift.Types as Types import qualified Thrift.Serializable as Serializable import qualified Thrift.Arbitraries as Arbitraries import qualified Module0_Types as Module0_Types import qualified Module1_Types as Module1_Types data Struct = Struct { struct_first :: Module0_Types.Struct , struct_second :: Module1_Types.Struct } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable Struct where encode = encode_Struct decode = decode_Struct instance Hashable.Hashable Struct where hashWithSalt salt record = salt `Hashable.hashWithSalt` struct_first record `Hashable.hashWithSalt` struct_second record instance DeepSeq.NFData Struct where rnf _record0 = DeepSeq.rnf (struct_first _record0) `seq` DeepSeq.rnf (struct_second _record0) `seq` () instance Arbitrary.Arbitrary Struct where arbitrary = Monad.liftM Struct (Arbitrary.arbitrary) `Monad.ap`(Arbitrary.arbitrary) shrink obj | obj == default_Struct = [] | otherwise = Maybe.catMaybes [ if obj == default_Struct{struct_first = struct_first obj} then Nothing else Just $ default_Struct{struct_first = struct_first obj} , if obj == default_Struct{struct_second = struct_second obj} then Nothing else Just $ default_Struct{struct_second = struct_second obj} ] from_Struct :: Struct -> Types.ThriftVal from_Struct record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v3 -> Just (1, ("first",Module0_Types.from_Struct _v3))) $ struct_first record , (\_v3 -> Just (2, ("second",Module1_Types.from_Struct _v3))) $ struct_second record ] write_Struct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Struct -> IO () write_Struct oprot record = Thrift.writeVal oprot $ from_Struct record encode_Struct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Struct -> BS.ByteString encode_Struct oprot record = Thrift.serializeVal oprot $ from_Struct record to_Struct :: Types.ThriftVal -> Struct to_Struct (Types.TStruct fields) = Struct{ struct_first = maybe (struct_first default_Struct) (\(_,_val5) -> (case _val5 of {Types.TStruct _val6 -> (Module0_Types.to_Struct (Types.TStruct _val6)); _ -> error "wrong type"})) (Map.lookup (1) fields), struct_second = maybe (struct_second default_Struct) (\(_,_val5) -> (case _val5 of {Types.TStruct _val7 -> (Module1_Types.to_Struct (Types.TStruct _val7)); _ -> error "wrong type"})) (Map.lookup (2) fields) } to_Struct _ = error "not a struct" read_Struct :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO Struct read_Struct iprot = to_Struct <$> Thrift.readVal iprot (Types.T_STRUCT typemap_Struct) decode_Struct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> Struct decode_Struct iprot bs = to_Struct $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_Struct) bs typemap_Struct :: Types.TypeMap typemap_Struct = Map.fromList [("first",(1,(Types.T_STRUCT Module0_Types.typemap_Struct))),("second",(2,(Types.T_STRUCT Module1_Types.typemap_Struct)))] default_Struct :: Struct default_Struct = Struct{ struct_first = Module0_Types.default_Struct, struct_second = Module1_Types.default_Struct} data BigStruct = BigStruct { bigStruct_s :: Module2_Types.Struct , bigStruct_id :: Int.Int32 } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable BigStruct where encode = encode_BigStruct decode = decode_BigStruct instance Hashable.Hashable BigStruct where hashWithSalt salt record = salt `Hashable.hashWithSalt` bigStruct_s record `Hashable.hashWithSalt` bigStruct_id record instance DeepSeq.NFData BigStruct where rnf _record8 = DeepSeq.rnf (bigStruct_s _record8) `seq` DeepSeq.rnf (bigStruct_id _record8) `seq` () instance Arbitrary.Arbitrary BigStruct where arbitrary = Monad.liftM BigStruct (Arbitrary.arbitrary) `Monad.ap`(Arbitrary.arbitrary) shrink obj | obj == default_BigStruct = [] | otherwise = Maybe.catMaybes [ if obj == default_BigStruct{bigStruct_s = bigStruct_s obj} then Nothing else Just $ default_BigStruct{bigStruct_s = bigStruct_s obj} , if obj == default_BigStruct{bigStruct_id = bigStruct_id obj} then Nothing else Just $ default_BigStruct{bigStruct_id = bigStruct_id obj} ] from_BigStruct :: BigStruct -> Types.ThriftVal from_BigStruct record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v11 -> Just (1, ("s",Module2_Types.from_Struct _v11))) $ bigStruct_s record , (\_v11 -> Just (2, ("id",Types.TI32 _v11))) $ bigStruct_id record ] write_BigStruct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BigStruct -> IO () write_BigStruct oprot record = Thrift.writeVal oprot $ from_BigStruct record encode_BigStruct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BigStruct -> BS.ByteString encode_BigStruct oprot record = Thrift.serializeVal oprot $ from_BigStruct record to_BigStruct :: Types.ThriftVal -> BigStruct to_BigStruct (Types.TStruct fields) = BigStruct{ bigStruct_s = maybe (bigStruct_s default_BigStruct) (\(_,_val13) -> (case _val13 of {Types.TStruct _val14 -> (Module2_Types.to_Struct (Types.TStruct _val14)); _ -> error "wrong type"})) (Map.lookup (1) fields), bigStruct_id = maybe (bigStruct_id default_BigStruct) (\(_,_val13) -> (case _val13 of {Types.TI32 _val15 -> _val15; _ -> error "wrong type"})) (Map.lookup (2) fields) } to_BigStruct _ = error "not a struct" read_BigStruct :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO BigStruct read_BigStruct iprot = to_BigStruct <$> Thrift.readVal iprot (Types.T_STRUCT typemap_BigStruct) decode_BigStruct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> BigStruct decode_BigStruct iprot bs = to_BigStruct $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_BigStruct) bs typemap_BigStruct :: Types.TypeMap typemap_BigStruct = Map.fromList [("s",(1,(Types.T_STRUCT Module2_Types.typemap_Struct))),("id",(2,Types.T_I32))] default_BigStruct :: BigStruct default_BigStruct = BigStruct{ bigStruct_s = Module2_Types.default_Struct, bigStruct_id = 0}
sinjar666/fbthrift
thrift/compiler/test/fixtures/qualified/gen-hs/Module2_Types.hs
Haskell
apache-2.0
7,963
{-# LANGUAGE TemplateHaskell, RankNTypes, FlexibleContexts #-} {-| Pure functions for manipulating reservations of temporary objects NOTE: Reservations aren't released specifically, they're just all released at the end of a job. This could be improved in the future. -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.WConfd.TempRes ( TempRes , mkTempRes , TempResState(..) , emptyTempResState , NodeUUID , InstanceUUID , DiskUUID , NetworkUUID , DRBDMinor , DRBDMap , trsDRBDL , computeDRBDMap , computeDRBDMap' , allocateDRBDMinor , releaseDRBDMinors , MAC , generateMAC , reserveMAC , generateDRBDSecret , reserveLV , IPv4ResAction(..) , IPv4Reservation(..) , reserveIp , releaseIp , generateIp , commitReleaseIp , commitReservedIps , listReservedIps , dropAllReservations , isReserved , reserve , dropReservationsFor , reserved ) where import Control.Lens.At import Control.Monad.Error import Control.Monad.State import Control.Monad.Trans.Maybe import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.Foldable as F import Data.Maybe import Data.Map (Map) import qualified Data.Map as M import Data.Monoid import qualified Data.Semigroup as Sem import qualified Data.Set as S import System.Random import qualified Text.JSON as J import Ganeti.BasicTypes import Ganeti.Config import qualified Ganeti.Constants as C import Ganeti.Errors import qualified Ganeti.JSON as J import Ganeti.Lens import qualified Ganeti.Network as N import Ganeti.Locking.Locks (ClientId) import Ganeti.Logging import Ganeti.Objects import Ganeti.THH import Ganeti.Objects.Lens (configNetworksL) import Ganeti.Utils import Ganeti.Utils.Monad import Ganeti.Utils.Random import qualified Ganeti.Utils.MultiMap as MM -- * The main reservation state -- ** Aliases to make types more meaningful: type NodeUUID = BS.ByteString type InstanceUUID = BS.ByteString type DiskUUID = BS.ByteString type NetworkUUID = BS.ByteString type DRBDMinor = Int -- | A map of the usage of DRBD minors type DRBDMap = Map NodeUUID (Map DRBDMinor DiskUUID) -- | A map of the usage of DRBD minors with possible duplicates type DRBDMap' = Map NodeUUID (Map DRBDMinor [DiskUUID]) -- * The state data structure -- | Types of IPv4 reservation actions. data IPv4ResAction = IPv4Reserve | IPv4Release deriving (Eq, Ord, Show, Bounded, Enum) instance J.JSON IPv4ResAction where showJSON IPv4Reserve = J.JSString . J.toJSString $ C.reserveAction showJSON IPv4Release = J.JSString . J.toJSString $ C.releaseAction readJSON = J.readEitherString >=> \s -> case () of _ | s == C.reserveAction -> return IPv4Reserve | s == C.releaseAction -> return IPv4Release | otherwise -> fail $ "Invalid IP reservation action: " ++ s -- | The values stored in the IPv4 reservation table. data IPv4Reservation = IPv4Res { ipv4ResAction :: IPv4ResAction , ipv4ResNetwork :: NetworkUUID , ipv4ResAddr :: Ip4Address } deriving (Eq, Ord, Show) instance J.JSON IPv4Reservation where -- Notice that addr and net are in a different order, to be compatible -- with the original Python representation (while it's used). showJSON (IPv4Res a net addr) = J.showJSON (a, addr, net) readJSON = fmap (\(a, addr, net) -> IPv4Res a net addr) . J.readJSON -- | A polymorphic data structure for managing temporary resources assigned -- to jobs. newtype TempRes j a = TempRes { getTempRes :: MM.MultiMap j a } deriving (Eq, Ord, Show) instance (Ord j, Ord a) => Sem.Semigroup (TempRes j a) where (TempRes x) <> (TempRes y) = TempRes $ x <> y instance (Ord j, Ord a) => Monoid (TempRes j a) where mempty = TempRes mempty mappend = (Sem.<>) instance (J.JSON j, Ord j, J.JSON a, Ord a) => J.JSON (TempRes j a) where showJSON = J.showJSON . getTempRes readJSON = liftM TempRes . J.readJSON -- | Create a temporary reservations from a given multi-map. mkTempRes :: MM.MultiMap j a -> TempRes j a mkTempRes = TempRes -- | The state of the temporary reservations $(buildObject "TempResState" "trs" [ simpleField "dRBD" [t| DRBDMap |] , simpleField "mACs" [t| TempRes ClientId MAC |] , simpleField "dRBDSecrets" [t| TempRes ClientId DRBDSecret |] , simpleField "lVs" [t| TempRes ClientId LogicalVolume |] , simpleField "iPv4s" [t| TempRes ClientId IPv4Reservation |] ]) emptyTempResState :: TempResState emptyTempResState = TempResState M.empty mempty mempty mempty mempty $(makeCustomLenses ''TempResState) -- ** Utility functions -- | Issues a reservation error. resError :: (MonadError GanetiException m) => String -> m a resError = throwError . ReservationError -- | Converts 'GenericError' into a 'ReservationError'. toResError :: (MonadError GanetiException m) => m a -> m a toResError = flip catchError (throwError . f) where f (GenericError msg) = ReservationError msg f e = e -- | Filter values from the nested map and remove any nested maps -- that become empty. filterNested :: (Ord a, Ord b) => (c -> Bool) -> Map a (Map b c) -> Map a (Map b c) filterNested p = M.filter (not . M.null) . fmap (M.filter p) -- | Converts a lens that works on maybe values into a lens that works -- on regular ones. A missing value on the input is replaced by -- 'mempty'. -- The output is is @Just something@ iff @something /= mempty@. maybeLens :: (Monoid a, Monoid b, Eq b) => Lens s t (Maybe a) (Maybe b) -> Lens s t a b maybeLens l f = l (fmap (mfilter (/= mempty) . Just) . f . fromMaybe mempty) -- * DRBD functions -- | Compute the map of used DRBD minor/nodes, including possible -- duplicates. -- An error is returned if the configuration isn't consistent -- (for example if a referenced disk is missing etc.). computeDRBDMap' :: (MonadError GanetiException m) => ConfigData -> TempResState -> m DRBDMap' computeDRBDMap' cfg trs = flip execStateT (fmap (fmap (: [])) (trsDRBD trs)) $ F.forM_ (configDisks cfg) addMinors where -- | Creates a lens for modifying the list of instances nodeMinor :: NodeUUID -> DRBDMinor -> Lens' DRBDMap' [DiskUUID] nodeMinor node minor = maybeLens (at node) . maybeLens (at minor) -- | Adds minors of a disk within the state monad addMinors disk = do let minors = getDrbdMinorsForDisk disk forM_ minors $ \(minor, node) -> nodeMinor (UTF8.fromString node) minor %= (UTF8.fromString (uuidOf disk) :) -- | Compute the map of used DRBD minor/nodes. -- Report any duplicate entries as an error. -- -- Unlike 'computeDRBDMap'', includes entries for all nodes, even if empty. computeDRBDMap :: (MonadError GanetiException m) => ConfigData -> TempResState -> m DRBDMap computeDRBDMap cfg trs = do m <- computeDRBDMap' cfg trs let dups = filterNested ((>= 2) . length) m unless (M.null dups) . resError $ "Duplicate DRBD ports detected: " ++ show (M.toList $ fmap M.toList dups) return $ fmap (fmap head . M.filter ((== 1) . length)) m `M.union` (fmap (const mempty) . J.fromContainer . configNodes $ cfg) -- Allocate a drbd minor. -- -- The free minor will be automatically computed from the existing devices. -- A node can not be given multiple times. -- The result is the list of minors, in the same order as the passed nodes. allocateDRBDMinor :: (MonadError GanetiException m, MonadState TempResState m) => ConfigData -> DiskUUID -> [NodeUUID] -> m [DRBDMinor] allocateDRBDMinor cfg disk nodes = do unless (nodes == ordNub nodes) . resError $ "Duplicate nodes detected in list '" ++ show nodes ++ "'" dMap <- computeDRBDMap' cfg =<< get let usedMap = fmap M.keysSet dMap let alloc :: S.Set DRBDMinor -> Map DRBDMinor DiskUUID -> (DRBDMinor, Map DRBDMinor DiskUUID) alloc used m = let k = findFirst 0 (M.keysSet m `S.union` used) in (k, M.insert k disk m) forM nodes $ \node -> trsDRBDL . maybeLens (at node) %%= alloc (M.findWithDefault mempty node usedMap) -- Release temporary drbd minors allocated for a given disk using -- 'allocateDRBDMinor'. releaseDRBDMinors :: (MonadState TempResState m) => DiskUUID -> m () releaseDRBDMinors disk = trsDRBDL %= filterNested (/= disk) -- * Other temporary resources -- | Tests if a given value is reserved for a given job. isReserved :: (Ord a, Ord j) => a -> TempRes j a -> Bool isReserved x = MM.elem x . getTempRes -- | Tries to reserve a given value for a given job. reserve :: (MonadError GanetiException m, Show a, Ord a, Ord j) => j -> a -> TempRes j a -> m (TempRes j a) reserve jobid x tr = do when (isReserved x tr) . resError $ "Duplicate reservation for resource '" ++ show x ++ "'" return . TempRes . MM.insert jobid x $ getTempRes tr dropReservationsFor :: (Ord a, Ord j) => j -> TempRes j a -> TempRes j a dropReservationsFor jobid = TempRes . MM.deleteAll jobid . getTempRes reservedFor :: (Ord a, Ord j) => j -> TempRes j a -> S.Set a reservedFor jobid = MM.lookup jobid . getTempRes reserved :: (Ord a, Ord j) => TempRes j a -> S.Set a reserved = MM.values . getTempRes -- | Computes the set of all reserved resources and passes it to -- the given function. -- This allows it to avoid resources that are already in use. withReserved :: (MonadError GanetiException m, Show a, Ord a, Ord j) => j -> (S.Set a -> m a) -> TempRes j a -> m (a, TempRes j a) withReserved jobid genfn tr = do x <- genfn (reserved tr) (,) x `liftM` reserve jobid x tr -- | Repeatedly tries to run a given monadic function until it succeeds -- and the returned value is free to reserve. -- If such a value is found, it's reserved and returned. -- Otherwise fails with an error. generate :: (MonadError GanetiException m, Show a, Ord a, Ord j) => j -> S.Set a -> m (Maybe a) -> TempRes j a -> m (a, TempRes j a) generate jobid existing genfn = withReserved jobid f where retries = 64 :: Int f res = do let vals = res `S.union` existing xOpt <- retryMaybeN retries (\_ -> mfilter (`S.notMember` vals) (MaybeT genfn)) maybe (resError "Not able generate new resource") -- TODO: (last tried: " ++ %s)" % new_resource return xOpt -- | A variant of 'generate' for randomized computations. generateRand :: (MonadError GanetiException m, Show a, Ord a, Ord j, RandomGen g) => g -> j -> S.Set a -> (g -> (Maybe a, g)) -> TempRes j a -> m (a, TempRes j a) generateRand rgen jobid existing genfn tr = evalStateT (generate jobid existing (state genfn) tr) rgen -- | Embeds a stateful computation in a stateful monad. stateM :: (MonadState s m) => (s -> m (a, s)) -> m a stateM f = get >>= f >>= \(x, s) -> liftM (const x) (put s) -- | Embeds a state-modifying computation in a stateful monad. modifyM :: (MonadState s m) => (s -> m s) -> m () modifyM f = get >>= f >>= put -- ** Functions common to all reservations -- | Removes all resources reserved by a given job. -- -- If a new reservation resource type is added, it must be added here as well. dropAllReservations :: ClientId -> State TempResState () dropAllReservations jobId = modify $ (trsMACsL %~ dropReservationsFor jobId) . (trsDRBDSecretsL %~ dropReservationsFor jobId) . (trsLVsL %~ dropReservationsFor jobId) . (trsIPv4sL %~ dropReservationsFor jobId) -- | Looks up a network by its UUID. lookupNetwork :: (MonadError GanetiException m) => ConfigData -> NetworkUUID -> m Network lookupNetwork cd netId = J.lookupContainer (resError $ "Network '" ++ show netId ++ "' not found") netId (configNetworks cd) -- ** IDs -- ** MAC addresses -- Randomly generate a MAC for an instance. -- Checks that the generated MAC isn't used by another instance. -- -- Note that we only consume, but not return the state of a random number -- generator. This is because the whole operation needs to be pure (for atomic -- 'IORef' updates) and therefore we can't use 'getStdRandom'. Therefore the -- approach we take is to instead use 'newStdGen' and discard the split -- generator afterwards. generateMAC :: (RandomGen g, MonadError GanetiException m, Functor m) => g -> ClientId -> Maybe NetworkUUID -> ConfigData -> StateT TempResState m MAC generateMAC rgen jobId netId cd = do net <- case netId of Just n -> Just <$> lookupNetwork cd n Nothing -> return Nothing let prefix = fromMaybe (clusterMacPrefix . configCluster $ cd) (networkMacPrefix =<< net) let existing = S.fromList $ getAllMACs cd StateT $ traverseOf2 trsMACsL (generateRand rgen jobId existing (over _1 Just . generateOneMAC prefix)) -- Reserves a MAC for an instance in the list of temporary reservations. reserveMAC :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> MAC -> ConfigData -> m () reserveMAC jobId mac cd = do let existing = S.fromList $ getAllMACs cd when (S.member mac existing) $ resError "MAC already in use" modifyM $ traverseOf trsMACsL (reserve jobId mac) -- ** DRBD secrets generateDRBDSecret :: (RandomGen g, MonadError GanetiException m, Functor m) => g -> ClientId -> ConfigData -> StateT TempResState m DRBDSecret generateDRBDSecret rgen jobId cd = do let existing = S.fromList $ getAllDrbdSecrets cd StateT $ traverseOf2 trsDRBDSecretsL (generateRand rgen jobId existing (over _1 Just . generateSecret C.drbdSecretLength)) -- ** LVs reserveLV :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> LogicalVolume -> ConfigData -> m () reserveLV jobId lv cd = do existing <- toError $ getAllLVs cd when (S.member lv existing) $ resError "MAC already in use" modifyM $ traverseOf trsLVsL (reserve jobId lv) -- ** IPv4 addresses -- | Lists all IPv4 addresses reserved for a given network. usedIPv4Addrs :: NetworkUUID -> S.Set IPv4Reservation -> S.Set Ip4Address usedIPv4Addrs netuuid = S.map ipv4ResAddr . S.filter ((== netuuid) . ipv4ResNetwork) -- | Reserve a given IPv4 address for use by an instance. reserveIp :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> NetworkUUID -> Ip4Address -> Bool -- ^ whether to check externally reserved IPs -> ConfigData -> m () reserveIp jobId netuuid addr checkExt cd = toResError $ do net <- lookupNetwork cd netuuid isres <- N.isReserved N.PoolInstances addr net when isres . resError $ "IP address already in use" when checkExt $ do isextres <- N.isReserved N.PoolExt addr net when isextres . resError $ "IP is externally reserved" let action = IPv4Res IPv4Reserve netuuid addr modifyM $ traverseOf trsIPv4sL (reserve jobId action) -- | Give a specific IP address back to an IP pool. -- The IP address is returned to the IP pool designated by network id -- and marked as reserved. releaseIp :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> NetworkUUID -> Ip4Address -> m () releaseIp jobId netuuid addr = let action = IPv4Res { ipv4ResAction = IPv4Release , ipv4ResNetwork = netuuid , ipv4ResAddr = addr } in modifyM $ traverseOf trsIPv4sL (reserve jobId action) -- Find a free IPv4 address for an instance and reserve it. generateIp :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> NetworkUUID -> ConfigData -> m Ip4Address generateIp jobId netuuid cd = toResError $ do net <- lookupNetwork cd netuuid let f res = do let ips = usedIPv4Addrs netuuid res addr <- N.findFree (`S.notMember` ips) net maybe (resError "Cannot generate IP. Network is full") (return . IPv4Res IPv4Reserve netuuid) addr liftM ipv4ResAddr . stateM $ traverseOf2 trsIPv4sL (withReserved jobId f) -- | Commit a reserved/released IP address to an IP pool. -- The IP address is taken from the network's IP pool and marked as -- reserved/free for instances. commitIp :: (MonadError GanetiException m, Functor m) => IPv4Reservation -> ConfigData -> m ConfigData commitIp (IPv4Res actType netuuid addr) cd = toResError $ do let call = case actType of IPv4Reserve -> N.reserve IPv4Release -> N.release f Nothing = resError $ "Network '" ++ show netuuid ++ "' not found" f (Just net) = Just `liftM` call N.PoolInstances addr net traverseOf (configNetworksL . J.alterContainerL netuuid) f cd -- | Immediately release an IP address, without using the reservations pool. commitReleaseIp :: (MonadError GanetiException m, Functor m) => NetworkUUID -> Ip4Address -> ConfigData -> m ConfigData commitReleaseIp netuuid addr = commitIp (IPv4Res IPv4Release netuuid addr) -- | Commit all reserved/released IP address to an IP pool. -- The IP addresses are taken from the network's IP pool and marked as -- reserved/free for instances. -- -- Note that the reservations are kept, they are supposed to be cleaned -- when a job finishes. commitReservedIps :: (MonadError GanetiException m, Functor m, MonadLog m) => ClientId -> TempResState -> ConfigData -> m ConfigData commitReservedIps jobId tr cd = do let res = reservedFor jobId (trsIPv4s tr) logDebug $ "Commiting reservations: " ++ show res F.foldrM commitIp cd res listReservedIps :: ClientId -> TempResState -> S.Set IPv4Reservation listReservedIps jobid = reservedFor jobid . trsIPv4s
mbakke/ganeti
src/Ganeti/WConfd/TempRes.hs
Haskell
bsd-2-clause
19,053
{-# LANGUAGE BangPatterns #-} -------------------------------------------------------------------------------- -- | -- Module : Foreign.CUDA.Analysis.Occupancy -- Copyright : [2009..2014] Trevor L. McDonell -- License : BSD -- -- Occupancy calculations for CUDA kernels -- -- <http://developer.download.nvidia.com/compute/cuda/3_0/sdk/docs/CUDA_Occupancy_calculator.xls> -- -- /Determining Registers Per Thread and Shared Memory Per Block/ -- -- To determine the number of registers used per thread in your kernel, simply -- compile the kernel code using the option -- -- > --ptxas-options=-v -- -- to nvcc. This will output information about register, local memory, shared -- memory, and constant memory usage for each kernel in the @.cu@ file. -- Alternatively, you can compile with the @-cubin@ option to nvcc. This will -- generate a @.cubin@ file, which you can open in a text editor. Look for the -- @code@ section with your kernel's name. Within the curly braces (@{ ... }@) -- for that code block, you will see a line with @reg = X@, where @x@ is the -- number of registers used by your kernel. You can also see the amount of -- shared memory used as @smem = Y@. However, if your kernel declares any -- external shared memory that is allocated dynamically, you will need to add -- the number in the @.cubin@ file to the amount you dynamically allocate at run -- time to get the correct shared memory usage. -- -- /Notes About Occupancy/ -- -- Higher occupancy does not necessarily mean higher performance. If a kernel -- is not bandwidth bound, then increasing occupancy will not necessarily -- increase performance. If a kernel invocation is already running at least one -- thread block per multiprocessor in the GPU, and it is bottlenecked by -- computation and not by global memory accesses, then increasing occupancy may -- have no effect. In fact, making changes just to increase occupancy can have -- other effects, such as additional instructions, spills to local memory (which -- is off chip), divergent branches, etc. As with any optimization, you should -- experiment to see how changes affect the *wall clock time* of the kernel -- execution. For bandwidth bound applications, on the other hand, increasing -- occupancy can help better hide the latency of memory accesses, and therefore -- improve performance. -- -------------------------------------------------------------------------------- module Foreign.CUDA.Analysis.Occupancy ( Occupancy(..), occupancy, optimalBlockSize, optimalBlockSizeBy, maxResidentBlocks, incPow2, incWarp, decPow2, decWarp ) where import Data.Ord import Data.List import Foreign.CUDA.Analysis.Device -- GPU Occupancy per multiprocessor -- data Occupancy = Occupancy { activeThreads :: !Int, -- ^ Active threads per multiprocessor activeThreadBlocks :: !Int, -- ^ Active thread blocks per multiprocessor activeWarps :: !Int, -- ^ Active warps per multiprocessor occupancy100 :: !Double -- ^ Occupancy of each multiprocessor (percent) } deriving (Eq, Ord, Show) -- | -- Calculate occupancy data for a given GPU and kernel resource usage -- {-# INLINEABLE occupancy #-} occupancy :: DeviceProperties -- ^ Properties of the card in question -> Int -- ^ Threads per block -> Int -- ^ Registers per thread -> Int -- ^ Shared memory per block (bytes) -> Occupancy occupancy !dev !thds !regs !smem = Occupancy at ab aw oc where at = ab * thds aw = ab * warps ab = minimum [limitWarpBlock, limitRegMP, limitSMemMP] oc = 100 * fromIntegral aw / fromIntegral (warpsPerMP gpu) regs' = 1 `max` regs smem' = 1 `max` smem floor' = floor :: Double -> Int ceiling' = ceiling :: Double -> Int ceilingBy x s = s * ceiling' (fromIntegral x / fromIntegral s) -- Physical resources -- gpu = deviceResources dev -- Allocation per thread block -- warps = ceiling' (fromIntegral thds / fromIntegral (threadsPerWarp gpu)) sharedMem = ceilingBy smem' (sharedMemAllocUnit gpu) registers = case allocation gpu of Block -> (warps `ceilingBy` regAllocWarp gpu * regs' * threadsPerWarp gpu) `ceilingBy` regAllocUnit gpu Warp -> warps * ceilingBy (regs' * threadsPerWarp gpu) (regAllocUnit gpu) -- Maximum thread blocks per multiprocessor -- limitWarpBlock = threadBlocksPerMP gpu `min` floor' (fromIntegral (warpsPerMP gpu) / fromIntegral warps) limitRegMP = threadBlocksPerMP gpu `min` floor' (fromIntegral (regFileSize gpu) / fromIntegral registers) limitSMemMP = threadBlocksPerMP gpu `min` floor' (fromIntegral (sharedMemPerMP gpu) / fromIntegral sharedMem) -- | -- Optimise multiprocessor occupancy as a function of thread block size and -- resource usage. This returns the smallest satisfying block size in increments -- of a single warp. -- {-# INLINEABLE optimalBlockSize #-} optimalBlockSize :: DeviceProperties -- ^ Architecture to optimise for -> (Int -> Int) -- ^ Register count as a function of thread block size -> (Int -> Int) -- ^ Shared memory usage (bytes) as a function of thread block size -> (Int, Occupancy) optimalBlockSize = flip optimalBlockSizeBy decWarp -- | -- As 'optimalBlockSize', but with a generator that produces the specific thread -- block sizes that should be tested. The generated list can produce values in -- any order, but the last satisfying block size will be returned. Hence, values -- should be monotonically decreasing to return the smallest block size yielding -- maximum occupancy, and vice-versa. -- {-# INLINEABLE optimalBlockSizeBy #-} optimalBlockSizeBy :: DeviceProperties -> (DeviceProperties -> [Int]) -> (Int -> Int) -> (Int -> Int) -> (Int, Occupancy) optimalBlockSizeBy !dev !fblk !freg !fsmem = maximumBy (comparing (occupancy100 . snd)) $ zip threads residency where residency = map (\t -> occupancy dev t (freg t) (fsmem t)) threads threads = fblk dev -- | Increments in powers-of-two, over the range of supported thread block sizes -- for the given device. -- {-# INLINEABLE incPow2 #-} incPow2 :: DeviceProperties -> [Int] incPow2 !dev = map ((2::Int)^) [lb, lb+1 .. ub] where round' = round :: Double -> Int lb = round' . logBase 2 . fromIntegral $ warpSize dev ub = round' . logBase 2 . fromIntegral $ maxThreadsPerBlock dev -- | Decrements in powers-of-two, over the range of supported thread block sizes -- for the given device. -- {-# INLINEABLE decPow2 #-} decPow2 :: DeviceProperties -> [Int] decPow2 !dev = map ((2::Int)^) [ub, ub-1 .. lb] where round' = round :: Double -> Int lb = round' . logBase 2 . fromIntegral $ warpSize dev ub = round' . logBase 2 . fromIntegral $ maxThreadsPerBlock dev -- | Decrements in the warp size of the device, over the range of supported -- thread block sizes. -- {-# INLINEABLE decWarp #-} decWarp :: DeviceProperties -> [Int] decWarp !dev = [block, block-warp .. warp] where !warp = warpSize dev !block = maxThreadsPerBlock dev -- | Increments in the warp size of the device, over the range of supported -- thread block sizes. -- {-# INLINEABLE incWarp #-} incWarp :: DeviceProperties -> [Int] incWarp !dev = [warp, 2*warp .. block] where warp = warpSize dev block = maxThreadsPerBlock dev -- | -- Determine the maximum number of CTAs that can be run simultaneously for a -- given kernel / device combination. -- {-# INLINEABLE maxResidentBlocks #-} maxResidentBlocks :: DeviceProperties -- ^ Properties of the card in question -> Int -- ^ Threads per block -> Int -- ^ Registers per thread -> Int -- ^ Shared memory per block (bytes) -> Int -- ^ Maximum number of resident blocks maxResidentBlocks !dev !thds !regs !smem = multiProcessorCount dev * activeThreadBlocks (occupancy dev thds regs smem)
mwu-tow/cuda
Foreign/CUDA/Analysis/Occupancy.hs
Haskell
bsd-3-clause
8,068
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[RnBinds]{Renaming and dependency analysis of bindings} This module does renaming and dependency analysis on value bindings in the abstract syntax. It does {\em not} do cycle-checks on class or type-synonym declarations; those cannot be done at this stage because they may be affected by renaming (which isn't fully worked out yet). -} module ETA.Rename.RnBinds ( -- Renaming top-level bindings rnTopBindsLHS, rnTopBindsRHS, rnValBindsRHS, -- Renaming local bindings rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS, -- Other bindings rnMethodBinds, renameSigs, mkSigTvFn, rnMatchGroup, rnGRHSs, rnGRHS, makeMiniFixityEnv, MiniFixityEnv, HsSigCtxt(..) ) where import {-# SOURCE #-} ETA.Rename.RnExpr( rnLExpr, rnStmts ) import ETA.HsSyn.HsSyn import ETA.TypeCheck.TcRnMonad import ETA.TypeCheck.TcEvidence ( emptyTcEvBinds ) import ETA.Rename.RnTypes import ETA.Rename.RnPat import ETA.Rename.RnNames import ETA.Rename.RnEnv import ETA.Main.DynFlags import ETA.BasicTypes.Avail import ETA.BasicTypes.Module import ETA.BasicTypes.Name import ETA.BasicTypes.NameEnv import ETA.BasicTypes.NameSet import ETA.BasicTypes.RdrName ( RdrName, rdrNameOcc ) import ETA.BasicTypes.SrcLoc import ETA.Utils.ListSetOps ( findDupsEq ) import ETA.BasicTypes.BasicTypes ( RecFlag(..) ) import ETA.Utils.Digraph ( SCC(..) ) import ETA.Utils.Bag import ETA.Utils.Outputable import ETA.Utils.FastString import Data.List ( partition, sort ) import ETA.Utils.Maybes ( orElse ) import Control.Monad -- TODO:#if __GLASGOW_HASKELL__ < 709 -- import Data.Traversable ( traverse ) -- #endif {- -- ToDo: Put the annotations into the monad, so that they arrive in the proper -- place and can be used when complaining. The code tree received by the function @rnBinds@ contains definitions in where-clauses which are all apparently mutually recursive, but which may not really depend upon each other. For example, in the top level program \begin{verbatim} f x = y where a = x y = x \end{verbatim} the definitions of @a@ and @y@ do not depend on each other at all. Unfortunately, the typechecker cannot always check such definitions. \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive definitions. In Proceedings of the International Symposium on Programming, Toulouse, pp. 217-39. LNCS 167. Springer Verlag.} However, the typechecker usually can check definitions in which only the strongly connected components have been collected into recursive bindings. This is precisely what the function @rnBinds@ does. ToDo: deal with case where a single monobinds binds the same variable twice. The vertag tag is a unique @Int@; the tags only need to be unique within one @MonoBinds@, so that unique-Int plumbing is done explicitly (heavy monad machinery not needed). ************************************************************************ * * * naming conventions * * * ************************************************************************ \subsection[name-conventions]{Name conventions} The basic algorithm involves walking over the tree and returning a tuple containing the new tree plus its free variables. Some functions, such as those walking polymorphic bindings (HsBinds) and qualifier lists in list comprehensions (@Quals@), return the variables bound in local environments. These are then used to calculate the free variables of the expression evaluated in these environments. Conventions for variable names are as follows: \begin{itemize} \item new code is given a prime to distinguish it from the old. \item a set of variables defined in @Exp@ is written @dvExp@ \item a set of variables free in @Exp@ is written @fvExp@ \end{itemize} ************************************************************************ * * * analysing polymorphic bindings (HsBindGroup, HsBind) * * ************************************************************************ \subsubsection[dep-HsBinds]{Polymorphic bindings} Non-recursive expressions are reconstructed without any changes at top level, although their component expressions may have to be altered. However, non-recursive expressions are currently not expected as \Haskell{} programs, and this code should not be executed. Monomorphic bindings contain information that is returned in a tuple (a @FlatMonoBinds@) containing: \begin{enumerate} \item a unique @Int@ that serves as the ``vertex tag'' for this binding. \item the name of a function or the names in a pattern. These are a set referred to as @dvLhs@, the defined variables of the left hand side. \item the free variables of the body. These are referred to as @fvBody@. \item the definition's actual code. This is referred to as just @code@. \end{enumerate} The function @nonRecDvFv@ returns two sets of variables. The first is the set of variables defined in the set of monomorphic bindings, while the second is the set of free variables in those bindings. The set of variables defined in a non-recursive binding is just the union of all of them, as @union@ removes duplicates. However, the free variables in each successive set of cumulative bindings is the union of those in the previous set plus those of the newest binding after the defined variables of the previous set have been removed. @rnMethodBinds@ deals only with the declarations in class and instance declarations. It expects only to see @FunMonoBind@s, and it expects the global environment to contain bindings for the binders (which are all class operations). ************************************************************************ * * \subsubsection{ Top-level bindings} * * ************************************************************************ -} -- for top-level bindings, we need to make top-level names, -- so we have a different entry point than for local bindings rnTopBindsLHS :: MiniFixityEnv -> HsValBinds RdrName -> RnM (HsValBindsLR Name RdrName) rnTopBindsLHS fix_env binds = do binds' <- rnValBindsLHS (topRecNameMaker fix_env) binds checkSimilarNames binds' return binds' isPatSynBind :: HsBindLR l r -> Bool isPatSynBind (PatSynBind _) = True isPatSynBind _ = False checkSimilarNames :: HsValBindsLR Name RdrName -> RnM () checkSimilarNames (ValBindsIn mbinds _) = do { let { (patSyns, others) = partitionBag (isPatSynBind . unLoc) mbinds } ; checkBinds patSyns ; checkBinds others } where checkBinds binds = do { let { bndrs = collectHsBindsBinders binds ; val_avails = map Avail bndrs ; similar_names = (findSames val_avails) } ; when (not (null similar_names)) (addSimDeclErrors similar_names) } checkSimilarNames b = pprPanic "checkSimilarNames" (ppr b) rnTopBindsRHS :: NameSet -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnTopBindsRHS bound_names binds = do { is_boot <- tcIsHsBootOrSig ; if is_boot then rnTopBindsBoot binds else rnValBindsRHS (TopSigCtxt bound_names False) binds } rnTopBindsBoot :: HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) -- A hs-boot file has no bindings. -- Return a single HsBindGroup with empty binds and renamed signatures rnTopBindsBoot (ValBindsIn mbinds sigs) = do { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds) ; (sigs', fvs) <- renameSigs HsBootCtxt sigs ; return (ValBindsOut [] sigs', usesOnly fvs) } rnTopBindsBoot b = pprPanic "rnTopBindsBoot" (ppr b) {- ********************************************************* * * HsLocalBinds * * ********************************************************* -} rnLocalBindsAndThen :: HsLocalBinds RdrName -> (HsLocalBinds Name -> RnM (result, FreeVars)) -> RnM (result, FreeVars) -- This version (a) assumes that the binding vars are *not* already in scope -- (b) removes the binders from the free vars of the thing inside -- The parser doesn't produce ThenBinds rnLocalBindsAndThen EmptyLocalBinds thing_inside = thing_inside EmptyLocalBinds rnLocalBindsAndThen (HsValBinds val_binds) thing_inside = rnLocalValBindsAndThen val_binds $ \ val_binds' -> thing_inside (HsValBinds val_binds') rnLocalBindsAndThen (HsIPBinds binds) thing_inside = do (binds',fv_binds) <- rnIPBinds binds (thing, fvs_thing) <- thing_inside (HsIPBinds binds') return (thing, fvs_thing `plusFV` fv_binds) rnIPBinds :: HsIPBinds RdrName -> RnM (HsIPBinds Name, FreeVars) rnIPBinds (IPBinds ip_binds _no_dict_binds) = do (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds return (IPBinds ip_binds' emptyTcEvBinds, plusFVs fvs_s) rnIPBind :: IPBind RdrName -> RnM (IPBind Name, FreeVars) rnIPBind (IPBind ~(Left n) expr) = do (expr',fvExpr) <- rnLExpr expr return (IPBind (Left n) expr', fvExpr) {- ************************************************************************ * * ValBinds * * ************************************************************************ -} -- Renaming local binding groups -- Does duplicate/shadow check rnLocalValBindsLHS :: MiniFixityEnv -> HsValBinds RdrName -> RnM ([Name], HsValBindsLR Name RdrName) rnLocalValBindsLHS fix_env binds = do { binds' <- rnValBindsLHS (localRecNameMaker fix_env) binds -- Check for duplicates and shadowing -- Must do this *after* renaming the patterns -- See Note [Collect binders only after renaming] in HsUtils -- We need to check for dups here because we -- don't don't bind all of the variables from the ValBinds at once -- with bindLocatedLocals any more. -- -- Note that we don't want to do this at the top level, since -- sorting out duplicates and shadowing there happens elsewhere. -- The behavior is even different. For example, -- import A(f) -- f = ... -- should not produce a shadowing warning (but it will produce -- an ambiguity warning if you use f), but -- import A(f) -- g = let f = ... in f -- should. ; let bound_names = collectHsValBinders binds' -- There should be only Ids, but if there are any bogus -- pattern synonyms, we'll collect them anyway, so that -- we don't generate subsequent out-of-scope messages ; envs <- getRdrEnvs ; checkDupAndShadowedNames envs bound_names ; return (bound_names, binds') } -- renames the left-hand sides -- generic version used both at the top level and for local binds -- does some error checking, but not what gets done elsewhere at the top level rnValBindsLHS :: NameMaker -> HsValBinds RdrName -> RnM (HsValBindsLR Name RdrName) rnValBindsLHS topP (ValBindsIn mbinds sigs) = do { mbinds' <- mapBagM (wrapLocM (rnBindLHS topP doc)) mbinds ; return $ ValBindsIn mbinds' sigs } where bndrs = collectHsBindsBinders mbinds doc = text "In the binding group for:" <+> pprWithCommas ppr bndrs rnValBindsLHS _ b = pprPanic "rnValBindsLHSFromDoc" (ppr b) -- General version used both from the top-level and for local things -- Assumes the LHS vars are in scope -- -- Does not bind the local fixity declarations rnValBindsRHS :: HsSigCtxt -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnValBindsRHS ctxt (ValBindsIn mbinds sigs) = do { (sigs', sig_fvs) <- renameSigs ctxt sigs ; binds_w_dus <- mapBagM (rnLBind (mkSigTvFn sigs')) mbinds ; case depAnalBinds binds_w_dus of (anal_binds, anal_dus) -> return (valbind', valbind'_dus) where valbind' = ValBindsOut anal_binds sigs' valbind'_dus = anal_dus `plusDU` usesOnly sig_fvs -- Put the sig uses *after* the bindings -- so that the binders are removed from -- the uses in the sigs } rnValBindsRHS _ b = pprPanic "rnValBindsRHS" (ppr b) -- Wrapper for local binds -- -- The *client* of this function is responsible for checking for unused binders; -- it doesn't (and can't: we don't have the thing inside the binds) happen here -- -- The client is also responsible for bringing the fixities into scope rnLocalValBindsRHS :: NameSet -- names bound by the LHSes -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnLocalValBindsRHS bound_names binds = rnValBindsRHS (LocalBindCtxt bound_names) binds -- for local binds -- wrapper that does both the left- and right-hand sides -- -- here there are no local fixity decls passed in; -- the local fixity decls come from the ValBinds sigs rnLocalValBindsAndThen :: HsValBinds RdrName -> (HsValBinds Name -> RnM (result, FreeVars)) -> RnM (result, FreeVars) rnLocalValBindsAndThen binds@(ValBindsIn _ sigs) thing_inside = do { -- (A) Create the local fixity environment new_fixities <- makeMiniFixityEnv [L loc sig | L loc (FixSig sig) <- sigs] -- (B) Rename the LHSes ; (bound_names, new_lhs) <- rnLocalValBindsLHS new_fixities binds -- ...and bring them (and their fixities) into scope ; bindLocalNamesFV bound_names $ addLocalFixities new_fixities bound_names $ do { -- (C) Do the RHS and thing inside (binds', dus) <- rnLocalValBindsRHS (mkNameSet bound_names) new_lhs ; (result, result_fvs) <- thing_inside binds' -- Report unused bindings based on the (accurate) -- findUses. E.g. -- let x = x in 3 -- should report 'x' unused ; let real_uses = findUses dus result_fvs -- Insert fake uses for variables introduced implicitly by -- wildcards (#4404) implicit_uses = hsValBindsImplicits binds' ; warnUnusedLocalBinds bound_names (real_uses `unionNameSet` implicit_uses) ; let -- The variables "used" in the val binds are: -- (1) the uses of the binds (allUses) -- (2) the FVs of the thing-inside all_uses = allUses dus `plusFV` result_fvs -- Note [Unused binding hack] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Note that *in contrast* to the above reporting of -- unused bindings, (1) above uses duUses to return *all* -- the uses, even if the binding is unused. Otherwise consider: -- x = 3 -- y = let p = x in 'x' -- NB: p not used -- If we don't "see" the dependency of 'y' on 'x', we may put the -- bindings in the wrong order, and the type checker will complain -- that x isn't in scope -- -- But note that this means we won't report 'x' as unused, -- whereas we would if we had { x = 3; p = x; y = 'x' } ; return (result, all_uses) }} -- The bound names are pruned out of all_uses -- by the bindLocalNamesFV call above rnLocalValBindsAndThen bs _ = pprPanic "rnLocalValBindsAndThen" (ppr bs) -- Process the fixity declarations, making a FastString -> (Located Fixity) map -- (We keep the location around for reporting duplicate fixity declarations.) -- -- Checks for duplicates, but not that only locally defined things are fixed. -- Note: for local fixity declarations, duplicates would also be checked in -- check_sigs below. But we also use this function at the top level. makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv makeMiniFixityEnv decls = foldlM add_one_sig emptyFsEnv decls where add_one_sig env (L loc (FixitySig names fixity)) = foldlM add_one env [ (loc,name_loc,name,fixity) | L name_loc name <- names ] add_one env (loc, name_loc, name,fixity) = do { -- this fixity decl is a duplicate iff -- the ReaderName's OccName's FastString is already in the env -- (we only need to check the local fix_env because -- definitions of non-local will be caught elsewhere) let { fs = occNameFS (rdrNameOcc name) ; fix_item = L loc fixity }; case lookupFsEnv env fs of Nothing -> return $ extendFsEnv env fs fix_item Just (L loc' _) -> do { setSrcSpan loc $ addErrAt name_loc (dupFixityDecl loc' name) ; return env} } dupFixityDecl :: SrcSpan -> RdrName -> SDoc dupFixityDecl loc rdr_name = vcat [ptext (sLit "Multiple fixity declarations for") <+> quotes (ppr rdr_name), ptext (sLit "also at ") <+> ppr loc] --------------------- -- renaming a single bind rnBindLHS :: NameMaker -> SDoc -> HsBind RdrName -- returns the renamed left-hand side, -- and the FreeVars *of the LHS* -- (i.e., any free variables of the pattern) -> RnM (HsBindLR Name RdrName) rnBindLHS name_maker _ bind@(PatBind { pat_lhs = pat }) = do -- we don't actually use the FV processing of rnPatsAndThen here (pat',pat'_fvs) <- rnBindPat name_maker pat return (bind { pat_lhs = pat', bind_fvs = pat'_fvs }) -- We temporarily store the pat's FVs in bind_fvs; -- gets updated to the FVs of the whole bind -- when doing the RHS below rnBindLHS name_maker _ bind@(FunBind { fun_id = rdr_name }) = do { name <- applyNameMaker name_maker rdr_name ; return (bind { fun_id = name , bind_fvs = placeHolderNamesTc }) } rnBindLHS name_maker _ (PatSynBind psb@PSB{ psb_id = rdrname }) | isTopRecNameMaker name_maker = do { addLocM checkConName rdrname ; name <- lookupLocatedTopBndrRn rdrname -- Should be bound at top level already ; return (PatSynBind psb{ psb_id = name }) } | otherwise -- Pattern synonym, not at top level = do { addErr localPatternSynonymErr -- Complain, but make up a fake -- name so that we can carry on ; name <- applyNameMaker name_maker rdrname ; return (PatSynBind psb{ psb_id = name }) } where localPatternSynonymErr :: SDoc localPatternSynonymErr = hang (ptext (sLit "Illegal pattern synonym declaration for") <+> quotes (ppr rdrname)) 2 (ptext (sLit "Pattern synonym declarations are only valid at top level")) rnBindLHS _ _ b = pprPanic "rnBindHS" (ppr b) rnLBind :: (Name -> [Name]) -- Signature tyvar function -> LHsBindLR Name RdrName -> RnM (LHsBind Name, [Name], Uses) rnLBind sig_fn (L loc bind) = setSrcSpan loc $ do { (bind', bndrs, dus) <- rnBind sig_fn bind ; return (L loc bind', bndrs, dus) } -- assumes the left-hands-side vars are in scope rnBind :: (Name -> [Name]) -- Signature tyvar function -> HsBindLR Name RdrName -> RnM (HsBind Name, [Name], Uses) rnBind _ bind@(PatBind { pat_lhs = pat , pat_rhs = grhss -- pat fvs were stored in bind_fvs -- after processing the LHS , bind_fvs = pat_fvs }) = do { mod <- getModule ; (grhss', rhs_fvs) <- rnGRHSs PatBindRhs rnLExpr grhss -- No scoped type variables for pattern bindings ; let all_fvs = pat_fvs `plusFV` rhs_fvs fvs' = filterNameSet (nameIsLocalOrFrom mod) all_fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan bndrs = collectPatBinders pat bind' = bind { pat_rhs = grhss', pat_rhs_ty = placeHolderType, bind_fvs = fvs' } is_wild_pat = case pat of L _ (WildPat {}) -> True L _ (BangPat (L _ (WildPat {}))) -> True -- #9127 _ -> False -- Warn if the pattern binds no variables, except for the -- entirely-explicit idiom _ = rhs -- which (a) is not that different from _v = rhs -- (b) is sometimes used to give a type sig for, -- or an occurrence of, a variable on the RHS ; whenWOptM Opt_WarnUnusedBinds $ when (null bndrs && not is_wild_pat) $ addWarn $ unusedPatBindWarn bind' ; fvs' `seq` -- See Note [Free-variable space leak] return (bind', bndrs, all_fvs) } rnBind sig_fn bind@(FunBind { fun_id = name , fun_infix = is_infix , fun_matches = matches }) -- invariant: no free vars here when it's a FunBind = do { let plain_name = unLoc name ; (matches', rhs_fvs) <- bindSigTyVarsFV (sig_fn plain_name) $ -- bindSigTyVars tests for Opt_ScopedTyVars rnMatchGroup (FunRhs plain_name is_infix) rnLExpr matches ; when is_infix $ checkPrecMatch plain_name matches' ; mod <- getModule ; let fvs' = filterNameSet (nameIsLocalOrFrom mod) rhs_fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan ; fvs' `seq` -- See Note [Free-variable space leak] return (bind { fun_matches = matches' , bind_fvs = fvs' }, [plain_name], rhs_fvs) } rnBind sig_fn (PatSynBind bind) = do { (bind', name, fvs) <- rnPatSynBind sig_fn bind ; return (PatSynBind bind', name, fvs) } rnBind _ b = pprPanic "rnBind" (ppr b) {- Note [Free-variable space leak] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have fvs' = trim fvs and we seq fvs' before turning it as part of a record. The reason is that trim is sometimes something like \xs -> intersectNameSet (mkNameSet bound_names) xs and we don't want to retain the list bound_names. This showed up in trac ticket #1136. -} rnPatSynBind :: (Name -> [Name]) -- Signature tyvar function -> PatSynBind Name RdrName -> RnM (PatSynBind Name Name, [Name], Uses) rnPatSynBind _sig_fn bind@(PSB { psb_id = L _ name , psb_args = details , psb_def = pat , psb_dir = dir }) -- invariant: no free vars here when it's a FunBind = do { pattern_synonym_ok <- xoptM Opt_PatternSynonyms ; unless pattern_synonym_ok (addErr patternSynonymErr) ; ((pat', details'), fvs1) <- rnPat PatSyn pat $ \pat' -> do -- We check the 'RdrName's instead of the 'Name's -- so that the binding locations are reported -- from the left-hand side { (details', fvs) <- case details of PrefixPatSyn vars -> do { checkDupRdrNames vars ; names <- mapM lookupVar vars ; return (PrefixPatSyn names, mkFVs (map unLoc names)) } InfixPatSyn var1 var2 -> do { checkDupRdrNames [var1, var2] ; name1 <- lookupVar var1 ; name2 <- lookupVar var2 -- ; checkPrecMatch -- TODO ; return (InfixPatSyn name1 name2, mkFVs (map unLoc [name1, name2])) } ; return ((pat', details'), fvs) } ; (dir', fvs2) <- case dir of Unidirectional -> return (Unidirectional, emptyFVs) ImplicitBidirectional -> return (ImplicitBidirectional, emptyFVs) ExplicitBidirectional mg -> do { (mg', fvs) <- rnMatchGroup PatSyn rnLExpr mg ; return (ExplicitBidirectional mg', fvs) } ; mod <- getModule ; let fvs = fvs1 `plusFV` fvs2 fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan ; let bind' = bind{ psb_args = details' , psb_def = pat' , psb_dir = dir' , psb_fvs = fvs' } ; fvs' `seq` -- See Note [Free-variable space leak] return (bind', [name], fvs1) -- See Note [Pattern synonym wrappers don't yield dependencies] } where lookupVar = wrapLocM lookupOccRn patternSynonymErr :: SDoc patternSynonymErr = hang (ptext (sLit "Illegal pattern synonym declaration")) 2 (ptext (sLit "Use -XPatternSynonyms to enable this extension")) {- Note [Pattern synonym wrappers don't yield dependencies] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When renaming a pattern synonym that has an explicit wrapper, references in the wrapper definition should not be used when calculating dependencies. For example, consider the following pattern synonym definition: pattern P x <- C1 x where P x = f (C1 x) f (P x) = C2 x In this case, 'P' needs to be typechecked in two passes: 1. Typecheck the pattern definition of 'P', which fully determines the type of 'P'. This step doesn't require knowing anything about 'f', since the wrapper definition is not looked at. 2. Typecheck the wrapper definition, which needs the typechecked definition of 'f' to be in scope. This behaviour is implemented in 'tcValBinds', but it crucially depends on 'P' not being put in a recursive group with 'f' (which would make it look like a recursive pattern synonym a la 'pattern P = P' which is unsound and rejected). -} --------------------- depAnalBinds :: Bag (LHsBind Name, [Name], Uses) -> ([(RecFlag, LHsBinds Name)], DefUses) -- Dependency analysis; this is important so that -- unused-binding reporting is accurate depAnalBinds binds_w_dus = (map get_binds sccs, map get_du sccs) where sccs = depAnal (\(_, defs, _) -> defs) (\(_, _, uses) -> nameSetElems uses) (bagToList binds_w_dus) get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind) get_binds (CyclicSCC binds_w_dus) = (Recursive, listToBag [b | (b,_,_) <- binds_w_dus]) get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses) get_du (CyclicSCC binds_w_dus) = (Just defs, uses) where defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs] uses = unionNameSets [u | (_,_,u) <- binds_w_dus] --------------------- -- Bind the top-level forall'd type variables in the sigs. -- E.g f :: a -> a -- f = rhs -- The 'a' scopes over the rhs -- -- NB: there'll usually be just one (for a function binding) -- but if there are many, one may shadow the rest; too bad! -- e.g x :: [a] -> [a] -- y :: [(a,a)] -> a -- (x,y) = e -- In e, 'a' will be in scope, and it'll be the one from 'y'! mkSigTvFn :: [LSig Name] -> (Name -> [Name]) -- Return a lookup function that maps an Id Name to the names -- of the type variables that should scope over its body.. mkSigTvFn sigs = \n -> lookupNameEnv env n `orElse` [] where extractScopedTyVars :: LHsType Name -> [Name] extractScopedTyVars (L _ (HsForAllTy Explicit _ ltvs _ _)) = hsLKiTyVarNames ltvs extractScopedTyVars _ = [] env :: NameEnv [Name] env = mkNameEnv [ (name, nwcs ++ extractScopedTyVars ty) -- Kind variables and type variables | L _ (TypeSig names ty nwcs) <- sigs , L _ name <- names] -- Note the pattern-match on "Explicit"; we only bind -- type variables from signatures with an explicit top-level for-all {- @rnMethodBinds@ is used for the method bindings of a class and an instance declaration. Like @rnBinds@ but without dependency analysis. NOTA BENE: we record each {\em binder} of a method-bind group as a free variable. That's crucial when dealing with an instance decl: \begin{verbatim} instance Foo (T a) where op x = ... \end{verbatim} This might be the {\em sole} occurrence of @op@ for an imported class @Foo@, and unless @op@ occurs we won't treat the type signature of @op@ in the class decl for @Foo@ as a source of instance-decl gates. But we should! Indeed, in many ways the @op@ in an instance decl is just like an occurrence, not a binder. -} rnMethodBinds :: Name -- Class name -> (Name -> [Name]) -- Signature tyvar function -> LHsBinds RdrName -> RnM (LHsBinds Name, FreeVars) rnMethodBinds cls sig_fn binds = do { checkDupRdrNames meth_names -- Check that the same method is not given twice in the -- same instance decl instance C T where -- f x = ... -- g y = ... -- f x = ... -- We must use checkDupRdrNames because the Name of the -- method is the Name of the class selector, whose SrcSpan -- points to the class declaration; and we use rnMethodBinds -- for instance decls too ; foldlM do_one (emptyBag, emptyFVs) (bagToList binds) } where meth_names = collectMethodBinders binds do_one (binds,fvs) bind = do { (bind', fvs_bind) <- rnMethodBind cls sig_fn bind ; return (binds `unionBags` bind', fvs_bind `plusFV` fvs) } rnMethodBind :: Name -> (Name -> [Name]) -> LHsBindLR RdrName RdrName -> RnM (Bag (LHsBindLR Name Name), FreeVars) rnMethodBind cls sig_fn (L loc bind@(FunBind { fun_id = name, fun_infix = is_infix , fun_matches = MG { mg_alts = matches , mg_origin = origin } })) = setSrcSpan loc $ do sel_name <- wrapLocM (lookupInstDeclBndr cls (ptext (sLit "method"))) name let plain_name = unLoc sel_name -- We use the selector name as the binder (new_matches, fvs) <- bindSigTyVarsFV (sig_fn plain_name) $ mapFvRn (rnMatch (FunRhs plain_name is_infix) rnLExpr) matches let new_group = mkMatchGroupName origin new_matches when is_infix $ checkPrecMatch plain_name new_group return (unitBag (L loc (bind { fun_id = sel_name , fun_matches = new_group , bind_fvs = fvs })), fvs `addOneFV` plain_name) -- The 'fvs' field isn't used for method binds -- Can't handle method pattern-bindings which bind multiple methods. rnMethodBind _ _ (L loc bind@(PatBind {})) = do addErrAt loc (methodBindErr bind) return (emptyBag, emptyFVs) -- Associated pattern synonyms are not implemented yet rnMethodBind _ _ (L loc bind@(PatSynBind {})) = do addErrAt loc $ methodPatSynErr bind return (emptyBag, emptyFVs) rnMethodBind _ _ b = pprPanic "rnMethodBind" (ppr b) {- ************************************************************************ * * \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)} * * ************************************************************************ @renameSigs@ checks for: \begin{enumerate} \item more than one sig for one thing; \item signatures given for things not bound here; \end{enumerate} At the moment we don't gather free-var info from the types in signatures. We'd only need this if we wanted to report unused tyvars. -} renameSigs :: HsSigCtxt -> [LSig RdrName] -> RnM ([LSig Name], FreeVars) -- Renames the signatures and performs error checks renameSigs ctxt sigs = do { mapM_ dupSigDeclErr (findDupSigs sigs) ; checkDupMinimalSigs sigs ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs' ; mapM_ misplacedSigErr bad_sigs -- Misplaced ; return (good_sigs, sig_fvs) } ---------------------- -- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory -- because this won't work for: -- instance Foo T where -- {-# INLINE op #-} -- Baz.op = ... -- We'll just rename the INLINE prag to refer to whatever other 'op' -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.) -- Doesn't seem worth much trouble to sort this. renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars) -- FixitySig is renamed elsewhere. renameSig _ (IdSig x) = return (IdSig x, emptyFVs) -- Actually this never occurs renameSig ctxt sig@(TypeSig vs ty _) = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs -- (named and anonymous) wildcards are bound here. ; (wcs, ty') <- extractWildcards ty ; bindLocatedLocalsFV wcs $ \wcs_new -> do { (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty' ; return (TypeSig new_vs new_ty wcs_new, fvs) } } renameSig ctxt sig@(GenericSig vs ty) = do { defaultSigs_on <- xoptM Opt_DefaultSignatures ; unless defaultSigs_on (addErr (defaultSigErr sig)) ; new_v <- mapM (lookupSigOccRn ctxt sig) vs ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty ; return (GenericSig new_v new_ty, fvs) } renameSig _ (SpecInstSig src ty) = do { (new_ty, fvs) <- rnLHsType SpecInstSigCtx ty ; return (SpecInstSig src new_ty,fvs) } -- {-# SPECIALISE #-} pragmas can refer to imported Ids -- so, in the top-level case (when mb_names is Nothing) -- we use lookupOccRn. If there's both an imported and a local 'f' -- then the SPECIALISE pragma is ambiguous, unlike all other signatures renameSig ctxt sig@(SpecSig v tys inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v _ -> lookupSigOccRn ctxt sig v -- ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys ; return (SpecSig new_v new_ty inl, fvs) } where do_one (tys,fvs) ty = do { (new_ty, fvs_ty) <- rnHsSigType (quotes (ppr v)) ty ; return ( new_ty:tys, fvs_ty `plusFV` fvs) } renameSig ctxt sig@(InlineSig v s) = do { new_v <- lookupSigOccRn ctxt sig v ; return (InlineSig new_v s, emptyFVs) } renameSig ctxt sig@(FixSig (FixitySig vs f)) = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs ; return (FixSig (FixitySig new_vs f), emptyFVs) } renameSig ctxt sig@(MinimalSig s bf) = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf return (MinimalSig s new_bf, emptyFVs) renameSig ctxt sig@(PatSynSig v (flag, qtvs) prov req ty) = do { v' <- lookupSigOccRn ctxt sig v ; let doc = TypeSigCtx $ quotes (ppr v) ; loc <- getSrcSpanM ; let (tv_kvs, mentioned) = extractHsTysRdrTyVars (ty:unLoc prov ++ unLoc req) ; tv_bndrs <- case flag of Implicit -> return $ mkHsQTvs . userHsTyVarBndrs loc $ mentioned Explicit -> do { let heading = ptext (sLit "In the pattern synonym type signature") <+> quotes (ppr sig) ; warnUnusedForAlls (heading $$ docOfHsDocContext doc) qtvs mentioned ; return qtvs } Qualified -> panic "renameSig: Qualified" ; bindHsTyVars doc Nothing tv_kvs tv_bndrs $ \ tyvars -> do { (prov', fvs1) <- rnContext doc prov ; (req', fvs2) <- rnContext doc req ; (ty', fvs3) <- rnLHsType doc ty ; let fvs = plusFVs [fvs1, fvs2, fvs3] ; return (PatSynSig v' (flag, tyvars) prov' req' ty', fvs) }} ppr_sig_bndrs :: [Located RdrName] -> SDoc ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs) okHsSig :: HsSigCtxt -> LSig a -> Bool okHsSig ctxt (L _ sig) = case (sig, ctxt) of (GenericSig {}, ClsDeclCtxt {}) -> True (GenericSig {}, _) -> False (TypeSig {}, _) -> True (PatSynSig {}, TopSigCtxt{}) -> True (PatSynSig {}, _) -> False (FixSig {}, InstDeclCtxt {}) -> False (FixSig {}, _) -> True (IdSig {}, TopSigCtxt {}) -> True (IdSig {}, InstDeclCtxt {}) -> True (IdSig {}, _) -> False (InlineSig {}, HsBootCtxt) -> False (InlineSig {}, _) -> True (SpecSig {}, TopSigCtxt {}) -> True (SpecSig {}, LocalBindCtxt {}) -> True (SpecSig {}, InstDeclCtxt {}) -> True (SpecSig {}, _) -> False (SpecInstSig {}, InstDeclCtxt {}) -> True (SpecInstSig {}, _) -> False (MinimalSig {}, ClsDeclCtxt {}) -> True (MinimalSig {}, _) -> False ------------------- findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]] -- Check for duplicates on RdrName version, -- because renamed version has unboundName for -- not-in-scope binders, which gives bogus dup-sig errors -- NB: in a class decl, a 'generic' sig is not considered -- equal to an ordinary sig, so we allow, say -- class C a where -- op :: a -> a -- default op :: Eq a => a -> a findDupSigs sigs = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs) where expand_sig sig@(FixSig (FixitySig ns _)) = zip ns (repeat sig) expand_sig sig@(InlineSig n _) = [(n,sig)] expand_sig sig@(TypeSig ns _ _) = [(n,sig) | n <- ns] expand_sig sig@(GenericSig ns _) = [(n,sig) | n <- ns] expand_sig _ = [] matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2 mtch (FixSig {}) (FixSig {}) = True mtch (InlineSig {}) (InlineSig {}) = True mtch (TypeSig {}) (TypeSig {}) = True mtch (GenericSig {}) (GenericSig {}) = True mtch _ _ = False -- Warn about multiple MINIMAL signatures checkDupMinimalSigs :: [LSig RdrName] -> RnM () checkDupMinimalSigs sigs = case filter isMinimalLSig sigs of minSigs@(_:_:_) -> dupMinimalSigErr minSigs _ -> return () {- ************************************************************************ * * \subsection{Match} * * ************************************************************************ -} rnMatchGroup :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> MatchGroup RdrName (Located (body RdrName)) -> RnM (MatchGroup Name (Located (body Name)), FreeVars) rnMatchGroup ctxt rnBody (MG { mg_alts = ms, mg_origin = origin }) = do { empty_case_ok <- xoptM Opt_EmptyCase ; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt)) ; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms ; return (mkMatchGroupName origin new_ms, ms_fvs) } rnMatch :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> LMatch RdrName (Located (body RdrName)) -> RnM (LMatch Name (Located (body Name)), FreeVars) rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody) rnMatch' :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> Match RdrName (Located (body RdrName)) -> RnM (Match Name (Located (body Name)), FreeVars) rnMatch' ctxt rnBody match@(Match { m_fun_id_infix = mf, m_pats = pats , m_type = maybe_rhs_sig, m_grhss = grhss }) = do { -- Result type signatures are no longer supported case maybe_rhs_sig of Nothing -> return () Just (L loc ty) -> addErrAt loc (resSigErr ctxt match ty) -- Now the main event -- note that there are no local ficity decls for matches ; rnPats ctxt pats $ \ pats' -> do { (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss ; let mf' = case (ctxt,mf) of (FunRhs funid isinfix,Just (L lf _,_)) -> Just (L lf funid,isinfix) _ -> Nothing ; return (Match { m_fun_id_infix = mf', m_pats = pats' , m_type = Nothing, m_grhss = grhss'}, grhss_fvs ) }} emptyCaseErr :: HsMatchContext Name -> SDoc emptyCaseErr ctxt = hang (ptext (sLit "Empty list of alternatives in") <+> pp_ctxt) 2 (ptext (sLit "Use EmptyCase to allow this")) where pp_ctxt = case ctxt of CaseAlt -> ptext (sLit "case expression") LambdaExpr -> ptext (sLit "\\case expression") _ -> ptext (sLit "(unexpected)") <+> pprMatchContextNoun ctxt resSigErr :: Outputable body => HsMatchContext Name -> Match RdrName body -> HsType RdrName -> SDoc resSigErr ctxt match ty = vcat [ ptext (sLit "Illegal result type signature") <+> quotes (ppr ty) , nest 2 $ ptext (sLit "Result signatures are no longer supported in pattern matches") , pprMatchInCtxt ctxt match ] {- ************************************************************************ * * \subsubsection{Guarded right-hand sides (GRHSs)} * * ************************************************************************ -} rnGRHSs :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> GRHSs RdrName (Located (body RdrName)) -> RnM (GRHSs Name (Located (body Name)), FreeVars) rnGRHSs ctxt rnBody (GRHSs grhss binds) = rnLocalBindsAndThen binds $ \ binds' -> do (grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss return (GRHSs grhss' binds', fvGRHSs) rnGRHS :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> LGRHS RdrName (Located (body RdrName)) -> RnM (LGRHS Name (Located (body Name)), FreeVars) rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody) rnGRHS' :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> GRHS RdrName (Located (body RdrName)) -> RnM (GRHS Name (Located (body Name)), FreeVars) rnGRHS' ctxt rnBody (GRHS guards rhs) = do { pattern_guards_allowed <- xoptM Opt_PatternGuards ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ -> rnBody rhs ; unless (pattern_guards_allowed || is_standard_guard guards') (addWarn (nonStdGuardErr guards')) ; return (GRHS guards' rhs', fvs) } where -- Standard Haskell 1.4 guards are just a single boolean -- expression, rather than a list of qualifiers as in the -- Glasgow extension is_standard_guard [] = True is_standard_guard [L _ (BodyStmt _ _ _ _)] = True is_standard_guard _ = False {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} dupSigDeclErr :: [(Located RdrName, Sig RdrName)] -> RnM () dupSigDeclErr pairs@((L loc name, sig) : _) = addErrAt loc $ vcat [ ptext (sLit "Duplicate") <+> what_it_is <> ptext (sLit "s for") <+> quotes (ppr name) , ptext (sLit "at") <+> vcat (map ppr $ sort $ map (getLoc . fst) pairs) ] where what_it_is = hsSigDoc sig dupSigDeclErr [] = panic "dupSigDeclErr" misplacedSigErr :: LSig Name -> RnM () misplacedSigErr (L loc sig) = addErrAt loc $ sep [ptext (sLit "Misplaced") <+> hsSigDoc sig <> colon, ppr sig] defaultSigErr :: Sig RdrName -> SDoc defaultSigErr sig = vcat [ hang (ptext (sLit "Unexpected default signature:")) 2 (ppr sig) , ptext (sLit "Use DefaultSignatures to enable default signatures") ] methodBindErr :: HsBindLR RdrName RdrName -> SDoc methodBindErr mbind = hang (ptext (sLit "Pattern bindings (except simple variables) not allowed in instance declarations")) 2 (ppr mbind) methodPatSynErr :: HsBindLR RdrName RdrName -> SDoc methodPatSynErr mbind = hang (ptext (sLit "Pattern synonyms not allowed in class/instance declarations")) 2 (ppr mbind) bindsInHsBootFile :: LHsBindsLR Name RdrName -> SDoc bindsInHsBootFile mbinds = hang (ptext (sLit "Bindings in hs-boot files are not allowed")) 2 (ppr mbinds) nonStdGuardErr :: Outputable body => [LStmtLR Name Name body] -> SDoc nonStdGuardErr guards = hang (ptext (sLit "accepting non-standard pattern guards (use PatternGuards to suppress this message)")) 4 (interpp'SP guards) unusedPatBindWarn :: HsBind Name -> SDoc unusedPatBindWarn bind = hang (ptext (sLit "This pattern-binding binds no variables:")) 2 (ppr bind) dupMinimalSigErr :: [LSig RdrName] -> RnM () dupMinimalSigErr sigs@(L loc _ : _) = addErrAt loc $ vcat [ ptext (sLit "Multiple minimal complete definitions") , ptext (sLit "at") <+> vcat (map ppr $ sort $ map getLoc sigs) , ptext (sLit "Combine alternative minimal complete definitions with `|'") ] dupMinimalSigErr [] = panic "dupMinimalSigErr"
pparkkin/eta
compiler/ETA/Rename/RnBinds.hs
Haskell
bsd-3-clause
47,418
----------------------------------------------------------------------------- -- | -- Module : Plugins.Monitors.Disk -- Copyright : (c) 2010, 2011, 2012 Jose A Ortega Ruiz -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- Disk usage and throughput monitors for Xmobar -- ----------------------------------------------------------------------------- module Plugins.Monitors.Disk (diskUConfig, runDiskU, startDiskIO) where import Plugins.Monitors.Common import StatFS import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Control.Exception (SomeException, handle) import Control.Monad (zipWithM) import qualified Data.ByteString.Lazy.Char8 as B import Data.List (isPrefixOf, find) import System.Directory (canonicalizePath) diskIOConfig :: IO MConfig diskIOConfig = mkMConfig "" ["total", "read", "write", "totalbar", "readbar", "writebar"] diskUConfig :: IO MConfig diskUConfig = mkMConfig "" ["size", "free", "used", "freep", "usedp", "freebar", "usedbar"] type DevName = String type Path = String type DevDataRef = IORef [(DevName, [Float])] mountedDevices :: [String] -> IO [(DevName, Path)] mountedDevices req = do s <- B.readFile "/etc/mtab" parse `fmap` mapM canon (devs s) where canon (d, p) = do {d' <- canonicalizePath d; return (d', p)} devs = filter isDev . map (firstTwo . B.words) . B.lines parse = map undev . filter isReq firstTwo (a:b:_) = (B.unpack a, B.unpack b) firstTwo _ = ("", "") isDev (d, _) = "/dev/" `isPrefixOf` d isReq (d, p) = p `elem` req || drop 5 d `elem` req undev (d, f) = (drop 5 d, f) diskDevices :: [String] -> IO [(DevName, Path)] diskDevices req = do s <- B.readFile "/proc/diskstats" parse `fmap` mapM canon (devs s) where canon (d, p) = do {d' <- canonicalizePath (d); return (d', p)} devs = map (third . B.words) . B.lines parse = map undev . filter isReq third (_:_:c:_) = ("/dev/" ++ (B.unpack c), B.unpack c) third _ = ("", "") isReq (d, p) = p `elem` req || drop 5 d `elem` req undev (d, f) = (drop 5 d, f) mountedOrDiskDevices :: [String] -> IO [(DevName, Path)] mountedOrDiskDevices req = do mnt <- mountedDevices req case mnt of [] -> diskDevices req other -> return other diskData :: IO [(DevName, [Float])] diskData = do s <- B.readFile "/proc/diskstats" let extract ws = (head ws, map read (tail ws)) return $ map (extract . map B.unpack . drop 2 . B.words) (B.lines s) mountedData :: DevDataRef -> [DevName] -> IO [(DevName, [Float])] mountedData dref devs = do dt <- readIORef dref dt' <- diskData writeIORef dref dt' return $ map (parseDev (zipWith diff dt' dt)) devs where diff (dev, xs) (_, ys) = (dev, zipWith (-) xs ys) parseDev :: [(DevName, [Float])] -> DevName -> (DevName, [Float]) parseDev dat dev = case find ((==dev) . fst) dat of Nothing -> (dev, [0, 0, 0]) Just (_, xs) -> let rSp = speed (xs !! 2) (xs !! 3) wSp = speed (xs !! 6) (xs !! 7) sp = speed (xs !! 2 + xs !! 6) (xs !! 3 + xs !! 7) speed x t = if t == 0 then 0 else 500 * x / t dat' = if length xs > 6 then [sp, rSp, wSp] else [0, 0, 0] in (dev, dat') speedToStr :: Float -> String speedToStr = showWithUnits 2 1 sizeToStr :: Integer -> String sizeToStr = showWithUnits 3 0 . fromIntegral findTempl :: DevName -> Path -> [(String, String)] -> String findTempl dev path disks = case find devOrPath disks of Just (_, t) -> t Nothing -> "" where devOrPath (d, _) = d == dev || d == path devTemplates :: [(String, String)] -> [(DevName, Path)] -> [(DevName, [Float])] -> [(String, [Float])] devTemplates disks mounted dat = map (\(d, p) -> (findTempl d p disks, findData d)) mounted where findData dev = case find ((==dev) . fst) dat of Nothing -> [0, 0, 0] Just (_, xs) -> xs runDiskIO' :: (String, [Float]) -> Monitor String runDiskIO' (tmp, xs) = do s <- mapM (showWithColors speedToStr) xs b <- mapM (showLogBar 0.8) xs setConfigValue tmp template parseTemplate $ s ++ b runDiskIO :: DevDataRef -> [(String, String)] -> [String] -> Monitor String runDiskIO dref disks _ = do dev <- io $ mountedOrDiskDevices (map fst disks) dat <- io $ mountedData dref (map fst dev) strs <- mapM runDiskIO' $ devTemplates disks dev dat return $ unwords strs startDiskIO :: [(String, String)] -> [String] -> Int -> (String -> IO ()) -> IO () startDiskIO disks args rate cb = do dev <- mountedOrDiskDevices (map fst disks) dref <- newIORef (map (\d -> (fst d, repeat 0)) dev) _ <- mountedData dref (map fst dev) runM args diskIOConfig (runDiskIO dref disks) rate cb fsStats :: String -> IO [Integer] fsStats path = do stats <- getFileSystemStats path case stats of Nothing -> return [0, 0, 0] Just f -> let tot = fsStatByteCount f free = fsStatBytesAvailable f used = fsStatBytesUsed f in return [tot, free, used] runDiskU' :: String -> String -> Monitor String runDiskU' tmp path = do setConfigValue tmp template [total, free, diff] <- io (handle ign $ fsStats path) let strs = map sizeToStr [total, free, diff] freep = if total > 0 then free * 100 `div` total else 0 fr = fromIntegral freep / 100 s <- zipWithM showWithColors' strs [100, freep, 100 - freep] sp <- showPercentsWithColors [fr, 1 - fr] fb <- showPercentBar (fromIntegral freep) fr ub <- showPercentBar (fromIntegral $ 100 - freep) (1 - fr) parseTemplate $ s ++ sp ++ [fb, ub] where ign = const (return [0, 0, 0]) :: SomeException -> IO [Integer] runDiskU :: [(String, String)] -> [String] -> Monitor String runDiskU disks _ = do devs <- io $ mountedDevices (map fst disks) strs <- mapM (\(d, p) -> runDiskU' (findTempl d p disks) p) devs return $ unwords strs
tsiliakis/xmobar
src/Plugins/Monitors/Disk.hs
Haskell
bsd-3-clause
6,056
module Core.Prelude where import Core.Data import Core.Syntax import Utilities lam :: Var -> Term -> Term lam = lambda int :: Integer -> Term int = literal . Int char :: Char -> Term char = literal . Char add :: Term -> Term -> Term add e1 e2 = primOp Add [e1, e2] nilDataCon, consDataCon :: DataCon nilDataCon = "[]" consDataCon = "(:)" nil :: Term nil = data_ nilDataCon [] cons :: Var -> Var -> Term cons x xs = data_ consDataCon [x, xs] trueDataCon, falseDataCon :: DataCon trueDataCon = "True" falseDataCon = "False" true, false :: Term true = data_ trueDataCon [] false = data_ falseDataCon [] if_ :: Term -> Term -> Term -> Term if_ e et ef = case_ e [(DataAlt trueDataCon [], et), (DataAlt falseDataCon [], ef)] bool :: Bool -> Term bool x = if x then true else false nothingDataCon, justDataCon :: DataCon nothingDataCon = "Nothing" justDataCon = "Just" nothing :: Term nothing = data_ nothingDataCon [] just :: Var -> Term just x = data_ justDataCon [x] jDataCon, sDataCon :: DataCon jDataCon = "J#" sDataCon = "S#" j_, s_ :: Var -> Term j_ x = data_ jDataCon [x] s_ x = data_ sDataCon [x] tupleDataCon :: Int -> Maybe DataCon tupleDataCon 1 = Nothing tupleDataCon n = Just $ '(' : replicate (n - 1) ',' ++ ")" unitDataCon, pairDataCon :: DataCon unitDataCon = fromJust $ tupleDataCon 0 pairDataCon = fromJust $ tupleDataCon 2 unit :: Term unit = tuple [] tuple :: [Var] -> Term tuple xs = case tupleDataCon (length xs) of Nothing -> var (expectHead "tuple" xs); Just dc -> data_ dc xs
batterseapower/chsc
Core/Prelude.hs
Haskell
bsd-3-clause
1,525
{-# language TypeInType, ScopedTypeVariables #-} module Silly where import Type.Reflection (Typeable, typeRep, TypeRep) import Type.Reflection.Unsafe (mkTrApp) import GHC.Exts (TYPE, RuntimeRep (..)) import Data.Kind (Type) mkTrFun :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep) (a :: TYPE r1) (b :: TYPE r2). TypeRep a -> TypeRep b -> TypeRep ((a -> b) :: Type) mkTrFun a b = typeRep `mkTrApp` a `mkTrApp` b -- originally reported that there was no (Typeable LiftedRep) instance, -- presumably to overeager RuntimeRep defaulting
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T16627.hs
Haskell
bsd-3-clause
562
<?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="ko-KR"> <title>FuzzDB Files</title> <maps> <homeID>fuzzdb</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/fuzzdb/src/main/javahelp/help_ko_KR/helpset_ko_KR.hs
Haskell
apache-2.0
960
-- Check that the record selector for maskMB unfolds in the body of f -- At one stage it didn't because the implicit unfolding looked too big -- #2581 module ShouldCompile where import Data.Array.Base data MBloom s a = MB { shiftMB :: {-# UNPACK #-} !Int , maskMB :: {-# UNPACK #-} !Int , bitArrayMB :: {-# UNPACK #-} !(STUArray s Int Int) } f a b c = case maskMB (MB a b c) of 3 -> True _ -> False
sdiehl/ghc
testsuite/tests/eyeball/record1.hs
Haskell
bsd-3-clause
444
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving #-} module Distribution.Server.Features.Search.TermBag ( TermId, TermBag, size, fromList, elems, termCount, ) where import Distribution.Server.Framework.MemSize import qualified Data.Vector.Unboxed as Vec import qualified Data.Map as Map import Data.Word (Word32) import Data.Bits newtype TermId = TermId Word32 deriving (Eq, Ord, Show, Enum, MemSize) instance Bounded TermId where minBound = TermId 0 maxBound = TermId 0x00FFFFFF data TermBag = TermBag !Int !(Vec.Vector TermIdAndCount) deriving Show -- We sneakily stuff both the TermId and the bag count into one 32bit word type TermIdAndCount = Word32 -- Bottom 24 bits is the TermId, top 8 bits is the bag count termIdAndCount :: TermId -> Int -> TermIdAndCount termIdAndCount (TermId termid) freq = (min (fromIntegral freq) 255 `shiftL` 24) .|. (termid .&. 0x00FFFFFF) getTermId :: TermIdAndCount -> TermId getTermId word = TermId (word .&. 0x00FFFFFF) getTermCount :: TermIdAndCount -> Int getTermCount word = fromIntegral (word `shiftR` 24) size :: TermBag -> Int size (TermBag sz _) = sz elems :: TermBag -> [TermId] elems (TermBag _ vec) = map getTermId (Vec.toList vec) termCount :: TermBag -> TermId -> Int termCount (TermBag _ vec) = binarySearch 0 (Vec.length vec - 1) where binarySearch :: Int -> Int -> TermId -> Int binarySearch !a !b !key | a > b = 0 | otherwise = let mid = (a + b) `div` 2 tidAndCount = vec Vec.! mid in case compare key (getTermId tidAndCount) of LT -> binarySearch a (mid-1) key EQ -> getTermCount tidAndCount GT -> binarySearch (mid+1) b key fromList :: [TermId] -> TermBag fromList termids = let bag = Map.fromListWith (+) [ (t, 1) | t <- termids ] sz = Map.foldl' (+) 0 bag vec = Vec.fromListN (Map.size bag) [ termIdAndCount termid freq | (termid, freq) <- Map.toAscList bag ] in TermBag sz vec instance MemSize TermBag where memSize (TermBag _ vec) = 2 + memSizeUVector 2 vec
mpickering/hackage-server
Distribution/Server/Features/Search/TermBag.hs
Haskell
bsd-3-clause
2,174
class Foo a where foo :: Int -> a data Emp = Emp String Int deriving (Eq, Show) data Tmp = Tmp String Int deriving (Eq, Show) instance Foo Emp where foo x = Emp "Permanent" x instance Foo Tmp where foo x = Tmp "Temporary" x test x y = if x == y then True else False x = 42 plus = (20.5+) hola :: (Num a) => a -> String hola 1 = "OK" hola _ = "Not OK" --a = ((1::Num a => a) == (1::Num a => a)) z = 2
gitrookie/functionalcode
code/Haskell/retpoly.hs
Haskell
mit
472
{-# OPTIONS -Wall #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} import qualified Data.List as List import qualified Data.Map.Strict as Map import qualified Data.Maybe as Maybe import Data.Text (Text) import Helpers.Graph (Graph) import qualified Helpers.Graph as Graph import Helpers.Parse import Text.Parsec type Polymer = String main :: IO () main = do (template, rules) <- parseTextIO parser let steps = iterate (insertBetweenPairs rules) template let step = steps !! 10 let counts :: [Int] = List.sort $ Map.elems $ Map.fromListWith (+) $ map (,1) step let answer = last counts - head counts print answer insertBetweenPairs :: Graph Polymer -> Polymer -> Polymer insertBetweenPairs rules template = let pairs = zip template (tail template) in head template : concatMap (\(a, b) -> Maybe.fromJust (Graph.lookupOnly [a, b] rules) ++ [b]) pairs parser :: Parsec Text () (Polymer, Graph Polymer) parser = do template <- polymer <* string "\n\n" rules <- Graph.directedGraph <$> rule `endBy` string "\n" return (template, rules) where polymer = many1 letter rule = do start <- polymer _ <- string " -> " end <- polymer return (start, end)
SamirTalwar/advent-of-code
2021/AOC_14_1.hs
Haskell
mit
1,226
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module ProducerExample where import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Exception (bracket) import Control.Monad (forM_) import Control.Monad.IO.Class (MonadIO(..)) import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack) import Kafka.Consumer (Offset) import Kafka.Producer import Data.Text (Text) -- Global producer properties producerProps :: ProducerProperties producerProps = brokersList ["localhost:9092"] <> sendTimeout (Timeout 10000) <> setCallback (deliveryCallback print) <> logLevel KafkaLogDebug -- Topic to send messages to targetTopic :: TopicName targetTopic = "kafka-client-example-topic" mkMessage :: Maybe ByteString -> Maybe ByteString -> ProducerRecord mkMessage k v = ProducerRecord { prTopic = targetTopic , prPartition = UnassignedPartition , prKey = k , prValue = v } -- Run an example runProducerExample :: IO () runProducerExample = bracket mkProducer clProducer runHandler >>= print where mkProducer = newProducer producerProps clProducer (Left _) = return () clProducer (Right prod) = closeProducer prod runHandler (Left err) = return $ Left err runHandler (Right prod) = sendMessages prod sendMessages :: KafkaProducer -> IO (Either KafkaError ()) sendMessages prod = do putStrLn "Producer is ready, send your messages!" msg1 <- getLine err1 <- produceMessage prod (mkMessage Nothing (Just $ pack msg1)) forM_ err1 print putStrLn "One more time!" msg2 <- getLine err2 <- produceMessage prod (mkMessage (Just "key") (Just $ pack msg2)) forM_ err2 print putStrLn "And the last one..." msg3 <- getLine err3 <- produceMessage prod (mkMessage (Just "key3") (Just $ pack msg3)) -- errs <- produceMessageBatch prod -- [ mkMessage (Just "b-1") (Just "batch-1") -- , mkMessage (Just "b-2") (Just "batch-2") -- , mkMessage Nothing (Just "batch-3") -- ] -- forM_ errs (print . snd) putStrLn "Thank you." return $ Right () -- | An example for sending messages synchronously using the 'produceMessage'' -- function -- sendMessageSync :: MonadIO m => KafkaProducer -> ProducerRecord -> m (Either KafkaError Offset) sendMessageSync producer record = liftIO $ do -- Create an empty MVar: var <- newEmptyMVar -- Produce the message and use the callback to put the delivery report in the -- MVar: res <- produceMessage' producer record (putMVar var) case res of Left (ImmediateError err) -> pure (Left err) Right () -> do -- Flush producer queue to make sure you don't get stuck waiting for the -- message to send: flushProducer producer -- Wait for the message's delivery report and map accordingly: takeMVar var >>= return . \case DeliverySuccess _ offset -> Right offset DeliveryFailure _ err -> Left err NoMessageError err -> Left err
haskell-works/kafka-client
example/ProducerExample.hs
Haskell
mit
3,229
module Main where import Test.QuickCheck import Test.QuickCheck.Gen (oneof) -- Trivial data Trivial = Trivial deriving (Eq, Show) trivialGen :: Gen Trivial trivialGen = return Trivial instance Arbitrary Trivial where arbitrary = trivialGen -- Identity data Identity a = Identity a deriving (Eq, Show) instance Arbitrary a => Arbitrary (Identity a) where arbitrary = identityGen identityGen :: Arbitrary a => Gen (Identity a) identityGen = do a <- arbitrary return (Identity a) identityGenInt :: Gen (Identity Int) identityGenInt = identityGen data Pair a b = Pair a b deriving (Eq, Show) pairGen :: (Arbitrary a, Arbitrary b) => Gen (Pair a b) pairGen = do a <- arbitrary b <- arbitrary return (Pair a b) instance (Arbitrary a, Arbitrary b) => Arbitrary (Pair a b) where arbitrary = pairGen pairGenIntString :: Gen (Pair Int String) pairGenIntString = pairGen data Sum a b = First a | Second b deriving (Eq,Show) sumGenEqual :: (Arbitrary a, Arbitrary b) => Gen (Sum a b) sumGenEqual = do a <- arbitrary b <- arbitrary oneof [return $ First a, return $ Second b] sumGenCharInt :: Gen (Sum Char Int) sumGenCharInt = sumGenEqual -- Let's leave it for now -- instance (Arbitrary a, -- Arbitrary b) => -- Gen (Sum a b) -- arbitrary = sumGenEqual -- Here we use the same idea as in Bounded class. sumGenFirstPls :: (Arbitrary a, Arbitrary b) => Gen (Sum a b) sumGenFirstPls = do a <- arbitrary b <- arbitrary frequency [(10, return $ First a), (1, return $ Second b)] sumGenCharIntFirst :: Gen (Sum Char Int) sumGenCharIntFirst = sumGenFirstPls main :: IO () main = do sample trivialGen
raventid/coursera_learning
haskell/chapter14/kicking-around-quickcheck/app/Main.hs
Haskell
mit
1,802
{- Inductive program synthesis : Agent training Author: Abdul Rahim Nizamani, ITIT, Gothenburg University, Sweden Started: 2013-09-29 Updated: 2013-09-29 -} {-# LANGUAGE DataKinds #-} module Main where import System.Environment (getArgs, getProgName) import Niz import Parsing import Data.Char import Instances import Interpreter import Data.List import Data.Word import Data.Maybe import Language.Haskell.Syntax import Language.Haskell.Parser import qualified Language.Haskell.Pretty as P import System.IO import Haskell import Data.Maybe (isNothing) import Control.Monad (foldM) import Control.Parallel.Strategies import Debug.Trace type Delta = [Axiom] noSrc = SrcLoc "" 0 0 ansatz :: Language -> [HsExp] ansatz "List" = [HsApp (HsVar (UnQual (HsIdent "rev"))) (HsVar (UnQual (HsIdent "x"))), HsApp (HsVar (UnQual (HsIdent "rev"))) (HsList [] )] ansatz "Math" = [--HsApp (HsVar (UnQual (HsIdent "f"))) (HsVar (UnQual (HsIdent "x"))), --HsApp (HsVar (UnQual (HsIdent "f"))) (HsLit (HsInt 0)), --HsApp (HsVar (UnQual (HsIdent "f"))) (HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsSymbol "+"))) (HsLit (HsInt 1))) HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsIdent "g"))) (HsLit (HsInt 0)), HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsIdent "g"))) (HsVar (UnQual (HsIdent "y"))), HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsIdent "g"))) (HsInfixApp (HsVar (UnQual (HsIdent "y"))) (HsQVarOp (UnQual (HsSymbol "+"))) (HsLit (HsInt 1))) ] ansatz "Analogy2" = [HsApp (HsVar (UnQual (HsIdent "f"))) (HsVar (UnQual (HsIdent "x")))] ansatz _ = [] langUnits :: Language -> Int -> [HsExp] langUnits "Stream" 1 = [HsVar (UnQual (HsIdent x)) | x <- ["Alice","Plays","Bob","Crawls"]] langUnits "Math" 1 = [HsLit (HsInt x) | x <- [0..9]] --langUnits "Math" 2 = [HsLit (HsInt x) | x <- [10..99]] langUnits "Analogy2" 1 = [HsVar (UnQual (HsIdent "Palm")), HsVar (UnQual (HsIdent "Feet")), HsVar (UnQual (HsIdent "Sole"))] langUnits "List" 1 = [HsList []] langUnits "Clause" 1 = [HsCon (UnQual (HsIdent x)) | x <- ["A","B","C"]] langUnits _ _ = [] langOps :: Language -> Int -> [HsExp] langOps "List" 1 = [HsVar (UnQual (HsIdent "rev"))] langOps "List" 2 = [HsVar (UnQual (HsSymbol "++"))] langOps "Math" 2 = [HsVar (UnQual (HsSymbol "+"))] -- ,HsVar (UnQual (HsIdent "g")) ] -- ,HsVar (UnQual (HsSymbol "*"))] langOps "Analogy2" 1 = [HsVar (UnQual (HsIdent "under")),HsVar (UnQual (HsIdent "f2"))] langOps "Clause" 1 = [HsVar (UnQual (HsIdent x)) | x <- ["raven","black"]] langOps _ _ = [] printMessage = do p <- getProgName putStrLn $ "Usage: " ++ p ++ " agent.hs" putStrLn $ " where: agent.hs contains the agent description and memory" -- | Save an agent in a file saveAgent :: Agent -> FilePath -> IO () saveAgent (Agent comments (width,depth,sol) lang file axioms) filename = do writeFile filename comments appendFile filename $ "-}\n" appendFile filename $ unlines $ map showAxiom axioms appendFile filename $ "\n" main :: IO () main = do args <- getArgs if length args < 1 then printMessage else do let [agentfile] = take 1 args agent' <- parseAgent agentfile if isNothing agent' then do putStrLn $ "Error reading agent." return () else do let (Just agent@(Agent c (width,depth,sol) lang file _)) = agent' (pos,neg) <- parseTrainingFile file expnew <- findDelta 0 agent neg pos --expnew <- trainAgent agent if null (fst expnew) then do --putStrLn $ "All examples solved. Nothing to learn." return () else do putStrLn $ "\nLearned this rule: " putStrLn . unlines . map showAxiom $ fst expnew putStrLn . show $ snd expnew putStrLn $ "Do you want the agent to remember it? (Y/n) " c <- getChar if c == 'n' || c == 'N' then do return () else do let (Agent c (width,depth,sol) lang file axioms) = agent let newltm = union axioms (fst expnew) let newagent = Agent c (width,depth,sol) lang file newltm saveAgent newagent agentfile putStrLn $ "Stored in memory." findDelta :: Int -> Agent -> [IP] -> [IP] -> IO ([Axiom],Int) findDelta len ag _ _ | len < 0 = return ([],0) findDelta len agent neg posex = do let (Agent c (width,depth,sol) lang file ltm) = agent let pos = [x | x@(IP p e v) <- posex, e /= HsVar (UnQual (HsIdent "x"))] let ded = [x | x@(IP p (HsVar (UnQual (HsIdent "x"))) v) <- posex] let posAxioms = [p :->> e | IP p e v <- pos] let optimum = sum ([v | IP p e v <- pos, v > 0] ++ [v | IP p e v <- ded, v > 0]) if optimum < 1 then return ([],0) else do if len > sum (map size pos) then do putStrLn $ "Size exceeded from " ++ show (sum (map size pos)) return (posAxioms,sum [v | (IP _ _ v) <- pos, v > 0]) else do if len > fromIntegral sol then do putStrLn $ "Maximum size reached: " ++ show sol return ([],0) else do if len < 1 then do ans <- mapM (findAnswerDecl ltm width depth) pos if and ans && not (null ans) then do newans <- mapM (findSolDecl ltm width depth) pos putStrLn $ "Computations1: " putStrLn $ unlines $ map (\x -> unlines $ map showState x) newans putStrLn $ "All examples solved. Nothing to learn.\n" return ([],0) else do newans <- mapM (findSolDecl ltm width depth) ded let lefts = [x | x@(Left _) <- (map fst (map head newans))] if null lefts && (not . null) ded then do putStrLn $ "Computations2: " putStrLn $ unlines $ map (\x -> unlines $ map showState x) newans putStrLn $ "All examples solved. Nothing to learn.\n" return ([],0) else findDelta 1 agent neg pos else do putStrLn $ "Searching at length: " ++ show len let funcs = [ (i, filter isPure (generateFuncsAll lang i pos)) | i <- [1..len] ] let delta2 = concat $ [ [[g1,g2],[g2,g1]] | i <- [1..(len `div` 2)], g1 <- fromJust (lookup i funcs), g2 <- fromJust (lookup (len-i) funcs), --isPure g1, --isPure g2, not (numberChange g1), not (numberChange g2), if i == (len-i) then g1 /= g2 else True, not (lhsNotSame g1 g2) ] let delta1 = [ [g] | g <- fromJust (lookup len funcs), not (numberChange g) --isPure g ] putStrLn $ " generated functions: " ++ show (length delta1 + length delta2) --appendFile "temp.txt" -- $ unlines $ map (\x -> concat . intersperse ", " $ map showAxiom x) delta let func delta = do result <- sequence $ parMap rpar (performance width depth sol ltm neg pos ded) delta let result' = [(x,y) | (Just x,y) <- result] let optimal = [(x,y) | (x,y) <- result', y == optimum] let best = maximum $ map snd result' let optimal' = [(x,y) | (x,y) <- result', y == best] if (not . null) optimal then do putStrLn $ "Optimal performance: " ++ show optimum putStrLn $ show (length optimal) ++ " optimal deltas found." let delta = chooseBestDelta optimal return $ Just delta else do if len == fromIntegral sol && (not . null) optimal' then do putStrLn $ "Best performance: " ++ show optimum putStrLn $ show (length optimal) ++ " best deltas found." let delta = chooseBestDelta optimal' return $ Just delta else return Nothing result2 <- func delta2 if result2 /= Nothing then return $ fromJust result2 else do result1 <- func delta1 if result1 /= Nothing then return $ fromJust result1 else findDelta (len+1) agent neg pos numberChange (HsLit (HsInt _) :->> _) = True numberChange (HsLit (HsInt _) :-> _) = True numberChange _ = False isPure (p :->> q) = let pvar = nub [HsVar e |(HsVar e) <- getSubExp p] qvar = nub [HsVar e |(HsVar e) <- getSubExp q] in null (qvar \\ pvar) isPure (p :-> q) = let pvar = nub [HsVar e |(HsVar e) <- getSubExp p] qvar = nub [HsVar e |(HsVar e) <- getSubExp q] in null (qvar \\ pvar) lhsNotSame ((HsVar _) :->> y) ((HsVar _) :->> q) = True lhsNotSame ((HsVar _) :->> y) ((HsVar _) :-> q) = True lhsNotSame ((HsVar _) :-> y) ((HsVar _) :-> q) = True lhsNotSame ((HsVar _) :-> y) ((HsVar _) :->> q) = True lhsNotSame (x :->> y) (p :->> q) = x == p lhsNotSame (x :-> y) (p :-> q) = x == p lhsNotSame _ _ = False ----------------------- chooseBestDelta :: [([Axiom],Int)] -> ([Axiom],Int) chooseBestDelta [] = ([],0) chooseBestDelta [x] = x chooseBestDelta deltas = let deltas' = [(ax,perf,length [p | p@(_ :->> _) <- ax]) | (ax,perf) <- deltas] maxArrowCount = maximum [arrows | (ax,perf,arrows) <- deltas'] deltas1 = [(ax,perf) | x@(ax,perf,arrows) <- deltas', arrows == maxArrowCount] in if length deltas1 == 1 then head deltas1 else let deltas2 = [(ax,perf,sum (map countVars ax)) | (ax,perf) <- deltas1] maxVarCount = maximum [varCount | (ax,perf,varCount) <- deltas2] deltas3 = [(ax,perf) | x@(ax,perf,vars) <- deltas2, vars == maxVarCount] in if length deltas3 == 1 then head deltas3 else head deltas3 countVars :: Axiom -> Int countVars (p :->> q) = countVars' p + countVars' q countVars (p :-> q) = countVars' p + countVars' q countVars' exp = length [HsVar e |(HsVar e) <- getSubExp exp] --learning :: Int -> Word -> Word -> HsModule -> [HsMatch] -> HsMatch -> IO (Maybe HsMatch) --learning len _ _ _ _ _ | len < 0 = return Nothing --learning 0 width depth ltm negex m@(HsMatch _ name pats (HsUnGuardedRhs rhs) _) = do -- let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats -- ans <- solveAnswer (fromIntegral width) (fromIntegral depth) ltm (Right exp, []) -- if ans == (Just rhs) -- then return Nothing -- else learning 1 width depth ltm negex m performance :: Int -> Int -> Int -> [Axiom] -> [IP] -> [IP] -> [IP] -> Delta -> IO (Maybe Delta,Int) performance width depth sol ltm negex pos ded func = do --putStrLn $ unlines $ map showAxiom func let ltm' = ltm ++ func ansPos <- mapM (\x@(IP _ _ y) -> do result <- findAnswerDecl ltm' width depth x return (result,y)) pos ansDed <- mapM (\x@(IP _ _ y) -> do result <- findSolDecl ltm' width depth x return (result,y)) ded ansNeg <- mapM (\x@(IP _ _ y) -> do result <- findAnswerDecl ltm' width depth x return (result,y)) negex let posUtil = sum [y | (True,y) <- ansPos] let dedUtil = sum [y | (sol,y) <- ansDed, (Right _,_) <- [head sol]] let negUtil = sum [y | (True,y) <- ansNeg] let util = posUtil + dedUtil - negUtil if or (map fst ansNeg) then return (Nothing,util) else do if and (map fst ansPos) then do if null [x | (x@(Left _),_) <- (map head (map fst ansDed))] then return (Just func,util) else return (Nothing,util) else return (Nothing,util) generateFuncsAll :: Language -> Int -> [IP] -> Delta generateFuncsAll _ len _ | len < 2 = [] generateFuncsAll lang len pos = let parts = [lhs | (IP lhs _ _) <- pos] ++ [rhs | (IP _ rhs _) <- pos] units = nub $ [x | x <- (concatMap getSubExp parts), size x == 1] ++ [HsVar (UnQual (HsIdent [c])) | c <- "x"] ++ langUnits lang 1 ++ ansatz lang unary = langOps lang 1 ++ [HsVar x | (HsApp (HsVar x) _) <- parts] binary = langOps lang 2 ++ [HsVar x | (HsInfixApp _ (HsQVarOp x) _) <- parts] funcs = [ (i, generateExps i units unary binary) | i <- [1..(len-1)] ] result = concat [ [p :->> q, q :->> p] | i <- [1 .. (len `div` 2)], p <- fromJust (lookup i funcs), q <- fromJust (lookup (len - i) funcs), if i == (len-i) then p /= q else True ] {- pats = nub [p' | i <- [1 .. (len-1)], p' <- generateLhs i units lhs, matchExpExp p' lhs] exps = [(HsApp (HsVar f) p) :->> exp | p <- pats, f <- [x | (HsApp (HsVar x) _) <- [lhs]], exp <- generateExps (len - (size p + 1)) units unary binary] ansatzExps = [p :->> rhs | -- p@(HsApp (HsVar (UnQual f)) ps) <- ansatz lang, p <- ansatz lang, rhs <- generateExps (len - 1) units unary binary] exps1 = [p :->> exp | p <- pats, exp <- generateExps (len - size p) units unary binary, matchExpExp exp rhs] exps2 = [p :->> rhs | p <- pats, size rhs == len - size p] result = (exps ++ exps1 ++ exps2 ++ ansatzExps) -- ++ expsexps) -} in result -- ++ [x :-> y | (x :->> y) <- result] -- generate patterns for expressions, given a list of patterns for element types -- for example, -- 5 -> _, x, 5 -- 5*3 -> x, 5*x, x*3, 5*3, x*y -- 1+2 -> x, 1+x, x+2, 1+2, x+y generateLhs :: Int -> [HsExp] -> HsExp -> [HsExp] generateLhs len _ _ | len < 1 = [] --generateLhs 1 units e@(HsInfixApp p qn q) -- only to generate (_ * _) -- = [HsInfixApp x qn y | x <- generateLhs 0 units p, -- y <- generateLhs 0 units q] -- ++ [u | u <- units, matchExpExp e u] generateLhs 1 units p = [u | u <- units] generateLhs len l (HsNegApp p) = (HsNegApp p) : (map HsNegApp $ generateLhs (len-1) l p) generateLhs len l (HsParen p) = (HsParen p) : (map HsParen $ generateLhs (len-1) l p) generateLhs len l (HsInfixApp p1 qn p2) = concat $ [ [HsInfixApp p1' qn p2' | p1' <- generateLhs i l p1, p2' <- generateLhs (len' - i) l p2] | i <- [0 .. len'] ] where len' = len - 1 generateLhs len l (HsApp qn p) = [HsApp qn x | x <- generateLhs (len-1) l p, matchExpExp p x] generateLhs len xs p@(HsList ps) = let pats = generateListPats len [] in pats ++ [HsInfixApp x (HsQConOp (Special HsCons)) y | x <- xs, y <- generateListPats (len - 1) (xs \\ [x])] generateLhs len xs p = [] generateExps :: Int -> [HsExp] -> [HsExp] -> [HsExp] -> [HsExp] generateExps len _ _ _ | len < 1 = [] generateExps 1 units _ _ = units generateExps 2 units funcs1 _ = [HsApp x y | x <- funcs1, y <- units] generateExps len units funcs1 funcs2 = let exps2 = generateExps (len-2) units funcs1 funcs2 exps1 = generateExps (len-1) units funcs1 funcs2 in [HsInfixApp x (HsQVarOp op) y | x <- exps2, y <- exps2, (HsVar op) <- funcs2] ++ [HsApp op arg | op <- funcs1, arg <- exps1] {- generateExps len units funcs1 funcs2 (HsInfixApp x (HsQConOp (Special HsCons)) y) = let exps = generateExps (len-1) units funcs1 funcs2 y lists = exps ++ [HsList [x]] ++ [HsInfixApp x (HsQConOp (Special HsCons)) l | l <- exps] in lists ++ [HsApp f l | l <- lists, f <- funcs1] ++ [HsInfixApp l1 (HsQVarOp f) l2 | l1 <- lists, l2 <- lists, (HsVar f) <- funcs2, (size l1 + size l2) < len ] generateExps len units funcs1 funcs2 p@(HsInfixApp x qn y) = result ++ [HsApp f r | f <- funcs1, r <- result, size r < len] where result = [HsInfixApp x qn y | x <- generateExps (len-2) units funcs1 funcs2 p, y <- generateExps (len-2) units funcs1 funcs2 p] -} -- generate patterns for list type, given a list of patterns for element types -- for example, given [1,x], it generates -- _, xs, [], (x:_), (x:[]), (x:xs), (1:_), (1:[]), (1:xs), (x:1:_), (1:x:_), ... generateListPats :: Int -> [HsExp] -> [HsExp] generateListPats len _ | len < 1 = [] generateListPats _ [] = [HsList [],HsVar (UnQual (HsIdent "l"))] generateListPats len xs = let listpats = generateListPats len [] in listpats ++ [HsInfixApp x (HsQConOp (Special HsCons)) y | x <- xs, y <- generateListPats (len - 1) (xs \\ [x])] -- generate a list of list expressions for each pattern -- the second argument is a list of functions of type :: [a] -> [a] -- the third argument is a list of functions of type :: [a] -> [a] -> [a] generateListExps :: Int -> [HsExp] -> [HsExp] -> HsExp -> [HsExp] generateListExps len _ _ _ | len < 1 = [HsList []] generateListExps _ _ _ HsWildCard = [HsList []] generateListExps _ _ _ (HsList []) = [HsList []] generateListExps len funcs1 funcs2 (HsVar x) = [HsVar x] ++ [HsApp f (HsVar x) | f <- funcs1] generateListExps len funcs1 funcs2 (HsInfixApp x (HsQConOp (Special HsCons)) y) = let exps = generateListExps (len-1) funcs1 funcs2 y lists = exps ++ [HsList [x]] ++ [HsInfixApp x (HsQConOp (Special HsCons)) l | l <- exps] in lists ++ [HsApp f l | l <- lists, f <- funcs1] ++ [HsInfixApp l1 (HsQVarOp f) l2 | l1 <- lists, l2 <- lists, (HsVar f) <- funcs2, (size l1 + size l2) < len] generateListExps _ _ _ _ = [HsList []] ------------------------------------------------------------------------------- -- HELPER FUNCTIONS ------------------------------------------------------------------------------- getInt :: Maybe HsExp -> Integer getInt (Just (HsLit (HsInt i))) = i getInt _ = 0 getString :: Maybe HsExp -> String getString (Just (HsLit (HsString s))) = s getString _ = "" -- check if the answer is the same as given, using Astar search findAnswerDecl :: [Axiom] -> Int -> Int -> IP -> IO Bool findAnswerDecl ltm width depth (IP exp rhs _) = do ans <- solveAnswer (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) return (isJust ans && equalExp (fromJust ans,rhs)) --findAnswerDecl ltm width depth (HsFunBind [HsMatch loc name pats (HsUnGuardedRhs rhs) _]) = do -- let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats -- ans <- solveAnswer (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) -- return (isJust ans && equalExp (fromJust ans,rhs)) -- find the solution (all proof steps) using the Astar search findSolDecl :: [Axiom] -> Int -> Int -> IP -> IO [StateD] -- if rhs is x, then search for any answer findSolDecl ltm width depth (IP exp (HsVar (UnQual (HsIdent "x"))) _) = do ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) Nothing if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] -- else search for the given answer findSolDecl ltm width depth (IP exp rhs _) = do ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] {- findSolDecl ltm width depth (HsFunBind [HsMatch loc name pats (HsUnGuardedRhs rhs) _]) = do let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] findSolDecl ltm width depth (HsFunBind [HsMatch loc name pats (HsUnGuardedRhs (HsVar (UnQual (HsIdent "x")))) _]) = do let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) Nothing if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] -} ------------------------------------------------------------------------------- -- UNUSED CODE ------------------------------------------------------------------------------- -- | Generate all functions of the given length generateFuncs :: HsMatch -> Int -> [HsMatch] generateFuncs m len | len < 1 = [] generateFuncs (HsMatch loc name pats (HsUnGuardedRhs rhs) x) 1 = [] -- | size rhs == 1 -- = [HsMatch loc name [HsPWildCard] (HsUnGuardedRhs rhs) x] generateFuncs m@(HsMatch loc name pats (HsUnGuardedRhs rhs) x) 2 = [HsMatch loc name [HsPVar (HsIdent "x")] (HsUnGuardedRhs (HsVar (UnQual (HsIdent "x")))) x] ++ if size m == 2 then [m] else [] generateFuncs m@(HsMatch loc name pats (HsUnGuardedRhs rhs) x) len = if size m == len then [m] else []
arnizamani/occam
occam.hs
Haskell
mit
22,531
{-# LANGUAGE TypeFamilies, GADTs, CPP #-} module Database.Selda.Selectors ( Assignment ((:=)), Selector, Coalesce , (!), (?), with, ($=) , selectorIndex, unsafeSelector ) where import Database.Selda.SqlRow (SqlRow) import Database.Selda.SqlType import Database.Selda.Column import Data.List (foldl') import Unsafe.Coerce -- | Coalesce nested nullable column into a single level of nesting. type family Coalesce a where Coalesce (Maybe (Maybe a)) = Coalesce (Maybe a) Coalesce a = a -- | A selector indicating the nth (zero-based) column of a table. -- -- Will cause errors in queries during compilation, execution, or both, -- unless handled with extreme care. You really shouldn't use it at all. unsafeSelector :: (SqlRow a, SqlType b) => Int -> Selector a b unsafeSelector = Selector -- | Extract the given column from the given row. (!) :: SqlType a => Row s t -> Selector t a -> Col s a (Many xs) ! (Selector i) = case xs !! i of Untyped x -> One (unsafeCoerce x) infixl 9 ! -- | Extract the given column from the given nullable row. -- Nullable rows usually result from left joins. -- If a nullable column is extracted from a nullable row, the resulting -- nested @Maybe@s will be squashed into a single level of nesting. (?) :: SqlType a => Row s (Maybe t) -> Selector t a -> Col s (Coalesce (Maybe a)) (Many xs) ? (Selector i) = case xs !! i of Untyped x -> One (unsafeCoerce x) infixl 9 ? upd :: Row s a -> Assignment s a -> Row s a upd (Many xs) (Selector i := (One x')) = case splitAt i xs of (left, _:right) -> Many (left ++ Untyped x' : right) _ -> error "BUG: too few columns in row!" upd (Many xs) (Modify (Selector i) f) = case splitAt i xs of (left, Untyped x:right) -> Many (left ++ f' (unsafeCoerce x) : right) _ -> error "BUG: too few columns in row!" where f' x = case f (One x) of One y -> Untyped y -- | A selector-value assignment pair. data Assignment s a where -- | Set the given column to the given value. (:=) :: Selector t a -> Col s a -> Assignment s t -- | Modify the given column by the given function. Modify :: Selector t a -> (Col s a -> Col s a) -> Assignment s t infixl 2 := -- | Apply the given function to the given column. ($=) :: Selector t a -> (Col s a -> Col s a) -> Assignment s t ($=) = Modify infixl 2 $= -- | For each selector-value pair in the given list, on the given tuple, -- update the field pointed out by the selector with the corresponding value. with :: Row s a -> [Assignment s a] -> Row s a with = foldl' upd -- | A column selector. Column selectors can be used together with the '!' and -- 'with' functions to get and set values on rows, or to specify -- foreign keys. newtype Selector t a = Selector {selectorIndex :: Int}
valderman/selda
selda/src/Database/Selda/Selectors.hs
Haskell
mit
2,813
{-# LANGUAGE DeriveDataTypeable, CPP #-} import GetURL import TimeIt import Data.Either import Control.Monad import System.IO import Control.Concurrent hiding(forkFinally) import Control.Exception import Text.Printf import qualified Data.ByteString as B import Data.Typeable import Prelude hiding (catch) data Async a = Async ThreadId (MVar (Either SomeException a)) forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action fun = mask $ \restore -> forkIO (do r <- try (restore action); fun r) async :: IO a -> IO (Async a) async action = do m <- newEmptyMVar t <- forkFinally action (putMVar m) return (Async t m) waitCatch :: Async a -> IO (Either SomeException a) waitCatch (Async _ var) = readMVar var wait :: Async a -> IO a wait m = do r <- waitCatch m case r of Left e -> throwIO e Right a -> return a cancel :: Async a -> IO () cancel (Async t var) = throwTo t ThreadKilled sites = ["http://forec.cn", "https://cn.bing.com", "https://www.baidu.com", "https://ipv6.google.com"] timeDownload :: String -> IO () timeDownload url = do (page, time) <- timeit $ getURL url printf "downloaded: %s (%d bytes, %.2fs)\n" url (B.length page) time main = do as <- mapM (async . timeDownload) sites forkIO $ do hSetBuffering stdin NoBuffering forever $ do c <- getChar when (c == 'q') $ mapM_ cancel as rs <- mapM waitCatch as printf "%d/%d succeeded\n" (length (rights rs)) (length rs)
Forec/learn
2017.3/Parallel Haskell/ch10/geturlscancel2.hs
Haskell
mit
1,569