code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Foo where bar = 0 {-@ assume (Prelude.++) :: [a] -> [a] -> [a] @-}
ssaavedra/liquidhaskell
tests/pos/Foo.hs
bsd-3-clause
77
0
4
19
10
7
3
2
1
{-# LANGUAGE CPP, RecordWildCards, FlexibleInstances, MultiParamTypeClasses #-} -- | -- Package configuration information: essentially the interface to Cabal, with -- some utilities -- -- (c) The University of Glasgow, 2004 -- module PackageConfig ( -- $package_naming -- * UnitId packageConfigId, expandedPackageConfigId, definitePackageConfigId, installedPackageConfigId, -- * The PackageConfig type: information about a package PackageConfig, InstalledPackageInfo(..), ComponentId(..), SourcePackageId(..), PackageName(..), Version(..), defaultPackageConfig, sourcePackageIdString, packageNameString, pprPackageConfig, ) where #include "HsVersions.h" import GhcPrelude import GHC.PackageDb import Data.Version import FastString import Outputable import Module import Unique -- ----------------------------------------------------------------------------- -- Our PackageConfig type is the InstalledPackageInfo from ghc-boot, -- which is similar to a subset of the InstalledPackageInfo type from Cabal. type PackageConfig = InstalledPackageInfo ComponentId SourcePackageId PackageName Module.InstalledUnitId Module.UnitId Module.ModuleName Module.Module -- TODO: there's no need for these to be FastString, as we don't need the uniq -- feature, but ghc doesn't currently have convenient support for any -- other compact string types, e.g. plain ByteString or Text. newtype SourcePackageId = SourcePackageId FastString deriving (Eq, Ord) newtype PackageName = PackageName FastString deriving (Eq, Ord) instance BinaryStringRep SourcePackageId where fromStringRep = SourcePackageId . mkFastStringByteString toStringRep (SourcePackageId s) = fastStringToByteString s instance BinaryStringRep PackageName where fromStringRep = PackageName . mkFastStringByteString toStringRep (PackageName s) = fastStringToByteString s instance Uniquable SourcePackageId where getUnique (SourcePackageId n) = getUnique n instance Uniquable PackageName where getUnique (PackageName n) = getUnique n instance Outputable SourcePackageId where ppr (SourcePackageId str) = ftext str instance Outputable PackageName where ppr (PackageName str) = ftext str defaultPackageConfig :: PackageConfig defaultPackageConfig = emptyInstalledPackageInfo sourcePackageIdString :: PackageConfig -> String sourcePackageIdString pkg = unpackFS str where SourcePackageId str = sourcePackageId pkg packageNameString :: PackageConfig -> String packageNameString pkg = unpackFS str where PackageName str = packageName pkg pprPackageConfig :: PackageConfig -> SDoc pprPackageConfig InstalledPackageInfo {..} = vcat [ field "name" (ppr packageName), field "version" (text (showVersion packageVersion)), field "id" (ppr unitId), field "exposed" (ppr exposed), field "exposed-modules" (ppr exposedModules), field "hidden-modules" (fsep (map ppr hiddenModules)), field "trusted" (ppr trusted), field "import-dirs" (fsep (map text importDirs)), field "library-dirs" (fsep (map text libraryDirs)), field "dynamic-library-dirs" (fsep (map text libraryDynDirs)), field "hs-libraries" (fsep (map text hsLibraries)), field "extra-libraries" (fsep (map text extraLibraries)), field "extra-ghci-libraries" (fsep (map text extraGHCiLibraries)), field "include-dirs" (fsep (map text includeDirs)), field "includes" (fsep (map text includes)), field "depends" (fsep (map ppr depends)), field "cc-options" (fsep (map text ccOptions)), field "ld-options" (fsep (map text ldOptions)), field "framework-dirs" (fsep (map text frameworkDirs)), field "frameworks" (fsep (map text frameworks)), field "haddock-interfaces" (fsep (map text haddockInterfaces)), field "haddock-html" (fsep (map text haddockHTMLs)) ] where field name body = text name <> colon <+> nest 4 body -- ----------------------------------------------------------------------------- -- UnitId (package names, versions and dep hash) -- $package_naming -- #package_naming# -- Mostly the compiler deals in terms of 'UnitId's, which are md5 hashes -- of a package ID, keys of its dependencies, and Cabal flags. You're expected -- to pass in the unit id in the @-this-unit-id@ flag. However, for -- wired-in packages like @base@ & @rts@, we don't necessarily know what the -- version is, so these are handled specially; see #wired_in_packages#. -- | Get the GHC 'UnitId' right out of a Cabalish 'PackageConfig' installedPackageConfigId :: PackageConfig -> InstalledUnitId installedPackageConfigId = unitId packageConfigId :: PackageConfig -> UnitId packageConfigId p = if indefinite p then newUnitId (componentId p) (instantiatedWith p) else DefiniteUnitId (DefUnitId (unitId p)) expandedPackageConfigId :: PackageConfig -> UnitId expandedPackageConfigId p = newUnitId (componentId p) (instantiatedWith p) definitePackageConfigId :: PackageConfig -> Maybe DefUnitId definitePackageConfigId p = case packageConfigId p of DefiniteUnitId def_uid -> Just def_uid _ -> Nothing
shlevy/ghc
compiler/main/PackageConfig.hs
bsd-3-clause
5,640
0
11
1,347
1,083
571
512
96
2
module Main where import System.Directory import System.Environment main :: IO () main = do (source:target:_) <- getArgs copyFile source target
mydaum/cabal
cabal-testsuite/PackageTests/CustomPreProcess/MyCustomPreprocessor.hs
bsd-3-clause
150
0
10
26
55
29
26
7
1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE ExistentialQuantification, NoImplicitPrelude #-} module GHC.Event.Internal ( -- * Event back end Backend , backend , delete , poll , modifyFd , modifyFdOnce -- * Event type , Event , evtRead , evtWrite , evtClose , eventIs -- * Lifetimes , Lifetime(..) , EventLifetime , eventLifetime , elLifetime , elEvent -- * Timeout type , Timeout(..) -- * Helpers , throwErrnoIfMinus1NoRetry ) where import Data.Bits ((.|.), (.&.)) import Data.OldList (foldl', filter, intercalate, null) import Foreign.C.Error (eINTR, getErrno, throwErrno) import System.Posix.Types (Fd) import GHC.Base import GHC.Num (Num(..)) import GHC.Show (Show(..)) -- | An I\/O event. newtype Event = Event Int deriving (Eq) evtNothing :: Event evtNothing = Event 0 {-# INLINE evtNothing #-} -- | Data is available to be read. evtRead :: Event evtRead = Event 1 {-# INLINE evtRead #-} -- | The file descriptor is ready to accept a write. evtWrite :: Event evtWrite = Event 2 {-# INLINE evtWrite #-} -- | Another thread closed the file descriptor. evtClose :: Event evtClose = Event 4 {-# INLINE evtClose #-} eventIs :: Event -> Event -> Bool eventIs (Event a) (Event b) = a .&. b /= 0 instance Show Event where show e = '[' : (intercalate "," . filter (not . null) $ [evtRead `so` "evtRead", evtWrite `so` "evtWrite", evtClose `so` "evtClose"]) ++ "]" where ev `so` disp | e `eventIs` ev = disp | otherwise = "" instance Monoid Event where mempty = evtNothing mappend = evtCombine mconcat = evtConcat evtCombine :: Event -> Event -> Event evtCombine (Event a) (Event b) = Event (a .|. b) {-# INLINE evtCombine #-} evtConcat :: [Event] -> Event evtConcat = foldl' evtCombine evtNothing {-# INLINE evtConcat #-} -- | The lifetime of an event registration. -- -- @since 4.8.1.0 data Lifetime = OneShot -- ^ the registration will be active for only one -- event | MultiShot -- ^ the registration will trigger multiple times deriving (Show, Eq) -- | The longer of two lifetimes. elSupremum :: Lifetime -> Lifetime -> Lifetime elSupremum OneShot OneShot = OneShot elSupremum _ _ = MultiShot {-# INLINE elSupremum #-} -- | @mappend@ == @elSupremum@ instance Monoid Lifetime where mempty = OneShot mappend = elSupremum -- | A pair of an event and lifetime -- -- Here we encode the event in the bottom three bits and the lifetime -- in the fourth bit. newtype EventLifetime = EL Int deriving (Show, Eq) instance Monoid EventLifetime where mempty = EL 0 EL a `mappend` EL b = EL (a .|. b) eventLifetime :: Event -> Lifetime -> EventLifetime eventLifetime (Event e) l = EL (e .|. lifetimeBit l) where lifetimeBit OneShot = 0 lifetimeBit MultiShot = 8 {-# INLINE eventLifetime #-} elLifetime :: EventLifetime -> Lifetime elLifetime (EL x) = if x .&. 8 == 0 then OneShot else MultiShot {-# INLINE elLifetime #-} elEvent :: EventLifetime -> Event elEvent (EL x) = Event (x .&. 0x7) {-# INLINE elEvent #-} -- | A type alias for timeouts, specified in seconds. data Timeout = Timeout {-# UNPACK #-} !Double | Forever deriving (Show) -- | Event notification backend. data Backend = forall a. Backend { _beState :: !a -- | Poll backend for new events. The provided callback is called -- once per file descriptor with new events. , _bePoll :: a -- backend state -> Maybe Timeout -- timeout in milliseconds ('Nothing' for non-blocking poll) -> (Fd -> Event -> IO ()) -- I/O callback -> IO Int -- | Register, modify, or unregister interest in the given events -- on the given file descriptor. , _beModifyFd :: a -> Fd -- file descriptor -> Event -- old events to watch for ('mempty' for new) -> Event -- new events to watch for ('mempty' to delete) -> IO Bool -- | Register interest in new events on a given file descriptor, set -- to be deactivated after the first event. , _beModifyFdOnce :: a -> Fd -- file descriptor -> Event -- new events to watch -> IO Bool , _beDelete :: a -> IO () } backend :: (a -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int) -> (a -> Fd -> Event -> Event -> IO Bool) -> (a -> Fd -> Event -> IO Bool) -> (a -> IO ()) -> a -> Backend backend bPoll bModifyFd bModifyFdOnce bDelete state = Backend state bPoll bModifyFd bModifyFdOnce bDelete {-# INLINE backend #-} poll :: Backend -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int poll (Backend bState bPoll _ _ _) = bPoll bState {-# INLINE poll #-} -- | Returns 'True' if the modification succeeded. -- Returns 'False' if this backend does not support -- event notifications on this type of file. modifyFd :: Backend -> Fd -> Event -> Event -> IO Bool modifyFd (Backend bState _ bModifyFd _ _) = bModifyFd bState {-# INLINE modifyFd #-} -- | Returns 'True' if the modification succeeded. -- Returns 'False' if this backend does not support -- event notifications on this type of file. modifyFdOnce :: Backend -> Fd -> Event -> IO Bool modifyFdOnce (Backend bState _ _ bModifyFdOnce _) = bModifyFdOnce bState {-# INLINE modifyFdOnce #-} delete :: Backend -> IO () delete (Backend bState _ _ _ bDelete) = bDelete bState {-# INLINE delete #-} -- | Throw an 'IOError' corresponding to the current value of -- 'getErrno' if the result value of the 'IO' action is -1 and -- 'getErrno' is not 'eINTR'. If the result value is -1 and -- 'getErrno' returns 'eINTR' 0 is returned. Otherwise the result -- value is returned. throwErrnoIfMinus1NoRetry :: (Eq a, Num a) => String -> IO a -> IO a throwErrnoIfMinus1NoRetry loc f = do res <- f if res == -1 then do err <- getErrno if err == eINTR then return 0 else throwErrno loc else return res
tolysz/prepare-ghcjs
spec-lts8/base/GHC/Event/Internal.hs
bsd-3-clause
6,288
0
16
1,779
1,392
773
619
138
3
{-# LANGUAGE BangPatterns, FlexibleContexts #-} module Main where import Data.Array.Base (unsafeRead, unsafeWrite) import Data.Array.ST import Data.Array.Unboxed import Control.Monad.ST main = print (divisorCounts 1000000 ! 342) isqrt :: Int -> Int isqrt n = floor (sqrt $ fromIntegral n) divisorCounts :: Int -> UArray Int Int divisorCounts n = runSTUArray $ do let !rt = isqrt n darr <- newArray (0,n) 1 :: ST s (STUArray s Int Int) let inc i = unsafeRead darr i >>= \k -> unsafeWrite darr i (k+1) note step i | i > n = return () | otherwise = do inc i note step (i+step) count j | j > rt = return () | otherwise = do note (2*j) (j*j) count (j+2) note 2 4 count 3 return darr
urbanslug/ghc
testsuite/tests/perf/should_run/T5113.hs
bsd-3-clause
841
4
17
289
281
151
130
27
1
sumList :: [Integer]-> Integer sumList []=0 sumList (x:xs) = x+ sum xs main=print(sumList [1,2,3,9])
manuchandel/Academics
Principles-Of-Programming-Languages/sumList.hs
mit
102
0
8
15
71
38
33
4
1
module Main where import System.Environment import qualified Language.Haskell.Exts.Annotated.Syntax import qualified Language.Haskell.Exts.Syntax import DeriveTemplate import Control.Arrow import Control.Applicative import Data.Functor import Data.Monoid $(deriveDesugarTemplate "genNormal" "Language.Haskell.Exts.Syntax.Module" False) $(deriveDesugarTemplate "genAnnotated" "Language.Haskell.Exts.Annotated.Syntax.Module" True) main = do progName <- getProgName args <- getArgs case args of [modName, funPrefix, mode, additionalArgNum] -> do let code = (if mode=="1" then genAnnotated else genNormal) modName funPrefix (read additionalArgNum) putStrLn code _ -> putStrLn $ "usage: ./" ++ progName ++ " module_name function_prefix normal:0/annotated:1 num_of_additional_args"
CindyLinz/Haskell.js
trans/desugar-template-src/Main.hs
mit
813
0
18
113
182
98
84
-1
-1
module MemoryManager.Util where import MemoryManager.Types checkAddress :: [MemorySource] -> Int -> MemorySource checkAddress sources addr = case (filter containsAddr sources) of [] -> error ("address unknown: " ++ show addr) (x:_) -> x where containsAddr (MemorySource base sc _) = base <= addr && addr < sc
christiaanb/SoOSiM
examples/MemoryManager/Util.hs
mit
334
0
11
72
115
60
55
10
2
-- Haskell version of https://gcc.gnu.org/onlinedocs/jit/intro/tutorial02.html {-# LANGUAGE OverloadedStrings #-} module Main where import Compiler.GCC.JIT import Foreign.Ptr import Foreign.C.Types import Control.Monad.IO.Class (liftIO) type FnType = CInt -> IO CInt foreign import ccall "dynamic" mkFun :: FunPtr FnType -> FnType createCode :: JIT () createCode = do intType <- getType JitInt paramI <- param Nothing intType "i" func <- function Nothing JitFunctionExported intType "square" [paramI] False block <- block func Nothing expr <- asRValue paramI >>= \rv -> binaryOp Nothing JitOpMult intType rv rv endWithReturn block Nothing expr return () main :: IO () main = do res <- withContext $ do setBoolOption JitDumpGeneratedCode True createCode withResult $ \r -> do fun <- getCode r "square" liftIO $ mkFun fun 5 print res
Slowki/hgccjit
example/Tutorial2.hs
mit
926
0
16
215
268
131
137
27
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.TrackEvent (js_getTrack, getTrack, TrackEvent, castToTrackEvent, gTypeTrackEvent) 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 "$1[\"track\"]" js_getTrack :: TrackEvent -> IO (Nullable GObject) -- | <https://developer.mozilla.org/en-US/docs/Web/API/TrackEvent.track Mozilla TrackEvent.track documentation> getTrack :: (MonadIO m) => TrackEvent -> m (Maybe GObject) getTrack self = liftIO (nullableToMaybe <$> (js_getTrack (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/TrackEvent.hs
mit
1,313
6
10
151
371
236
135
22
1
module Map where import Data.Char square :: [Double] -> [Double] square (x:xs) = x * x : square xs square [] = [] square' :: [Double] -> [Double] square' xs = map squareOne xs where squareOne x = x * x upperCase :: String -> String upperCase (x:xs) = toUpper x : upperCase xs upperCase [] = [] map' :: (a -> b) -> [a] -> [b] map' f (x:xs) = f x : map' f xs map' _ _ = []
bionikspoon/playing-with-haskell---oreilly
ch04/Map.hs
mit
417
0
7
128
217
114
103
14
1
{-| Agda main module. -} module Agda.Main where import Control.Monad.State import Data.Maybe import System.Environment import System.Console.GetOpt import Agda.Interaction.CommandLine import Agda.Interaction.ExitCode (AgdaError(..), exitSuccess, exitAgdaWith) import Agda.Interaction.Options import Agda.Interaction.Options.Help (Help (..)) import Agda.Interaction.Monad import Agda.Interaction.EmacsTop (mimicGHCi) import Agda.Interaction.JSONTop (jsonREPL) import Agda.Interaction.Imports (MaybeWarnings'(..)) import Agda.Interaction.FindFile ( SourceFile(SourceFile) ) import qualified Agda.Interaction.Imports as Imp import qualified Agda.Interaction.Highlighting.Dot as Dot import qualified Agda.Interaction.Highlighting.LaTeX as LaTeX import Agda.Interaction.Highlighting.HTML import Agda.TypeChecking.Monad import qualified Agda.TypeChecking.Monad.Benchmark as Bench import Agda.TypeChecking.Errors import Agda.TypeChecking.Warnings import Agda.TypeChecking.Pretty import Agda.Compiler.Backend import Agda.Compiler.Builtin import Agda.Utils.Monad import Agda.Utils.String import Agda.VersionCommit import qualified Agda.Utils.Benchmark as UtilsBench import Agda.Utils.Except ( MonadError(catchError, throwError) ) import Agda.Utils.Impossible -- | The main function runAgda :: [Backend] -> IO () runAgda backends = runAgda' $ builtinBackends ++ backends -- | The main function without importing built-in backends runAgda' :: [Backend] -> IO () runAgda' backends = runTCMPrettyErrors $ do progName <- liftIO getProgName argv <- liftIO getArgs opts <- liftIO $ runOptM $ parseBackendOptions backends argv defaultOptions case opts of Left err -> liftIO $ optionError err Right (bs, opts) -> do setTCLens stBackends bs let enabled (Backend b) = isEnabled b (options b) bs' = filter enabled bs () <$ runAgdaWithOptions backends generateHTML (interaction bs') progName opts where interaction bs = backendInteraction bs $ defaultInteraction opts defaultInteraction :: CommandLineOptions -> TCM (Maybe Interface) -> TCM () defaultInteraction opts | i = runIM . interactionLoop | ghci = mimicGHCi . (failIfInt =<<) | json = jsonREPL . (failIfInt =<<) | otherwise = (() <$) where i = optInteractive opts ghci = optGHCiInteraction opts json = optJSONInteraction opts failIfInt Nothing = return () failIfInt (Just _) = __IMPOSSIBLE__ -- | Run Agda with parsed command line options and with a custom HTML generator runAgdaWithOptions :: [Backend] -- ^ Backends only for printing usage and version information -> TCM () -- ^ HTML generating action -> (TCM (Maybe Interface) -> TCM a) -- ^ Backend interaction -> String -- ^ program name -> CommandLineOptions -- ^ parsed command line options -> TCM (Maybe a) runAgdaWithOptions backends generateHTML interaction progName opts | Just hp <- optShowHelp opts = Nothing <$ liftIO (printUsage backends hp) | optShowVersion opts = Nothing <$ liftIO (printVersion backends) | isNothing (optInputFile opts) && not (optInteractive opts) && not (optGHCiInteraction opts) && not (optJSONInteraction opts) = Nothing <$ liftIO (printUsage backends GeneralHelp) | otherwise = do -- Main function. -- Bill everything to root of Benchmark trie. UtilsBench.setBenchmarking UtilsBench.BenchmarkOn -- Andreas, Nisse, 2016-10-11 AIM XXIV -- Turn benchmarking on provisionally, otherwise we lose track of time spent -- on e.g. LaTeX-code generation. -- Benchmarking might be turned off later by setCommandlineOptions Bench.billTo [] checkFile `finally_` do -- Print benchmarks. Bench.print -- Print accumulated statistics. printStatistics 1 Nothing =<< useTC lensAccumStatistics where checkFile = Just <$> do when (optInteractive opts) $ liftIO $ putStr splashScreen interaction $ do setCommandLineOptions opts hasFile <- hasInputFile -- Andreas, 2013-10-30 The following 'resetState' kills the -- verbosity options. That does not make sense (see fail/Issue641). -- 'resetState' here does not seem to serve any purpose, -- thus, I am removing it. -- resetState if not hasFile then return Nothing else do let mode = if optOnlyScopeChecking opts then Imp.ScopeCheck else Imp.TypeCheck file <- SourceFile <$> getInputFile (i, mw) <- Imp.typeCheckMain file mode =<< Imp.sourceInfo file -- An interface is only generated if the mode is -- Imp.TypeCheck and there are no warnings. result <- case (mode, mw) of (Imp.ScopeCheck, _) -> return Nothing (_, NoWarnings) -> return $ Just i (_, SomeWarnings ws) -> do ws' <- applyFlagsToTCWarnings ws case ws' of [] -> return Nothing cuws -> tcWarningsToError cuws reportSDoc "main" 50 $ pretty i whenM (optGenerateHTML <$> commandLineOptions) $ generateHTML whenM (isJust . optDependencyGraph <$> commandLineOptions) $ Dot.generateDot $ i whenM (optGenerateLaTeX <$> commandLineOptions) $ LaTeX.generateLaTeX i -- Print accumulated warnings ws <- tcWarnings . classifyWarnings <$> Imp.getAllWarnings AllWarnings unless (null ws) $ do let banner = text $ "\n" ++ delimiter "All done; warnings encountered" reportSDoc "warning" 1 $ vcat $ punctuate "\n" $ banner : (prettyTCM <$> ws) return result -- | Print usage information. printUsage :: [Backend] -> Help -> IO () printUsage backends hp = do progName <- getProgName putStr $ usage standardOptions_ progName hp when (hp == GeneralHelp) $ mapM_ (putStr . backendUsage) backends backendUsage :: Backend -> String backendUsage (Backend b) = usageInfo ("\n" ++ backendName b ++ " backend options") $ map void (commandLineFlags b) -- | Run a TCM action in IO; catch and pretty print errors. runTCMPrettyErrors :: TCM () -> IO () runTCMPrettyErrors tcm = do r <- runTCMTop $ tcm `catchError` \err -> do s2s <- prettyTCWarnings' =<< Imp.getAllWarningsOfTCErr err s1 <- prettyError err let ss = filter (not . null) $ s2s ++ [s1] unless (null s1) (liftIO $ putStr $ unlines ss) throwError err case r of Right _ -> exitSuccess Left _ -> exitAgdaWith TCMError `catchImpossible` \e -> do putStr $ show e exitAgdaWith ImpossibleError
kucherenko/jscpd
fixtures/haskell/file2.hs
mit
6,894
0
25
1,778
1,684
865
819
132
6
module ProjectEuler.Problem144 ( problem ) where import Data.List import Petbox import ProjectEuler.Types problem :: Problem problem = pureProblem 144 Solved result {- Idea: Let's first work out some formulas that might become necessary. - Given a point (x_0, y_0) on the ellipse, we should be able to find the tangent line, from where we can figure out the reflection. y_0 = -4 x_0^2 / y_0 + b => b = (y_0^2 + 4x_0^2) / y_0 = 100 / y_0 Therefore the tangent line is: 4x_0 x + y_0 y - 100 = 0 And the slope for the normal line = -1 / m = -1 / ( -4 x_0 / y_0 ) = y_0 / (4 x_0) And the normal line is: y_0 x - 4 x_0 y + 3 x_0 y_0 = 0 - For two given points A, B on the ellipse, we should be able to figure out the next point, this involves: + connect A and B to form a line. + figure out how line AB reflects when hitting tangent line at B + on the reflected line, find point C on the ellipse. (we should just need the resulting slope to figure out the line, this is because we have assumed that B is on the ellipse.) TODO: some cleanup is definitely needed. -} type Point = (Double, Double) type V2 = (Double, Double) point0, point1 :: Point point0 = (0, 10.1) point1 = (1.4, -9.6) diff :: Point -> Point -> V2 diff (a0,b0) (a1,b1) = (a0-a1,b0-b1) cross :: V2 -> V2 -> Double cross (a0,b0) (a1,b1) = a0 * b1 - a1 * b0 dot :: V2 -> V2 -> Double dot (a0,b0) (a1,b1) = a0 * a1 + b0 * b1 distSq :: Point -> Point -> Double distSq (xA,yA) (xB,yB) = (xA-xB) ^! 2 + (yA-yB) ^! 2 {- Compute next point of impact inside 4 x^2 + y^2 = 100. Requires that pointB to be on the ellipse. Implementation detail: - first compute vector for A -> B (call this u) - then compute vector for tangent at B (call this t) - by computing cross product and dot product of u and t, we get the information about the angle turning from u to t (could be negative), if we rotate t by that angle, the resulting vector has the slope of the reflected line. - note that: + sine(theta) = |cross product| / (|u| * |t|) + cosine(theta) = dot product / (|u| * |t|) since both cross product and dot product contains |u| * |t|, we can construct the un-normalized rotation matrix by pretending that cross product is sin(theta) and dot product is cos(theta). We'll get a scaled result but all we care about is the slope of the reflected line, which stays unchanged when scaling. -} nextPoint :: Point -> Point -> Point nextPoint pointA pointB@(xB,yB) = if distSq pt0 pointB < distSq pt1 pointB then pt1 else pt0 where vecU = diff pointB pointA vecT@(dxT,dyT) = (yB, -4 * xB) -- convert from slope crossProd = cross vecU vecT -- the direction of reflection is vector t rotated by theta. dotProd = dot vecU vecT (dxU',dyU') = (dxT * dotProd - dyT * crossProd, dxT * crossProd + dyT * dotProd) -- it should be the case that cross vecU vecT == cross vecT vecU' -- m is slope of u' m = dyU' / dxU' b = yB - m * xB delta = 100 * m * m - 4 * b * b + 400 x0 = (-m*b + sqrt delta) / (4 + m*m) -- TODO: looks like sqrt might not be necessary? x1 = (-m*b - sqrt delta) / (4 + m*m) pt0 = (x0, m*x0 + b) pt1 = (x1, m*x1 + b) {- yB = m * xB + b => b = yB - m * xB - 4x^2 + y^2 = 100 - y = m * x + b delta (discriminant) = 400 m^2 - 16 b^2 + 1600 = 4 * (100 m^2 - 4 b^2 + 400) -} {- Here are 50 points generated for using gnuplot for a visual verification: 1.4 -9.6 -3.9905976193616177 -6.024991498863841 0.32458287808384445 9.978906945202928 0.4164904357818666 -9.965246753974995 -4.473443497221033 4.466901958705094 1.1323378646973856 9.740187053680758 5.3650666227919835e-2 -9.999424304631402 -1.834442373413963 9.302649338467692 3.288249509749743 7.5332370629446075 -0.22649147776392195 -9.989735053643876 -0.566604327517025 9.935584438982744 4.9043104270523665 -1.9470379915198812 -0.852425522663563 -9.853602534771078 -0.11872610922242588 9.997180424697534 2.3747408946139372 -8.800137654252506 -2.615512387847177 -8.522697917682631 0.14655157781557387 9.995703604057049 0.7610819050196274 -9.883471927182606 -4.981530796736325 -0.8587221230818711 0.6368968968992175 9.91854068756491 0.19334674607421926 -9.992520610092834 -3.0161672800006487 7.975646666961492 2.03349686329844 9.135620505900057 -7.838654327826237e-2 -9.99877103444876 -1.0138087400312523 9.79228100876119 4.677230354958941 3.5346944460027387 -0.47086766253242757 -9.95555797419336 -0.28348101128361813 9.98391476651151 3.7179664302226856 -6.6863220454109715 -1.5583638907057538 -9.501894965562276 1.6527799669369146e-2 9.999945366218375 1.3410299891504862 -9.633615846233237 -4.095888446893905 -5.73539809624442 0.34202582033842277 9.976576234003694 0.3962776516617539 -9.968543328449442 -4.382458899620835 4.814168253451109 1.1829624198601882 9.716089730585763 4.400059833845979e-2 -9.999612781972282 -1.7597800494284364 9.360165421109537 3.398381275631299 7.335122277218992 -0.24044091059075776 -9.988430941547183 -0.5405461155003715 9.941390224112006 4.857676431972964 -2.3689488658511912 -0.8914989030577212 -9.839762132459683 -0.10807016478782465 9.997663895027225 2.2832435680603007 -8.896470942775291 -2.71553654688531 -8.39663295911646 0.158114718947752 9.99499869647857 0.7272445339229124 -9.893657642728346 -4.995629667644142 -0.4180154243741523 -} result :: Int result = fst . firstSuchThat (\(_,(x,y)) -> -- this range of x is distinctive so that simply checking sign on y is efficient and correct. x >= -0.01 && x <= 0.01 && y > 0) . zip [0..] -- If the beam leaves at iteration n, there are (n-1) hits on wall, therefore we begin with 0. $ unfoldr (Just . go) (point0, point1) where go (pt0, pt1) = (pt1, (pt1, pt2)) where pt2 = nextPoint pt0 pt1
Javran/Project-Euler
src/ProjectEuler/Problem144.hs
mit
5,997
0
16
1,305
758
429
329
47
2
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./OWL2/MS.hs Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Datatypes specific to the Manchester Syntax of OWL 2 References : <http://www.w3.org/TR/owl2-manchester-syntax/> -} module OWL2.MS where import Common.Id import Common.IRI import qualified OWL2.AS as AS import Data.Data import qualified Data.Map as Map import qualified Data.Set as Set {- | annotions are annotedAnnotationList that must be preceded by the keyword @Annotations:@ if non-empty -} type Annotations = [AS.Annotation] type AnnotatedList a = [(Annotations, a)] -- | this datatype extends the Manchester Syntax to also allow GCIs data Extended = Misc Annotations | ClassEntity AS.ClassExpression | ObjectEntity AS.ObjectPropertyExpression | SimpleEntity AS.Entity deriving (Show, Eq, Ord, Typeable, Data) -- | frames with annotated lists data ListFrameBit = AnnotationBit (AnnotatedList AS.AnnotationProperty) -- relation | ExpressionBit (AnnotatedList AS.ClassExpression) -- relation | ObjectBit (AnnotatedList AS.ObjectPropertyExpression) -- relation | DataBit (AnnotatedList AS.DataPropertyExpression) -- relation | IndividualSameOrDifferent (AnnotatedList AS.NamedIndividual) -- relation | ObjectCharacteristics (AnnotatedList AS.Character) | DataPropRange (AnnotatedList AS.DataRange) | IndividualFacts (AnnotatedList Fact) deriving (Show, Eq, Ord, Typeable, Data) data AnnoType = Declaration | Assertion | XmlError String deriving (Show, Eq, Ord, Typeable, Data) -- | frames which start with annotations data AnnFrameBit = AnnotationFrameBit AnnoType | DataFunctional | DatatypeBit AS.DataRange | ClassDisjointUnion [AS.ClassExpression] | ClassHasKey [AS.ObjectPropertyExpression] [AS.DataPropertyExpression] | ObjectSubPropertyChain [AS.ObjectPropertyExpression] deriving (Show, Eq, Ord, Typeable, Data) data Fact = ObjectPropertyFact AS.PositiveOrNegative AS.ObjectPropertyExpression AS.NamedIndividual | DataPropertyFact AS.PositiveOrNegative AS.DataPropertyExpression AS.Literal deriving (Show, Eq, Ord, Typeable, Data) data FrameBit = ListFrameBit (Maybe AS.Relation) ListFrameBit | AnnFrameBit Annotations AnnFrameBit deriving (Show, Eq, Ord, Typeable, Data) data Frame = Frame Extended [FrameBit] deriving (Show, Eq, Ord, Typeable, Data) data Axiom = PlainAxiom { axiomTopic :: Extended -- the Class or Individual , axiomBit :: FrameBit -- the property expressed by the sentence } deriving (Show, Eq, Ord, Typeable, Data) {- Individual: alex <------ axiomTopic Facts: hasParent john <------ axiomBit -} mkExtendedEntity :: AS.Entity -> Extended mkExtendedEntity e@(AS.Entity _ ty iri) = case ty of AS.Class -> ClassEntity $ AS.Expression iri AS.ObjectProperty -> ObjectEntity $ AS.ObjectProp iri _ -> SimpleEntity e getAxioms :: Frame -> [Axiom] getAxioms (Frame e fbl) = map (PlainAxiom e) fbl axToFrame :: Axiom -> Frame axToFrame (PlainAxiom e fb) = Frame e [fb] instance GetRange Axiom where getRange = Range . joinRanges . map rangeSpan . Set.toList . symsOfAxiom data Ontology = Ontology { name :: AS.OntologyIRI , imports :: [AS.ImportIRI] , ann :: [Annotations] , ontFrames :: [Frame] } deriving (Show, Eq, Ord, Typeable, Data) data OntologyDocument = OntologyDocument { prefixDeclaration :: AS.PrefixMap , ontology :: Ontology } deriving (Show, Eq, Ord, Typeable, Data) instance GetRange OntologyDocument emptyOntology :: [Frame] -> Ontology emptyOntology = Ontology nullIRI [] [] emptyOntologyDoc :: OntologyDocument emptyOntologyDoc = OntologyDocument Map.empty $ emptyOntology [] isEmptyOntology :: Ontology -> Bool isEmptyOntology (Ontology oiri annoList impList fs) = isNullIRI oiri && null annoList && null impList && null fs isEmptyOntologyDoc :: OntologyDocument -> Bool isEmptyOntologyDoc (OntologyDocument ns onto) = Map.null ns && isEmptyOntology onto emptyAnnoList :: [a] -> AnnotatedList a emptyAnnoList = map $ \ x -> ([], x) symsOfAxiom :: Axiom -> Set.Set AS.Entity symsOfAxiom (PlainAxiom e f) = Set.union (symsOfExtended e) $ symsOfFrameBit f symsOfExtended :: Extended -> Set.Set AS.Entity symsOfExtended e = case e of Misc as -> symsOfAnnotations as SimpleEntity s -> Set.singleton s ObjectEntity o -> symsOfObjectPropertyExpression o ClassEntity c -> symsOfClassExpression c symsOfObjectPropertyExpression :: AS.ObjectPropertyExpression -> Set.Set AS.Entity symsOfObjectPropertyExpression o = case o of AS.ObjectProp i -> Set.singleton $ AS.mkEntity AS.ObjectProperty i AS.ObjectInverseOf i -> symsOfObjectPropertyExpression i symsOfClassExpression :: AS.ClassExpression -> Set.Set AS.Entity symsOfClassExpression ce = case ce of AS.Expression c -> Set.singleton $ AS.mkEntity AS.Class c AS.ObjectJunction _ cs -> Set.unions $ map symsOfClassExpression cs AS.ObjectComplementOf c -> symsOfClassExpression c AS.ObjectOneOf is -> Set.fromList $ map (AS.mkEntity AS.NamedIndividual) is AS.ObjectValuesFrom _ oe c -> Set.union (symsOfObjectPropertyExpression oe) $ symsOfClassExpression c AS.ObjectHasValue oe i -> Set.insert (AS.mkEntity AS.NamedIndividual i) $ symsOfObjectPropertyExpression oe AS.ObjectHasSelf oe -> symsOfObjectPropertyExpression oe AS.ObjectCardinality (AS.Cardinality _ _ oe mc) -> Set.union (symsOfObjectPropertyExpression oe) $ maybe Set.empty symsOfClassExpression mc AS.DataValuesFrom _ de dr -> Set.union (Set.fromList $ map (AS.mkEntity AS.DataProperty) de) $ symsOfDataRange dr AS.DataHasValue de _ -> Set.singleton $ AS.mkEntity AS.DataProperty de AS.DataCardinality (AS.Cardinality _ _ d m) -> Set.insert (AS.mkEntity AS.DataProperty d) $ maybe Set.empty symsOfDataRange m symsOfDataRange :: AS.DataRange -> Set.Set AS.Entity symsOfDataRange dr = case dr of AS.DataType t _ -> Set.singleton $ AS.mkEntity AS.Datatype t AS.DataJunction _ ds -> Set.unions $ map symsOfDataRange ds AS.DataComplementOf d -> symsOfDataRange d AS.DataOneOf _ -> Set.empty symsOfAnnotation :: AS.Annotation -> Set.Set AS.Entity symsOfAnnotation (AS.Annotation as p _) = Set.insert (AS.mkEntity AS.AnnotationProperty p) $ Set.unions (map symsOfAnnotation as) symsOfAnnotations :: Annotations -> Set.Set AS.Entity symsOfAnnotations = Set.unions . map symsOfAnnotation symsOfFrameBit :: FrameBit -> Set.Set AS.Entity symsOfFrameBit fb = case fb of ListFrameBit _ lb -> symsOfListFrameBit lb AnnFrameBit as af -> Set.union (symsOfAnnotations as) $ symsOfAnnFrameBit af symsOfAnnFrameBit :: AnnFrameBit -> Set.Set AS.Entity symsOfAnnFrameBit af = case af of AnnotationFrameBit _ -> Set.empty DataFunctional -> Set.empty DatatypeBit dr -> symsOfDataRange dr ClassDisjointUnion cs -> Set.unions $ map symsOfClassExpression cs ClassHasKey os ds -> Set.union (Set.unions $ map symsOfObjectPropertyExpression os) . Set.fromList $ map (AS.mkEntity AS.DataProperty) ds ObjectSubPropertyChain os -> Set.unions $ map symsOfObjectPropertyExpression os symsOfListFrameBit :: ListFrameBit -> Set.Set AS.Entity symsOfListFrameBit lb = case lb of AnnotationBit l -> annotedSyms (Set.singleton . AS.mkEntity AS.AnnotationProperty) l ExpressionBit l -> annotedSyms symsOfClassExpression l ObjectBit l -> annotedSyms symsOfObjectPropertyExpression l DataBit l -> annotedSyms (Set.singleton . AS.mkEntity AS.DataProperty) l IndividualSameOrDifferent l -> annotedSyms (Set.singleton . AS.mkEntity AS.NamedIndividual) l ObjectCharacteristics l -> annotedSyms (const Set.empty) l DataPropRange l -> annotedSyms symsOfDataRange l IndividualFacts l -> annotedSyms symsOfFact l symsOfFact :: Fact -> Set.Set AS.Entity symsOfFact fact = case fact of ObjectPropertyFact _ oe i -> Set.insert (AS.mkEntity AS.NamedIndividual i) $ symsOfObjectPropertyExpression oe DataPropertyFact _ d _ -> Set.singleton $ AS.mkEntity AS.DataProperty d annotedSyms :: (a -> Set.Set AS.Entity) -> AnnotatedList a -> Set.Set AS.Entity annotedSyms f l = Set.union (Set.unions $ map (symsOfAnnotations . fst) l) . Set.unions $ map (f . snd) l
spechub/Hets
OWL2/MS.hs
gpl-2.0
8,327
0
15
1,356
2,471
1,245
1,226
161
11
module Network.Gitit2.Handler.Diff ( getDiffR ) where import Control.Exception (catch, throw) import Data.FileStore (diff, RevisionId) import qualified Data.FileStore as FS import Data.List (intercalate) import Network.Gitit2.Import import Network.Gitit2.Page (pathForFile) getDiffR :: HasGitit master => RevisionId -> RevisionId -> Page -> GH master Html getDiffR fromRev toRev page = do fs <- filestore <$> getYesod pagePath <- pathForPage page let filePath = pathForFile page rawDiff <- liftIO $ catch (diff fs pagePath (Just fromRev) (Just toRev)) $ \e -> case e of FS.NotFound -> diff fs filePath (Just fromRev) (Just toRev) _ -> throw e makePage pageLayout{ pgName = Just page , pgTabs = [] , pgSelectedTab = EditTab } $ [whamlet| <h1 .title>#{page} <h2 .revision>#{fromRev} &rarr; #{toRev} <pre> $forall t <- rawDiff $case t $of FS.Both xs _ <span .unchanged>#{intercalate "\n" xs} $of FS.First xs <span .deleted>#{intercalate "\n" xs} $of FS.Second xs <span .added>#{intercalate "\n" xs} |]
thkoch2001/gitit2
Network/Gitit2/Handler/Diff.hs
gpl-2.0
1,322
0
15
468
276
148
128
-1
-1
module Language.Haskell.HsColour.ColourHighlight ( Colour(..) , Highlight(..) , base256, unbase , rgb24bit_to_xterm256 , projectToBasicColour8 , hlProjectToBasicColour8 ) where {-@ LIQUID "--totality" @-} import Data.Word -- | Colours supported by ANSI codes. data Colour = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White | Rgb Word8 Word8 Word8 deriving (Eq,Show,Read) {-@ measure isBasic :: Colour -> Int isBasic (Black) = 1 isBasic (Red) = 1 isBasic (Green) = 1 isBasic (Yellow) = 1 isBasic (Blue) = 1 isBasic (Magenta) = 1 isBasic (Cyan) = 1 isBasic (White) = 1 isBasic (Rgb r g b) = 0 @-} {-@ invariant {v:Colour | (((isBasic v) == 1) || ((isBasic v) == 0))} @-} {-@ ensureBasic :: String -> Colour -> BasicColour @-} ensureBasic :: String -> Colour -> Colour ensureBasic msg (Rgb _ _ _) = error $ "ensureBasic: " ++ msg ensureBasic _ x = x {-@ type BasicColour = {v:Colour | (isBasic v) = 1} @-} -- | Convert an integer in the range [0,2^24-1] to its base 256-triplet, passing the result to the given continuation (avoid unnecessary tupleism). base256 :: Integral int => (Word8 -> Word8 -> Word8 -> r) -> int -> r base256 kont x = let (r,gb) = divMod x 256 (g,b) = divMod gb 256 fi = fromIntegral in kont (fi r) (fi g) (fi b) -- | Convert a three-digit numeral in the given (as arg 1) base to its integer value. unbase :: Integral int => int -> Word8 -> Word8 -> Word8 -> int unbase base r g b = (fi r*base+fi g)*base+fi b where fi = fromIntegral -- | Approximate a 24-bit Rgb colour with a colour in the xterm256 6x6x6 colour cube, returning its index. rgb24bit_to_xterm256 :: (Integral t) => Word8 -> Word8 -> Word8 -> t rgb24bit_to_xterm256 r g b = let f = (`div` 43) in 16 + unbase 6 (f r) (f g) (f b) -- | Ap\"proxi\"mate a 24-bit Rgb colour with an ANSI8 colour. Will leave other colours unchanged and will never return an 'Rgb' constructor value. {-@ projectToBasicColour8 :: Colour -> BasicColour @-} projectToBasicColour8 :: Colour -> Colour projectToBasicColour8 (Rgb r g b) = let f = (`div` 128) in ensureBasic "projectToBasicColour8" $ toEnum ( unbase 2 (f r) (f g) (f b) ) projectToBasicColour8 x = x -- | Lift 'projectToBasicColour8' to 'Highlight's hlProjectToBasicColour8 :: Highlight -> Highlight hlProjectToBasicColour8 (Foreground c) = Foreground (projectToBasicColour8 c) hlProjectToBasicColour8 (Background c) = Background (projectToBasicColour8 c) hlProjectToBasicColour8 h = h instance Enum Colour where toEnum 0 = Black toEnum 1 = Red toEnum 2 = Green toEnum 3 = Yellow toEnum 4 = Blue toEnum 5 = Magenta toEnum 6 = Cyan toEnum 7 = White -- Arbitrary extension; maybe just 'error' out instead toEnum x = base256 Rgb (x-8) fromEnum Black = 0 fromEnum Red = 1 fromEnum Green = 2 fromEnum Yellow = 3 fromEnum Blue = 4 fromEnum Magenta = 5 fromEnum Cyan = 6 fromEnum White = 7 -- Arbitrary extension; maybe just 'error' out instead fromEnum (Rgb r g b) = 8 + unbase 256 r g b -- | Types of highlighting supported by ANSI codes (and some extra styles). data Highlight = Normal | Bold | Dim | Underscore | Blink | ReverseVideo | Concealed | Foreground Colour | Background Colour -- The above styles are ANSI-supported, with the exception of the 'Rgb' constructor for 'Colour's. Below are extra styles (e.g. for Html rendering). | Italic deriving (Eq,Show,Read)
nikivazou/hscolour
Language/Haskell/HsColour/ColourHighlight.hs
gpl-2.0
3,704
0
12
989
836
447
389
66
1
{- | Module : $Header$ Description : Interface to the CspCASLProver (Isabelle based) theorem prover Copyright : (c) Liam O'Reilly and Markus Roggenbach, Swansea University 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Interface for CspCASLProver theorem prover. -} {- Interface between CspCASLProver and Hets: Hets writes CspCASLProver's Isabelle .thy files and starts Isabelle with CspProver User extends .thy file with proofs User finishes Isabelle Hets reads in created *.deps files -} module CspCASLProver.CspCASLProver ( cspCASLProver ) where import CASL.AS_Basic_CASL import CASL.Fold import CASL.Sign (CASLSign, Sign (..), sortSet) import Common.AS_Annotation (Named, mapNamedM) import Common.Result import qualified Comorphisms.CASL2PCFOL as CASL2PCFOL import qualified Comorphisms.CASL2SubCFOL as CASL2SubCFOL import qualified Comorphisms.CFOL2IsabelleHOL as CFOL2IsabelleHOL import CspCASL.SignCSP import CspCASL.Morphism (CspCASLMorphism) import CspCASLProver.Consts import CspCASLProver.IsabelleUtils import CspCASLProver.Utils import qualified Data.Maybe as Maybe import qualified Data.Set as Set import Isabelle.IsaProve (isaProve) import qualified Isabelle.IsaSign as Isa import Logic.Prover import Logic.Comorphism (wrapMapTheory) -- | The string that Hets uses as CspCASLProver cspCASLProverS :: String cspCASLProverS = "CspCASLProver" -- | The wrapper function that is CspCASL Prover cspCASLProver :: Prover CspCASLSign CspCASLSen CspCASLMorphism () () cspCASLProver = mkProverTemplate cspCASLProverS () cspCASLProverProve -- | The main cspCASLProver function cspCASLProverProve :: String -> Theory CspCASLSign CspCASLSen () -> a -> IO [ProofStatus ()] cspCASLProverProve thName (Theory ccSign ccSensThSens) _freedefs = let -- get the CASL signature of the data part of the CspcASL theory caslSign = ccSig2CASLSign ccSign -- Get a list of CspCASL named sentences ccNamedSens = toNamedList ccSensThSens -- A filter to change a CspCASLSen to a CASLSen (if possible) caslSenFilter ccSen = case ccSen of ExtFORMULA (ProcessEq {}) -> Nothing sen -> Just $ foldFormula (mapRecord $ const ()) sen -- All named CASL sentences from the datapart caslNamedSens = Maybe.mapMaybe (mapNamedM caslSenFilter) ccNamedSens -- Generate data encoding. This may fail. Result diag dataTh = produceDataEncoding caslSign caslNamedSens in case dataTh of Nothing -> do -- Data translation failed putStrLn $ "Sorry, could not encode the data part:" ++ show diag return [] Just (dataThSig, dataThSens, pcfolSign, cfolSign) -> do {- Data translation succeeded Write out the data encoding -} writeIsaTheory (mkThyNameDataEnc thName) (Theory dataThSig (toThSens dataThSens)) {- Generate and write out the preAlpbate, justification theorems and the instances code. -} writeIsaTheory (mkThyNamePreAlphabet thName) (producePreAlphabet thName caslSign pcfolSign) {- Generate and write out the Alpbatet construction, bar types and choose functions. -} writeIsaTheory (mkThyNameAlphabet thName) (produceAlphabet thName caslSign) -- Generate and write out the integration theorems writeIsaTheory (mkThyNameIntThms thName) (produceIntegrationTheorems thName caslSign) {- Generate and Isabelle to prove the process refinements (also produces the processes) -} isaProve thName (produceProcesses thName ccSign ccNamedSens pcfolSign cfolSign) () {- |Produce the Isabelle theory of the data part of a CspCASL specification. The data transalation can fail. If it does fail there will be an error message. Its arguments are the CASL signature from the data part and a list of the named CASL sentences from the data part. Returned are the Isabelle signature, Isabelle named sentences and also the CASL signature of the data part after translation to pcfol (i.e. with out subsorting) and cfol (i.e. with out subsorting and partiality). -} produceDataEncoding :: CASLSign -> [Named CASLFORMULA] -> Result (Isa.Sign, [Named Isa.Sentence], CASLSign, CASLSign) produceDataEncoding caslSign caslNamedSens = let -- Comorphisms casl2pcfol = wrapMapTheory CASL2PCFOL.CASL2PCFOL pcfol2cfol = wrapMapTheory $ CASL2SubCFOL.CASL2SubCFOL True CASL2SubCFOL.AllSortBottoms cfol2isabelleHol = wrapMapTheory CFOL2IsabelleHOL.CFOL2IsabelleHOL in do {- Remove Subsorting from the CASL part of the CspCASL specification -} th_pcfol <- casl2pcfol (caslSign, caslNamedSens) -- Next Remove partial functions th_cfol <- pcfol2cfol th_pcfol -- Next Translate to IsabelleHOL code (th_isa_Sig, th_isa_Sens) <- cfol2isabelleHol th_cfol return (th_isa_Sig, th_isa_Sens, fst th_pcfol, fst th_cfol) {- | Produce the Isabelle theory which contains the PreAlphabet, Justification Theorems and also the instances code. We need the PFOL signature which is the data part CASL signature after translation to PCFOL (i.e. without subsorting) to pass on as an argument. -} producePreAlphabet :: String -> CASLSign -> CASLSign -> Theory Isa.Sign Isa.Sentence () producePreAlphabet thName caslSign pfolSign = let sortList = Set.toList (sortSet caslSign) {- empty Isabelle signature which imports the data encoding and quotient.thy (which is needed for the instances code) -} isaSignEmpty = Isa.emptySign {Isa.imports = [mkThyNameDataEnc thName , quotientThyS] } -- Start with our empty Isabelle theory, add the constructs (isaSign, isaSens) = addInstanceOfEquiv $ addJustificationTheorems caslSign pfolSign $ addAllGaAxiomsCollections caslSign pfolSign $ addEqFun sortList $ addAllCompareWithFun caslSign $ addPreAlphabet sortList (isaSignEmpty, []) in Theory isaSign (toThSens isaSens) {- |Produce the Isabelle theory which contains the Alphabet construction, and also the bar types and choose fucntions for CspCASLProver. -} produceAlphabet :: String -> CASLSign -> Theory Isa.Sign Isa.Sentence () produceAlphabet thName caslSign = let sortList = Set.toList (sortSet caslSign) -- empty Isabelle signature which imports the preAlphabet encoding isaSignEmpty = Isa.emptySign { Isa.imports = [mkThyNamePreAlphabet thName]} {- Start with our empty isabelle theory, add the Alphabet type , then the bar types and finally the choose functions. -} (isaSign, isaSens) = addAllChooseFunctions sortList $ addAllBarTypes sortList $ addAlphabetType (isaSignEmpty, []) in Theory isaSign (toThSens isaSens) {- |Produce the Isabelle theory which contains the Integration Theorems on data -} produceIntegrationTheorems :: String -> CASLSign -> Theory Isa.Sign Isa.Sentence () produceIntegrationTheorems thName caslSign = let sortList = Set.toList (sortSet caslSign) -- empty Isabelle signature which imports the alphabet encoding isaSignEmpty = Isa.emptySign {Isa.imports = [mkThyNameAlphabet thName] } {- Start with our empty isabelle theory and add the integration theorems. -} (isaSign, isaSens) = addAllIntegrationTheorems sortList caslSign (isaSignEmpty, []) in Theory isaSign (toThSens isaSens) {- |Produce the Isabelle theory which contains the Process Translations and process refinement theorems. We -- need the PCFOL and CFOL signatures of the data part after translation to PCFOL and CFOL to pass -- along to the process translation. -} produceProcesses :: String -> CspCASLSign -> [Named CspCASLSen] -> CASLSign -> CASLSign -> Theory Isa.Sign Isa.Sentence () produceProcesses thName ccSign ccNamedSens pcfolSign cfolSign = let caslSign = ccSig2CASLSign ccSign cspSign = ccSig2CspSign ccSign sortList = Set.toList (sortSet caslSign) sortRel' = sortRel caslSign chanNameMap = chans cspSign {- Isabelle signature which imports the integration theorems encoding and CSP_F -} isaSignEmpty = Isa.emptySign {Isa.imports = [mkThyNameIntThms thName , cspFThyS] } {- Start with our empty isabelle theory and add the processes the the process refinement theorems. -} (isaSign, isaSens) = addProcTheorems ccNamedSens ccSign pcfolSign cfolSign $ addProcMap ccNamedSens ccSign pcfolSign cfolSign $ addProcNameDatatype cspSign $ addFlatTypes sortList $ addProjFlatFun $ addEventDataType sortRel' chanNameMap (isaSignEmpty, []) in Theory isaSign (toThSens isaSens)
nevrenato/HetsAlloy
CspCASLProver/CspCASLProver.hs
gpl-2.0
9,414
0
17
2,421
1,378
725
653
116
3
------------------------------------------------------------------------------ -- A simple banner program: Mark P Jones, 1992 -- -- Many years ago, I was helping out on a stand at a computer show. -- Or at least, I would have been if anyone had been interested in -- what we had on the stand. So instead, I sat down to see if I -- could write a banner program -- something to print messages out -- in large letters. -- -- The original program was in Basic, but here is a version in Hugs. -- The program itself is only two lines long and that is rather pleasing, -- but the raw data for the letters (and the function mapping characters -- to letters) take up rather more space. I don't have that Basic version -- anymore. I wonder whether the complete Hugs code is that much shorter? -- -- One of the nice things about this program is that the main program is -- completely independent of the size of characters. You could easily add -- a new font, perhaps with higher resolution (bigger letters), or even -- variable width characters, and the program would take it all in its -- stride. -- -- If you have a wide screen (>80 cols), you might like to try evaluating: -- -- (putStr . concat . map say . lines . say) "Hi" -- -- and contemplating how easy it might have been to get my original -- Basic version to perform this trick... -- -- Enjoy! ------------------------------------------------------------------------------ module D_Say where import Char( ord, chr, isSpace, isUpper, isLower, isDigit ) import List( transpose ) sayit :: String -> IO () sayit = putStr . say say = ('\n':) . unlines . map join . transpose . map picChar where join = foldr1 (\xs ys -> xs ++ " " ++ ys) -- mapping characters to letters: -------------------------------------------- picChar c | isUpper c = alphas !! (ord c - ord 'A') | isLower c = alphas !! (ord c - ord 'a') | isSpace c = blank | isDigit c = digits !! (ord c - ord '0') | c=='/' = slant | c=='\\' = reverse slant | otherwise = head ([ letter | (c',letter) <- punct, c'==c ] ++ [nothing]) -- letters data: ------------------------------------------------------------- blank = [" ", " ", " ", " ", " "] slant = [" ", " ", " ", " ", "" ] nothing= repeat "" punct = [('.', [" ", " ", " ", " .. ", " .. "]), ('?', [" ??? ", "? ?", " ? ", " ? ", " . "]), ('!', [" ! ", " ! ", " ! ", " ! ", " . "]), ('-', [" ", " ", "-----", " ", " "]), ('+', [" + ", " + ", "+++++", " + ", " + "]), (':', [" ", " :: ", " ", " :: ", " "]), (';', [" ", " ;; ", " ", " ;; ", " ;; "]) ] digits = [[" OOO ", "0 00", "0 0 0", "00 0", " 000 "], [" 1 ", " 11 ", " 1 ", " 1 ", "11111"], [" 222 ", "2 2", " 2 ", " 2 ", "22222"], ["3333 ", " 3", " 333 ", " 3", "3333 "], [" 4 ", " 44 ", " 4 4 ", "44444", " 4 "], ["55555", "5 ", "5555 ", " 5", "5555 "], [" 66", " 6 ", " 666 ", "6 6", " 666 "], ["77777", " 7", " 7 ", " 7 ", " 7 "], [" 888 ", "8 8", " 888 ", "8 8", " 888 "], [" 999 ", "9 9", " 999 ", " 9 ", "99 "]] alphas = [[" A ", " A A ", "AAAAA", "A A", "A A"], ["BBBB ", "B B", "BBBB ", "B B", "BBBB "], [" CCCC", "C ", "C ", "C ", " CCCC"], ["DDDD ", "D D", "D D", "D D", "DDDD "], ["EEEEE", "E ", "EEEEE", "E ", "EEEEE"], ["FFFFF", "F ", "FFFF ", "F ", "F "], [" GGGG", "G ", "G GG", "G G", " GGG "], ["H H", "H H", "HHHHH", "H H", "H H"], ["IIIII", " I ", " I ", " I ", "IIIII"], ["JJJJJ", " J ", " J ", "J J ", " JJ "], ["K K", "K K ", "KKK ", "K K ", "K K"], ["L ", "L ", "L ", "L ", "LLLLL"], ["M M", "MM MM", "M M M", "M M", "M M"], ["N N", "NN N", "N N N", "N NN", "N N"], [" OOO ", "O O", "O O", "O O", " OOO "], ["PPPP ", "P P", "PPPP ", "P ", "P "], [" QQQ ", "Q Q", "Q Q Q", "Q Q ", " QQ Q"], ["RRRR ", "R R", "RRRR ", "R R ", "R R"], [" SSSS", "S ", " SSS ", " S", "SSSS "], ["TTTTT", " T ", " T ", " T ", " T "], ["U U", "U U", "U U", "U U", " UUU "], ["V V", "V V", "V V", " V V ", " V "], ["W W", "W W", "W W", "W W W", " W W "], ["X X", " X X ", " X ", " X X ", "X X"], ["Y Y", " Y Y ", " Y ", " Y ", " Y "], ["ZZZZZ", " Z ", " Z ", " Z ", "ZZZZZ"] ] -- end of banner program -----------------------------------------------------
gennady-em/haskel
src/D_Say.hs
gpl-2.0
5,046
0
12
1,907
1,209
766
443
61
1
{-# LANGUAGE CPP, OverloadedStrings #-} module Buildsome.Chart ( make ) where import Buildsome.Stats (Stats(..)) import Data.ByteString (ByteString) import Data.Map (Map) import Data.Monoid ((<>)) import Lib.FilePath (FilePath) import Prelude hiding (FilePath) import qualified Buildsome.BuildMaps as BuildMaps import qualified Buildsome.Stats as Stats import qualified Data.ByteString.Char8 as BS8 import qualified Data.Map as M #ifdef WITH_CHARTS_SUPPORT import Control.Monad (void) import Data.Default.Class (def) import qualified Graphics.Rendering.Chart as Chart import qualified Graphics.Rendering.Chart.Backend.Cairo as ChartCairo buildTimes :: Stats -> Chart.PieChart buildTimes stats = def { Chart._pie_data = dataPoints } where dataPoints = let f (targetRep, targetStats) = def { Chart._pitem_label = BS8.unpack $ BuildMaps.targetRepPath targetRep , Chart._pitem_value = realToFrac (Stats.tsTime targetStats) } in map f $ M.toList $ Stats.ofTarget stats makePieChart :: Stats -> FilePath -> IO () makePieChart stats filePath = do putStrLn $ "Writing chart to " ++ show filePath void $ ChartCairo.renderableToFile fileOptions (Chart.toRenderable plot) $ BS8.unpack filePath where fileOptions = def { ChartCairo._fo_format = ChartCairo.SVG , ChartCairo._fo_size = (16384, 16384) } plot = def { Chart._pie_plot = buildTimes stats } #else makePieChart :: Stats -> FilePath -> IO () makePieChart _ _ = putStrLn "Re-build buildsome with the Charts flag enabled to get pie charts!" #endif type Key = ByteString data Node = Node { nodeDests :: [Key] , nodeFontSize :: Double } newtype Graph = Graph { _graph :: Map Key Node } indent :: ByteString -> ByteString indent = BS8.unlines . map (" " <>) . BS8.lines dotRenderGraph :: ByteString -> Graph -> ByteString dotRenderGraph graphName (Graph nodes) = BS8.unlines $ [ "digraph " <> graphName <> " {" , indent "rankdir=LR;" ] ++ map (indent . nodeStr) (M.toList nodes) ++ [ "}" ] where nodeStr (node, Node dests fontSize) = BS8.unlines $ ( BS8.pack (show node) <> " [fontsize=" <> BS8.pack (show fontSize) <> "];" ) : [ " " <> BS8.pack (show node) <> " -> " <> BS8.pack (show dest) <> ";" | dest <- dests ] statsGraph :: Stats -> Graph statsGraph = Graph . M.map toNode . M.mapKeys BuildMaps.targetRepPath . M.filter hasDeps . Stats.ofTarget where hasDeps targetStats = not $ null $ Stats.tsDirectDeps targetStats toNode targetStats = Node { nodeDests = map targetAsByteString $ Stats.tsDirectDeps targetStats , nodeFontSize = 20 + 5 * realToFrac (Stats.tsTime targetStats) } targetAsByteString = BuildMaps.targetRepPath . BuildMaps.computeTargetRep makeDotChart :: Stats -> FilePath -> IO () makeDotChart stats filePath = do putStrLn $ "Writing dot file to " ++ show filePath BS8.writeFile (BS8.unpack filePath) $ dotRenderGraph "Dependencies" $ statsGraph stats make :: Stats -> FilePath -> IO () make stats filePathBase = do makePieChart stats (filePathBase <> ".svg") makeDotChart stats (filePathBase <> ".dot")
nadavshemer/buildsome
src/Buildsome/Chart.hs
gpl-2.0
3,203
0
16
667
941
508
433
60
1
module H.Data where import Control.Applicative import qualified Data.List as L import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Data.Text.Lazy.Builder (toLazyText) import Data.Text.Format (left) import Data.Text.Buildable (Buildable) import Data.Time import Test.QuickCheck data Task = Task { description :: String , tags :: [String] , context :: Maybe String , isComplete :: Bool , estimated :: Maybe DiffTime , spent :: Maybe DiffTime , started :: Maybe LocalTime } deriving (Eq, Show) class Encode a where encode :: a -> String instance Encode Task where encode t = (if isComplete t then "x " else "") ++ maybe "" (\c -> '@':c ++ " ") (context t) ++ description t ++ " " ++ concat (fmap (\tg -> '+' : tg ++ " ") (tags t)) ++ maybe "" (\s -> '(' : encode s ++ maybe "" (\sp -> ',' : encode sp) (spent t) ++ ") ") (estimated t) ++ maybe "" (\s -> '{' : encode s ++ "}") (started t) instance Encode DiffTime where encode 0 = "" encode tod = encode . timeToTimeOfDay $ tod instance Encode TimeOfDay where encode (TimeOfDay 0 0 _) = "" encode tod = show (todHour tod) ++ ":" ++ twoDigit (todMin tod) instance Encode Day where encode = (\(y, m, d) -> L.intercalate "/" [twoDigit m, twoDigit d, show y]) . toGregorian instance Encode LocalTime where encode lt = encode (localDay lt) ++ case encode (localTimeOfDay lt) of "" -> "" tod -> ' ' : tod twoDigit :: Buildable a => a -> String twoDigit = LT.unpack . toLazyText . left 2 '0' emptyTask :: Task emptyTask = Task "" [] Nothing False Nothing Nothing Nothing task :: String -> Task task d = emptyTask { description = d } describe :: String -> Task -> Task describe d t = t { description = description t ++ d } tag :: String -> Task -> Task tag tg tk = tk { tags = tg : tags tk } contextualize :: String -> Task -> Task contextualize c t = t { context = Just c } complete :: Task -> Task complete t = t { isComplete = True } estimate :: DiffTime -> Task -> Task estimate tm tk = tk { estimated = Just tm } spend :: DiffTime -> Task -> Task spend tm tk = tk { spent = Just tm } start :: LocalTime -> Task -> Task start tm tk = tk { started = Just tm } hours :: Int -> DiffTime hours n = timeOfDayToTime $ TimeOfDay n 0 0 minutes :: Int -> DiffTime minutes n = timeOfDayToTime $ TimeOfDay 0 n 0 normalize :: Task -> Task normalize t = t { description = strip . description $ t } strip :: String -> String strip = T.unpack . T.strip . T.pack -- Visible for testing only (here to avoid orphans) instance Arbitrary Task where arbitrary = (start <$> aLocalTime) <.> (spend <$> aDiffTime) <.> (estimate <$> aDiffTime) <.> (contextualize <$> nonEmptyAlphaNums) <.> (tag <$> nonEmptyAlphaNums) <.> (describe <$> nonEmptyAlphaNums) <*> pure emptyTask nonEmptyAlphaNums :: Gen String nonEmptyAlphaNums = (getNonEmpty <$> arbitrary) `suchThat` all isAlphaNum isAlphaNum :: Char -> Bool isAlphaNum = (`elem` (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'])) aDiffTime :: Gen DiffTime aDiffTime = ((+) . hours <$> (getNonNegative <$> arbitrary `suchThat` (<24))) <*> (minutes <$> (getNonNegative <$> arbitrary `suchThat` (<60))) aTimeOfDay :: Gen TimeOfDay aTimeOfDay = timeToTimeOfDay <$> aDiffTime aLocalTime :: Gen LocalTime aLocalTime = LocalTime <$> (fromGregorian 2014 <$> (getNonNegative <$> arbitrary) <*> (getNonNegative <$> arbitrary)) <*> aTimeOfDay (<.>) :: Applicative f => f (b -> c) -> f (a -> b) -> f (a -> c) f <.> g = ((.) <$> f) <*> g
josuf107/H
H/Data.hs
gpl-2.0
3,737
0
17
952
1,412
762
650
104
1
{-#LANGUAGE BangPatterns #-} {- Enumerate all closed Knight's Tours in an arbitrarity sized chessboard. Multi-threaded version. Usage: KnightTours m n +RTS -N Compile with: ghc -O3 -threaded -rtsopts -fllvm --make KnightTours Examples: A small example is the 3x12 board Author: Jyotirmoy Bhattacharya ([email protected]) This program has been put into the public domain by the author. -} module Main (main) where import Prelude hiding ((!),read,replicate) import qualified Prelude import Control.Parallel.Strategies import Control.Parallel import Data.Char (chr,ord) import qualified Data.Vector.Unboxed as V import qualified Data.Vector as BV import qualified Data.Vector.Unboxed.Mutable as MV import Data.Vector.Generic ((!),(//),unsafeIndex, toList,generate, replicate,freeze,thaw) import Data.Vector.Generic.Mutable (read,write,unsafeRead,unsafeWrite) import Control.Monad.ST import Control.Monad import System.Environment (getArgs) main::IO () main = do [p,q] <- (map Prelude.read) <$> getArgs guard (p>0 && q>0) let chessG = mkChessGraph p q let cycles = enumHamCycle chessG n <- countAndPrint 0 chessG cycles putStrLn $ "Total cycles = "++(show n) where countAndPrint::Int->Graph->[V.Vector Int]->IO Int countAndPrint !accum g [] = return accum countAndPrint !accum g (c:cs) = do putStrLn $ prettyPath g (toList c) countAndPrint (accum+1) g cs data Graph = Graph{ gNVerts::Int, gNames::BV.Vector String, gNeighs::BV.Vector [Int] } deriving Show -- Enumerate all Hamiltonian cycles in the given graph enumHamCycle::Graph->[V.Vector Int] enumHamCycle g = completeHamCyclePar g 1 (n - 1) path visited where n = gNVerts g path = replicate n 0 visited = (replicate n False) // [(0,True)] -- Try to complete a path into a Hamiltonian cycle -- (parallel version) completeHamCyclePar::Graph->Int->Int ->V.Vector Int->V.Vector Bool ->[V.Vector Int] completeHamCyclePar g !depth !remain !path !visited | remain == 0 = if 0 `elem` choices then [path] else [] | depth < 6 = concat $ withStrategy (evalList rpar) [completeHamCyclePar g (depth+1) (remain-1) (path // [(depth,c)]) (visited // [(c,True)]) | c <- choices, not $ visited ! c ] | otherwise = runST $ do p <- thaw path v <- thaw visited completeHamCycleSeq g remain p v where last= path ! (depth-1) choices = (gNeighs g) ! last -- Try to complete a path into a Hamiltonian cycles -- (sequential version) completeHamCycleSeq::Graph->Int ->MV.MVector s Int->MV.MVector s Bool ->ST s [V.Vector Int] completeHamCycleSeq g !remain !path !visited = do let depth = gNVerts g - remain last <- unsafeRead path (depth-1) let !choices = (gNeighs g) `unsafeIndex` last if remain == 0 then if 0 `elem` choices then do ans <- freeze path return [ans] else return [] else do children <- forM choices $ \c -> do v <- unsafeRead visited c if v then do return [] else do unsafeWrite path depth c unsafeWrite visited c True ans <- completeHamCycleSeq g (remain-1) path visited unsafeWrite visited c False ans `seq` (return ans) return $ concat children -- Make the graph corresponding to -- a knight's moves on a mxn chessboard mkChessGraph::Int->Int->Graph mkChessGraph m n = Graph {gNVerts = nv, gNames = generate nv genName, gNeighs = generate nv genNeighs} where nv = m*n deidx k = k `divMod` n idx i j = i*n+j genName k = let (i,j) = deidx k in chr (ord 'A'+i):(show j) genNeighs k = let (i,j) = deidx k in [idx p q| (x,y)<-[(1,2),(1,-2),(-1,2),(-1,-2), (2,1),(2,-1),(-2,1),(-2,-1)], let p = i+x, let q = j+y, p>=0 && p<m && q>=0 && q<n] -- Pretty print path in a graph prettyPath::Graph->[Int]->String prettyPath g = concat . map ((gNames g) !)
jmoy/knights_tours
haskell/KnightTours.hs
gpl-3.0
4,283
0
21
1,236
1,492
789
703
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module IniParser where import Control.Applicative import Data.ByteString (ByteString) import Data.Map (Map) import qualified Data.Map as M import Text.RawString.QQ import Text.Trifecta -- INI File Format -- # comment -- ; comment -- [section] -- host=wikipedia.org -- alias=claw newtype Header = Header String deriving (Eq, Ord, Show) type Name = String type Value = String type Assignments = Map Name Value data Section = Section Header Assignments deriving (Eq, Show) newtype Config = Config (Map Header Assignments) deriving (Eq, Show) skipEOL :: Parser () skipEOL = skipMany (oneOf "\n") skipWhitespace :: Parser () skipWhitespace = skipMany (char ' ' <|> char '\n') skipComments :: Parser () skipComments = skipMany (do _ <- char ';' <|> char '#' skipMany (noneOf "\n") skipEOL) parseBracketPair :: Parser a -> Parser a parseBracketPair p = char '[' *> p <* char ']' parseHeader :: Parser Header parseHeader = parseBracketPair (Header <$> some letter) parseAssignment :: Parser (Name, Value) parseAssignment = do name <- some alphaNum _ <- char '=' val <- some (noneOf "\n") skipEOL return (name, val) parseSection :: Parser Section parseSection = do skipWhitespace skipComments h <- parseHeader skipEOL skipComments assignments <- some parseAssignment return $ Section h (M.fromList assignments) rollup :: Section -> Map Header Assignments -> Map Header Assignments rollup (Section h a) m = M.insert h a m parseIni :: Parser Config parseIni = do sections <- some parseSection let mapOfSections = foldr rollup M.empty sections return $ Config mapOfSections ----------------------------------------- -- Examples ----------------------------------------- headerEx :: ByteString headerEx = "[blah]" commentEx :: ByteString commentEx = "; last modified 1 April\ \ 2001 by John Doe" commentEx' :: ByteString commentEx' = "; blah\n; woot\n \n;hah" sectionEx :: ByteString sectionEx = "; ignore me\n[states]\nChris=Texas" assignmentEx :: ByteString assignmentEx = "woot=1" sectionEx' :: ByteString sectionEx' = [r| ; ignore me [states] Chris=Texas |] sectionEx'' :: ByteString sectionEx'' = [r| ; comment [section] host=wikipedia.org alias=claw [whatisit] red=intoothandclaw |]
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
ParserCombinators/src/IniParser.hs
gpl-3.0
2,434
0
11
515
636
334
302
79
1
module ClanFetcher( Clan(..), TagExpr, ClanID, matchTagExpr, prettyTagExpr, tagExprGet, getClanList, clanListFromCache , matchClanByID ) where import Prelude as P import Control.Applicative import Control.Exception import Control.Monad import Data.ByteString.Char8 as B import Data.ByteString.Lazy.Char8 as L import Data.List as List import Data.Maybe import Data.Ord import Network.Socket import Network.HTTP import Network.Stream import Network.URI import Network.Tremulous.NameInsensitive import TremFormatting import Constants import Monad2 data TagExpr = TagPrefix !TI | TagSuffix !TI | TagInfix !TI | TagContained !TI !TI deriving Eq instance Ord TagExpr where compare = comparing tagExprGet tagExprGet :: TagExpr -> TI tagExprGet x = case x of TagPrefix v -> v TagSuffix v -> v TagInfix v -> v TagContained v _ -> v type ClanID = Int data Clan = Clan { clanID :: !ClanID , name :: !TI , website , irc :: !B.ByteString , websitealive :: !Bool , tagexpr :: !TagExpr , clanserver :: !(Maybe SockAddr) } matchClanByID :: [Clan] -> TI -> ClanID -> Bool matchClanByID clans raw cid = case List.find (\x -> clanID x == cid) clans of Just a -> matchTagExpr (tagexpr a) raw Nothing -> False mkTagExpr :: B.ByteString -> Maybe TagExpr mkTagExpr str | Just (x, xs) <- B.uncons str = case x of '<' -> Just (TagPrefix (mk xs)) '>' -> Just (TagSuffix (mk xs)) '^' -> Just (TagInfix (mk xs)) '%' -> let (a, b) = B.break (=='%') xs in Just (TagContained (mk a) (mk (B.drop 1 b))) _ -> Nothing | otherwise = Nothing matchTagExpr :: TagExpr -> TI -> Bool matchTagExpr expr raw = case expr of TagPrefix (TI _ xs) -> xs `B.isPrefixOf` str TagSuffix (TI _ xs) -> xs `B.isSuffixOf` str TagInfix (TI _ xs) -> xs `B.isInfixOf` str TagContained (TI _ xs) (TI _ ys)-> xs `B.isPrefixOf` str && ys `B.isSuffixOf` str where str = cleanedCase raw prettyTagExpr :: TagExpr -> B.ByteString prettyTagExpr expr = case expr of TagPrefix bs -> esc bs `B.append` wild TagSuffix bs -> wild `B.append` esc bs TagInfix bs -> B.concat [wild, esc bs, wild] TagContained a b-> B.concat [esc a, wild, esc b] where wild = "<span color=\"#BBB\">*</span>" esc = htmlEscapeBS . original rawToClan :: L.ByteString -> IO (Maybe [Clan]) rawToClan = fmap sequence . mapM (f . B.split '\t' . lazyToStrict) . P.filter (not . L.null) . L.split '\n' where f (rclanID:rname:rexpr:website:rwebsitealive:irc:rserver:_) | Just tagexpr <- mkTagExpr rexpr , Just (clanID,_) <- B.readInt rclanID = do let (ip, port1) = B.break (==':') rserver port = B.drop 1 port1 websitealive = rwebsitealive == "1" clanserver <- if B.null ip || B.null port then return Nothing else getDNS (B.unpack ip) (B.unpack port) return $ Just Clan { name = mkAlphaNum rname, .. } f _ = return Nothing getClanList :: String -> IO (Maybe [Clan]) getClanList url = do cont <- get url case cont of Nothing -> return Nothing Just raw -> do file <- cacheFile clans <- rawToClan raw when (isJust clans) $ L.writeFile file raw return clans clanListFromCache :: IO [Clan] clanListFromCache = handle err $ do file <- cacheFile fromMaybe [] <$> (rawToClan =<< L.readFile file) where err (_ :: IOException) = return [] lazyToStrict :: L.ByteString -> B.ByteString lazyToStrict = B.concat . toChunks cacheFile :: IO FilePath cacheFile = inCacheDir "clans" get :: HStream ty => String -> IO (Maybe ty) get url = case parseURI url of Nothing -> return Nothing Just uri -> do resp <- ex $ simpleHTTP (mkRequest GET uri) return $ case resp of Right (Response (2,0,0) _ _ body) -> Just body _ -> Nothing -- It doesn't catch everything apparently where ex = handle (\(_ :: IOException) -> return (Left ErrorReset))
Cadynum/Apelsin
src/ClanFetcher.hs
gpl-3.0
3,774
65
18
757
1,617
824
793
-1
-1
{-# LANGUAGE OverloadedStrings #-} module System.DevUtils.Base.Cloud.Amazon.RDS ( RDS (..), RDSRoot (..), RDSConfig (..), RDSRegion (..), RDSTypes (..), RDSTiers (..) ) where import System.DevUtils.Base.Cloud.Amazon.Misc import System.DevUtils.Base.Currency import Data.Aeson import Control.Applicative import Control.Monad data RDS = RDS { } data RDSRoot = RDSRoot { vers :: Version, config :: RDSConfig } deriving (Show, Read, Eq) instance FromJSON RDSRoot where parseJSON (Object v) = RDSRoot <$> v .: "vers" <*> v .: "config" parseJSON _ = mzero data RDSConfig = RDSConfig { regions :: [RDSRegion] } deriving (Show, Read, Eq) instance FromJSON RDSConfig where parseJSON (Object v) = RDSConfig <$> v .: "regions" parseJSON _ = mzero data RDSRegion = RDSRegion { region :: String, types :: [RDSTypes] } deriving (Show, Read, Eq) instance FromJSON RDSRegion where parseJSON (Object v) = RDSRegion <$> v .: "region" <*> v .: "types" parseJSON _ = mzero data RDSTypes = RDSTypes { tiers :: [RDSTiers] } deriving (Show, Read, Eq) instance FromJSON RDSTypes where parseJSON (Object v) = RDSTypes <$> v .: "tiers" parseJSON _ = mzero data RDSTiers = RDSTiers { name :: String, prices :: CurrencyObject } deriving (Show, Read, Eq) instance FromJSON RDSTiers where parseJSON (Object v) = RDSTiers <$> v .: "name" <*> v .: "prices" parseJSON _ = mzero
adarqui/DevUtils-Base
src/System/DevUtils/Base/Cloud/Amazon/RDS.hs
gpl-3.0
1,403
1
9
266
482
275
207
55
0
{- - Copyright (c) 2010, Terrence Cole. - - This file is part of Trash, Terrence's Re-Bourne Again SHell. - - Trash is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Trash is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Trash. If not, see <http://www.gnu.org/licenses/>. -} module JobControl where import Command import Parser import System.Exit import System.Posix.IO import System.Posix.Process import System.Posix.Types builtins = [ -- directory commands "cd", "pushd", "popd", "back", "forward", "up", "down", "next", "previous", -- env command "export", "unset" ] data Direction = GoLeft | GoRight dispatchCommand :: Command -> IO (Maybe ProcessStatus) dispatchCommand (SimpleCommand flags words redirs) = do let (wEnv, wTgt, wArgs) = splitCommand words if elem (wordDescWord wTgt) builtins then execBuiltinCommand (SimpleCommand flags words redirs) else execSimpleCommand (SimpleCommand flags words redirs) -- run two commands back-to-back dispatchCommand (ConnectionCommand flags first second ";") = do a <- dispatchCommand first b <- dispatchCommand second return b -- only run second if first succeeds dispatchCommand (ConnectionCommand flags first second "&&") = do a <- dispatchCommand first case a of Just rv -> case rv of Exited ExitSuccess -> dispatchCommand second _ -> return a Nothing -> return Nothing -- only run second if first fails dispatchCommand (ConnectionCommand flags first second "||") = do a <- dispatchCommand first case a of Just rv -> case rv of Exited ExitSuccess -> return a _ -> dispatchCommand second Nothing -> return Nothing {- dispatchCommand (ConnectionCommand flags first second "|") = do (readFd, writeFd) <- createPipe let writer = Redirect 1 RedirOutputDirection (RedirecteeFD (fromIntegral writeFd)) let reader = Redirect 0 RedirInputDirection (RedirecteeFD (fromIntegral readFd)) putStrLn "1" dispatchCommand (addRedirect GoRight writer first) putStrLn "2" dispatchCommand (addRedirect GoLeft reader second) putStrLn "3" return () -} dispatchCommand _ = return Nothing execSimpleCommand :: Command -> IO (Maybe ProcessStatus) execSimpleCommand (SimpleCommand flags words redirs) = do let wrapper = childMain words redirs child_id <- forkProcess wrapper child_status <- getProcessStatus True True child_id return child_status builtinUnrecognized = do putStrLn "Unrecognized command" return $ Just $ Exited ExitSuccess execBuiltinCommand :: Command -> IO (Maybe ProcessStatus) execBuiltinCommand (SimpleCommand flags words redirs) = do let (wEnv, wTgt, wArgs) = splitCommand words case (wordDescWord wTgt) of "cd" -> return $ Just $ Exited ExitSuccess _ -> builtinUnrecognized addRedirect :: Direction -> Redirect -> Command -> Command addRedirect _ redir (SimpleCommand flags words redirs) = SimpleCommand flags words (redirs ++ [redir]) addRedirect GoLeft redir (ConnectionCommand flags left _ _) = addRedirect GoLeft redir left addRedirect GoRight redir (ConnectionCommand flags _ right _) = addRedirect GoRight redir right -- Splits out he env overrides, the command target and command args -- FIXME: right now this just returns the first word, this need to skip env overrides splitCommand :: [WordDesc] -> ([WordDesc], WordDesc, [WordDesc]) splitCommand (w:ws) = ([], w, ws) childMain :: [WordDesc] -> [Redirect] -> IO () childMain words redirs = do let (wEnv, wTgt, wArgs) = splitCommand words let args = map wordDescWord wArgs childSetupRedirects redirs rv <- executeFile (wordDescWord wTgt) True args Nothing return () childSetupRedirects :: [Redirect] -> IO () childSetupRedirects [] = return () childSetupRedirects (r:rs) = do childSetupRedirect r childSetupRedirects rs childSetupRedirect :: Redirect -> IO () childSetupRedirect (Redirect src inst (RedirecteeFD dst)) = do let srcFd = Fd (fromIntegral src) let dstFd = Fd (fromIntegral dst) childSetupRedirectFd dstFd srcFd childSetupRedirect (Redirect src inst (RedirecteeName name)) = do --openFd :: FilePath -> OpenMode -> Maybe FileMode -> OpenFileFlags -> IO Fd let srcFd = Fd (fromIntegral src) let (openMode, openFlags) = argsForInst inst dstFd <- openFd name openMode (Just 0o777) openFlags childSetupRedirectFd dstFd srcFd argsForInst :: RedirectInstruction -> (OpenMode, OpenFileFlags) -- (OpenFileFlags append excl noctty nonblock trunc) argsForInst RedirOutputDirection = (WriteOnly, (OpenFileFlags False False True False True)) argsForInst RedirInputDirection = (ReadOnly, (OpenFileFlags False False True False True)) -- open new fd on top of old fd and close the old copy childSetupRedirectFd :: Fd -> Fd -> IO () childSetupRedirectFd oldFd newFd = do newFd <- dupTo oldFd newFd --closeFd oldFd return ()
terrence2/trash
src/JobControl.hs
gpl-3.0
5,715
0
15
1,381
1,243
618
625
86
6
module Main where okVal :: Int okVal = 23 main :: IO () main = putStrLn "I have {okVal} apples."
scvalex/interpol
Test/One.hs
gpl-3.0
99
0
6
22
32
18
14
5
1
{- | Functions for exporting Jammit audio (as WAV) and sheet music (as PDF). -} module Sound.Jammit.Export ( Library , fuzzySearchBy , exactSearchBy , loadLibrary , getAudioParts , getSheetParts , audioSource , runAudio , runSheet ) where import Control.Applicative (liftA2) import Control.Monad (forM) import Data.Char (toLower) import Data.Int (Int16, Int32) import Data.List (isInfixOf, sort, isPrefixOf) import Data.Maybe (catMaybes) import System.Directory (getDirectoryContents) import System.FilePath ((</>), splitFileName, takeFileName) import Sound.Jammit.Internal.Image import Sound.Jammit.Base import Sound.Jammit.Internal.Audio import Sound.Jammit.Internal.TempIO import qualified Data.Conduit.Audio as A import Control.Monad.Trans.Resource (MonadResource, runResourceT) type Library = [(FilePath, Info, [Track])] -- | Filter the library based on some string selector. The selector is -- applied case-insensitively, and the song's field only has to contain the -- search term rather than match it exactly. fuzzySearchBy :: (Info -> String) -> String -> Library -> Library fuzzySearchBy f str = let str' = map toLower str in filter $ \(_, info, _) -> str' `isInfixOf` map toLower (f info) -- | Filter the library based on some string selector. The selector must match -- exactly. exactSearchBy :: (Info -> String) -> String -> Library -> Library exactSearchBy f str = filter $ \(_, info, _) -> f info == str -- | Given the top-level Jammit library directory, finds all song packages. loadLibrary :: FilePath -> IO Library loadLibrary jmt = do dirs <- songSubdirs jmt fmap catMaybes $ forM dirs $ \d -> do maybeInfo <- loadInfo d maybeTrks <- loadTracks d return $ liftA2 (\i t -> (d, i, t)) maybeInfo maybeTrks -- | A mapping from audio part to absolute filename of an audio file. getAudioParts :: Library -> [(AudioPart, FilePath)] getAudioParts lib = do (dir, info, trks) <- lib trk <- trks case trackTitle trk >>= \t -> titleToAudioPart t (instrument info) of Nothing -> [] Just ap -> [(ap, dir </> (identifier trk ++ "_jcfx"))] -- | A mapping from sheet part to -- @(prefix of image files, line height in pixels)@. getSheetParts :: Library -> [(SheetPart, (FilePath, Integer))] getSheetParts lib = do (dir, _info, trks) <- lib trk <- trks case (trackTitle trk >>= \t -> titleToPart t, scoreSystemInterval trk) of (Just p, Just ht) -> let sheet = (Notation p, (dir </> (identifier trk ++ "_jcfn"), ht)) tab = (Tab p, (dir </> (identifier trk ++ "_jcft"), ht)) in if elem (partToInstrument p) [Guitar, Bass] then [sheet, tab] else [sheet] _ -> [] audioSource :: (MonadResource m) => FilePath -> IO (A.AudioSource m Int16) audioSource fp = if takeFileName fp `elem` [tttDrums, tttDrumsBack] then fmap (A.padStart $ A.Frames 38) $ readIMA fp else readIMA fp -- I've only found one audio file where the instruments are not aligned: -- the drums and drums backing track for Take the Time are 38 samples ahead -- of the other instruments. So as a hack, we pad the front of them by 38 -- samples to line things up. where tttDrums = "793EAAE0-6761-44D7-9A9A-1FB451A2A438_jcfx" tttDrumsBack = "37EE5AA5-4049-4CED-844A-D34F6B165F67_jcfx" runAudio :: [FilePath] -- ^ AIFCs to mix in normally -> [FilePath] -- ^ AIFCs to mix in inverted -> FilePath -- ^ the resulting WAV file -> IO () runAudio pos neg fp = do pos' <- mapM audioSource pos neg' <- mapM audioSource neg let src = case (pos', neg') of ([] , [] ) -> A.silent (A.Frames 0) 44100 2 ([p] , [] ) -> p ([] , [n] ) -> A.mapSamples negate16 n (p : ps, [] ) -> i32To16 $ mix16To32 p ps ([] , n : ns) -> i32To16 $ A.mapSamples negate $ mix16To32 n ns (p : ps, n : ns) -> i32To16 $ A.mix (mix16To32 p ps) $ A.mapSamples negate $ mix16To32 n ns i16To32 = A.mapSamples (fromIntegral :: Int16 -> Int32) i32To16 = A.mapSamples (fromIntegral . clamp (-32768, 32767) :: Int32 -> Int16) negate16 :: Int16 -> Int16 negate16 x = if x == minBound then maxBound else negate x mix16To32 x xs = foldr A.mix (i16To32 x) (map i16To32 xs) runResourceT $ writeWAV fp src runSheet :: [(FilePath, Integer)] -- ^ pairs of @(png file prefix, line height in px)@ -> Int -- ^ how many sheet music systems per page -> FilePath -- ^ the resulting PDF -> IO () runSheet trks lns fout = runTempIO fout $ do trkLns <- liftIO $ forM trks $ \(fp, ht) -> do let (dir, file) = splitFileName fp ls <- getDirectoryContents dir return (map (dir </>) $ sort $ filter (file `isPrefixOf`) ls, ht) jpegs <- partsToPages trkLns lns pdf <- newTempFile "pages.pdf" liftIO $ jpegsToPDF jpegs pdf return pdf
michelshalom/jammittools
src/Sound/Jammit/Export.hs
gpl-3.0
4,827
0
19
1,063
1,507
814
693
97
7
-- Author: Stefan Eng -- License: GPL v3 -- File: xmonad.hs -- Description: -- Xmonad window manager configuration file. import XMonad import XMonad.Hooks.ManageDocks import XMonad.Hooks.DynamicLog import XMonad.Util.Run (spawnPipe, hPutStrLn) import XMonad.Util.Cursor (setDefaultCursor, xC_left_ptr) main = do handle <- spawnPipe "xmobar" xmonad $ defaultConfig { modMask = myModMask , terminal = myTerminal , manageHook = myManageHook , layoutHook = myLayoutHook , startupHook = myStartupHook , logHook = dynamicLogWithPP xmobarPP { ppOutput = hPutStrLn handle } } -- the mod modifier -- set to windows key myModMask :: KeyMask myModMask = mod4Mask -- use rxvt-unicode as terminal -- config file in dotfiles/X/Xresources myTerminal :: String myTerminal = "urxvt" -- not quite sure exactly what the options are for manageHook myManageHook :: ManageHook myManageHook = manageDocks <+> manageHook defaultConfig -- same goes for the layoutHook myLayoutHook = avoidStruts $ layoutHook defaultConfig -- this should probably go into an X config file and not here setMyCursor :: X () setMyCursor = setDefaultCursor xC_left_ptr -- startup hook runs when xmonad starts myStartupHook :: X () myStartupHook = setMyCursor -- dynamic logging for xmobar -- pass a handle to it --myLogHook :: X () --myLogHook handle = dynamicLogWithPP xmobarPP { ppOutput = hPutStrLn handle }
stefaneng/dotfiles
haskell/xmonad/xmonad.hs
gpl-3.0
1,519
0
13
354
217
131
86
26
1
module Language.SMTLib2.Composite.Lens where import Language.SMTLib2 import Language.SMTLib2.Internals.Embed import qualified Data.Traversable as T import Control.Monad import Data.Functor.Constant import Control.Lens import Data.GADT.Compare import Control.Applicative import Data.Functor.Identity type LensM m s t a b = forall f . (Traversable f) => (a -> f b) -> s -> m (f t) type LensM' m s a = LensM m s s a a lensM :: (Monad m) => (s -> m a) -> (s -> b -> m t) -> LensM m s t a b lensM g s f x = g x >>= T.mapM (s x) . f mget :: (Monad m) => LensM m s t a b -> s -> m a mget l s = liftM getConstant $ l Constant s mset :: (Monad m) => LensM m s t a b -> s -> b -> m t mset l s v = liftM runIdentity $ l (const $ Identity v) s withLensM :: (Monad m) => LensM' m a b -> (b -> m b) -> a -> m a withLensM l f x = do el <- mget l x nel <- f el mset l x nel type CompLens a b = forall m e. (Embed m e,GetType e,GCompare e,Monad m) => LensM' m (a e) (b e) composeLensM :: Monad m => LensM' m a b -> LensM' m b c -> LensM' m a c composeLensM l1 l2 = lensM (\st -> do x <- mget l1 st mget l2 x) (\st y -> do x <- mget l1 st nx <- mset l2 x y mset l1 st nx) idLensM :: Monad m => LensM' m a a idLensM = liftLens id liftLens :: Monad m => Lens' a b -> LensM' m a b liftLens l = lensM (\st -> return (st ^. l)) (\st el -> return (st & l .~ el)) type MaybeLens a b = Lens a (Maybe a) (Maybe b) b getMaybe :: a -> MaybeLens a b -> Maybe b getMaybe x l = getConst $ l Const x setMaybe :: a -> MaybeLens a b -> b -> Maybe a setMaybe x l y = runIdentity $ l (const $ return y) x composeMaybe :: MaybeLens a b -> MaybeLens b c -> MaybeLens a c composeMaybe l1 l2 = lens (\x -> do y <- x `getMaybe` l1 y `getMaybe` l2) (\x new -> do y <- x `getMaybe` l1 ny <- y & l2 .~ new x & l1 .~ ny) maybeLens :: Lens' a b -> MaybeLens a b maybeLens l = lens (\x -> Just $ x ^. l) (\x new -> Just $ x & l .~ new) nothingLens :: MaybeLens a b nothingLens = lens (\_ -> Nothing) (\_ _ -> Nothing) forceMaybe :: MaybeLens a b -> Lens' a b forceMaybe l = lens (\x -> case getMaybe x l of Just r -> r) (\x new -> case setMaybe x l new of Just nx -> nx) just :: MaybeLens (Maybe a) a just = lens id (const $ Just . Just)
hguenther/smtlib2
extras/composite/Language/SMTLib2/Composite/Lens.hs
gpl-3.0
2,443
0
12
769
1,230
627
603
-1
-1
module TM.Formatter ( paint, srnd, formatTask, printTaskTree ) where import TM.Task import TM.Time (timeAgoUTC) import TM.Util (splitBy) import Data.Time.Clock.POSIX (POSIXTime) colors :: [(String, String)] colors = [ ("red", "\x1b[1;91m") , ("green", "\x1B[1;92m") , ("yellow", "\x1b[1;93m") , ("blue", "\x1b[1;94m") , ("magenta", "\x1b[1;95m") , ("cyan", "\x1b[1;96m") , ("reset", "\x1b[1;0m")] color :: String -> String color a = case lookup a colors of Nothing -> "" (Just c) -> c paint :: String -> String -> String paint textColor t = color textColor ++ t ++ color "reset" srnd :: String -> String -> String srnd "[" t = "[" ++ t ++ "]" srnd "(" t = "(" ++ t ++ ")" srnd _ t = t formatTask :: FTask -> String formatTask (t,now) = (unwords . filter (not . null)) (fitem t) where fnumber = srnd "[" . paint "red" . show ftag = srnd "(" . paint "green" fsign False = "" fsign True = paint "green" "✔" ftime = srnd "(" . paint "blue" fitem i = [ fnumber (tid i) , ftag (tag i) , fsign (completed i) , text i , ftime (timeAgoUTC (createdAt i) now) ] placeholder :: String vertical :: String connector :: String ending :: String placeholder = " " vertical = paint "blue" " │ " connector = paint "blue" " ├── " ending = paint "blue" " └── " type FTask = (Task, POSIXTime) data FNode a = FNode { indent :: String , isLast :: Bool , isRoot :: Bool , formatter :: a -> String } drawNode :: FNode a -> a -> String drawNode (FNode _ _ True f) t = concat [f t, "\n"] drawNode (FNode i True _ f) t = concat [i, ending, f t, "\n"] drawNode (FNode i False _ f) t = concat [i, connector, f t, "\n"] drawTree :: FNode FTask -> [FTask] -> FTask -> String drawTree fn tasks root = node ++ children where (base,rest) = splitBy (\(t,_) -> parentId t == tid (fst root)) tasks children = concat (drawChildren False fn base rest) node = drawNode fn root nextFNode :: FNode a -> Bool -> Bool -> FNode a nextFNode fn l r | isRoot fn = fn { isLast = l, isRoot = r } | isLast fn = fn { isLast = l, isRoot = r, indent = indent fn ++ placeholder } | otherwise = fn { isLast = l, isRoot = r, indent = indent fn ++ vertical } drawChildren :: Bool -> FNode FTask -> [FTask] -> [FTask] -> [String] drawChildren _ _ [] _ = [] drawChildren r fnode (ft:[]) rest = [drawTree (nextFNode fnode True r) rest ft] drawChildren r fnode fts rest = initNodes ++ [lastNode] where initNodes = map (drawTree (nextFNode fnode False r) rest) (init fts) lastNode = drawTree (nextFNode fnode True r) rest (last fts) printTaskTree :: POSIXTime -> [Task] -> String printTaskTree now tasks = concat (drawChildren True (FNode "" True True formatTask) base rest) where (base,rest) = splitBy (\(t,_) -> parentId t == 0) ftasks ftasks = map (\t -> (t, now)) tasks
evgenim/tm
src/TM/Formatter.hs
gpl-3.0
3,080
0
13
871
1,252
670
582
75
2
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Test.HTCF.ArrowXml where import Test.Framework import Text.XML.HXT.Core import HTCF.ArrowXml fileA = "testsuite/Test/HTCF/file-a.xml" test_nameIn = do results <- runX (readDocument [withValidate no] fileA >>> getChildren >>> isElem >>> hasName "html" >>> getChildren >>> isElem >>> hasName "body" >>> getChildren >>> isElem >>> nameIn ["pre", "code"] >>> getChildren >>> getText) assertEqual ["main = putStrLn \"hello world\"\n", "$ runghc hello1.hs", "Prelude> :load hello1.hs\n*Main> main\n", "main = interact (const \"hello world\\n\")\n"] results test_qNameIn = do results <- runX (readDocument [withValidate no] fileA >>> propagateNamespaces >>> getChildren >>> isElem >>> hasName "html" >>> getChildren >>> isElem >>> hasName "body" >>> getChildren >>> --isElem >>> hasQName (mkQName "xx" "pre" "http://www.w3.org/1999/xhtml") >>> --isElem >>> hasQName (mkNsName "http://www.w3.org/1999/xhtml" "pre") >>> isElem >>> qNameIn [(mkQName "xx" "pre" "http://www.w3.org/1999/xhtml") ,(mkQName "xx" "code" "http://www.w3.org/1999/xhtml")] >>> getChildren >>> getText) assertEqual ["main = putStrLn \"hello world\"\n", "$ runghc hello1.hs", "Prelude> :load hello1.hs\n*Main> main\n", "main = interact (const \"hello world\\n\")\n"] results -- stripName may be put anywhere test_stripName = do results <- runX (readDocument [withValidate no] fileA >>> getChildren >>> isElem >>> hasName "html" >>> getChildren >>> isElem >>> hasName "body" >>> stripName "p" >>> -- strip <p>-elements getChildren >>> isElem >>> getChildren >>> getText) resultS <- runX (readDocument [withValidate no] fileA >>> stripName "p" >>> -- strip <p>-elements getChildren >>> isElem >>> hasName "html" >>> getChildren >>> isElem >>> hasName "body" >>> getChildren >>> isElem >>> getChildren >>> getText) assertEqual ["Test", " is for testing.", "main = putStrLn \"hello world\"\n", "$ runghc hello1.hs", "Prelude> :load hello1.hs\n*Main> main\n", "main = interact (const \"hello world\\n\")\n"] results assertEqual ["Test", " is for testing.", "main = putStrLn \"hello world\"\n", "$ runghc hello1.hs", "Prelude> :load hello1.hs\n*Main> main\n", "main = interact (const \"hello world\\n\")\n"] resultS test_stripNames = do results <- runX (readDocument [withValidate no] fileA >>> stripNames ["pre","code"] >>> getChildren >>> isElem >>> hasName "html" >>> getChildren >>> isElem >>> hasName "body" >>> getChildren >>> isElem >>> getChildren >>> getText) resultS <- runX (readDocument [withValidate no] fileA >>> getChildren >>> isElem >>> hasName "html" >>> stripNames ["pre","code"] >>> getChildren >>> isElem >>> hasName "body" >>> getChildren >>> isElem >>> getChildren >>> getText) assertEqual ["Test", " is for testing.", "This is first paragraph.", "To run it, enter this at a shell prompt:", "This is third paragraph.", "This is the fourth paragraph."] results assertEqual ["Test", " is for testing.", "This is first paragraph.", "To run it, enter this at a shell prompt:", "This is third paragraph.", "This is the fourth paragraph."] resultS test_stripQNames = do results <- runX (readDocument [withValidate no] fileA >>> propagateNamespaces >>> stripQNames [(mkNsName "pre" "http://www.w3.org/1999/xhtml"), (mkNsName "code" "http://www.w3.org/1999/xhtml")] >>> getChildren >>> isElem >>> hasName "html" >>> getChildren >>> isElem >>> hasName "body" >>> getChildren >>> isElem >>> getChildren >>> getText) assertEqual ["Test", " is for testing.", "This is first paragraph.", "To run it, enter this at a shell prompt:", "This is third paragraph.", "This is the fourth paragraph."] results
lueck/htcf
testsuite/Test/HTCF/ArrowXml.hs
gpl-3.0
5,165
0
24
2,033
843
431
412
135
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.MapsEngine.Rasters.Process -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Process a raster asset. -- -- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.rasters.process@. module Network.Google.Resource.MapsEngine.Rasters.Process ( -- * REST Resource RastersProcessResource -- * Creating a Request , rastersProcess , RastersProcess -- * Request Lenses , rpId ) where import Network.Google.MapsEngine.Types import Network.Google.Prelude -- | A resource alias for @mapsengine.rasters.process@ method which the -- 'RastersProcess' request conforms to. type RastersProcessResource = "mapsengine" :> "v1" :> "rasters" :> Capture "id" Text :> "process" :> QueryParam "alt" AltJSON :> Post '[JSON] ProcessResponse -- | Process a raster asset. -- -- /See:/ 'rastersProcess' smart constructor. newtype RastersProcess = RastersProcess' { _rpId :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'RastersProcess' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rpId' rastersProcess :: Text -- ^ 'rpId' -> RastersProcess rastersProcess pRpId_ = RastersProcess' { _rpId = pRpId_ } -- | The ID of the raster. rpId :: Lens' RastersProcess Text rpId = lens _rpId (\ s a -> s{_rpId = a}) instance GoogleRequest RastersProcess where type Rs RastersProcess = ProcessResponse type Scopes RastersProcess = '["https://www.googleapis.com/auth/mapsengine"] requestClient RastersProcess'{..} = go _rpId (Just AltJSON) mapsEngineService where go = buildClient (Proxy :: Proxy RastersProcessResource) mempty
rueshyna/gogol
gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Rasters/Process.hs
mpl-2.0
2,611
0
13
619
303
186
117
48
1
module Fibonacci where fibonacci :: Int -> [Int] fibonacci 0 = [0, 0] fibonacci 1 = [1, 0] fibonacci 2 = [1, 1] fibonacci 3 = [2, 1] fibonacci n = [sum m, m !! 0] where m = fibonacci (n - 1) -- fib :: Int -> Int fib n|n >= 0 || (mod n 2) == 0 = fibonacci n !! 0 |otherwise = 0 - (fibonacci (0 - n) !! 0) --
ice1000/OI-codes
codewars/101-200/fibonacci.hs
agpl-3.0
339
0
11
107
192
103
89
11
1
{-# LANGUAGE TypeFamilies #-} module Math.Topology.KnotTh.Invariants.HomflyPolynomial ( homflyPolynomial , minimalHomflyPolynomial ) where import Math.Topology.KnotTh.Invariants.Util.Poly import Math.Topology.KnotTh.Tangle class (Knotted k) => KnottedWithHomflyPolynomial k where type HomflyPolynomial k :: * homflyPolynomial :: k DiagramCrossing -> HomflyPolynomial k minimalHomflyPolynomial :: k DiagramCrossing -> HomflyPolynomial k instance KnottedWithHomflyPolynomial OrientedTangle where type HomflyPolynomial OrientedTangle = Poly2 homflyPolynomial = error "not implemented" minimalHomflyPolynomial = error "not implemented"
mishun/tangles
src/Math/Topology/KnotTh/Invariants/HomflyPolynomial.hs
lgpl-3.0
680
0
8
109
122
70
52
14
0
module Main where import Lib import Text.Printf (printf) main :: IO () main = do putStr "Verifying Sum is a valid Functor and Applicative" verifySumIsFunctor verifySumIsApplicative putStr "\nVerifying Validation is a valid Functor and Applicative" verifyValidationIsFunctor verifyValidationIsApplicative
dmp1ce/Haskell-Programming-Exercises
Chapter 17/VariationsOnEither/app/Main.hs
unlicense
319
0
7
52
56
27
29
11
1
{- Data types exported by CCS -} module Language.CCS.Data where import Data.Hashable import qualified Data.HashSet as HS import qualified Data.HashMap.Strict as HM newtype CLib = CLib String deriving (Ord, Eq, Show) newtype CInclude = CInclude String deriving (Ord, Eq, Show) data CompOpt = CompOptDef String | CompOptKV String String deriving Show newtype CStruc = CStruct String deriving (Ord, Eq, Show) data OSName = WINDOWS | FREEBSD | LINUX | OSX deriving (Eq, Show) data NativeLang = CLang | CPlusPlus | ObjectiveC deriving (Eq, Show) newtype OSGroup = OSGroup (OSName, NativeLang) deriving (Eq, Show) newtype CSPrologue = CSPrologue [String] deriving Show data FieldValue = CField String | HField String | FieldTxt String deriving (Eq,Show) newtype CMacro = CMacro String deriving (Eq,Show) data EnumValue = EmptyEnum | FromMacro String | EnumText String | EnumSize String | EnumOffset String String | EnumComplex [EnumValue] deriving (Eq,Show) data CSVal = CFieldOffset String String | CHashDef String | CSVerbatim String | CDblHash | CSizeOf String deriving (Eq,Show) data CCSType = CSEnum String [(String, EnumValue)] | CSClass String [(String, String, EnumValue)] | CSStruct String String [(String, String, String)] deriving (Eq,Show) data CCSFile = CCSFile { ccsPrologue :: CSPrologue ,ccsLib :: CLib ,ccsIndent :: Int ,ccsIncludes :: [CInclude] ,ccsTypes :: [CCSType] ,ccsEpilogue :: [CSVal] } deriving Show data NativeTxt = MacroDef String | StructSize String | StructOffset String String deriving (Eq, Show) isMacro :: NativeTxt -> Bool isMacro (MacroDef _) = True isMacro _ = False isNotMacro :: NativeTxt -> Bool isNotMacro = not . isMacro newtype NativeVal = NativeVal String deriving (Eq, Show) hwsalt :: Int -> NativeTxt -> Int hwsalt i (MacroDef s) = hashWithSalt (hashWithSalt i s) "@$MacroDef" hwsalt i (StructSize s) = hashWithSalt (hashWithSalt i s) "@$Sizeof" hwsalt i (StructOffset s f) = hashWithSalt (hashWithSalt (hashWithSalt i s) f) "@$Sizeof" instance Hashable NativeTxt where hashWithSalt = hwsalt type CCSMap = HM.HashMap NativeTxt NativeVal type CCSet = HS.HashSet NativeTxt printNTV :: (NativeTxt , NativeVal) -> IO () printNTV (n, NativeVal s) = putStrLn $ (show n) ++ " = " ++ s addFieldVal str (CField f) set = HS.insert (StructOffset str f) set addFieldVal _ (HField h) set = HS.insert (MacroDef h) set addFieldVal _ _ set = set addMacro str set = HS.insert (MacroDef str) set addSizeOf str set = HS.insert (StructSize str) set addOffset str f set = HS.insert (StructOffset str f) set
kapilash/ccs2cs
src/Language/CCS/Data.hs
apache-2.0
3,313
0
9
1,177
924
515
409
84
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.GlusterfsVolumeSource where import GHC.Generics import Data.Text import qualified Data.Aeson -- | GlusterfsVolumeSource represents a Glusterfs Mount that lasts the lifetime of a pod. data GlusterfsVolumeSource = GlusterfsVolumeSource { endpoints :: Text -- ^ EndpointsName is the endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md#create-a-pod , path :: Text -- ^ Path is the Glusterfs volume path. More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md#create-a-pod , readOnly :: Maybe Bool -- ^ ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md#create-a-pod } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON GlusterfsVolumeSource instance Data.Aeson.ToJSON GlusterfsVolumeSource
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/GlusterfsVolumeSource.hs
apache-2.0
1,104
0
9
141
97
60
37
16
0
module Problem068 where import Data.List main = print $ join $ maximum $ filter (\s -> length (join s) == 16) $ filter check cs where cs = map (6:) $ permutations $ [1..5] ++ [7..10] join as = let (os, ps) = halve as in concat $ zipWith3 (\a b c -> show a ++ show b ++ show c) os ps (tail (cycle ps)) check as = let (os, ps) = halve as in same $ zipWith3 (\a b c -> a + b + c) os ps (tail (cycle ps)) halve as = let l = length as `div` 2 in (take l as, drop l as) same [] = True same (a:as) = all (== a) as
vasily-kartashov/playground
euler/problem-068.hs
apache-2.0
540
0
13
154
330
168
162
12
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction, FlexibleInstances #-} -- * Demonstrating `non-compositional', context-sensitive processing -- * The final style module PushNegF where import Intro2 hiding (main) -- When I first mentioned the initial and final styles in passing -- in July 2009 in Oxford, one Oxford professor said: -- ``Isn't it bloody obvious that you can't pattern-match in the final -- style?'' -- The answer: it isn't bloody and it isn't obvious and it is not -- impossible to pattern-match in the final style. -- Pushing negation down -- We are going to write push_neg as an interpreter. -- After all, that's all we can do with an expression in a final form. -- * The nested pattern-matching establishes a context: -- * push_neg :: Exp -> Exp -- * push_neg e@Lit{} = e -- * push_neg e@(Neg (Lit _)) = e -- * push_neg (Neg (Neg e)) = push_neg e -- * push_neg (Neg (Add e1 e2)) = Add (push_neg (Neg e1)) (push_neg (Neg e2)) -- * push_neg (Add e1 e2) = Add (push_neg e1) (push_neg e2) -- * // -- So, we define the context data Ctx = Pos | Neg -- * Tagless transformer -- We transform one interpreter into another instance ExpSYM repr => ExpSYM (Ctx -> repr) where lit n Pos = lit n lit n Neg = neg (lit n) neg e Pos = e Neg neg e Neg = e Pos add e1 e2 ctx = add (e1 ctx) (e2 ctx) -- homomorhism -- On the first line, there are two occurrences of lit. -- But those two lit belong to different interpreters! -- The observation holds for all other lines. -- The transformation here seems more insightful than that in -- PushNegI.hs: we see that with respect to |add|, the transformation -- is just the homomorphism. -- The `interpreter' for pushing the negation down push_neg e = e Pos -- * // -- To remind, here is our sample term tf1_view = view tf1 -- "(8 + (-(1 + 2)))" tf1_norm = push_neg tf1 -- The new expression can be evaluated with any interpreter tf1_norm_view = view tf1_norm -- "(8 + ((-1) + (-2)))" -- The result of the standard evaluation (the `meaning') is preserved tf1_norm_eval = eval tf1_norm -- 5 -- Add an extra negation tf1n_norm = push_neg (neg tf1) -- see the result tf1n_norm_view = view tf1n_norm -- "((-8) + (1 + 2))" tf1n_norm_eval = eval tf1n_norm -- -5 -- Negate the already negated term tf1nn_norm = push_neg (neg tf1n_norm) tf1nn_norm_view = view tf1nn_norm -- "(8 + ((-1) + (-2)))" main = do print PushNegF.tf1_view print tf1_norm_view print tf1n_norm_view if tf1_norm_view == tf1nn_norm_view then return () else error "Double neg" print tf1nn_norm_view if eval tf1 == tf1_norm_eval then return () else error "Normalization" if eval tf1 == - tf1n_norm_eval then return () else error "Normalization"
egaburov/funstuff
Haskell/tytag/codes/PushNegF.hs
apache-2.0
2,792
0
9
594
380
207
173
32
4
{- Copyright 2014 Matthew Gordon. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied. See the License for the specific language governing permissions and limitations under the License. -} module Funk.Module ( Module, empty, addDecl, getDecl, getDecls, addDef, importDecls, getDefs ) where import qualified Data.Foldable import Data.List (concatMap) import qualified Data.Map.Strict as Map import Data.Maybe (catMaybes) import Control.Monad ((<=<)) import qualified Funk.AST as AST data Module name = Module (Map.Map name (ModuleEntry name)) data ModuleEntry name = ModuleEntry { moduleEntryDecl :: Maybe (AST.Decl name), moduleEntryDefs :: [AST.Def name] } foldrModule :: (ModuleEntry name -> a -> a) -> a -> Module name -> a foldrModule f a (Module m) = Data.Foldable.foldr f a m mapModule :: (ModuleEntry name -> a) -> Module name -> [a] mapModule f = foldrModule ((:) . f) [] getEntry :: Ord name => Module name -> name -> Maybe (ModuleEntry name) getEntry (Module m) n = Map.lookup n m -- |Create an empty Module. empty :: Module name empty = Module Map.empty -- |Add a new declaration to the module. -- If the declaration is already in the module, it is replaced. If -- there is already a definition in the module but no declaration, -- the given declaration is attached to the definition. addDecl :: Ord name => AST.Decl name -> Module name -> Module name addDecl d@(AST.Decl n _) (Module m) = Module $ Map.insert n (ModuleEntry (Just d) []) m -- |Get a declaration from the module by name -- Returns Nothing if the given name does not occur in the module -- /or/ if the name is defined but has no type declaration. getDecl :: Ord name => Module name -> name -> Maybe (AST.Decl name) getDecl m = moduleEntryDecl <=< getEntry m -- |Get a list of all declaration in the module -- Names with definitions but no type declarations are -- not returned in this list. getDecls :: Module name -> [AST.Decl name] getDecls = catMaybes . mapModule moduleEntryDecl -- |Add a new definition to a module -- If the name is not already in the module, it is added. If the name -- has a declaration, the definition is attached to that declaration. -- If the name already has a definition or definitions, the new -- definition is added to the list of definitions. addDef :: Ord name => AST.Def name -> Module name -> Module name addDef def@(AST.Def n _ _) (Module m) = Module $ Map.alter addDef' n m where addDef' (Just (ModuleEntry decl defs)) = Just (ModuleEntry decl (def:defs)) addDef' Nothing = Just (ModuleEntry Nothing [def]) -- |Add the declarations from one module to the namespace of another. -- The definitions are not imported, only the declarations. If the -- same name occurs in both module, the new name will override the -- old one. The intention is that the definition of the name type -- (specifically it's Ord instance) should be used to prevent or -- control these collision as required. importDecls :: Ord name => Module name -> Module name -> Module name importDecls src dest = foldr addDecl dest (getDecls src) -- Just returns all definitions for all functions as one big list -- with no type information. This will want to be updated -- once renaming and type checking are farther along. getDefs :: Module name -> [AST.Def name] getDefs (Module es) = concatMap moduleEntryDefs (Map.elems es)
matthewscottgordon/funk
src/Funk/Module.hs
apache-2.0
3,853
0
12
805
776
412
364
45
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QAbstractFileEngine.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Core.QAbstractFileEngine ( FileFlag, FileFlags, eReadOwnerPerm, fReadOwnerPerm, eWriteOwnerPerm, fWriteOwnerPerm, eExeOwnerPerm, fExeOwnerPerm, eReadUserPerm, fReadUserPerm, eWriteUserPerm, fWriteUserPerm, eExeUserPerm, fExeUserPerm, eReadGroupPerm, fReadGroupPerm, eWriteGroupPerm, fWriteGroupPerm, eExeGroupPerm, fExeGroupPerm, eReadOtherPerm, fReadOtherPerm, eWriteOtherPerm, fWriteOtherPerm, eExeOtherPerm, fExeOtherPerm, eLinkType, fLinkType, fFileType, eDirectoryType, fDirectoryType, eBundleType, fBundleType, eHiddenFlag, fHiddenFlag, eLocalDiskFlag, fLocalDiskFlag, eExistsFlag, fExistsFlag, eRootFlag, fRootFlag, fRefresh, ePermsMask, fPermsMask, eTypesMask, fTypesMask, eFlagsMask, fFlagsMask, eFileInfoAll, fFileInfoAll , FileName, eDefaultName, eBaseName, ePathName, eAbsoluteName, eAbsolutePathName, eLinkName, eCanonicalName, eCanonicalPathName, eBundleName , FileOwner, eOwnerUser, eOwnerGroup , FileTime, eCreationTime, eModificationTime, eAccessTime , QAbstractFileEngineExtension, eAtEndExtension, eFastReadLineExtension ) where import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CFileFlag a = CFileFlag a type FileFlag = QEnum(CFileFlag Int) ieFileFlag :: Int -> FileFlag ieFileFlag x = QEnum (CFileFlag x) instance QEnumC (CFileFlag Int) where qEnum_toInt (QEnum (CFileFlag x)) = x qEnum_fromInt x = QEnum (CFileFlag x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> FileFlag -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () data CFileFlags a = CFileFlags a type FileFlags = QFlags(CFileFlags Int) ifFileFlags :: Int -> FileFlags ifFileFlags x = QFlags (CFileFlags x) instance QFlagsC (CFileFlags Int) where qFlags_toInt (QFlags (CFileFlags x)) = x qFlags_fromInt x = QFlags (CFileFlags x) withQFlagsResult x = do ti <- x return $ qFlags_fromInt $ fromIntegral ti withQFlagsListResult x = do til <- x return $ map qFlags_fromInt til instance Qcs (QObject c -> FileFlags -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qFlags_fromInt hint) return () eReadOwnerPerm :: FileFlag eReadOwnerPerm = ieFileFlag $ 16384 eWriteOwnerPerm :: FileFlag eWriteOwnerPerm = ieFileFlag $ 8192 eExeOwnerPerm :: FileFlag eExeOwnerPerm = ieFileFlag $ 4096 eReadUserPerm :: FileFlag eReadUserPerm = ieFileFlag $ 1024 eWriteUserPerm :: FileFlag eWriteUserPerm = ieFileFlag $ 512 eExeUserPerm :: FileFlag eExeUserPerm = ieFileFlag $ 256 eReadGroupPerm :: FileFlag eReadGroupPerm = ieFileFlag $ 64 eWriteGroupPerm :: FileFlag eWriteGroupPerm = ieFileFlag $ 32 eExeGroupPerm :: FileFlag eExeGroupPerm = ieFileFlag $ 16 eReadOtherPerm :: FileFlag eReadOtherPerm = ieFileFlag $ 4 eWriteOtherPerm :: FileFlag eWriteOtherPerm = ieFileFlag $ 2 eExeOtherPerm :: FileFlag eExeOtherPerm = ieFileFlag $ 1 eLinkType :: FileFlag eLinkType = ieFileFlag $ 65536 instance QeFileType FileFlag where eFileType = ieFileFlag $ 131072 eDirectoryType :: FileFlag eDirectoryType = ieFileFlag $ 262144 eBundleType :: FileFlag eBundleType = ieFileFlag $ 524288 eHiddenFlag :: FileFlag eHiddenFlag = ieFileFlag $ 1048576 eLocalDiskFlag :: FileFlag eLocalDiskFlag = ieFileFlag $ 2097152 eExistsFlag :: FileFlag eExistsFlag = ieFileFlag $ 4194304 eRootFlag :: FileFlag eRootFlag = ieFileFlag $ 8388608 instance QeRefresh FileFlag where eRefresh = ieFileFlag $ 16777216 ePermsMask :: FileFlag ePermsMask = ieFileFlag $ 65535 eTypesMask :: FileFlag eTypesMask = ieFileFlag $ 983040 eFlagsMask :: FileFlag eFlagsMask = ieFileFlag $ 267386880 eFileInfoAll :: FileFlag eFileInfoAll = ieFileFlag $ 268435455 fReadOwnerPerm :: FileFlags fReadOwnerPerm = ifFileFlags $ 16384 fWriteOwnerPerm :: FileFlags fWriteOwnerPerm = ifFileFlags $ 8192 fExeOwnerPerm :: FileFlags fExeOwnerPerm = ifFileFlags $ 4096 fReadUserPerm :: FileFlags fReadUserPerm = ifFileFlags $ 1024 fWriteUserPerm :: FileFlags fWriteUserPerm = ifFileFlags $ 512 fExeUserPerm :: FileFlags fExeUserPerm = ifFileFlags $ 256 fReadGroupPerm :: FileFlags fReadGroupPerm = ifFileFlags $ 64 fWriteGroupPerm :: FileFlags fWriteGroupPerm = ifFileFlags $ 32 fExeGroupPerm :: FileFlags fExeGroupPerm = ifFileFlags $ 16 fReadOtherPerm :: FileFlags fReadOtherPerm = ifFileFlags $ 4 fWriteOtherPerm :: FileFlags fWriteOtherPerm = ifFileFlags $ 2 fExeOtherPerm :: FileFlags fExeOtherPerm = ifFileFlags $ 1 fLinkType :: FileFlags fLinkType = ifFileFlags $ 65536 fFileType :: FileFlags fFileType = ifFileFlags $ 131072 fDirectoryType :: FileFlags fDirectoryType = ifFileFlags $ 262144 fBundleType :: FileFlags fBundleType = ifFileFlags $ 524288 fHiddenFlag :: FileFlags fHiddenFlag = ifFileFlags $ 1048576 fLocalDiskFlag :: FileFlags fLocalDiskFlag = ifFileFlags $ 2097152 fExistsFlag :: FileFlags fExistsFlag = ifFileFlags $ 4194304 fRootFlag :: FileFlags fRootFlag = ifFileFlags $ 8388608 fRefresh :: FileFlags fRefresh = ifFileFlags $ 16777216 fPermsMask :: FileFlags fPermsMask = ifFileFlags $ 65535 fTypesMask :: FileFlags fTypesMask = ifFileFlags $ 983040 fFlagsMask :: FileFlags fFlagsMask = ifFileFlags $ 267386880 fFileInfoAll :: FileFlags fFileInfoAll = ifFileFlags $ 268435455 data CFileName a = CFileName a type FileName = QEnum(CFileName Int) ieFileName :: Int -> FileName ieFileName x = QEnum (CFileName x) instance QEnumC (CFileName Int) where qEnum_toInt (QEnum (CFileName x)) = x qEnum_fromInt x = QEnum (CFileName x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> FileName -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eDefaultName :: FileName eDefaultName = ieFileName $ 0 eBaseName :: FileName eBaseName = ieFileName $ 1 ePathName :: FileName ePathName = ieFileName $ 2 eAbsoluteName :: FileName eAbsoluteName = ieFileName $ 3 eAbsolutePathName :: FileName eAbsolutePathName = ieFileName $ 4 eLinkName :: FileName eLinkName = ieFileName $ 5 eCanonicalName :: FileName eCanonicalName = ieFileName $ 6 eCanonicalPathName :: FileName eCanonicalPathName = ieFileName $ 7 eBundleName :: FileName eBundleName = ieFileName $ 8 data CFileOwner a = CFileOwner a type FileOwner = QEnum(CFileOwner Int) ieFileOwner :: Int -> FileOwner ieFileOwner x = QEnum (CFileOwner x) instance QEnumC (CFileOwner Int) where qEnum_toInt (QEnum (CFileOwner x)) = x qEnum_fromInt x = QEnum (CFileOwner x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> FileOwner -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eOwnerUser :: FileOwner eOwnerUser = ieFileOwner $ 0 eOwnerGroup :: FileOwner eOwnerGroup = ieFileOwner $ 1 data CFileTime a = CFileTime a type FileTime = QEnum(CFileTime Int) ieFileTime :: Int -> FileTime ieFileTime x = QEnum (CFileTime x) instance QEnumC (CFileTime Int) where qEnum_toInt (QEnum (CFileTime x)) = x qEnum_fromInt x = QEnum (CFileTime x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> FileTime -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eCreationTime :: FileTime eCreationTime = ieFileTime $ 0 eModificationTime :: FileTime eModificationTime = ieFileTime $ 1 eAccessTime :: FileTime eAccessTime = ieFileTime $ 2 data CQAbstractFileEngineExtension a = CQAbstractFileEngineExtension a type QAbstractFileEngineExtension = QEnum(CQAbstractFileEngineExtension Int) ieQAbstractFileEngineExtension :: Int -> QAbstractFileEngineExtension ieQAbstractFileEngineExtension x = QEnum (CQAbstractFileEngineExtension x) instance QEnumC (CQAbstractFileEngineExtension Int) where qEnum_toInt (QEnum (CQAbstractFileEngineExtension x)) = x qEnum_fromInt x = QEnum (CQAbstractFileEngineExtension x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QAbstractFileEngineExtension -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eAtEndExtension :: QAbstractFileEngineExtension eAtEndExtension = ieQAbstractFileEngineExtension $ 0 eFastReadLineExtension :: QAbstractFileEngineExtension eFastReadLineExtension = ieQAbstractFileEngineExtension $ 1
uduki/hsQt
Qtc/Enums/Core/QAbstractFileEngine.hs
bsd-2-clause
15,097
0
18
3,213
4,102
2,092
2,010
432
1
-- Code for reading and writing reference counts. module Database.VCache.Refct ( readRefctBytes , toRefctBytes , writeRefctBytes , Refct ) where import Control.Exception import Data.Word import Data.Bits import Foreign.Ptr import Foreign.Storable import Database.LMDB.Raw type Refct = Int -- simple variable-width encoding for reference counts. Encoding is -- base256 then adding 1. (The lead byte should always be non-zero, -- but that isn't checked here.) readRefctBytes :: MDB_val -> IO Refct readRefctBytes v = rd (mv_data v) (mv_size v) 0 where rd _ 0 rc = return (rc + 1) rd p n rc = do w8 <- peek p let rc' = (rc `shiftL` 8) .|. fromIntegral w8 rd (p `plusPtr` 1) (n - 1) rc' -- compute list of bytes for a big-endian encoding. -- Reference count must be positive! toRefctBytes :: Refct -> [Word8] toRefctBytes = rcb [] . subtract 1 . assertPositive where rcb l 0 = l rcb l rc = rcb (fromIntegral rc : l) (rc `shiftR` 8) assertPositive n = assert (n > 0) n -- write a reference variable-width count into an MDB_val. -- -- Note: given buffer should be large enough for any reference count. writeRefctBytes :: Ptr Word8 -> Refct -> IO MDB_val writeRefctBytes p0 = wrcb p0 0 . toRefctBytes where wrcb _ n [] = return $! MDB_val { mv_data = p0, mv_size = n } wrcb p n (b:bs) = do { poke p b ; wrcb (p `plusPtr` 1) (n + 1) bs }
dmbarbour/haskell-vcache
hsrc_lib/Database/VCache/Refct.hs
bsd-2-clause
1,409
0
14
324
428
231
197
28
2
module Language.Drasil.HTML.Helpers where import Prelude hiding ((<>)) import Text.PrettyPrint (Doc, text, empty, ($$), (<>), (<+>), vcat, hcat, nest, cat, hcat) import Data.List (intersperse, foldl1) import Language.Drasil hiding (Expr) --import Language.Drasil.Document (Document, MaxWidthPercent) import Language.Drasil.Printing.AST (Expr) html, headTag, body, title, paragraph, code, tr, th, td, figure, figcaption, li, pa, ba :: Doc -> Doc -- | HTML tag wrapper html = wrap "html" [] -- | Head tag wrapper headTag = wrap "head" [] -- | Body tag wrapper body = wrap "body" [] -- | Title tag wrapper title = wrap "title" [] -- | Paragraph tag wrapper paragraph = wrap "p" ["paragraph"] -- | Code tag wrapper code = wrap "code" ["code"] -- | Table row tag wrapper tr = wrap "tr" [] -- | Table header tag wrapper th = wrap "th" [] -- | Table cell tag wrapper td = wrap "td" [] -- | Figure tag wrapper figure = wrap "figure" [] -- | Figcaption tag wrapper figcaption = wrap "figcaption" [] -- | List tag wrapper li = wrap "li" [] -- | Paragraph in list tag wrapper pa = wrap "p" [] ba = wrap "b" [] ol, ul, table :: [String] -> Doc -> Doc -- | Ordered list tag wrapper ol = wrap "ol" -- | Unordered list tag wrapper ul = wrap "ul" -- | Table tag wrapper table = wrap "table" img :: [(String, Doc)] -> Doc -- | Image tag wrapper img = wrapInside "img" -- | Helper for HTML headers h :: Int -> Doc -> Doc h n | n < 1 = error "Illegal header (too small)" | n > 7 = error "Illegal header (too large)" | otherwise = wrap ("h" ++ show n) [] data Variation = Class | Id wrap :: String -> [String] -> Doc -> Doc wrap a = wrapGen Class a empty wrap' :: String -> [String] -> Doc -> Doc wrap' a = wrapGen' hcat Class a empty -- | Helper for wrapping HTML tags. -- The forth argument provides class names for the CSS. wrapGen' :: ([Doc] -> Doc) -> Variation -> String -> Doc -> [String] -> Doc -> Doc wrapGen' sepf _ s _ [] = \x -> let tb c = text $ "<" ++ c ++ ">" in sepf [tb s, indent x, tb $ '/':s] wrapGen' sepf Class s _ ts = \x -> let tb c = text $ "<" ++ c ++ " class=\"" ++ foldr1 (++) (intersperse " " ts) ++ "\">" in let te c = text $ "</" ++ c ++ ">" in sepf [tb s, indent x, te s] wrapGen' sepf Id s ti _ = \x -> let tb c = text ("<" ++ c ++ " id=\"") <> ti <> text "\">" te c = text $ "</" ++ c ++ ">" in sepf [tb s, indent x, te s] wrapGen :: Variation -> String -> Doc -> [String] -> Doc -> Doc wrapGen = wrapGen' cat -- | Helper for wrapping attributes in a tag. -- | The first argument is tag name. -- | The String in the pair is the attribute name, -- | The Doc is the value for different attributes. wrapInside :: String -> [(String, Doc)] -> Doc wrapInside t p = text ("<" ++ t ++ " ") <> foldl1 (<>) (map foldStr p) <> text ">" where foldStr (attr, val) = text (attr ++ "=\"") <> val <> text "\" " -- | Helper for setting up captions caption :: Doc -> Doc caption = wrap "p" ["caption"] refwrap :: Doc -> Doc -> Doc refwrap = flip (wrapGen Id "div") [""] -- | Helper for setting up links to references reflink :: String -> Doc -> Doc reflink ref txt = text ("<a href=#" ++ ref ++ ">") <> txt <> text "</a>" -- | Helper for setting up links to references with additional information reflinkInfo :: String -> Doc -> Doc -> Doc reflinkInfo ref txt info = text ("<a href=#" ++ ref ++ ">") <> txt <> text "</a>" <+> info -- | Helper for setting up links to external URIs reflinkURI :: String -> Doc -> Doc reflinkURI ref txt = text ("<a href=\"" ++ ref ++ "\">") <> txt <> text "</a>" -- | Helper for setting up figures image :: Doc -> Doc -> MaxWidthPercent -> Doc image f c 100 = figure $ vcat [ img [("src", f), ("alt", c)], figcaption c] image f c wp = figure $ vcat [ img [("src", f), ("alt", c), ("width", text $ show wp ++ "%")], figcaption c] em, sup, sub, bold :: Doc -> Doc -- | Emphasis (italics) tag em = wrap' "em" [] -- | Superscript tag sup = wrap' "sup" [] -- | Subscript tag sub = wrap' "sub" [] -- | Bold tag bold = wrap' "b" [] articleTitle, author :: Doc -> Doc -- | Title header articleTitle t = divTag ["title"] (h 1 t) -- | Author header author a = divTag ["author"] (h 2 a) -- | Div tag wrapper divTag :: [String] -> Doc -> Doc divTag = wrap "div" spanTag :: [String] -> Doc -> Doc spanTag = wrap "span" indent :: Doc -> Doc indent = nest 2 -- Not used since we use MathJax handles this -- | Create and markup fractions -- fraction :: Doc -> Doc -> Doc -- fraction a b = -- divTag ["fraction"] (spanTag ["fup"] a $$ spanTag ["fdn"] b) -- Not used since we use MathJax handles this -- -- | Build cases for case expressions -- cases :: [(Expr,Expr)] -> (Expr -> Doc) -> Doc -- cases ps pExpr = spanTag ["casebr"] (text "{") $$ divTag ["cases"] -- (makeCases ps pExpr) -- | Build case expressions makeCases :: [(Expr,Expr)] -> (Expr -> Doc) -> Doc makeCases [] _ = empty makeCases (p:ps) pExpr = spanTag [] (pExpr (fst p) <> text " , " <> spanTag ["case"] (pExpr (snd p))) $$ makeCases ps pExpr
JacquesCarette/literate-scientific-software
code/drasil-printers/Language/Drasil/HTML/Helpers.hs
bsd-2-clause
5,232
0
15
1,319
1,711
936
775
93
1
module ProjectEuler.Problem004 (solution004) where import Data.Digits import Data.List import Util solution004 :: Integer solution004 = last $ filter (isPalindrome . digits 10) $ sort [ x * y | x <- [100..999], y <- [x..999]]
guillaume-nargeot/project-euler-haskell
src/ProjectEuler/Problem004.hs
bsd-3-clause
228
0
10
37
91
50
41
6
1
{-# LANGUAGE OverloadedStrings #-} module Website.Template ( TemplateToken(..), wrapTemplate, PartialToken ) where import Text.Blaze.Html5 hiding (map) import Text.Blaze.Html5.Attributes hiding (id) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import GameData import Data.Function import Data.List import Data.Ord import Prelude hiding (div, round) -- | A datatype meant to be passed to the wrapTemplate function to construct the menus. data TemplateToken = TemplateToken { teamList :: [TeamInfo], -- | A sorted list representing all teams matchList :: [MatchInfo],-- | A sorted list representing all matches path :: String -- | The path to the the root of the website relative to the webpage. } -- | A partially applied constructor that lacks the path for a TemplateToken type PartialToken = String -> TemplateToken -- | Should take a page and wrap it with a left, right, and top menu displaying the teams, matches, and indices respectively wrapTemplate :: TemplateToken -- | The token containing all data for the menus -> Html -- | The HTML to be wrapped. -> Html -- | The wrapped HTML wrapTemplate _ = id --wrapTemplate token page = docTypeHtml $ do -- link ! rel "stylesheet" ! type_ "text/css" ! href (toValue $ path token ++ "screen.css") -- ul ! A.id "nav-left" $ mapM_ (\team -> li -- (a ! href (toValue $ path token ++ show (number team) ++ ".html") $ toHtml $ number team)) $ -- teamList token -- ul ! A.id "nav-right" $ mapM_ (\(MatchInfo (a1, a2)) -> li -- (a ! href (toValue $ path token ++ "matches/" ++ round a1 ++ ".html") $ toHtml (round a1))) $ -- matchList token -- ul ! A.id "nav-top" $ do -- li $ a ! href (toValue $ path token ++ "index.html") $ " Average " -- li $ a ! href (toValue $ path token ++ "auto.html") $ " Autonomous " -- li $ a ! href (toValue $ path token ++ "main.html") $ " Teleop " -- li $ a ! href (toValue $ path token ++ "climb.html") $ " Climbing " -- div ! customAttribute "class" "main-page" $ page
TheGreenMachine/Scouting-Backend
src/Website/Template.hs
bsd-3-clause
2,147
0
9
509
183
127
56
23
1
{-| Module : Cache Description : Caching library used by AriaDB License : BSD3 Maintainer : [email protected] Stability : experimental This cache library exports 3 functions get, upsert and delete that is used by AriaDB for faster reads. This library uses LRU cache library which handles all these three requests in O(log n). Objects read are always cached. Objects inserted in B+ Tree are cached by default. Objects deleted from B+ Tree are also removed from the cache. -} module Cache (get, upsert, remove, lruCacheSize) where import Aria import qualified BPlusTree.BPlusTree as BPTree import BPlusTree.Leaf as Leaf import BPlusTree.Types import Data.Cache.LRU as LRU import Data.IORef -- | Maximum size of LRU cache. The LRU cache is guaranteed to not grow above -- the specified number of entries. lruCacheSize :: Maybe Integer lruCacheSize = Just 10000 -- | 'get' takes an LRU cache and a key, and returns the corresponding value. -- If the (key, value) is present in the cache, the value is returned -- immediately otherwise value is looked up in the B+ Tree and the cache is -- updated with complete leaf key-values to boost up sequential reads. get :: IORef (LRU AriaKey AriaValue) -> AriaKey -> IO (Maybe AriaValue) get lruCache key = do cacheValue <- readIORef lruCache let (newCache, val) = LRU.lookup key cacheValue case val of Just v -> do writeIORef lruCache newCache return (Just v) Nothing -> do val' <- BPTree.get key case val' of Just v -> do -- point caching: for random repeated reads -- let newCache = LRU.insert key v cacheValue -- writeIORef lruCache newCache -- bulk load: put whole leaf in cache: for seq reads leafName <- BPTree.findLeaf key bulkload lruCache leafName return (Just v) Nothing -> return Nothing -- | 'upsert' takes an LRU cache, a key and a value and inserts this key -- value pair in B+ Tree if key was not present earlier, or updates its value -- otherwise and updates the cache accordingly. upsert :: IORef (LRU AriaKey AriaValue) -> AriaKey -> AriaValue -> IO () upsert lruCache key value = do cacheValue <- readIORef lruCache let newCache = LRU.insert key value cacheValue writeIORef lruCache newCache BPTree.upsert $ AriaKV key value -- | 'remove' takes an LRU cache and a key. It removes the corresponding -- (key, value) pair from B+ Tree and cache if the key was present. remove :: IORef (LRU AriaKey AriaValue) -> AriaKey -> IO () remove lruCache key = do cacheValue <- readIORef lruCache let (newCache, _) = LRU.delete key cacheValue writeIORef lruCache newCache BPTree.remove key -- | It loads up entire key-value pairs in the leaf into the cache. The leaf -- values are prepended to the existing ones. LRU cache library achieves it in -- O(n*logn). Loading entire leaf will greatly enhance the sequential reads. bulkload :: IORef (LRU AriaKey AriaValue) -> BPTFileName -> IO () bulkload lruCache leafName = do leaf <- Leaf.readLeaf leafName cacheValue <- readIORef lruCache let oldCacheValues = LRU.toList cacheValue let newCacheValues = getKVList leaf let newCache = LRU.fromList lruCacheSize (newCacheValues ++ oldCacheValues) writeIORef lruCache newCache -- | Essentially, it drops those key-value pairs whose values are 'Nothing'. -- Those keys are deleted keys and need not be added in the cache. getKVList :: Leaf -> [(AriaKey, AriaValue)] getKVList leaf = map getKV filteredList where filteredList = filter isSndNonEmpty zippedList where zippedList = zip (Leaf.keys leaf) (Leaf.values leaf) -- | This function is to assist 'getKVList' to map over the list to remove those -- key-value whose value is 'Nothing'. getKV :: (AriaKey, Maybe AriaValue) -> (AriaKey, AriaValue) getKV kv = case snd kv of Just x -> (fst kv, x ) Nothing -> (fst kv, "") -- this case won't arise. -- | This function checks if the second entry in the pair is 'Nothing'. This is -- to filter the zipped list in 'getKVList' isSndNonEmpty :: (a, Maybe b) -> Bool isSndNonEmpty x = case snd x of Just _ -> True Nothing -> False
proneetv/ariaDB
src/Service/Cache.hs
bsd-3-clause
4,368
0
19
1,069
775
389
386
57
3
-- 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. module Duckling.Volume.ES.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Volume.ES.Corpus tests :: TestTree tests = testGroup "ES Tests" [ makeCorpusTest [This Volume] corpus ]
rfranek/duckling
tests/Duckling/Volume/ES/Tests.hs
bsd-3-clause
597
0
9
96
80
51
29
11
1
module Data.Geo.GPX.Lens.MaxlonL where import Data.Geo.GPX.Type.Longitude import Data.Lens.Common class MaxlonL a where maxlonL :: Lens a Longitude
tonymorris/geo-gpx
src/Data/Geo/GPX/Lens/MaxlonL.hs
bsd-3-clause
153
0
7
21
42
26
16
5
0
{-# LANGUAGE CPP #-} module SAWScript.AutoMatch.ArgMapping ( ArgMapping , typeBins , nameLocs , makeArgMapping , removeName , lookupName , lookupType , emptyArgMapping , isEmptyArgMapping ) where import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Data.Maybe #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import SAWScript.AutoMatch.Declaration import SAWScript.AutoMatch.Util -- | A bidirectional mapping representing what arguments have what types at what positions in a declaration -- Abstract, because we preserve the invariant that the maps contained are coherent. data ArgMapping = ArgMapping { typeBins_ :: Map Type (Set (Name, Int)) , nameLocs_ :: Map Name (Int, Type) } deriving (Show) typeBins :: ArgMapping -> Map Type (Set (Name, Int)) typeBins = typeBins_ nameLocs :: ArgMapping -> Map Name (Int, Type) nameLocs = nameLocs_ -- | Make an argMapping from a list of Args makeArgMapping :: [Arg] -> ArgMapping makeArgMapping = ArgMapping <$> foldr (uncurry (\k -> Map.insertWith Set.union k . Set.singleton)) Map.empty . map (\(i, a) -> (argType a, (argName a, i))) . zip [0..] <*> foldr (uncurry Map.insert) Map.empty . map (\(i, a) -> (argName a, (i, argType a))) . zip [0..] -- | Remove a name from an ArgMapping removeName :: Name -> ArgMapping -> ArgMapping removeName name mapping = fromMaybe mapping $ do (nameIndex, nameType) <- Map.lookup name (nameLocs mapping) return $ ArgMapping (deleteFromSetMap nameType (name, nameIndex) (typeBins mapping)) (Map.delete name (nameLocs mapping)) -- | Look up a name's type and position in the original declaration lookupName :: Name -> ArgMapping -> Maybe (Int, Type) lookupName name (ArgMapping _ nls) = Map.lookup name nls -- | Look up all the names of a given type and their indices lookupType :: Type -> ArgMapping -> Maybe (Set (Name, Int)) lookupType typ (ArgMapping tbs _) = Map.lookup typ tbs -- | The empty ArgMapping emptyArgMapping :: ArgMapping emptyArgMapping = makeArgMapping [] -- | Test if an ArgMapping is empty isEmptyArgMapping :: ArgMapping -> Bool isEmptyArgMapping (ArgMapping t n) = Map.null t && Map.null n
GaloisInc/saw-script
src/SAWScript/AutoMatch/ArgMapping.hs
bsd-3-clause
2,381
0
18
542
651
360
291
51
1
data LL a = Nil | Cons (LL a) a instance Show a => Show (LL a) where showsPrec _ (Cons lst x) = ("Cons (" ++) . showsPrec 11 lst . (") " ++) . showsPrec 11 x showsPrec _ Nil = ("Nil" ++)
YoshikuniJujo/funpaala
samples/27_basic_type_classes/leftList1.hs
bsd-3-clause
192
2
9
50
107
56
51
5
0
module BrownPLT.JavaScript.Environment ( env , localVars , EnvTree (..) ) where import Data.List import Data.Maybe import qualified Data.Map as M import Data.Map (Map) import qualified Data.Set as S import Data.Set (Set) import Text.ParserCombinators.Parsec.Pos (SourcePos) import BrownPLT.JavaScript.Syntax -- Intermediate data structure that contains locally declared names and -- all references to identifers. data Partial = Partial { partialLocals :: M.Map String SourcePos, partialReferences :: M.Map String SourcePos, partialNested :: [Partial] } empty :: Partial empty = Partial M.empty M.empty [] ref :: Id SourcePos -> Partial ref (Id p v) = Partial M.empty (M.singleton v p) [] decl :: Id SourcePos -> Partial decl (Id p v) = Partial (M.singleton v p) M.empty [] nest :: Partial -> Partial nest partial = Partial M.empty M.empty [partial] -- Combine partial results from the same lexical scope. unions :: [Partial] -> Partial unions ps = Partial (M.unions (map partialLocals ps)) (M.unions (map partialReferences ps)) (concatMap partialNested ps) javascript :: JavaScript SourcePos -> Partial javascript (Script _ ss) = unions (map stmt ss) lvalue :: LValue SourcePos -> Partial lvalue lv = case lv of LVar p x -> ref (Id p x) LDot _ e _ -> expr e LBracket _ e1 e2 -> unions [expr e1, expr e2] expr :: Expression SourcePos -> Partial expr e = case e of StringLit _ _ -> empty RegexpLit _ _ _ _ -> empty NumLit _ _ -> empty IntLit _ _ -> empty BoolLit _ _ -> empty NullLit _ -> empty ArrayLit _ es -> unions (map expr es) ObjectLit _ props -> unions (map (expr.snd) props) ThisRef _ -> empty VarRef _ id -> empty DotRef _ e _ -> expr e BracketRef _ e1 e2 -> unions [expr e1, expr e2] NewExpr _ e1 es -> unions [expr e1, unions $ map expr es] PrefixExpr _ _ e -> expr e InfixExpr _ _ e1 e2 -> unions [expr e1, expr e2] CondExpr _ e1 e2 e3 -> unions [expr e1, expr e2, expr e3] AssignExpr _ _ lv e -> unions [lvalue lv, expr e] UnaryAssignExpr _ _ lv -> lvalue lv ParenExpr _ e -> expr e ListExpr _ es -> unions (map expr es) CallExpr _ e es -> unions [expr e, unions $ map expr es] FuncExpr _ args s -> nest $ unions [unions $ map decl args, stmt s] caseClause :: CaseClause SourcePos -> Partial caseClause cc = case cc of CaseClause _ e ss -> unions [expr e, unions $ map stmt ss] CaseDefault _ ss -> unions $ map stmt ss -- TODO: Verify that this is a declaration and not a reference. catchClause :: CatchClause SourcePos -> Partial catchClause (CatchClause _ id s) = unions [decl id, stmt s] varDecl :: VarDecl SourcePos -> Partial varDecl (VarDecl _ id Nothing) = decl id varDecl (VarDecl _ id (Just e)) = unions [decl id, expr e] forInit :: ForInit SourcePos -> Partial forInit fi = case fi of NoInit -> empty VarInit ds -> unions $ map varDecl ds ExprInit e -> expr e forInInit :: ForInInit SourcePos -> Partial forInInit (ForInVar id) = decl id forInInit (ForInNoVar id) = ref id stmt :: Statement SourcePos -> Partial stmt s = case s of BlockStmt _ ss -> unions $ map stmt ss EmptyStmt _ -> empty ExprStmt _ e -> expr e IfStmt _ e s1 s2 -> unions [expr e, stmt s1, stmt s2] IfSingleStmt _ e s -> unions [expr e, stmt s] SwitchStmt _ e cases -> unions [expr e, unions $ map caseClause cases] WhileStmt _ e s -> unions [expr e, stmt s] DoWhileStmt _ s e -> unions [stmt s, expr e] BreakStmt _ _ -> empty ContinueStmt _ _ -> empty LabelledStmt _ _ s -> stmt s ForInStmt _ fii e s -> unions [forInInit fii, expr e, stmt s] ForStmt _ fi me1 me2 s -> unions [forInit fi, maybe empty expr me1, maybe empty expr me2, stmt s] TryStmt _ s catches ms -> unions [stmt s, unions $ map catchClause catches, maybe empty stmt ms] ThrowStmt _ e -> expr e ReturnStmt _ me -> maybe empty expr me WithStmt _ e s -> unions [expr e, stmt s] VarDeclStmt _ decls -> unions $ map varDecl decls FunctionStmt _ fnId args s -> unions [decl fnId, nest $ unions [unions $ map decl args, stmt s]] -- |The statically-determinate lexical structure of a JavaScript program. data EnvTree = EnvTree (M.Map String SourcePos) [EnvTree] -- A 'Partial' specifies identifier references in addition to identifier -- declarations. We descend into a 'Partial', pushing enclosing declarations -- in to remove references to identifiers declared in the enclosing scope. -- Any referencs to identifiers not declared in either the current or the -- enclosing scope are local definitions of global variables. makeEnvTree :: Map String SourcePos -- ^enclosing environment -> Partial -- ^local environment and references -> (EnvTree,Map String SourcePos) -- ^environment and global definitions makeEnvTree enclosing (Partial locals references nested) = (tree,globals) where nestedResults = map (makeEnvTree (locals `M.union` enclosing)) nested tree = EnvTree locals (map fst nestedResults) globals' = (references `M.difference` locals) `M.difference` enclosing globals = M.unions (globals':(map snd nestedResults)) env :: Map String SourcePos -- ^browser/testing environment -> [Statement SourcePos] -> (EnvTree,Map String SourcePos) env globals program = makeEnvTree globals (unions $ map stmt program) localVars :: [Statement SourcePos] -> [(String, SourcePos)] localVars body = M.toList locals where Partial locals _ _ = unions $ map stmt body
ducis/flapjax-fixed
WebBits-1.0/src/BrownPLT/JavaScript/Environment.hs
bsd-3-clause
5,472
0
14
1,179
2,091
1,033
1,058
117
22
{- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - USAGE: hooty (-1|-4)? (-n <number to make>)? The `hooty` program generates any number of UUIDs (one by default), using either the version 1 (time and MAC) or version 4 (random) algorithm (version 1 is the default). On all platforms, `hooty` uses the native implementation. -n, --number <number> Create <number> many UUIDs in one go. -1, --sequential Create version 1 (time and MAC) UUIDs. -4, --random Create version 4 (random) UUIDs. -h, -?, --help Print this help and exit. --version Print version and exit. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} {-# LANGUAGE TemplateHaskell , PatternGuards #-} import qualified System.UUID.V1 as V1 import qualified System.UUID.V4 as V4 import Options import Messages import qualified Macros as Macros import System.Environment import System.Exit import Control.Monad import Control.Applicative import Data.Maybe import Data.Word import qualified Data.Map as Map main = do m <- opts let lk = (`Map.lookup` m) when (isJust $ lk "h") $ do stdout << usage exitWith ExitSuccess when (isJust $ lk "version") $ do stdout << version exitWith ExitSuccess when (all (isJust . lk) ["1","4"]) $ do bail "Please specify either version 1 or version 4, not both." let n :: Word n = fromMaybe 1 $ maybeRead =<< lk "n" gen = if isJust $ lk "4" then V4.uuid else V1.uuid mapM_ (const $ print =<< gen) [1..n] bail :: String -> IO a bail s = do stderr << s stderr << usage exitFailure usage = $(Macros.usage) version = "hooty-" ++ $(Macros.version) opts = do args <- getArgs case runParser options () "command line arguments" args of Right list -> return $ foldr ($) Map.empty list Left e -> bail $ show e options = do res <- choice [ eof >> return [] , many1 options' ] eof return res options' = do o <- choice opts opt o where opt o@[c] | c `elem` "h14" = return $ Map.insert o "" | c == 'n' = choice [ eof >> fail "Option requires an argument." , try $ do s <- initialChar '-' fail $ "Option requiring argument followed by:\n " ++ s , fmap (Map.insert o) anyString ] | otherwise = prb $ "unimplemented option '" ++ o ++ "'" opt "version" = return $ Map.insert "version" "" opt o = prb $ "unimplemented option '" ++ o ++ "'" prb s = fail $ "Please report a bug -- " ++ s ++ "." opts = map try [ option "h?" ["help"] , option "1" ["sequential"] , option "4" ["random"] , option "n" ["number"] , option "" ["version"] ] ++ [ fail "Invalid option." ] maybeRead s | [(a, _)] <- reads s = Just a | otherwise = Nothing
solidsnack/system-uuid
Main.hs
bsd-3-clause
3,529
1
12
1,492
780
393
387
77
3
module Main where import qualified EFA.Application.Plot as PlotIO import qualified EFA.IO.TableParser as Table import qualified EFA.Signal.Signal as S import qualified EFA.Signal.ConvertTable as CT import EFA.Utility.Map (checkedLookup) import qualified Graphics.Gnuplot.Terminal.Default as Def import qualified Data.NonEmpty as NonEmpty import qualified Data.Map as Map plot3D :: ( S.UTSignal2 [] [] Double, S.PSignal2 [] [] Double, S.NSignal2 [] [] Double ) -> IO () plot3D (x, y, z) = PlotIO.surface "test" Def.cons x y z plot2D :: ( S.PSignal [] Double, NonEmpty.T [] (S.NSignal [] Double) ) -> IO () plot2D (x, y) = PlotIO.xy "test" Def.cons id x $ fmap (PlotIO.label "eta") $ NonEmpty.flatten y main :: IO () main = do tabEn <- Table.read "engine.txt" tabMo <- Table.read "motor.txt" Table.write "combined.txt" (Map.union tabEn tabEn) let em3D = CT.convertToSignal3D (checkedLookup "demo/table" tabEn "table2D_efficiencyMap") : CT.convertToSignal3D (checkedLookup "demo/table" tabMo "table2D_efficiencyMap_firstQuadrant") : [] em2D = CT.convertToSignal3D2D (checkedLookup "demo/table" tabEn "table2D_efficiencyMap") : CT.convertToSignal3D2D (checkedLookup "demo/table" tabMo "table2D_efficiencyMap_firstQuadrant") : CT.convertToSignal2D (checkedLookup "demo/table" tabEn "maxTorque") : CT.convertToSignal2D (checkedLookup "demo/table" tabEn "dragTorque") : [] mapM_ plot3D em3D mapM_ plot2D em2D
energyflowanalysis/efa-2.1
demo/tables/Main.hs
bsd-3-clause
1,578
0
16
347
479
252
227
43
1
{-# OPTIONS -XDeriveDataTypeable -XUndecidableInstances -XExistentialQuantification -XMultiParamTypeClasses -XTypeSynonymInstances -XFlexibleInstances -XScopedTypeVariables -XFunctionalDependencies -XFlexibleContexts -XRecordWildCards -XIncoherentInstances -XTypeFamilies -XTypeOperators -XOverloadedStrings -XTemplateHaskell -XNoMonomorphismRestriction #-} {- | MFlow run stateful server processes. This version is the first stateful web framework that is as RESTful as a web framework can be. The routes are expressed as normal, monadic Haskell code in the FlowM monad. Local links point to alternative routes within this monadic computation just like a textual menu in a console application. Any GET page is directly reachable by means of a RESTful URL. At any moment the flow can respond to the back button or to any RESTful path that the user may paste in the navigation bar. If the procedure is waiting for another different page, the FlowM monad backtrack until the path partially match . From this position the execution goes forward until the rest of the path match. This way the statelessness is optional. However, it is possible to store a session state, which may backtrack or not when the navigation goes back and forth. It is up to the programmer. All the flow of requests and responses are coded by the programmer in a single procedure. Although single request-response flows are possible. Therefore, the code is more understandable. It is not continuation based. It uses a log for thread state persistence and backtracking for handling the back button. Back button state synchronization is supported out-of-the-box The MFlow architecture is scalable, since the state is serializable and small The processes are stopped and restarted by the application server on demand, including the execution state (if the Workflow monad is used). Therefore session management is automatic. State consistence and transactions are given by the TCache package. The processes interact trough widgets, that are an extension of formlets with additional applicative combinators, formatting, link management, callbacks, modifiers, caching, ByteString conversion and AJAX. All is coded in pure Haskell. The interfaces and communications are abstract, but there are bindings for blaze-html, HSP, Text.XHtml and ByteString , Hack and WAI but it can be extended to non Web based architectures. Bindings for hack, and HSP >= 0.8, are not compiled by Hackage, and do not appear, but are included in the package files. To use them, add then to the exported modules and execute cabal install It is designed for applications that can be run with no deployment with runghc in order to speed up the development process. see <http://haskell-web.blogspot.com.es/2013/05/a-web-application-in-tweet.html> This module implement stateful processes (flows) that are optionally persistent. This means that they automatically store and recover his execution state. They are executed by the MFlow app server. defined in the "MFlow" module. These processes interact with the user trough user interfaces made of widgets (see below) that return back statically typed responses to the calling process. Because flows are stateful, not request-response, the code is more understandable, because all the flow of request and responses is coded by the programmer in a single procedure in the FlowM monad. Although single request-response flows and callbacks are possible. This module is abstract with respect to the formatting (here referred with the type variable @view@) . For an instantiation for "Text.XHtml" import "MFlow.Forms.XHtml", "MFlow.Hack.XHtml.All" or "MFlow.Wai.XHtml.All" . To use Haskell Server Pages import "MFlow.Forms.HSP". However the functions are documented here. `ask` is the only method for user interaction. It run in the @MFlow view m@ monad, with @m@ the monad chosen by the user, usually IO. It send user interfaces (in the @View view m@ monad) and return statically typed responses. The user interface definitions are based on a extension of formlets (<http://www.haskell.org/haskellwiki/Formlets>) with the addition of caching, links, formatting, attributes, extra combinators, callbacks and modifiers. The interaction with the user is stateful. In the same computation there may be many request-response interactions, in the same way than in the case of a console applications. * APPLICATION SERVER Therefore, session and state management is simple and transparent: it is in the Haskell structures in the scope of the computation. `transient` (normal) procedures have no persistent session state and `stateless` procedures accept a single request and return a single response. `MFlow.Forms.step` is a lifting monad transformer that permit persistent server procedures that remember the execution state even after system shutdowns by using the package workflow (<http://hackage.haskell.org/package/Workflow>) internally. This state management is transparent. There is no programmer interface for session management. The programmer set the process timeout and the session timeout with `setTimeouts`. If the procedure has been stopped due to the process timeout or due to a system shutdown, the procedure restart in the last state when a request for this procedure arrives (if the procedure uses the `step` monad transformer) * WIDGETS The correctness of the web responses is assured by the use of formLets. But unlike formLets in its current form, it permits the definition of widgets. /A widget is a combination of formLets and links within its own formatting template/, all in the same definition in the same source file, in plain declarative Haskell style. The formatting is abstract. It has to implement the 'FormInput' class. There are instances for Text.XHtml ("MFlow.Forms.XHtml"), Haskell Server Pages ("MFlow.Forms.HSP") and ByteString. So widgets can use any formatting that is instance of `FormInput`. It is possible to use more than one format in the same widget. Links defined with `wlink` are treated the same way than forms. They are type safe and return values to the same flow of execution. It is possible to combine links and forms in the same widget by using applicative combinators but also additional applicative combinators like \<+> !*> , |*|. Widgets are also monoids, so they can be combined as such. * NEW IN THIS RELEASE [@Runtime templates@] 'template', 'edTemplate', 'witerate' and 'dField' permit the edition of the widget content at runtime, and the management of placeholders with input fields and data fields within the template with no navigation in the client, little bandwidth usage and little server load. Even less than using 'autoRefresh'. * IN PREVIOUS RELEASES {@AutoRefresh@] Using `autoRefresh`, Dynamic widgets can refresh themselves with new information without forcing a refresh of the whole page [@Push@] With `push` a widget can push new content to the browser when something in the server happens [@Error traces@] using the monadloc package, now each runtime error (in a monadic statement) has a complete execution trace. [@RESTful URLs@] Now each page is directly reachable by means of a intuitive, RESTful URL, whose path is composed by the succession of links clicked to reach such page and such point in the procedure. Just what you would expect. [@Page flows@] each widget-formlet can have its own independent behavior within the page. They can refresh independently trough AJAX by means of 'autoRefresh'. Additionally, 'pageFlow' initiates the page flow mode or a subpage flow by adding a well know identifier prefix for links and form parameters. [@Modal Dialogs@] 'wdialog' present a widget within a modal or non modal jQuery dialog. while a monadic widget-formlet can add different form elements depending on the user responses, 'wcallback' can substitute the widget by other. (See 'Demos/demos.blaze.hs' for some examples) [@JQuery widgets@] with MFlow interface: 'getSpinner', 'datePicker', 'wdialog' [@WAI interface@] Now MFlow works with Snap and other WAI developments. Include "MFlow.Wai" or "MFlow.Wai.Blaze.Html.All" to use it. [@blaze-html support@] see <http://hackage.haskell.org/package/blaze-html> import "MFlow.Forms.Blaze.Html" or "MFlow.Wai.Blaze.Html.All" to use Blaze-Html [@AJAX@] Now an Ajax procedures (defined with 'ajax' can perform many interactions with the browser widgets, instead of a single request-response (see 'ajaxSend'). [@Active widgets@] "MFlow.Forms.Widgets" contains active widgets that interact with the server via Ajax and dynamically control other widgets: 'wEditList', 'autocomplete' 'autocompleteEdit' and others. [@Requirements@] a widget can specify JavaScript files, JavaScript online scripts, CSS files, online CSS and server processes and any other instance of the 'Requirement' class. See 'requires' and 'WebRequirements' [@content-management@] for templating and online edition of the content template. See 'tFieldEd' 'tFieldGen' and 'tField' [@multilanguage@] see 'mField' and 'mFieldEd' [@URLs to internal states@] if the web navigation is trough GET forms or links, an URL can express a direct path to the nth step of a flow, So this URL can be shared with other users. Just like in the case of an ordinary stateless application. [@Back Button@] This is probably the first implementation in any language where the navigation can be expressed procedurally and still it works well with the back button, thanks to monad magic. (See <http://haskell-web.blogspot.com.es/2012/03//failback-monad.html>) [@Cached widgets@] with `cachedWidget` it is possible to cache the rendering of a widget as a ByteString (maintaining type safety) , the caching can be permanent or for a certain time. this is very useful for complex widgets that present information. Specially if the widget content comes from a database and it is shared by all users. [@Callbacks@] `waction` add a callback to a widget. It is executed when its input is validated. The callback may initiate a flow of interactions with the user or simply executes an internal computation. Callbacks are necessary for the creation of abstract container widgets that may not know the behavior of its content. with callbacks, the widget manages its content as black boxes. [@Modifiers@] `wmodify` change the visualization and result returned by the widget. For example it may hide a login form and substitute it by the username if already logged. Example: @ ask $ wform userloginform \``validate`\` valdateProc \``waction`\` loginProc \``wmodify`\` hideIfLogged@ [@attributes for formLet elements@] to add attributes to widgets. See the '<!' operator [@ByteString normalization and heterogeneous formatting@] For caching the rendering of widgets at the ByteString level, and to permit many formatting styles in the same page, there are operators that combine different formats which are converted to ByteStrings. For example the header and footer may be coded in XML, while the formlets may be formatted using Text.XHtml. [@File Server@] With file caching. See "MFlow.File Server" -} module MFlow.Forms( -- * Basic definitions -- FormLet(..), FlowM, View(..), FormElm(..), FormInput(..) -- * Users , Auth(..), userRegister, setAuthMethod, userValidate, isLogged, setAdminUser, getAdminName ,getCurrentUser,getUserSimple, getUser, userFormLine, userLogin,logout, paranoidLogout ,encryptedLogout, userWidget, paranoidUserWidget, encryptedUserWidget, login, paranoidLogin, encryptedLogin, userName, -- * User interaction ask, page, askt, clearEnv, clearEnv', wstateless, pageFlow, -- * formLets -- | They usually produce the HTML form elements (depending on the FormInput instance used) -- It is possible to modify their attributes with the `<!` operator. -- They are combined with applicative combinators and some additional ones -- formatting can be added with the formatting combinators. -- modifiers change their presentation and behavior getString,getInt,getInteger, getTextBox ,getMultilineText,getBool,getSelect, setOption,setSelectedOption, getPassword, getRadio, setRadio, setRadioActive, wlabel, getCheckBoxes, genCheckBoxes, setCheckBox, submitButton,resetButton, whidden, wlink, absLink, getKeyValueParam, fileUpload, getRestParam, returning, wform, firstOf, manyOf, allOf, wraw, wrender, notValid -- * FormLet modifiers ,validate, noWidget, stop, waction, wcallback, wmodify, -- * Caching widgets cachedWidget, wcached, wfreeze, -- * Widget combinators (<+>),(|*>),(|+|), (**>),(<**),(<|>),(<*),(<$>),(<*>),(>:>) ---- * Normalized (convert to ByteString) widget combinators ---- | These dot operators are identical to the non dot operators, with the addition of the conversion of the arguments to lazy ByteStrings ---- ---- The purpose is to combine heterogeneous formats into ByteString-formatted widgets that ---- can be cached with `cachedWidget` --,(.<+>.), (.|*>.), (.|+|.), (.**>.),(.<**.), (.<|>.), -- * Formatting combinators ,(<<<),(++>),(<++),(<!) ---- * Normalized (convert to ByteString) formatting combinators ---- | Some combinators that convert the formatting of their arguments to lazy ByteString ----(.<<.),(.<++.),(.++>.) -- * ByteString tags ,btag,bhtml,bbody -- * send raw bytestring data ,rawSend -- * Normalization ,flatten, normalize -- * Running the flow monad ,runFlow, transientNav, runFlowOnce, runFlowIn ,runFlowConf,MFlow.Forms.Internals.step -- * controlling backtracking ,goingBack,returnIfForward, breturn, preventGoingBack, compensate, onBacktrack, retry -- * Setting parameters ,setHttpHeader ,setHeader ,addHeader ,getHeader ,setSessionData ,getSessionData ,getSData ,delSessionData ,setTimeouts -- * Cookies ,setCookie ,setParanoidCookie ,setEncryptedCookie -- * Ajax ,ajax ,ajaxSend ,ajaxSend_ -- * Requirements ,Requirements(..) ,WebRequirement(..) ,requires -- * Utility ,getSessionId ,getLang ,genNewId ,getNextId ,changeMonad ,FailBack ,fromFailBack ,toFailBack ) where import Data.RefSerialize hiding ((<|>),empty) import Data.TCache import Data.TCache.Memoization import MFlow import MFlow.Forms.Internals import MFlow.Cookies import Data.ByteString.Lazy.Char8 as B(ByteString,cons,append,empty,fromChunks,unpack) import Data.ByteString.Lazy.UTF8 hiding (length, take) import qualified Data.String as S import qualified Data.Text as T import Data.Text.Encoding import Data.List --import qualified Data.CaseInsensitive as CI import Data.Typeable import Data.Monoid import Control.Monad.State.Strict import Data.Maybe import Control.Applicative import Control.Exception import Control.Concurrent import Control.Workflow as WF import Control.Monad.Identity import Unsafe.Coerce import Data.List(intersperse) import Data.IORef import qualified Data.Map as M import System.IO.Unsafe import Data.Char(isNumber,toLower) import Network.HTTP.Types.Header import MFlow.Forms.Cache -- | Validates a form or widget result against a validating procedure -- -- @getOdd= getInt Nothing `validate` (\x -> return $ if mod x 2==0 then Nothing else Just "only odd numbers, please")@ validate :: (FormInput view, Monad m) => View view m a -> (a -> WState view m (Maybe view)) -> View view m a validate formt val= View $ do FormElm form mx <- runView formt case mx of Just x -> do me <- val x modify (\s -> s{inSync= True}) case me of Just str -> return $ FormElm ( form <> inred str) Nothing Nothing -> return $ FormElm form mx _ -> return $ FormElm form mx -- | Actions are callbacks that are executed when a widget is validated. -- A action may be a complete flow in the flowM monad. It takes complete control of the navigation -- while it is executed. At the end it return the result to the caller and display the original -- calling page. -- It is useful when the widget is inside widget containers that may treat it as a black box. -- -- It returns a result that can be significant or, else, be ignored with '<**' and '**>'. -- An action may or may not initiate his own dialog with the user via `ask` waction :: (FormInput view, Monad m) => View view m a -> (a -> FlowM view m b) -> View view m b waction f ac = do x <- f s <- get let env = mfEnv s let seq = mfSequence s put s{mfSequence=mfSequence s+ 100,mfEnv=[],newAsk=True} r <- flowToView $ ac x modify $ \s-> s{mfSequence= seq, mfEnv= env} return r where flowToView x= View $ do r <- runSup $ runFlowM x case r of NoBack x -> return (FormElm mempty $ Just x) BackPoint x-> return (FormElm mempty $ Just x) GoBack-> do modify $ \s ->s{notSyncInAction= True} return (FormElm mempty Nothing) -- | change the rendering and the return value of a page. This is superseded by page flows. wmodify :: (Monad m, FormInput v) => View v m a -> (v -> Maybe a -> WState v m (v, Maybe b)) -> View v m b wmodify formt act = View $ do FormElm f mx <- runView formt (f',mx') <- act f mx return $ FormElm f' mx' -- | Display a text box and return a non empty String getString :: (FormInput view,Monad m) => Maybe String -> View view m String getString ms = getTextBox ms `validate` \s -> if null s then return (Just $ fromStr "") else return Nothing -- | Display a text box and return an Integer (if the value entered is not an Integer, fails the validation) getInteger :: (FormInput view, MonadIO m) => Maybe Integer -> View view m Integer getInteger = getTextBox -- | Display a text box and return a Int (if the value entered is not an Int, fails the validation) getInt :: (FormInput view, MonadIO m) => Maybe Int -> View view m Int getInt = getTextBox -- | Display a password box getPassword :: (FormInput view, Monad m) => View view m String getPassword = getParam Nothing "password" Nothing newtype Radio a= Radio a -- | Implement a radio button that perform a submit when pressed. -- the parameter is the name of the radio group setRadioActive :: (FormInput view, MonadIO m, Read a, Typeable a, Eq a, Show a) => a -> String -> View view m (Radio a) setRadioActive v n = View $ do st <- get put st{needForm= HasElems } let env = mfEnv st mn <- getParam1 n env let str = if typeOf v == typeOf(undefined :: String) then unsafeCoerce v else show v return $ FormElm (finput n "radio" str ( isValidated mn && v== fromValidated mn) (Just "this.form.submit()")) (fmap Radio $ valToMaybe mn) -- | Implement a radio button -- the parameter is the name of the radio group setRadio :: (FormInput view, MonadIO m, Read a, Typeable a, Eq a, Show a) => a -> String -> View view m (Radio a) setRadio v n= View $ do st <- get put st{needForm= HasElems} let env = mfEnv st mn <- getParam1 n env let str = if typeOf v == typeOf(undefined :: String) then unsafeCoerce v else show v return $ FormElm (finput n "radio" str ( isValidated mn && v== fromValidated mn) Nothing) (fmap Radio $ valToMaybe mn) -- | encloses a set of Radio boxes. Return the option selected getRadio :: (Monad m, Functor m, FormInput view) => [String -> View view m (Radio a)] -> View view m a getRadio rs= do id <- genNewId Radio r <- firstOf $ map (\r -> r id) rs return r data CheckBoxes = CheckBoxes [String] instance Monoid CheckBoxes where mappend (CheckBoxes xs) (CheckBoxes ys)= CheckBoxes $ xs ++ ys mempty= CheckBoxes [] --instance (Monad m, Functor m) => Monoid (View v m CheckBoxes) where -- mappend x y= mappend <$> x <*> y -- mempty= return (CheckBoxes []) -- | Display a text box and return the value entered if it is readable( Otherwise, fail the validation) setCheckBox :: (FormInput view, MonadIO m) => Bool -> String -> View view m CheckBoxes setCheckBox checked v= View $ do n <- genNewId st <- get put st{needForm= HasElems} let env = mfEnv st strs= map snd $ filter ((==) n . fst) env mn= if null strs then Nothing else Just $ head strs val = inSync st let ret= case val of -- !> show val of True -> Just $ CheckBoxes strs -- !> show strs False -> Nothing return $ FormElm ( finput n "checkbox" v ( checked || (isJust mn && v== fromJust mn)) Nothing) ret -- | Read the checkboxes dynamically created by JavaScript within the view parameter -- see for example `selectAutocomplete` in "MFlow.Forms.Widgets" genCheckBoxes :: (Monad m, FormInput view) => view -> View view m CheckBoxes genCheckBoxes v= View $ do n <- genNewId st <- get put st{needForm= HasElems} let env = mfEnv st strs= map snd $ filter ((==) n . fst) env mn= if null strs then Nothing else Just $ head strs val <- gets inSync let ret= case val of True -> Just $ CheckBoxes strs False -> Nothing return $ FormElm (ftag "span" v `attrs`[("id",n)]) ret whidden :: (Monad m, FormInput v,Read a, Show a, Typeable a) => a -> View v m a whidden x= View $ do n <- genNewId env <- gets mfEnv let showx= case cast x of Just x' -> x' Nothing -> show x r <- getParam1 n env return . FormElm (finput n "hidden" showx False Nothing) $ valToMaybe r getCheckBoxes :: (FormInput view, Monad m)=> View view m CheckBoxes -> View view m [String] getCheckBoxes boxes = View $ do n <- genNewId st <- get let env = mfEnv st let form= finput n "hidden" "" False Nothing mr <- getParam1 n env let env = mfEnv st modify $ \st -> st{needForm= HasElems} FormElm form2 mr2 <- runView boxes return $ FormElm (form <> form2) $ case (mr `asTypeOf` Validated ("" :: String),mr2) of (NoParam,_) -> Nothing (Validated _,Nothing) -> Just [] (Validated _, Just (CheckBoxes rs)) -> Just rs getTextBox :: (FormInput view, Monad m, Typeable a, Show a, Read a) => Maybe a -> View view m a getTextBox ms = getParam Nothing "text" ms getParam :: (FormInput view, Monad m, Typeable a, Show a, Read a) => Maybe String -> String -> Maybe a -> View view m a getParam look type1 mvalue = View $ do tolook <- case look of Nothing -> genNewId Just n -> return n let nvalue x = case x of Nothing -> "" Just v -> case cast v of Just v' -> v' Nothing -> show v st <- get let env = mfEnv st put st{needForm= HasElems} r <- getParam1 tolook env case r of Validated x -> return $ FormElm (finput tolook type1 (nvalue $ Just x) False Nothing) $ Just x NotValidated s err -> return $ FormElm (finput tolook type1 s False Nothing <> err) $ Nothing NoParam -> return $ FormElm (finput tolook type1 (nvalue mvalue) False Nothing) $ Nothing --getCurrentName :: MonadState (MFlowState view) m => m String --getCurrentName= do -- st <- get -- let parm = mfSequence st -- return $ "p"++show parm -- | Display a multiline text box and return its content getMultilineText :: (FormInput view , Monad m) => T.Text -> View view m T.Text getMultilineText nvalue = View $ do tolook <- genNewId env <- gets mfEnv r <- getParam1 tolook env case r of Validated x -> return $ FormElm (ftextarea tolook x) $ Just x NotValidated s err -> return $ FormElm (ftextarea tolook (T.pack s)) Nothing NoParam -> return $ FormElm (ftextarea tolook nvalue) Nothing --instance (MonadIO m, Functor m, FormInput view) => FormLet Bool m view where -- digest mv = getBool b "True" "False" -- where -- b= case mv of -- Nothing -> Nothing -- Just bool -> Just $ case bool of -- True -> "True" -- False -> "False" -- | Display a dropdown box with the two values (second (true) and third parameter(false)) -- . With the value of the first parameter selected. getBool :: (FormInput view, Monad m, Functor m) => Bool -> String -> String -> View view m Bool getBool mv truestr falsestr= do r <- getSelect $ setOption truestr (fromStr truestr) <! (if mv then [("selected","true")] else []) <|> setOption falsestr(fromStr falsestr) <! if not mv then [("selected","true")] else [] if r == truestr then return True else return False -- | Display a dropdown box with the options in the first parameter is optionally selected -- . It returns the selected option. getSelect :: (FormInput view, Monad m,Typeable a, Read a) => View view m (MFOption a) -> View view m a getSelect opts = View $ do tolook <- genNewId st <- get let env = mfEnv st put st{needForm= HasElems} r <- getParam1 tolook env setSessionData $ fmap MFOption $ valToMaybe r FormElm form mr <- (runView opts) return $ FormElm (fselect tolook form) $ valToMaybe r newtype MFOption a= MFOption a deriving Typeable instance (FormInput view,Monad m, Functor m) => Monoid (View view m (MFOption a)) where mappend = (<|>) mempty = Control.Applicative.empty -- | Set the option for getSelect. Options are concatenated with `<|>` setOption :: (Monad m, Show a, Eq a, Typeable a, FormInput view) => a -> view -> View view m (MFOption a) setOption n v = do mo <- getSessionData case mo of Nothing -> setOption1 n v False Just Nothing -> setOption1 n v False Just (Just (MFOption o)) -> setOption1 n v $ n == o -- | Set the selected option for getSelect. Options are concatenated with `<|>` setSelectedOption :: (Monad m, Show a, Eq a, Typeable a, FormInput view) => a -> view -> View view m (MFOption a) setSelectedOption n v= do mo <- getSessionData case mo of Nothing -> setOption1 n v True Just Nothing -> setOption1 n v True Just (Just o) -> setOption1 n v $ n == o setOption1 :: (FormInput view, Monad m, Typeable a, Eq a, Show a) => a -> view -> Bool -> View view m (MFOption a) setOption1 nam val check= View $ do st <- get let env = mfEnv st put st{needForm= HasElems} let n = if typeOf nam == typeOf(undefined :: String) then unsafeCoerce nam else show nam return . FormElm (foption n val check) . Just $ MFOption nam -- | upload a file to a temporary file in the server -- -- The user can move, rename it etc. fileUpload :: (FormInput view, Monad m,Functor m) => View view m (String ,String ,String ) -- ^ ( original file, file type, temporal uploaded) fileUpload= getParam Nothing "file" Nothing <** modify ( \st -> st{mfFileUpload = True}) -- | Enclose Widgets within some formatting. -- @view@ is intended to be instantiated to a particular format -- -- NOTE: It has a infix priority : @infixr 5@ less than the one of @++>@ and @<++@ of the operators, so use parentheses when appropriate, -- unless the we want to enclose all the widgets in the right side. -- Most of the type errors in the DSL are due to the low priority of this operator. -- -- This is a widget, which is a table with some links. it returns an Int -- -- > import MFlow.Forms.Blaze.Html -- > -- > tableLinks :: View Html Int -- > table ! At.style "border:1;width:20%;margin-left:auto;margin-right:auto" -- > <<< caption << text "choose an item" -- > ++> thead << tr << ( th << b << text "item" <> th << b << text "times chosen") -- > ++> (tbody -- > <<< tr ! rowspan "2" << td << linkHome -- > ++> (tr <<< td <<< wlink IPhone (b << text "iphone") <++ td << ( b << text (fromString $ show ( cart V.! 0))) -- > <|> tr <<< td <<< wlink IPod (b << text "ipad") <++ td << ( b << text (fromString $ show ( cart V.! 1))) -- > <|> tr <<< td <<< wlink IPad (b << text "ipod") <++ td << ( b << text (fromString $ show ( cart V.! 2)))) -- > ) (<<<) :: (Monad m, Monoid view) => (view ->view) -> View view m a -> View view m a (<<<) v form= View $ do FormElm f mx <- runView form return $ FormElm (v f) mx infixr 5 <<< -- | Append formatting code to a widget -- -- @ getString "hi" '<++' H1 '<<' "hi there"@ -- -- It has a infix priority: @infixr 6@ higher than '<<<' and most other operators. (<++) :: (Monad m, Monoid v) => View v m a -> v -> View v m a (<++) form v= View $ do FormElm f mx <- runView form return $ FormElm ( f <> v) mx infixr 6 ++> infixr 6 <++ -- | Prepend formatting code to a widget -- -- @bold '<<' "enter name" '++>' 'getString' 'Nothing' @ -- -- It has a infix priority: @infixr 6@ higher than '<<<' and most other operators (++>) :: (Monad m, Monoid view) => view -> View view m a -> View view m a html ++> w = -- (html <>) <<< digest View $ do FormElm f mx <- runView w return $ FormElm (html <> f) mx -- | Add attributes to the topmost tag of a widget -- -- It has a fixity @infix 8@ infixl 8 <! widget <! attribs= View $ do FormElm fs mx <- runView widget return $ FormElm (fs `attrs` attribs) mx -- (head fs `attrs` attribs:tail fs) mx -- case fs of -- [hfs] -> return $ FormElm [hfs `attrs` attribs] mx -- _ -> error $ "operator <! : malformed widget: "++ concatMap (unpack. toByteString) fs -- | Is an example of login\/register validation form needed by 'userWidget'. In this case -- the form field appears in a single line. it shows, in sequence, entries for the username, -- password, a button for logging, a entry to repeat password necessary for registering -- and a button for registering. -- The user can build its own user login\/validation forms by modifying this example -- -- @ userFormLine= -- (User \<\$\> getString (Just \"enter user\") \<\*\> getPassword \<\+\> submitButton \"login\") -- \<\+\> fromStr \" password again\" \+\> getPassword \<\* submitButton \"register\" -- @ userFormLine :: (FormInput view, Functor m, Monad m) => View view m (Maybe (UserStr,PasswdStr), Maybe PasswdStr) userFormLine= ((,) <$> getString (Just "enter user") <! [("size","5")] <*> getPassword <! [("size","5")] <** submitButton "login") <+> (fromStr " password again" ++> getPassword <! [("size","5")] <** submitButton "register") -- | Example of user\/password form (no validation) to be used with 'userWidget' userLogin :: (FormInput view, Functor m, Monad m) => View view m (Maybe (UserStr,PasswdStr), Maybe String) userLogin= ((,) <$> fromStr "Enter User: " ++> getString Nothing <! [("size","4")] <*> fromStr " Enter Pass: " ++> getPassword <! [("size","4")] <** submitButton "login") <+> (noWidget <* noWidget) -- | Empty widget that does not validate. May be used as \"empty boxes\" inside larger widgets. -- -- It returns a non valid value. noWidget :: (FormInput view, Monad m, Functor m) => View view m a noWidget= Control.Applicative.empty -- | a synonym of noWidget that can be used in a monadic expression in the View monad does not continue stop :: (FormInput view, Monad m, Functor m) => View view m a stop= Control.Applicative.empty -- | Render a Show-able value and return it wrender :: (Monad m, Functor m, Show a, FormInput view) => a -> View view m a wrender x = (fromStr $ show x) ++> return x -- | Render raw view formatting. It is useful for displaying information. wraw :: Monad m => view -> View view m () wraw x= View . return . FormElm x $ Just () -- To display some rendering and return a no valid value notValid :: Monad m => view -> View view m a notValid x= View . return $ FormElm x Nothing -- | If the user is logged or is anonymous isLogged :: MonadState (MFlowState v) m => m Bool isLogged= do rus <- return . tuser =<< gets mfToken return . not $ rus == anonymous -- | return the result if going forward -- -- If the process is backtracking, it does not validate, -- in order to continue the backtracking returnIfForward :: (Monad m, FormInput view,Functor m) => b -> View view m b returnIfForward x = do back <- goingBack if back then noWidget else return x -- | forces backtracking if the widget validates, because a previous page handle this widget response -- . This is useful for recurrent cached widgets or `absLink`s that are present in multiple pages. For example -- in the case of menus or common options. The active elements of this widget must be cached with no timeout. retry :: Monad m => View v m a -> View v m () retry w = View $ do FormElm v mx <- runView w when (isJust mx) $ modify $ \st -> st{inSync = False} return $ FormElm v Nothing -- | It creates a widget for user login\/registering. If a user name is specified -- in the first parameter, it is forced to login\/password as this specific user. -- If this user was already logged, the widget return the user without asking. -- If the user press the register button, the new user-password is registered and the -- user logged. userWidget :: ( MonadIO m, Functor m , FormInput view) => Maybe String -> View view m (Maybe (UserStr,PasswdStr), Maybe String) -> View view m String userWidget muser formuser = userWidget' muser formuser login1 -- | Uses 4 different keys to encrypt the 4 parts of a MFlow cookie. paranoidUserWidget muser formuser = userWidget' muser formuser paranoidLogin1 -- | Uses a single key to encrypt the MFlow cookie. encryptedUserWidget muser formuser = userWidget' muser formuser encryptedLogin1 userWidget' muser formuser login1Func = do user <- getCurrentUser if muser== Just user || isNothing muser && user/= anonymous then returnIfForward user else formuser `validate` val muser `wcallback` login1Func where val _ (Nothing,_) = return . Just $ fromStr "Please fill in the user/passwd to login, or user/passwd/passwd to register" val mu (Just us, Nothing)= if isNothing mu || isJust mu && fromJust mu == fst us then userValidate us else return . Just $ fromStr "This user has no permissions for this task" val mu (Just us, Just p)= if isNothing mu || isJust mu && fromJust mu == fst us then if Data.List.length p > 0 && snd us== p then return Nothing else return . Just $ fromStr "The passwords do not match" else return . Just $ fromStr "wrong user for the operation" -- val _ _ = return . Just $ fromStr "Please fill in the fields for login or register" login1 :: (MonadIO m, MonadState (MFlowState view) m) => (Maybe (UserStr, PasswdStr), Maybe t) -> m UserStr login1 uname = login1' uname login paranoidLogin1 uname = login1' uname paranoidLogin encryptedLogin1 uname = login1' uname encryptedLogin login1' (Just (uname,_), Nothing) loginFunc= loginFunc uname >> return uname login1' (Just us@(u,p), Just _) loginFunc= do -- register button pressed userRegister u p loginFunc u return u -- | change the user -- -- It is supposed that the user has been validated login uname = login' uname setCookie paranoidLogin uname = login' uname setParanoidCookie encryptedLogin uname = login' uname setEncryptedCookie login' :: (Num a1, S.IsString a, MonadIO m, MonadState (MFlowState view) m) => String -> (String -> String -> a -> Maybe a1 -> m ()) -> m () login' uname setCookieFunc = do back <- goingBack if back then return () else do st <- get let t = mfToken st u = tuser t when (u /= uname) $ do let t'= t{tuser= uname} -- moveState (twfname t) t t' put st{mfToken= t'} liftIO $ deleteTokenInList t liftIO $ addTokenToList t' setCookieFunc cookieuser uname "/" (Just $ 365*24*60*60) logout = logout' setCookie paranoidLogout = logout' setParanoidCookie encryptedLogout = logout' setEncryptedCookie -- | logout. The user is reset to the `anonymous` user logout' :: (Num a1,S.IsString a, MonadIO m, MonadState (MFlowState view) m) => (String -> [Char] -> a -> Maybe a1 -> m ()) -> m () logout' setCookieFunc = do public back <- goingBack if back then return () else do st <- get let t = mfToken st t'= t{tuser= anonymous} when (tuser t /= anonymous) $ do -- moveState (twfname t) t t' put st{mfToken= t'} -- liftIO $ deleteTokenInList t liftIO $ addTokenToList t' setCookieFunc cookieuser anonymous "/" (Just $ -1000) -- | If not logged, perform login. otherwise return the user -- -- @getUserSimple= getUser Nothing userFormLine@ getUserSimple :: ( FormInput view, Typeable view) => FlowM view IO String getUserSimple= getUser Nothing userFormLine -- | Very basic user authentication. The user is stored in a cookie. -- it looks for the cookie. If no cookie, it ask to the user for a `userRegister`ed -- user-password combination. -- The user-password combination is only asked if the user has not logged already -- otherwise, the stored username is returned. -- -- @getUser mu form= ask $ userWidget mu form@ getUser :: ( FormInput view, Typeable view) => Maybe String -> View view IO (Maybe (UserStr,PasswdStr), Maybe String) -> FlowM view IO String getUser mu form= ask $ userWidget mu form -- | Authentication against `userRegister`ed users. -- to be used with `validate` userValidate :: (FormInput view,MonadIO m) => (UserStr,PasswdStr) -> m (Maybe view) userValidate (u,p) = liftIO $ do Auth _ val <- getAuthMethod val u p >>= return . fmap fromStr -- | for compatibility with the same procedure in 'MFLow.Forms.Test.askt'. -- This is the non testing version -- -- > askt v w= ask w -- -- hide one or the other askt :: FormInput v => (Int -> a) -> View v IO a -> FlowM v IO a askt v w = ask w -- | It is the way to interact with the user. -- It takes a widget and return the input result. If the widget is not validated (return @Nothing@) -- , the page is presented again -- -- If the environment or the URL has the parameters being looked at, maybe as a result of a previous interaction, -- it will not ask to the user and return the result. -- To force asking in any case, add an `clearEnv` statement before. -- It also handles ajax requests -- -- 'ask' also synchronizes the execution of the flow with the user page navigation by -- * Backtracking (invoking previous 'ask' statement in the flow) when detecting mismatches between -- get and post parameters and what is expected by the widgets -- until a total or partial match is found. -- -- * Advancing in the flow by matching a single requests with one or more successive ask statements -- -- Backtracking and advancing can occur in a single request, so the flow in any state can reach any -- other state in the flow if the request has the required parameters. ask :: (FormInput view) => View view IO a -> FlowM view IO a ask w = do resetCachePolicy st1 <- get >>= \s -> return s{mfSequence= let seq= mfSequence s in if seq ==inRecovery then 0 else seq ,mfHttpHeaders =[],mfAutorefresh= False } if not . null $ mfTrace st1 then fail "" else do -- AJAX let env= mfEnv st1 mv1= lookup "ajax" env majax1= mfAjax st1 case (majax1,mv1,M.lookup (fromJust mv1)(fromJust majax1), lookup "val" env) of (Just ajaxl,Just v1,Just f, Just v2) -> do FlowM . lift $ (unsafeCoerce f) v2 FlowM $ lift nextMessage ask w -- END AJAX _ -> do -- mfPagePath : contains the REST path of the page. -- it is set for each page -- if it does not exist then it comes from a state recovery, backtrack (to fill-in the field) let pagepath = mfPagePath st1 if null pagepath then fail "" -- !> "null pagepath" -- if exist and it is not prefix of the current path being navigated to, backtrack else if not $ pagepath `isPrefixOf` mfPath st1 then fail "" -- !> ("pagepath fail with "++ show (mfPath st1)) else do let st= st1{needForm= NoElems, inSync= False, linkMatched= False ,mfRequirements= [] ,mfInstalledScripts= if newAsk st1 then [] else mfInstalledScripts st1} put st FormElm forms mx <- FlowM . lift $ runView w -- !> "eval" setCachePolicy st' <- get if notSyncInAction st' then put st'{notSyncInAction=False}>> ask w else case mx of Just x -> do put st'{newAsk= True, mfEnv=[]} breturn x -- !> ("BRETURN "++ show (mfPagePath st') ) Nothing -> if not (inSync st') && not (newAsk st') -- !> ("insync="++show (inSync st')) -- !> ("newask="++show (newAsk st')) then fail "" -- !> "FAIL sync" else if mfAutorefresh st' then do resetState st st' -- !> ("EN AUTOREFRESH" ++ show [ mfPagePath st,mfPath st,mfPagePath st']) -- modify $ \st -> st{mfPagePath=mfPagePath st'} !> "REPEAT" FlowM $ lift nextMessage ask w else do reqs <- FlowM $ lift installAllRequirements -- !> "REPEAT" st' <- get -- !> (B.unpack $ toByteString reqs) let header= mfHeader st' t= mfToken st' cont <- case (needForm st') of HasElems -> do frm <- formPrefix st' forms False -- !> ("formPrefix="++ show(mfPagePath st')) return . header $ reqs <> frm _ -> return . header $ reqs <> forms let HttpData ctype c s= toHttpData cont liftIO . sendFlush t $ HttpData (ctype ++ mfHttpHeaders st') (mfCookies st' ++ c) s resetState st st' FlowM $ lift nextMessage -- !> "NEXTMESSAGE" ask w where resetState st st'= put st{mfCookies=[] -- if autorefresh, keep the list of installed scripts ,mfInstalledScripts= if mfAutorefresh st' then mfInstalledScripts st' else [] ,newAsk= False ,mfToken= mfToken st' ,mfPageFlow= mfPageFlow st' ,mfAjax= mfAjax st' ,mfData= mfData st' ,mfSomeNotValidates= False ,mfPagePath= mfPagePath st'} -- | A synonym of ask. -- -- Maybe more appropriate for pages with long interactions with the user -- while the result has little importance. page :: (FormInput view) => View view IO a -> FlowM view IO a page= ask nextMessage :: MonadIO m => WState view m () nextMessage = do st <- get let t= mfToken st t1= mfkillTime st t2= mfSessionTime st msg <- liftIO ( receiveReqTimeout t1 t2 t) let req= getParams msg env= updateParams inPageFlow (mfEnv st) req -- !> ("PAGEFLOW="++ show inPageFlow) npath= pwfPath msg path= mfPath st inPageFlow= mfPagePath st `isPrefixOf` npath put st{ mfPath= npath , mfPageFlow= inPageFlow , mfEnv= env } where -- comparePaths _ n [] xs= n -- comparePaths o n _ [] = o -- comparePaths o n (v:path) (v': npath) | v== v' = comparePaths o (n+1)path npath -- | otherwise= n updateParams :: Bool -> Params -> Params -> Params updateParams False _ req= req updateParams True env req= let old= takeWhile isparam env (new,rest)= Data.List.span isparam req parms= new++ old++ rest -- let params= takeWhile isparam env -- fs= fst $ head req -- parms= (case findIndex (\p -> fst p == fs) params of -- Nothing -> params -- Just i -> Data.List.take i params) -- ++ req in parms -- !> "IN PAGE FLOW" !> ("parms=" ++ show parms ) -- !> ("env=" ++ show env) -- !> ("req=" ++ show req) isparam ('p': r:_,_)= isNumber r isparam ('c': r:_,_)= isNumber r isparam _= False -- | Creates a stateless flow (see `stateless`) whose behavior is defined as a widget. It is a -- higher level form of the latter wstateless :: (Typeable view, FormInput view) => View view IO () -> Flow wstateless w = runFlow . transientNav . ask $ w **> (stop `asTypeOf` w) -- | Wrap a widget with form element within a form-action element. -- Usually this is not necessary since this wrapping is done automatically by the @View@ monad, unless -- there are more than one form in the page. wform :: (Monad m, FormInput view) => View view m b -> View view m b wform= insertForm --wform x = View $ do -- FormElm form mr <- (runView $ x ) -- st <- get -- form1 <- formPrefix st form True -- put st{needForm=HasForm} -- return $ FormElm form1 mr resetButton :: (FormInput view, Monad m) => String -> View view m () resetButton label= View $ return $ FormElm (finput "reset" "reset" label False Nothing) $ Just () submitButton :: (FormInput view, Monad m) => String -> View view m String submitButton label= getParam Nothing "submit" $ Just label newtype AjaxSessionId= AjaxSessionId String deriving Typeable -- | Install the server code and return the client code for an AJAX interaction. -- It is very lightweight, It does no t need jQuery. -- -- This example increases the value of a text box each time the box is clicked -- -- > ask $ do -- > let elemval= "document.getElementById('text1').value" -- > ajaxc <- ajax $ \n -> return $ elemval <> "='" <> B.pack(show(read n +1)) <> "'" -- > b << text "click the box" -- > ++> getInt (Just 0) <! [("id","text1"),("onclick", ajaxc elemval)] ajax :: (MonadIO m, FormInput v) => (String -> View v m ByteString) -- ^ user defined procedure, executed in the server.Receives the value of the JavaScript expression and must return another JavaScript expression that will be executed in the web browser -> View v m (String -> String) -- ^ returns a function that accept a JavaScript expression and return a JavaScript event handler expression that invokes the ajax server procedure ajax f = do requires[JScript ajaxScript] t <- gets mfToken id <- genNewId installServerControl id $ \x-> do setSessionData $ AjaxSessionId id r <- f x liftIO $ sendFlush t (HttpData [("Content-Type", "text/plain")][] r ) return () installServerControl :: (FormInput v,MonadIO m) => String -> (String -> View v m ()) -> View v m (String -> String) installServerControl id f= do t <- gets mfToken st <- get let ajxl = fromMaybe M.empty $ mfAjax st let ajxl'= M.insert id (unsafeCoerce f ) ajxl put st{mfAjax=Just ajxl'} return $ \param -> "doServer("++"'" ++ twfname t ++"','"++id++"',"++ param++")" -- | Send the JavaScript expression, generated by the procedure parameter as a ByteString, execute it in the browser and the result is returned back -- -- The @ajaxSend@ invocation must be inside a ajax procedure or else a /No ajax session set/ error will be produced ajaxSend :: (Read a,Monoid v, MonadIO m) => View v m ByteString -> View v m a ajaxSend cmd= View $ do AjaxSessionId id <- getSessionData `onNothing` error "no AjaxSessionId set" env <- getEnv t <- getToken case (lookup "ajax" $ env, lookup "val" env) of (Nothing,_) -> return $ FormElm mempty Nothing (Just id, Just _) -> do FormElm __ (Just str) <- runView cmd liftIO $ sendFlush t $ HttpData [("Content-Type", "text/plain")][] $ str <> readEvalLoop t id "''" nextMessage env <- getEnv case (lookup "ajax" $ env,lookup "val" env) of (Nothing,_) -> return $ FormElm mempty Nothing (Just id, Just v2) -> do return $ FormElm mempty . Just $ read v2 where readEvalLoop t id v = "doServer('"<> fromString (twfname t)<>"','"<> fromString id<>"',"<>v<>");" :: ByteString -- | Like @ajaxSend@ but the result is ignored ajaxSend_ :: (MonadIO m, Monoid v) => View v m ByteString -> View v m () ajaxSend_ = ajaxSend wlabel :: (Monad m, FormInput view) => view -> View view m a -> View view m a wlabel str w = do id <- genNewId ftag "label" str `attrs` [("for",id)] ++> w <! [("id",id)] -- | Creates a link to a the next step within the flow. -- A link can be composed with other widget elements. -- It can not be broken by its own definition. -- It points to the page that created it. wlink :: (Typeable a, Show a, MonadIO m, FormInput view) => a -> view -> View view m a wlink x v= View $ do verb <- getWFName st <- get let name = --mfPrefix st ++ (map toLower $ if typeOf x== typeOf(undefined :: String) then unsafeCoerce x else show x) lpath = mfPath st newPath= mfPagePath st ++ [name] r <- if linkMatched st then return Nothing -- only a link match per page or monadic sentence in page else case newPath `isPrefixOf` lpath of True -> do modify $ \s -> s{inSync= True ,linkMatched= True ,mfPagePath= newPath } return $ Just x -- !> (name ++ "<-" ++ "link path=" ++show newPath) False -> return Nothing -- !> ( "NOT MATCHED "++name++" link path= "++show newPath -- ++ "path="++ show lpath) let path= concat ['/':v| v <- newPath ] return $ FormElm (flink path v) r -- | Creates an absolute link. While a `wlink` path depend on the page where it is located and -- ever points to the code of the page that had it inserted, an absLink point to the first page -- in the flow that inserted it. It is useful for creating a backtracking point in combination with `retry` -- -- > page $ absLink "here" << p << "here link" -- > page $ p << "second page" ++> wlink () << p << "click here" -- > page $ p << "third page" ++> retry (absLink "here" << p << "will go back") -- > page $ p << "fourth page" ++> wlink () << p << "will not reach here" -- -- After navigating to the third page, when -- clicking in the link, will backtrack to the first, and will validate the first link as if the click -- where done in the first page. Then the second page would be displayed. -- -- In monadic widgets, it also backtrack to the statement where the absLink is located without the -- need of retry: -- -- > page $ do -- > absLink "here" << p << "here link" -- > p << "second statement" ++> wlink () << p << "click here" -- > p << "third statement" ++> (absLink "here" << p << "will present the first statement alone") -- > p << "fourth statement" ++> wlink () << p << "will not reach here" --absLink x = wcached (show x) 0 . wlink x absLink x v= View $ do verb <- getWFName st <- get let name = -- mfPrefix st (map toLower $ if typeOf x== typeOf(undefined :: String) then unsafeCoerce x else show x) lpath = mfPath st newPath= mfPagePath st ++ [name] r <- if linkMatched st then return Nothing -- only a link match per page or monadic sentence in page else case newPath `isPrefixOf` lpath of True -> do modify $ \s -> s{inSync= True ,linkMatched= True ,mfPagePath= newPath } return $ Just x -- !> (name ++ "<- abs" ++ "lpath=" ++show lpath) False -> return Nothing -- !> ( "NOT MATCHED "++name++" LP= "++show lpath) path <- liftIO $ cachedByKey (show x) 0 . return $ currentPath st ++ ('/':name) return $ FormElm (flink path v) r -- !> name -- | When some user interface return some response to the server, but it is not produced by -- a form or a link, but for example by an script, @returning@ convert this code into a -- widget. -- -- At runtime the parameter is read from the environment and validated. -- -- . The parameter is the visualization code, that accept a serialization function that generate -- the server invocation string, used by the visualization to return the value by means -- of an script, usually. returning :: (Typeable a, Read a, Show a,Monad m, FormInput view) => ((a->String) ->view) -> View view m a returning expr=View $ do verb <- getWFName name <- genNewId env <- gets mfEnv let string x= let showx= case cast x of Just x' -> x' _ -> show x in (verb ++ "?" ++ name ++ "=" ++ showx) toSend= expr string r <- getParam1 name env return $ FormElm toSend $ valToMaybe r --instance (Widget a b m view, Monoid view) => Widget [a] b m view where -- widget xs = View $ do -- forms <- mapM(\x -> (runView $ widget x )) xs -- let vs = concatMap (\(FormElm v _) -> v) forms -- res = filter isJust $ map (\(FormElm _ r) -> r) forms -- res1= if null res then Nothing else head res -- return $ FormElm [mconcat vs] res1 -- | Concat a list of widgets of the same type, return a the first validated result firstOf :: (FormInput view, Monad m, Functor m)=> [View view m a] -> View view m a firstOf xs= foldl' (<|>) noWidget xs -- View $ do -- forms <- mapM runView xs -- let vs = concatMap (\(FormElm v _) -> [mconcat v]) forms -- res = filter isJust $ map (\(FormElm _ r) -> r) forms -- res1= if null res then Nothing else head res -- return $ FormElm vs res1 -- | from a list of widgets, it return the validated ones. manyOf :: (FormInput view, MonadIO m, Functor m)=> [View view m a] -> View view m [a] manyOf xs= whidden () *> (View $ do forms <- mapM runView xs let vs = mconcat $ map (\(FormElm v _) -> v) forms res1= catMaybes $ map (\(FormElm _ r) -> r) forms nval <- gets mfSomeNotValidates return . FormElm vs $ if nval then Nothing else Just res1) -- | like manyOf, but does not validate if one or more of the widgets does not validate allOf xs= manyOf xs `validate` \rs -> if length rs== length xs then return Nothing else return $ Just "Not all of the required data completed" (>:>) :: (Monad m, Monoid v) => View v m a -> View v m [a] -> View v m [a] (>:>) w ws = View $ do FormElm fs mxs <- runView $ ws FormElm f1 mx <- runView w return $ FormElm (f1 <> fs) $ case( mx,mxs) of (Just x, Just xs) -> Just $ x:xs (Nothing, mxs) -> mxs (Just x, _) -> Just [x] -- | Intersperse a widget in a list of widgets. the results is a 2-tuple of both types. -- -- it has a infix priority @infixr 5@ (|*>) :: (MonadIO m, Functor m, FormInput view) => View view m r -> [View view m r'] -> View view m (Maybe r,Maybe r') (|*>) x xs= View $ do fs <- mapM runView xs FormElm fx rx <- runView x let (fxs, rxss) = unzip $ map (\(FormElm v r) -> (v,r)) fs rs= filter isJust rxss rxs= if null rs then Nothing else head rs return $ FormElm (fx <> mconcat (intersperse fx fxs) <> fx) $ case (rx,rxs) of (Nothing, Nothing) -> Nothing other -> Just other infixr 5 |*> -- | Put a widget before and after other. Useful for navigation links in a page that appears at toAdd -- and at the bottom of a page. -- It has a low infix priority: @infixr 1@ (|+|) :: (Functor m, FormInput view, MonadIO m) => View view m r -> View view m r' -> View view m (Maybe r, Maybe r') (|+|) w w'= w |*> [w'] infixr 1 |+| -- | Flatten a binary tree of tuples of Maybe results produced by the \<+> operator -- into a single tuple with the same elements in the same order. -- This is useful for easing matching. For example: -- -- @ res \<- ask $ wlink1 \<+> wlink2 wform \<+> wlink3 \<+> wlink4@ -- -- @res@ has type: -- -- @Maybe (Maybe (Maybe (Maybe (Maybe a,Maybe b),Maybe c),Maybe d),Maybe e)@ -- -- but @flatten res@ has type: -- -- @ (Maybe a, Maybe b, Maybe c, Maybe d, Maybe e)@ flatten :: Flatten (Maybe tree) list => tree -> list flatten res= doflat $ Just res class Flatten tree list where doflat :: tree -> list type Tuple2 a b= Maybe (Maybe a, Maybe b) type Tuple3 a b c= Maybe ( (Tuple2 a b), Maybe c) type Tuple4 a b c d= Maybe ( (Tuple3 a b c), Maybe d) type Tuple5 a b c d e= Maybe ( (Tuple4 a b c d), Maybe e) type Tuple6 a b c d e f= Maybe ( (Tuple5 a b c d e), Maybe f) instance Flatten (Tuple2 a b) (Maybe a, Maybe b) where doflat (Just(ma,mb))= (ma,mb) doflat Nothing= (Nothing,Nothing) instance Flatten (Tuple3 a b c) (Maybe a, Maybe b,Maybe c) where doflat (Just(mx,mc))= let(ma,mb)= doflat mx in (ma,mb,mc) doflat Nothing= (Nothing,Nothing,Nothing) instance Flatten (Tuple4 a b c d) (Maybe a, Maybe b,Maybe c,Maybe d) where doflat (Just(mx,mc))= let(ma,mb,md)= doflat mx in (ma,mb,md,mc) doflat Nothing= (Nothing,Nothing,Nothing,Nothing) instance Flatten (Tuple5 a b c d e) (Maybe a, Maybe b,Maybe c,Maybe d,Maybe e) where doflat (Just(mx,mc))= let(ma,mb,md,me)= doflat mx in (ma,mb,md,me,mc) doflat Nothing= (Nothing,Nothing,Nothing,Nothing,Nothing) instance Flatten (Tuple6 a b c d e f) (Maybe a, Maybe b,Maybe c,Maybe d,Maybe e,Maybe f) where doflat (Just(mx,mc))= let(ma,mb,md,me,mf)= doflat mx in (ma,mb,md,me,mf,mc) doflat Nothing= (Nothing,Nothing,Nothing,Nothing,Nothing,Nothing) --infixr 7 .<<. ---- | > (.<<.) w x = w $ toByteString x --(.<<.) :: (FormInput view) => (ByteString -> ByteString) -> view -> ByteString --(.<<.) w x = w ( toByteString x) -- ---- | > (.<+>.) x y = normalize x <+> normalize y --(.<+>.) -- :: (Monad m, FormInput v, FormInput v1) => -- View v m a -> View v1 m b -> View ByteString m (Maybe a, Maybe b) --(.<+>.) x y = normalize x <+> normalize y -- ---- | > (.|*>.) x y = normalize x |*> map normalize y --(.|*>.) -- :: (Functor m, MonadIO m, FormInput v, FormInput v1) => -- View v m r -- -> [View v1 m r'] -> View ByteString m (Maybe r, Maybe r') --(.|*>.) x y = normalize x |*> map normalize y -- ---- | > (.|+|.) x y = normalize x |+| normalize y --(.|+|.) -- :: (Functor m, MonadIO m, FormInput v, FormInput v1) => -- View v m r -> View v1 m r' -> View ByteString m (Maybe r, Maybe r') --(.|+|.) x y = normalize x |+| normalize y -- ---- | > (.**>.) x y = normalize x **> normalize y --(.**>.) -- :: (Monad m, Functor m, FormInput v, FormInput v1) => -- View v m a -> View v1 m b -> View ByteString m b --(.**>.) x y = normalize x **> normalize y -- ---- | > (.<**.) x y = normalize x <** normalize y --(.<**.) -- :: (Monad m, Functor m, FormInput v, FormInput v1) => -- View v m a -> View v1 m b -> View ByteString m a --(.<**.) x y = normalize x <** normalize y -- ---- | > (.<|>.) x y= normalize x <|> normalize y --(.<|>.) -- :: (Monad m, Functor m, FormInput v, FormInput v1) => -- View v m a -> View v1 m a -> View ByteString m a --(.<|>.) x y= normalize x <|> normalize y -- ---- | > (.<++.) x v= normalize x <++ toByteString v --(.<++.) :: (Monad m, FormInput v, FormInput v') => View v m a -> v' -> View ByteString m a --(.<++.) x v= normalize x <++ toByteString v -- ---- | > (.++>.) v x= toByteString v ++> normalize x --(.++>.) :: (Monad m, FormInput v, FormInput v') => v -> View v' m a -> View ByteString m a --(.++>.) v x= toByteString v ++> normalize x instance FormInput ByteString where toByteString= id toHttpData = HttpData [contentHtml ] [] ftag x= btag x [] inred = btag "b" [("style", "color:red")] finput n t v f c= btag "input" ([("type", t) ,("name", n),("value", v)] ++ if f then [("checked","true")] else [] ++ case c of Just s ->[( "onclick", s)]; _ -> [] ) "" ftextarea name text= btag "textarea" [("name", name)] $ fromChunks [encodeUtf8 text] fselect name options= btag "select" [("name", name)] options foption value content msel= btag "option" ([("value", value)] ++ selected msel) content where selected msel = if msel then [("selected","true")] else [] attrs = addAttrs formAction action method form = btag "form" [("action", action),("method", method)] form fromStr = fromString fromStrNoEncode= fromString flink v str = btag "a" [("href", v)] str ------ page Flows ---- -- | Prepares the state for a page flow. It add a prefix to every form element or link identifier for the formlets and also -- keep the state of the links clicked and form input entered within the widget. -- If the computation within the widget has branches @if@ @case@ etc, each branch must have its pageFlow with a distinct identifier. -- See <http://haskell-web.blogspot.com.es/2013/06/the-promising-land-of-monadic-formlets.html> pageFlow :: (Monad m, Functor m, FormInput view) => String -> View view m a -> View view m a pageFlow str widget=do s <- get if mfPageFlow s == False then do put s{mfPrefix= str ++ mfPrefix s ,mfSequence=0 ,mfPageFlow= True } -- !> ("PARENT pageflow. prefix="++ str) r<- widget <** (modify (\s' -> s'{mfSequence= mfSequence s ,mfPrefix= mfPrefix s })) modify (\s -> s{mfPageFlow=False} ) return r -- !> ("END PARENT pageflow. prefix="++ str)) else do put s{mfPrefix= str++ mfPrefix s,mfSequence=0} -- !> ("PARENT pageflow. prefix="++ str) -- !> ("CHILD pageflow. prefix="++ str) widget <** (modify (\s' -> s'{mfSequence= mfSequence s ,mfPrefix= mfPrefix s})) -- !> ("END CHILD pageflow. prefix="++ str)) -- !> ("END CHILD pageflow. prefix="++ str)) -- | send raw bytestring data to the client. usable for -- -- example -- -- > do -- setHttpHeader "Content-Type" "text//plain" -- maxAge 36000 -- rawSend longdata rawSend :: (FormInput v,MonadIO m, Functor m) => ByteString -> View v m () rawSend dat= do setCachePolicy st <- get tok <- getToken liftIO $ sendFlush tok $ HttpData ( mfHttpHeaders st) (mfCookies st) dat modify $ \st -> st{mfAutorefresh= True} stop
agocorona/MFlow
src/MFlow/Forms.hs
bsd-3-clause
64,421
33
31
16,998
12,931
6,766
6,165
-1
-1
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} module Github.Data.Definitions where import Data.Time import Data.Data import qualified Control.Exception as E import qualified Data.Map as M -- | Errors have been tagged according to their source, so you can more easily -- dispatch and handle them. data Error = HTTPConnectionError E.SomeException -- ^ A HTTP error occurred. The actual caught error is included. | ParseError String -- ^ An error in the parser itself. | JsonError String -- ^ The JSON is malformed or unexpected. | UserError String -- ^ Incorrect input. deriving Show -- | A date in the Github format, which is a special case of ISO-8601. newtype GithubDate = GithubDate { fromGithubDate :: UTCTime } deriving (Show, Data, Typeable, Eq, Ord) data Commit = Commit { commitSha :: String ,commitParents :: [Tree] ,commitUrl :: String ,commitGitCommit :: GitCommit ,commitCommitter :: Maybe GithubOwner ,commitAuthor :: Maybe GithubOwner ,commitFiles :: [File] ,commitStats :: Maybe Stats } deriving (Show, Data, Typeable, Eq, Ord) data Tree = Tree { treeSha :: String ,treeUrl :: String ,treeGitTrees :: [GitTree] } deriving (Show, Data, Typeable, Eq, Ord) data GitTree = GitTree { gitTreeType :: String ,gitTreeSha :: String -- Can be empty for submodule ,gitTreeUrl :: Maybe String ,gitTreeSize :: Maybe Int ,gitTreePath :: String ,gitTreeMode :: String } deriving (Show, Data, Typeable, Eq, Ord) data GitCommit = GitCommit { gitCommitMessage :: String ,gitCommitUrl :: String ,gitCommitCommitter :: GitUser ,gitCommitAuthor :: GitUser ,gitCommitTree :: Tree ,gitCommitSha :: Maybe String ,gitCommitParents :: [Tree] } deriving (Show, Data, Typeable, Eq, Ord) data GithubOwner = GithubUser { githubOwnerAvatarUrl :: String ,githubOwnerLogin :: String ,githubOwnerUrl :: String ,githubOwnerId :: Int ,githubOwnerGravatarId :: Maybe String } | GithubOrganization { githubOwnerAvatarUrl :: String ,githubOwnerLogin :: String ,githubOwnerUrl :: String ,githubOwnerId :: Int } deriving (Show, Data, Typeable, Eq, Ord) data GitUser = GitUser { gitUserName :: String ,gitUserEmail :: String ,gitUserDate :: GithubDate } deriving (Show, Data, Typeable, Eq, Ord) data File = File { fileBlobUrl :: String ,fileStatus :: String ,fileRawUrl :: String ,fileAdditions :: Int ,fileSha :: String ,fileChanges :: Int ,filePatch :: String ,fileFilename :: String ,fileDeletions :: Int } deriving (Show, Data, Typeable, Eq, Ord) data Stats = Stats { statsAdditions :: Int ,statsTotal :: Int ,statsDeletions :: Int } deriving (Show, Data, Typeable, Eq, Ord) data Comment = Comment { commentPosition :: Maybe Int ,commentLine :: Maybe Int ,commentBody :: String ,commentCommitId :: Maybe String ,commentUpdatedAt :: UTCTime ,commentHtmlUrl :: Maybe String ,commentUrl :: String ,commentCreatedAt :: Maybe UTCTime ,commentPath :: Maybe String ,commentUser :: GithubOwner ,commentId :: Int } deriving (Show, Data, Typeable, Eq, Ord) data NewComment = NewComment { newCommentBody :: String } deriving (Show, Data, Typeable, Eq, Ord) data EditComment = EditComment { editCommentBody :: String } deriving (Show, Data, Typeable, Eq, Ord) data Diff = Diff { diffStatus :: String ,diffBehindBy :: Int ,diffPatchUrl :: String ,diffUrl :: String ,diffBaseCommit :: Commit ,diffCommits :: [Commit] ,diffTotalCommits :: Int ,diffHtmlUrl :: String ,diffFiles :: [File] ,diffAheadBy :: Int ,diffDiffUrl :: String ,diffPermalinkUrl :: String } deriving (Show, Data, Typeable, Eq, Ord) data Gist = Gist { gistUser :: GithubOwner ,gistGitPushUrl :: String ,gistUrl :: String ,gistDescription :: Maybe String ,gistCreatedAt :: GithubDate ,gistPublic :: Bool ,gistComments :: Int ,gistUpdatedAt :: GithubDate ,gistHtmlUrl :: String ,gistId :: String ,gistFiles :: [GistFile] ,gistGitPullUrl :: String } deriving (Show, Data, Typeable, Eq, Ord) data GistFile = GistFile { gistFileType :: String ,gistFileRawUrl :: String ,gistFileSize :: Int ,gistFileLanguage :: Maybe String ,gistFileFilename :: String ,gistFileContent :: Maybe String } deriving (Show, Data, Typeable, Eq, Ord) data GistComment = GistComment { gistCommentUser :: GithubOwner ,gistCommentUrl :: String ,gistCommentCreatedAt :: GithubDate ,gistCommentBody :: String ,gistCommentUpdatedAt :: GithubDate ,gistCommentId :: Int } deriving (Show, Data, Typeable, Eq, Ord) data Blob = Blob { blobUrl :: String ,blobEncoding :: String ,blobContent :: String ,blobSha :: String ,blobSize :: Int } deriving (Show, Data, Typeable, Eq, Ord) data NewGitReference = NewGitReference { newGitReferenceRef :: String ,newGitReferenceSha :: String } deriving (Show, Data, Typeable, Eq, Ord) data GitReference = GitReference { gitReferenceObject :: GitObject ,gitReferenceUrl :: String ,gitReferenceRef :: String } deriving (Show, Data, Typeable, Eq, Ord) data GitObject = GitObject { gitObjectType :: String ,gitObjectSha :: String ,gitObjectUrl :: String } deriving (Show, Data, Typeable, Eq, Ord) data Issue = Issue { issueClosedAt :: Maybe GithubDate ,issueUpdatedAt :: GithubDate ,issueEventsUrl :: String ,issueHtmlUrl :: Maybe String ,issueClosedBy :: Maybe GithubOwner ,issueLabels :: [IssueLabel] ,issueNumber :: Int ,issueAssignee :: Maybe GithubOwner ,issueUser :: GithubOwner ,issueTitle :: String ,issuePullRequest :: Maybe PullRequestReference ,issueUrl :: String ,issueCreatedAt :: GithubDate ,issueBody :: Maybe String ,issueState :: String ,issueId :: Int ,issueComments :: Int ,issueMilestone :: Maybe Milestone } deriving (Show, Data, Typeable, Eq, Ord) data NewIssue = NewIssue { newIssueTitle :: String , newIssueBody :: Maybe String , newIssueAssignee :: Maybe String , newIssueMilestone :: Maybe Int , newIssueLabels :: Maybe [String] } deriving (Show, Data, Typeable, Eq, Ord) data EditIssue = EditIssue { editIssueTitle :: Maybe String , editIssueBody :: Maybe String , editIssueAssignee :: Maybe String , editIssueState :: Maybe String , editIssueMilestone :: Maybe Int , editIssueLabels :: Maybe [String] } deriving (Show, Data, Typeable, Eq, Ord) data Milestone = Milestone { milestoneCreator :: GithubOwner ,milestoneDueOn :: Maybe GithubDate ,milestoneOpenIssues :: Int ,milestoneNumber :: Int ,milestoneClosedIssues :: Int ,milestoneDescription :: Maybe String ,milestoneTitle :: String ,milestoneUrl :: String ,milestoneCreatedAt :: GithubDate ,milestoneState :: String } deriving (Show, Data, Typeable, Eq, Ord) data IssueLabel = IssueLabel { labelColor :: String ,labelUrl :: String ,labelName :: String } deriving (Show, Data, Typeable, Eq, Ord) data PullRequestReference = PullRequestReference { pullRequestReferenceHtmlUrl :: Maybe String ,pullRequestReferencePatchUrl :: Maybe String ,pullRequestReferenceDiffUrl :: Maybe String } deriving (Show, Data, Typeable, Eq, Ord) data IssueComment = IssueComment { issueCommentUpdatedAt :: GithubDate ,issueCommentUser :: GithubOwner ,issueCommentUrl :: String ,issueCommentCreatedAt :: GithubDate ,issueCommentBody :: String ,issueCommentId :: Int } deriving (Show, Data, Typeable, Eq, Ord) -- | Data describing an @Event@. data EventType = Mentioned -- ^ The actor was @mentioned in an issue body. | Subscribed -- ^ The actor subscribed to receive notifications for an issue. | Unsubscribed -- ^ The issue was unsubscribed from by the actor. | Referenced -- ^ The issue was referenced from a commit message. The commit_id attribute is the commit SHA1 of where that happened. | Merged -- ^ The issue was merged by the actor. The commit_id attribute is the SHA1 of the HEAD commit that was merged. | Assigned -- ^ The issue was assigned to the actor. | Closed -- ^ The issue was closed by the actor. When the commit_id is present, it identifies the commit that closed the issue using “closes / fixes #NN” syntax. | Reopened -- ^ The issue was reopened by the actor. | ActorUnassigned -- ^ The issue was unassigned to the actor | Labeled -- ^ A label was added to the issue. | Unlabeled -- ^ A label was removed from the issue. | Milestoned -- ^ The issue was added to a milestone. | Demilestoned -- ^ The issue was removed from a milestone. | Renamed -- ^ The issue title was changed. | Locked -- ^ The issue was locked by the actor. | Unlocked -- ^ The issue was unlocked by the actor. | HeadRefDeleted -- ^ The pull request’s branch was deleted. | HeadRefRestored -- ^ The pull request’s branch was restored. deriving (Show, Data, Typeable, Eq, Ord) data Event = Event { eventActor :: GithubOwner ,eventType :: EventType ,eventCommitId :: Maybe String ,eventUrl :: String ,eventCreatedAt :: GithubDate ,eventId :: Int ,eventIssue :: Maybe Issue } deriving (Show, Data, Typeable, Eq, Ord) data SimpleOrganization = SimpleOrganization { simpleOrganizationUrl :: String ,simpleOrganizationAvatarUrl :: String ,simpleOrganizationId :: Int ,simpleOrganizationLogin :: String } deriving (Show, Data, Typeable, Eq, Ord) data Organization = Organization { organizationType :: String ,organizationBlog :: Maybe String ,organizationLocation :: Maybe String ,organizationLogin :: String ,organizationFollowers :: Int ,organizationCompany :: Maybe String ,organizationAvatarUrl :: String ,organizationPublicGists :: Int ,organizationHtmlUrl :: String ,organizationEmail :: Maybe String ,organizationFollowing :: Int ,organizationPublicRepos :: Int ,organizationUrl :: String ,organizationCreatedAt :: GithubDate ,organizationName :: Maybe String ,organizationId :: Int } deriving (Show, Data, Typeable, Eq, Ord) data PullRequest = PullRequest { pullRequestClosedAt :: Maybe GithubDate ,pullRequestCreatedAt :: GithubDate ,pullRequestUser :: GithubOwner ,pullRequestPatchUrl :: String ,pullRequestState :: String ,pullRequestNumber :: Int ,pullRequestHtmlUrl :: String ,pullRequestUpdatedAt :: GithubDate ,pullRequestBody :: String ,pullRequestIssueUrl :: String ,pullRequestDiffUrl :: String ,pullRequestUrl :: String ,pullRequestLinks :: PullRequestLinks ,pullRequestMergedAt :: Maybe GithubDate ,pullRequestTitle :: String ,pullRequestId :: Int } deriving (Show, Data, Typeable, Eq, Ord) data DetailedPullRequest = DetailedPullRequest { -- this is a duplication of a PullRequest detailedPullRequestClosedAt :: Maybe GithubDate ,detailedPullRequestCreatedAt :: GithubDate ,detailedPullRequestUser :: GithubOwner ,detailedPullRequestPatchUrl :: String ,detailedPullRequestState :: String ,detailedPullRequestNumber :: Int ,detailedPullRequestHtmlUrl :: String ,detailedPullRequestUpdatedAt :: GithubDate ,detailedPullRequestBody :: String ,detailedPullRequestIssueUrl :: String ,detailedPullRequestDiffUrl :: String ,detailedPullRequestUrl :: String ,detailedPullRequestLinks :: PullRequestLinks ,detailedPullRequestMergedAt :: Maybe GithubDate ,detailedPullRequestTitle :: String ,detailedPullRequestId :: Int ,detailedPullRequestMergedBy :: Maybe GithubOwner ,detailedPullRequestChangedFiles :: Int ,detailedPullRequestHead :: PullRequestCommit ,detailedPullRequestComments :: Int ,detailedPullRequestDeletions :: Int ,detailedPullRequestAdditions :: Int ,detailedPullRequestReviewComments :: Int ,detailedPullRequestBase :: PullRequestCommit ,detailedPullRequestCommits :: Int ,detailedPullRequestMerged :: Bool ,detailedPullRequestMergeable :: Maybe Bool } deriving (Show, Data, Typeable, Eq, Ord) data EditPullRequest = EditPullRequest { editPullRequestTitle :: Maybe String ,editPullRequestBody :: Maybe String ,editPullRequestState :: Maybe EditPullRequestState } deriving (Show) data PullRequestLinks = PullRequestLinks { pullRequestLinksReviewComments :: String ,pullRequestLinksComments :: String ,pullRequestLinksHtml :: String ,pullRequestLinksSelf :: String } deriving (Show, Data, Typeable, Eq, Ord) data PullRequestCommit = PullRequestCommit { pullRequestCommitLabel :: String ,pullRequestCommitRef :: String ,pullRequestCommitSha :: String ,pullRequestCommitUser :: GithubOwner ,pullRequestCommitRepo :: Repo } deriving (Show, Data, Typeable, Eq, Ord) data SearchReposResult = SearchReposResult { searchReposTotalCount :: Int ,searchReposRepos :: [Repo] } deriving (Show, Data, Typeable, Eq, Ord) data Repo = Repo { repoSshUrl :: Maybe String ,repoDescription :: Maybe String ,repoCreatedAt :: Maybe GithubDate ,repoHtmlUrl :: String ,repoSvnUrl :: Maybe String ,repoForks :: Maybe Int ,repoHomepage :: Maybe String ,repoFork :: Maybe Bool ,repoGitUrl :: Maybe String ,repoPrivate :: Bool ,repoCloneUrl :: Maybe String ,repoSize :: Maybe Int ,repoUpdatedAt :: Maybe GithubDate ,repoWatchers :: Maybe Int ,repoOwner :: GithubOwner ,repoName :: String ,repoLanguage :: Maybe String ,repoMasterBranch :: Maybe String ,repoPushedAt :: Maybe GithubDate -- ^ this is Nothing for new repositories ,repoId :: Int ,repoUrl :: String ,repoOpenIssues :: Maybe Int ,repoHasWiki :: Maybe Bool ,repoHasIssues :: Maybe Bool ,repoHasDownloads :: Maybe Bool ,repoParent :: Maybe RepoRef ,repoSource :: Maybe RepoRef ,repoHooksUrl :: String } deriving (Show, Data, Typeable, Eq, Ord) data RepoRef = RepoRef GithubOwner String -- Repo owner and name deriving (Show, Data, Typeable, Eq, Ord) data SearchCodeResult = SearchCodeResult { searchCodeTotalCount :: Int ,searchCodeCodes :: [Code] } deriving (Show, Data, Typeable, Eq, Ord) data Code = Code { codeName :: String ,codePath :: String ,codeSha :: String ,codeUrl :: String ,codeGitUrl :: String ,codeHtmlUrl :: String ,codeRepo :: Repo } deriving (Show, Data, Typeable, Eq, Ord) data Content = ContentFile ContentData | ContentDirectory [ContentData] deriving (Show, Data, Typeable, Eq, Ord) data ContentData = ContentData { contentType :: String ,contentEncoding :: String ,contentSize :: Int ,contentName :: String ,contentPath :: String ,contentData :: String ,contentSha :: String ,contentUrl :: String ,contentGitUrl :: String ,contentHtmlUrl :: String } deriving (Show, Data, Typeable, Eq, Ord) data Contributor -- | An existing Github user, with their number of contributions, avatar -- URL, login, URL, ID, and Gravatar ID. = KnownContributor Int String String String Int String -- | An unknown Github user with their number of contributions and recorded name. | AnonymousContributor Int String deriving (Show, Data, Typeable, Eq, Ord) -- | This is only used for the FromJSON instance. data Languages = Languages { getLanguages :: [Language] } deriving (Show, Data, Typeable, Eq, Ord) -- | A programming language with the name and number of characters written in -- it. data Language = Language String Int deriving (Show, Data, Typeable, Eq, Ord) data Tag = Tag { tagName :: String ,tagZipballUrl :: String ,tagTarballUrl :: String ,tagCommit :: BranchCommit } deriving (Show, Data, Typeable, Eq, Ord) data Branch = Branch { branchName :: String ,branchCommit :: BranchCommit } deriving (Show, Data, Typeable, Eq, Ord) data BranchCommit = BranchCommit { branchCommitSha :: String ,branchCommitUrl :: String } deriving (Show, Data, Typeable, Eq, Ord) data DetailedOwner = DetailedUser { detailedOwnerCreatedAt :: GithubDate ,detailedOwnerType :: String ,detailedOwnerPublicGists :: Int ,detailedOwnerAvatarUrl :: String ,detailedOwnerFollowers :: Int ,detailedOwnerFollowing :: Int ,detailedOwnerHireable :: Maybe Bool ,detailedOwnerGravatarId :: Maybe String ,detailedOwnerBlog :: Maybe String ,detailedOwnerBio :: Maybe String ,detailedOwnerPublicRepos :: Int ,detailedOwnerName :: Maybe String ,detailedOwnerLocation :: Maybe String ,detailedOwnerCompany :: Maybe String ,detailedOwnerEmail :: Maybe String ,detailedOwnerUrl :: String ,detailedOwnerId :: Int ,detailedOwnerHtmlUrl :: String ,detailedOwnerLogin :: String } | DetailedOrganization { detailedOwnerCreatedAt :: GithubDate ,detailedOwnerType :: String ,detailedOwnerPublicGists :: Int ,detailedOwnerAvatarUrl :: String ,detailedOwnerFollowers :: Int ,detailedOwnerFollowing :: Int ,detailedOwnerBlog :: Maybe String ,detailedOwnerBio :: Maybe String ,detailedOwnerPublicRepos :: Int ,detailedOwnerName :: Maybe String ,detailedOwnerLocation :: Maybe String ,detailedOwnerCompany :: Maybe String ,detailedOwnerUrl :: String ,detailedOwnerId :: Int ,detailedOwnerHtmlUrl :: String ,detailedOwnerLogin :: String } deriving (Show, Data, Typeable, Eq, Ord) data RepoWebhook = RepoWebhook { repoWebhookUrl :: String ,repoWebhookTestUrl :: String ,repoWebhookId :: Integer ,repoWebhookName :: String ,repoWebhookActive :: Bool ,repoWebhookEvents :: [RepoWebhookEvent] ,repoWebhookConfig :: M.Map String String ,repoWebhookLastResponse :: RepoWebhookResponse ,repoWebhookUpdatedAt :: GithubDate ,repoWebhookCreatedAt :: GithubDate } deriving (Show, Data, Typeable, Eq, Ord) data RepoWebhookEvent = WebhookWildcardEvent | WebhookCommitCommentEvent | WebhookCreateEvent | WebhookDeleteEvent | WebhookDeploymentEvent | WebhookDeploymentStatusEvent | WebhookForkEvent | WebhookGollumEvent | WebhookIssueCommentEvent | WebhookIssuesEvent | WebhookMemberEvent | WebhookPageBuildEvent | WebhookPublicEvent | WebhookPullRequestReviewCommentEvent | WebhookPullRequestEvent | WebhookPushEvent | WebhookReleaseEvent | WebhookStatusEvent | WebhookTeamAddEvent | WebhookWatchEvent deriving (Show, Data, Typeable, Eq, Ord) data RepoWebhookResponse = RepoWebhookResponse { repoWebhookResponseCode :: Maybe Int ,repoWebhookResponseStatus :: String ,repoWebhookResponseMessage :: Maybe String } deriving (Show, Data, Typeable, Eq, Ord) data PullRequestEvent = PullRequestEvent { pullRequestEventAction :: PullRequestEventType ,pullRequestEventNumber :: Int ,pullRequestEventPullRequest :: DetailedPullRequest ,pullRequestRepository :: Repo ,pullRequestSender :: GithubOwner } deriving (Show, Data, Typeable, Eq, Ord) data PullRequestEventType = PullRequestOpened | PullRequestClosed | PullRequestSynchronized | PullRequestReopened | PullRequestAssigned | PullRequestUnassigned | PullRequestLabeled | PullRequestUnlabeled deriving (Show, Data, Typeable, Eq, Ord) data PingEvent = PingEvent { pingEventZen :: String ,pingEventHook :: RepoWebhook ,pingEventHookId :: Int } deriving (Show, Data, Typeable, Eq, Ord) data EditPullRequestState = EditPullRequestStateOpen | EditPullRequestStateClosed deriving Show
thoughtbot/github
Github/Data/Definitions.hs
bsd-3-clause
19,049
0
10
3,388
4,515
2,687
1,828
534
0
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Set import qualified Data.Map as Map import qualified Test.Framework as TF import qualified Test.Framework.Providers.HUnit as TFH import qualified Test.HUnit as TH import Syntax import Id import Type import SSA import SSALiveness main :: IO () main = TF.defaultMain tests testEq :: (Eq a, Show a) => String -> a -> a -> TF.Test testEq msg actual expected = TFH.testCase msg (TH.assertEqual msg expected actual) tests :: [TF.Test] tests = [testEasy, testLoop] (<==) :: VId -> Op -> Inst a <== b = Inst (Just a) b infix 1 <== testEasy :: TF.Test testEasy = testEq "easy_ssa" (analyzeLiveness fundef) dat where fundef = SSAFundef (LId "f" :-: TInt) [] [] [blk] blk = Block "entry" emptyPhi [ "a" <== SId (ci32 (0 :: Int)) , "b" <== SArithBin Add (OpVar ("a" :-: TInt)) (ci32 (1 :: Int)) , "c" <== SArithBin Add (OpVar ("a" :-: TInt)) (ci32 (2 :: Int)) , "d" <== SArithBin Add (OpVar ("b" :-: TInt)) (OpVar ("c" :-: TInt)) ] (TRet (OpVar ("d" :-: TInt))) dat = LiveInfo (Map.singleton "entry" blive) blive = BlockLive Map.empty [ InstLive empty (singleton "a") , InstLive (singleton "a") (fromList ["a", "b"]) , InstLive (fromList ["a", "b"]) (fromList ["b", "c"]) , InstLive (fromList ["b", "c"]) (singleton "d") ] (InstLive (singleton "d") empty) testLoop :: TF.Test testLoop = testEq "liveness_loop" (analyzeLiveness fundef) dat where fundef = SSAFundef (LId "f" :-: TInt) [] [] [blkEntry, blkL0, blkL1] blkEntry = Block "entry" emptyPhi [ "s" <== SId (ci32 (3 :: Int)) ] (TJmp "l0") blkL0 = Block "l0" (Phi ["a"] (Map.fromList [("entry", [OpVar ("s" :-: TInt)]), ("l0", [OpVar ("a" :-: TInt)])])) [ "b" <== SCmpBin LE (OpVar ("a" :-: TInt)) (ci32 (1 :: Int)) ] (TBr (OpVar ("b" :-: TInt)) "l1" "l0") blkL1 = Block "l1" (Phi [] (Map.singleton "l0" [])) [] (TRet (OpVar ("a" :-: TInt))) dat = LiveInfo (Map.fromList [("entry", bliveEntry), ("l0", bliveL0), ("l1", bliveL1)]) bliveEntry = BlockLive Map.empty [ InstLive empty (singleton "s") ] (InstLive (singleton "s") (singleton "s")) bliveL0 = BlockLive (Map.fromList [("entry", InstLive (singleton "s") (singleton "a")), ("l0", InstLive (singleton "a") (singleton "a"))]) [ InstLive (singleton "a") (fromList ["a", "b"]) ] (InstLive (fromList ["a", "b"]) (singleton "a")) bliveL1 = BlockLive (Map.fromList [("l0", InstLive (singleton "a") (singleton "a"))]) [] (InstLive (singleton "a") empty)
koba-e964/hayashii-mcc
test/LivenessTest.hs
bsd-3-clause
2,557
0
17
527
1,161
628
533
65
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Heed ( main ) where import qualified Control.Concurrent.BroadcastChan as BChan import Control.Concurrent.STM.TVar (newTVarIO) import Control.Lens ((&), (.~), (^..)) import Control.Monad (forM, forM_) import qualified Data.Ini as Ini import qualified Data.Map.Strict as Map import Data.Monoid ((<>)) import qualified Data.Text as T import Data.Time.Clock (getCurrentTime) import Data.Version (showVersion) import Database.PostgreSQL.Simple as PG import Development.GitRev (gitHash) import Heed.Database (feedInfoId) import Heed.Extract (startUpdateThread) import Heed.Query (allFeeds) import Heed.Server (genAuthMain) import Heed.Types (BackendConf(..), execQuery, runBe, threadMap) import Heed.Utils (Port, defPort) import Network.HTTP.Client (newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Options.Applicative (Parser, ParserInfo, execParser, help, info, infoOption, long) import Paths_heed_backend (version) import System.Environment (setEnv) import System.Exit (die) import qualified System.Log.FastLogger as Log import qualified System.Log.FastLogger.Date as LogDate import Text.Read (readEither) -- | List of Environment variables to setup for PostgreSQL pgEnvVar :: [String] pgEnvVar = ["PGUSER", "PGDATABASE"] -- | Connect to PostgreSQL and start rest backend main :: IO () main = do _ <- execParser optsParser timeCache <- LogDate.newTimeCache LogDate.simpleTimeFormat Log.withTimedFastLogger timeCache (Log.LogStdout Log.defaultBufSize) $ \logger -> do putStrLn "Starting heed-backend" port <- setupEnvGetPort baConf <- setupBackendConf logger feedsE <- runBe baConf $ execQuery allFeeds now <- getCurrentTime threads <- case feedsE of Left _ -> die "Can't get feed list from db" Right feeds -> do threadIds <- forM feeds (startUpdateThread now baConf) let nameThreadList = zip (feeds ^.. traverse . feedInfoId) threadIds return $ Map.fromList nameThreadList tvarThreads <- newTVarIO threads genAuthMain (baConf & (threadMap .~ tvarThreads)) port -- | Read ini file and setup 'pgEnvVar' variables setupEnvGetPort :: IO Port setupEnvGetPort = do iniFile <- Ini.readIniFile "/etc/heed/backend.ini" case iniFile of Left e -> die $ "Invalid ini file: " ++ e Right ini -> do forM_ pgEnvVar $ \var -> setEnv var . T.unpack $ either (const "") id (Ini.lookupValue "postgresql" (T.pack var) ini) return $ getPort ini -- | Get port fron ini or 'defPort' getPort :: Ini.Ini -> Port getPort ini = either (const defPort) id $ do port <- Ini.lookupValue "websocket" "port" ini readEither . T.unpack $ port -- | Create 'BackendConf' for the server setupBackendConf :: Log.TimedFastLogger -> IO BackendConf setupBackendConf logger = BackendConf <$> PG.connectPostgreSQL "" <*> newManager tlsManagerSettings <*> BChan.newBroadcastChan <*> pure logger <*> newTVarIO Map.empty -- | Only parse --version and --help optsParser :: ParserInfo String optsParser = info (versionOption <*> pure "") mempty versionOption :: Parser (a -> a) versionOption = infoOption (concat [showVersion version, " ", $(gitHash)]) (long "version" <> help "Show version")
Arguggi/heed
heed-backend/src/Heed.hs
bsd-3-clause
3,477
0
23
746
928
504
424
-1
-1
{-# LANGUAGE TemplateHaskell, TypeFamilies, ExistentialQuantification, TypeOperators, ScopedTypeVariables, TupleSections #-} module Data.Bitmap.StringRGB24A4VR.Internal ( BitmapImageString(..) , BitmapStringRGB24A4VR(..), bmps_dimensions, bmps_data , bytesPerRow , bitmapStringBytesPerRow , widthPadding , encodeIBF_RGB24A4VR' , tryIBF_RGB24A4VR' , padByte , imageSize ) where import Control.Applicative import Control.Arrow import Control.Monad.Record hiding (get) import Data.Binary import Data.Bitmap.Class import Data.Bitmap.Pixel import Data.Bitmap.Reflectable import Data.Bitmap.Searchable import Data.Bitmap.Types import Data.Bitmap.Util hiding (padByte) import Data.Bits import qualified Data.ByteString as B import qualified Data.Serialize as S import qualified Data.String.Class as S import Data.Tagged import Text.Printf -- | Container for a string that represents a sequence of raw pixels lacking the alpha component and that is stored upside down data BitmapImageString = forall s. (S.StringCells s) => BitmapImageString {_polyval_bitmapImageString :: s} instance Eq BitmapImageString where a == b = case (a, b) of ((BitmapImageString sa), (BitmapImageString sb)) -> S.toStrictByteString sa == S.toStrictByteString sb a /= b = case (a, b) of ((BitmapImageString sa), (BitmapImageString sb)) -> S.toStrictByteString sa /= S.toStrictByteString sb -- | A bitmap represented as a string -- -- This is essentially the format of pixels -- in the BMP format in which each row is aligned to -- a four-byte boundry and each row contains a series of -- RGB pixels. -- -- This type is most efficient for programs interacting heavily with BMP files. data BitmapStringRGB24A4VR = BitmapStringRGB24A4VR { _bmps_dimensions :: (Int, Int) -- ^ Width and height of the bitmap , _bmps_data :: BitmapImageString -- ^ Data stored in a string } mkLabels [''BitmapStringRGB24A4VR] instance Binary BitmapStringRGB24A4VR where get = pure BitmapStringRGB24A4VR <*> get <*> (BitmapImageString <$> (get :: Get B.ByteString)) put b = put (bmps_dimensions <: b) >> put (case bmps_data <: b of (BitmapImageString s) -> S.toLazyByteString s) instance S.Serialize BitmapStringRGB24A4VR where get = pure BitmapStringRGB24A4VR <*> S.get <*> (BitmapImageString <$> (S.get :: S.Get B.ByteString)) put b = S.put (bmps_dimensions <: b) >> S.put (case bmps_data <: b of (BitmapImageString s) -> S.toLazyByteString s) instance Bitmap BitmapStringRGB24A4VR where type BIndexType BitmapStringRGB24A4VR = Int type BPixelType BitmapStringRGB24A4VR = PixelRGB depth = const Depth24RGB dimensions = (bmps_dimensions <:) getPixel b (row, column) = let bytesPixel = 3 bytesRow = fst $ bitmapStringBytesPerRow b maxRow = abs . pred . snd . dimensions $ b offset = bytesRow * (maxRow - row) + bytesPixel * column in case bmps_data <: b of (BitmapImageString s) -> PixelRGB $ ((fromIntegral . S.toWord8 $ s `S.index` (offset )) `shiftL` 16) .|. ((fromIntegral . S.toWord8 $ s `S.index` (offset + 1)) `shiftL` 8) .|. ((fromIntegral . S.toWord8 $ s `S.index` (offset + 2))) constructPixels f dms@(width, height) = BitmapStringRGB24A4VR dms . (BitmapImageString :: B.ByteString -> BitmapImageString) $ S.unfoldrN (imageSize dms) getComponent (0 :: Int, 0 :: Int, 0 :: Int, 0 :: Int) where getComponent (row, column, orgb, paddingLeft) | paddingLeft > 0 = Just (padCell, (row, column, orgb, pred paddingLeft)) | orgb > 2 = getComponent (row, succ column, 0, 0) | column > maxColumn = getComponent (succ row, 0, 0, paddingSize) | row > maxRow = Nothing | otherwise = let pixel = f (row, column) componentGetter = case orgb of 0 -> untag' . S.toMainChar . (red <:) 1 -> untag' . S.toMainChar . (green <:) 2 -> untag' . S.toMainChar . (blue <:) _ -> undefined in Just (componentGetter pixel, (row, column, succ orgb, 0)) maxRow = abs . pred $ height maxColumn = abs . pred $ width paddingSize = snd $ bytesPerRow width 3 4 padCell = untag' . S.toMainChar $ padByte untag' = untag :: Tagged B.ByteString a -> a imageEncoders = updateIdentifiableElements (map (second unwrapGenericBitmapSerializer) defaultImageEncoders) $ [ (IBF_RGB24A4VR, ImageEncoder $ encodeIBF_RGB24A4VR') ] imageDecoders = updateIdentifiableElements (map (second unwrapGenericBitmapSerializer) defaultImageDecoders) $ [ (IBF_RGB24A4VR, ImageDecoder $ tryIBF_RGB24A4VR') ] encodeIBF_RGB24A4VR' :: (S.StringCells s) => BitmapStringRGB24A4VR -> s encodeIBF_RGB24A4VR' b = case (bmps_data <: b) of (BitmapImageString s) -> S.fromStringCells s tryIBF_RGB24A4VR' :: (S.StringCells s) => BitmapStringRGB24A4VR -> s -> Either String BitmapStringRGB24A4VR tryIBF_RGB24A4VR' bmp s | S.length s < minLength = Left $ printf "Data.Bitmap.StringRGB24A4VR.Internal.tryIBF_RGB24A4VR': string is too small to contain the pixels of a bitmap with the dimensions of the passed bitmap, which are (%d, %d); the string is %d bytes long, but needs to be at least %d bytes long" (fromIntegral width :: Integer) (fromIntegral height :: Integer) (S.length s) minLength | otherwise = Right $ (bmps_data =: BitmapImageString s) bmp where (width, height) = bmps_dimensions <: bmp minLength = imageSize (bmps_dimensions <: bmp) bitmapStringBytesPerRow :: BitmapStringRGB24A4VR -> (Int, Int) bitmapStringBytesPerRow b = bytesPerRow (fst $ bmps_dimensions <: b) 3 4 widthPadding :: Int -> String widthPadding w = replicate (snd $ bytesPerRow w 3 4) $ S.toChar padByte -- | Return (rowSize, paddingSize) based on width, bytes per pixel, and alignment bytesPerRow :: Int -> Int -> Int -> (Int, Int) bytesPerRow width bytes_per_pixel alignment = (rawRowSize + off', off') where rawRowSize = bytes_per_pixel * width off = rawRowSize `mod` alignment off' | off == 0 = 0 | otherwise = alignment - off padByte :: Word8 padByte = 0x00 imageSize :: Dimensions Int -> Int imageSize (width, height) = (fst $ bytesPerRow width 3 4) * height instance BitmapSearchable BitmapStringRGB24A4VR where findSubBitmapEqual super sub = case (bmps_data <: super, bmps_data <: sub) of ((BitmapImageString dataSuper), (BitmapImageString dataSub)) -> let (widthSuper, heightSuper) = bmps_dimensions <: super (widthSub, heightSub) = bmps_dimensions <: sub superBytesPerRow = fst $ bitmapStringBytesPerRow super subBytesPerRow = fst $ bitmapStringBytesPerRow sub maxSuperRow = heightSuper - heightSub maxSuperColumn = widthSuper - widthSub maxOffRow = abs . pred $ heightSub offRowSize = subBytesPerRow - (snd $ bitmapStringBytesPerRow sub) r' (row, column) | column > maxSuperColumn = r' (succ row, 0) | row > maxSuperRow = Nothing | matches 0 = Just (maxSuperRow - row, column) | otherwise = r' (row, succ column) where superBaseIndex = row * superBytesPerRow + 3 * column matches offRow | offRow > maxOffRow = True | (S.toStringCells :: S.StringCells s => s -> B.ByteString) (subStr (superBaseIndex + offRow * superBytesPerRow) offRowSize dataSuper) /= (S.toStringCells :: S.StringCells s => s -> B.ByteString) (subStr (offRow * subBytesPerRow) offRowSize dataSub) = False | otherwise = matches (succ offRow) in r' instance BitmapReflectable BitmapStringRGB24A4VR
bairyn/bitmaps
src/Data/Bitmap/StringRGB24A4VR/Internal.hs
bsd-3-clause
8,772
5
24
2,748
2,176
1,175
1,001
143
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ConstraintKinds #-} module Futhark.Representation.SOACS.SOAC ( SOAC(..) , StreamForm(..) , typeCheckSOAC -- * Utility , getStreamOrder , getStreamAccums -- * Generic traversal , SOACMapper(..) , identitySOACMapper , mapSOACM ) where import Control.Applicative import Control.Monad.Writer import Control.Monad.Identity import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import Data.Maybe import Data.List import Prelude import Futhark.Representation.AST import qualified Futhark.Analysis.Alias as Alias import qualified Futhark.Util.Pretty as PP import Futhark.Util.Pretty ((</>), ppr, comma, commasep, Doc, Pretty, parens, text) import qualified Futhark.Representation.AST.Pretty as PP import Futhark.Representation.AST.Attributes.Aliases import Futhark.Transform.Substitute import Futhark.Transform.Rename import Futhark.Optimise.Simplifier.Lore import Futhark.Representation.Ranges (Ranges, removeLambdaRanges, removeExtLambdaRanges) import Futhark.Representation.AST.Attributes.Ranges import Futhark.Representation.Aliases (Aliases, removeLambdaAliases, removeExtLambdaAliases) import Futhark.Analysis.Usage import qualified Futhark.TypeCheck as TC import Futhark.Analysis.Metrics import qualified Futhark.Analysis.Range as Range data SOAC lore = Map Certificates SubExp (LambdaT lore) [VName] | Reduce Certificates SubExp Commutativity (LambdaT lore) [(SubExp, VName)] | Scan Certificates SubExp (LambdaT lore) [(SubExp, VName)] | Redomap Certificates SubExp Commutativity (LambdaT lore) (LambdaT lore) [SubExp] [VName] | Scanomap Certificates SubExp (LambdaT lore) (LambdaT lore) [SubExp] [VName] | Stream Certificates SubExp (StreamForm lore) (ExtLambdaT lore) [VName] | Write Certificates SubExp (LambdaT lore) [VName] [(SubExp, VName)] -- Write <cs> <length> <lambda> <original index and value arrays> -- <input/output arrays along with their sizes> -- -- <length> is the length of each index array and value array, since they -- all must be the same length for any fusion to make sense. If you have a -- list of index-value array pairs of different sizes, you need to use -- multiple writes instead. -- -- The lambda body returns the output in this manner: -- -- [index_0, index_1, ..., index_n, value_0, value_1, ..., value_n] -- -- This must be consistent along all Write-related optimisations. -- -- The original index arrays and value arrays are concatenated. deriving (Eq, Ord, Show) data StreamForm lore = MapLike StreamOrd | RedLike StreamOrd Commutativity (LambdaT lore) [SubExp] | Sequential [SubExp] deriving (Eq, Ord, Show) -- | Like 'Mapper', but just for 'SOAC's. data SOACMapper flore tlore m = SOACMapper { mapOnSOACSubExp :: SubExp -> m SubExp , mapOnSOACLambda :: Lambda flore -> m (Lambda tlore) , mapOnSOACExtLambda :: ExtLambda flore -> m (ExtLambda tlore) , mapOnSOACVName :: VName -> m VName , mapOnSOACCertificates :: Certificates -> m Certificates } -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper lore lore m identitySOACMapper = SOACMapper { mapOnSOACSubExp = return , mapOnSOACLambda = return , mapOnSOACExtLambda = return , mapOnSOACVName = return , mapOnSOACCertificates = return } -- | Map a monadic action across the immediate children of a -- SOAC. The mapping does not descend recursively into subexpressions -- and is done left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper flore tlore m -> SOAC flore -> m (SOAC tlore) mapSOACM tv (Map cs w lam arrs) = Map <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv w <*> mapOnSOACLambda tv lam <*> mapM (mapOnSOACVName tv) arrs mapSOACM tv (Reduce cs w comm lam input) = Reduce <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv w <*> pure comm <*> mapOnSOACLambda tv lam <*> (zip <$> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs) where (nes, arrs) = unzip input mapSOACM tv (Scan cs w lam input) = Scan <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv w <*> mapOnSOACLambda tv lam <*> (zip <$> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs) where (nes, arrs) = unzip input mapSOACM tv (Redomap cs w comm lam0 lam1 nes arrs) = Redomap <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv w <*> pure comm <*> mapOnSOACLambda tv lam0 <*> mapOnSOACLambda tv lam1 <*> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs mapSOACM tv (Scanomap cs w lam0 lam1 nes arrs) = Scanomap <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv w <*> mapOnSOACLambda tv lam0 <*> mapOnSOACLambda tv lam1 <*> mapM (mapOnSOACSubExp tv) nes <*> mapM (mapOnSOACVName tv) arrs mapSOACM tv (Stream cs size form lam arrs) = Stream <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv size <*> mapOnStreamForm form <*> mapOnSOACExtLambda tv lam <*> mapM (mapOnSOACVName tv) arrs where mapOnStreamForm (MapLike o) = pure $ MapLike o mapOnStreamForm (RedLike o comm lam0 acc) = RedLike <$> pure o <*> pure comm <*> mapOnSOACLambda tv lam0 <*> mapM (mapOnSOACSubExp tv) acc mapOnStreamForm (Sequential acc) = Sequential <$> mapM (mapOnSOACSubExp tv) acc mapSOACM tv (Write cs len lam ivs as) = Write <$> mapOnSOACCertificates tv cs <*> mapOnSOACSubExp tv len <*> mapOnSOACLambda tv lam <*> mapM (mapOnSOACVName tv) ivs <*> mapM (\(aw,a) -> (,) <$> mapOnSOACSubExp tv aw <*> mapOnSOACVName tv a) as instance Attributes lore => FreeIn (SOAC lore) where freeIn = execWriter . mapSOACM free where walk f x = tell (f x) >> return x free = SOACMapper { mapOnSOACSubExp = walk freeIn , mapOnSOACLambda = walk freeInLambda , mapOnSOACExtLambda = walk freeInExtLambda , mapOnSOACVName = walk freeIn , mapOnSOACCertificates = walk freeIn } instance Attributes lore => Substitute (SOAC lore) where substituteNames subst = runIdentity . mapSOACM substitute where substitute = SOACMapper { mapOnSOACSubExp = return . substituteNames subst , mapOnSOACLambda = return . substituteNames subst , mapOnSOACExtLambda = return . substituteNames subst , mapOnSOACVName = return . substituteNames subst , mapOnSOACCertificates = return . substituteNames subst } instance Attributes lore => Rename (SOAC lore) where rename = mapSOACM renamer where renamer = SOACMapper rename rename rename rename rename soacType :: SOAC lore -> [ExtType] soacType (Map _ size f _) = staticShapes $ mapType size f soacType (Reduce _ _ _ fun _) = staticShapes $ lambdaReturnType fun soacType (Scan _ width lam _) = staticShapes $ map (`arrayOfRow` width) $ lambdaReturnType lam soacType (Redomap _ outersize _ outerfun innerfun _ _) = staticShapes $ let acc_tp = lambdaReturnType outerfun acc_el_tp = lambdaReturnType innerfun res_el_tp = drop (length acc_tp) acc_el_tp in case res_el_tp of [] -> acc_tp _ -> acc_tp ++ map (`arrayOfRow` outersize) res_el_tp soacType (Scanomap _ outersize outerfun innerfun _ _) = staticShapes $ let acc_tp = map (`arrayOfRow` outersize) $ lambdaReturnType outerfun acc_el_tp = lambdaReturnType innerfun res_el_tp = drop (length acc_tp) acc_el_tp in case res_el_tp of [] -> acc_tp _ -> acc_tp ++ map (`arrayOfRow` outersize) res_el_tp soacType (Stream _ outersize form lam _) = map (substNamesInExtType substs) rtp where nms = map paramName $ take (1 + length accs) params substs = HM.fromList $ zip nms (outersize:accs) ExtLambda params _ rtp = lam accs = case form of MapLike _ -> [] RedLike _ _ _ acc -> acc Sequential acc -> acc soacType (Write _cs _w lam _ivs as) = staticShapes $ zipWith arrayOfRow (snd $ splitAt (n `div` 2) lam_ts) ws where lam_ts = lambdaReturnType lam n = length lam_ts ws = map fst as instance Attributes lore => TypedOp (SOAC lore) where opType = pure . soacType instance (Attributes lore, Aliased lore) => AliasedOp (SOAC lore) where opAliases (Map _ _ f _) = map (const mempty) $ lambdaReturnType f opAliases (Reduce _ _ _ f _) = map (const mempty) $ lambdaReturnType f opAliases (Scan _ _ f _) = map (const mempty) $ lambdaReturnType f opAliases (Redomap _ _ _ _ innerfun _ _) = map (const mempty) $ lambdaReturnType innerfun opAliases (Scanomap _ _ _ innerfun _ _) = map (const mempty) $ lambdaReturnType innerfun opAliases (Stream _ _ form lam _) = let a1 = case form of MapLike _ -> [] RedLike _ _ lam0 _ -> map (const mempty) $ lambdaReturnType lam0 Sequential _ -> [] in a1 ++ map (const mempty) (extLambdaReturnType lam) opAliases (Write _cs _len lam _ivs _as) = map (const mempty) $ lambdaReturnType lam -- Only Map, Redomap and Stream can consume anything. The operands -- to Scan and Reduce functions are always considered "fresh". consumedInOp (Map _ _ lam arrs) = HS.map consumedArray $ consumedByLambda lam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName (lambdaParams lam)) arrs consumedInOp (Redomap _ _ _ foldlam _ nes arrs) = HS.map consumedArray $ consumedByLambda foldlam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName $ drop (length nes) (lambdaParams foldlam)) arrs consumedInOp (Stream _ _ form lam arrs) = HS.fromList $ subExpVars $ case form of MapLike{} -> map (consumedArray []) $ HS.toList $ consumedByExtLambda lam Sequential accs -> map (consumedArray accs) $ HS.toList $ consumedByExtLambda lam RedLike _ _ _ accs -> map (consumedArray accs) $ HS.toList $ consumedByExtLambda lam where consumedArray accs v = fromMaybe (Var v) $ lookup v $ paramsToInput accs -- Drop the chunk parameter, which cannot alias anything. paramsToInput accs = zip (map paramName $ drop 1 $ extLambdaParams lam) (accs++map Var arrs) consumedInOp _ = mempty instance (Attributes lore, Attributes (Aliases lore), CanBeAliased (Op lore)) => CanBeAliased (SOAC lore) where type OpWithAliases (SOAC lore) = SOAC (Aliases lore) addOpAliases (Map cs size lam args) = Map cs size (Alias.analyseLambda lam) args addOpAliases (Reduce cs size comm lam input) = Reduce cs size comm (Alias.analyseLambda lam) input addOpAliases (Scan cs size lam input) = Scan cs size (Alias.analyseLambda lam) input addOpAliases (Redomap cs size comm outerlam innerlam acc arr) = Redomap cs size comm (Alias.analyseLambda outerlam) (Alias.analyseLambda innerlam) acc arr addOpAliases (Scanomap cs size outerlam innerlam acc arr) = Scanomap cs size (Alias.analyseLambda outerlam) (Alias.analyseLambda innerlam) acc arr addOpAliases (Stream cs size form lam arr) = Stream cs size (analyseStreamForm form) (Alias.analyseExtLambda lam) arr where analyseStreamForm (RedLike o comm lam0 acc) = RedLike o comm (Alias.analyseLambda lam0) acc analyseStreamForm (Sequential acc) = Sequential acc analyseStreamForm (MapLike o ) = MapLike o addOpAliases (Write cs len lam ivs as) = Write cs len (Alias.analyseLambda lam) ivs as removeOpAliases = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaAliases) (return . removeExtLambdaAliases) return return instance Attributes lore => IsOp (SOAC lore) where safeOp _ = False substNamesInExtType :: HM.HashMap VName SubExp -> ExtType -> ExtType substNamesInExtType _ tp@(Prim _) = tp substNamesInExtType subs (Mem se space) = Mem (substNamesInSubExp subs se) space substNamesInExtType subs (Array btp shp u) = let shp' = ExtShape $ map (substNamesInExtDimSize subs) (extShapeDims shp) in Array btp shp' u substNamesInSubExp :: HM.HashMap VName SubExp -> SubExp -> SubExp substNamesInSubExp _ e@(Constant _) = e substNamesInSubExp subs (Var idd) = HM.lookupDefault (Var idd) idd subs substNamesInExtDimSize :: HM.HashMap VName SubExp -> ExtDimSize -> ExtDimSize substNamesInExtDimSize _ (Ext o) = Ext o substNamesInExtDimSize subs (Free o) = Free $ substNamesInSubExp subs o instance (Attributes inner, Ranged inner) => RangedOp (SOAC inner) where opRanges op = replicate (length $ soacType op) unknownRange instance (Attributes lore, CanBeRanged (Op lore)) => CanBeRanged (SOAC lore) where type OpWithRanges (SOAC lore) = SOAC (Ranges lore) removeOpRanges = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaRanges) (return . removeExtLambdaRanges) return return addOpRanges (Map cs w lam args) = Map cs w (Range.runRangeM $ Range.analyseLambda lam) args addOpRanges (Reduce cs w comm lam input) = Reduce cs w comm (Range.runRangeM $ Range.analyseLambda lam) input addOpRanges (Scan cs w lam input) = Scan cs w (Range.runRangeM $ Range.analyseLambda lam) input addOpRanges (Redomap cs w comm outerlam innerlam acc arr) = Redomap cs w comm (Range.runRangeM $ Range.analyseLambda outerlam) (Range.runRangeM $ Range.analyseLambda innerlam) acc arr addOpRanges (Scanomap cs w outerlam innerlam acc arr) = Scanomap cs w (Range.runRangeM $ Range.analyseLambda outerlam) (Range.runRangeM $ Range.analyseLambda innerlam) acc arr addOpRanges (Stream cs w form lam arr) = Stream cs w (Range.runRangeM $ analyseStreamForm form) (Range.runRangeM $ Range.analyseExtLambda lam) arr where analyseStreamForm (MapLike o ) = return $ MapLike o analyseStreamForm (Sequential acc) = return $ Sequential acc analyseStreamForm (RedLike o comm lam0 acc) = do lam0' <- Range.analyseLambda lam0 return $ RedLike o comm lam0' acc addOpRanges (Write cs len lam ivs as) = Write cs len (Range.runRangeM $ Range.analyseLambda lam) ivs as instance (Attributes lore, CanBeWise (Op lore)) => CanBeWise (SOAC lore) where type OpWithWisdom (SOAC lore) = SOAC (Wise lore) removeOpWisdom = runIdentity . mapSOACM remove where remove = SOACMapper return (return . removeLambdaWisdom) (return . removeExtLambdaWisdom) return return instance (Aliased lore, UsageInOp (Op lore)) => UsageInOp (SOAC lore) where usageInOp (Map _ _ f arrs) = usageInLambda f arrs usageInOp (Redomap _ _ _ _ f _ arrs) = usageInLambda f arrs usageInOp _ = mempty typeCheckSOAC :: TC.Checkable lore => SOAC (Aliases lore) -> TC.TypeM lore () typeCheckSOAC (Map cs size fun arrexps) = do mapM_ (TC.requireI [Prim Cert]) cs TC.require [Prim int32] size arrargs <- TC.checkSOACArrayArgs size arrexps TC.checkLambda fun arrargs typeCheckSOAC (Redomap ass size _ outerfun innerfun accexps arrexps) = typeCheckScanomapRedomap ass size outerfun innerfun accexps arrexps typeCheckSOAC (Scanomap ass size outerfun innerfun accexps arrexps) = typeCheckScanomapRedomap ass size outerfun innerfun accexps arrexps typeCheckSOAC (Stream ass size form lam arrexps) = do let accexps = getStreamAccums form mapM_ (TC.requireI [Prim Cert]) ass TC.require [Prim int32] size accargs <- mapM TC.checkArg accexps arrargs <- mapM lookupType arrexps _ <- TC.checkSOACArrayArgs size arrexps let chunk = head $ extLambdaParams lam let asArg t = (t, mempty) inttp = Prim int32 lamarrs'= map (`setOuterSize` Var (paramName chunk)) arrargs TC.checkExtLambda lam $ asArg inttp : accargs ++ map asArg lamarrs' let acc_len= length accexps let lamrtp = take acc_len $ extLambdaReturnType lam unless (staticShapes (map TC.argType accargs) == lamrtp) $ TC.bad $ TC.TypeError "Stream with inconsistent accumulator type in lambda." -- check reduce's lambda, if any _ <- case form of RedLike _ _ lam0 _ -> do let acct = map TC.argType accargs outerRetType = lambdaReturnType lam0 TC.checkLambda lam0 $ map TC.noArgAliases $ accargs ++ accargs unless (acct == outerRetType) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but stream's reduce lambda returns type " ++ prettyTuple outerRetType ++ "." _ -> return () -- just get the dflow of lambda on the fakearg, which does not alias -- arr, so we can later check that aliases of arr are not used inside lam. -- let fakearg = (fromDecl $ addNames $ removeNames $ typeOf arr', mempty, srclocOf pos) let fake_lamarrs' = map asArg lamarrs' (_,occurs) <- TC.collectOccurences $ TC.checkExtLambda lam $ asArg inttp : accargs ++ fake_lamarrs' let usages = TC.usageMap occurs arr_aliases <- mapM TC.lookupAliases arrexps let aliased_syms = HS.toList $ HS.fromList $ concatMap HS.toList arr_aliases when (any (`HM.member` usages) aliased_syms) $ TC.bad $ TC.TypeError "Stream with input array used inside lambda." -- check outerdim of Lambda's streamed-in array params are NOT specified, -- and that return type inner dimens are all specified but not as other -- lambda parameters! let lamarr_rtp = drop acc_len $ extLambdaReturnType lam lamarr_ptp = map paramType $ drop (acc_len+1) $ extLambdaParams lam names_lamparams = HS.fromList $ map paramName $ extLambdaParams lam _ <- mapM (checkOuterDim (paramName chunk) . head . shapeDims . arrayShape) lamarr_ptp _ <- mapM (checkInnerDim names_lamparams . tail . extShapeDims . arrayShape) lamarr_rtp return () where checkOuterDim chunknm outdim = do let chunk_str = textual chunknm case outdim of Constant _ -> TC.bad $ TC.TypeError ("Stream: outer dimension of stream should NOT"++ " be specified since it is "++chunk_str++"by default.") Var idd -> unless (idd == chunknm) $ TC.bad $ TC.TypeError ("Stream: outer dimension of stream should NOT"++ " be specified since it is "++chunk_str++"by default.") boundDim (Free (Var idd)) = return $ Just idd boundDim (Free _ ) = return Nothing boundDim (Ext _ ) = TC.bad $ TC.TypeError $ "Stream's lambda: inner dimensions of the"++ " streamed-out arrays MUST be specified!" checkInnerDim lamparnms innerdims = do rtp_iner_syms <- catMaybes <$> mapM boundDim innerdims case find (`HS.member` lamparnms) rtp_iner_syms of Just name -> TC.bad $ TC.TypeError $ "Stream's lambda: " ++ pretty name ++ " cannot specify an inner result shape" _ -> return True typeCheckSOAC (Write cs w lam _ivs as) = do -- Requirements: -- -- 0. @lambdaReturnType@ of @lam@ must be a list -- [index types..., value types]. -- -- 1. The number of index types must be equal to the number of value types -- and the number of arrays in @as@. -- -- 2. Each index type must have the type i32. -- -- 3. Each array pair in @as@ and the value types must have the same type -- (though not necessarily the same length). -- -- 4. Each array in @as@ is consumed. This is not really a check, but more -- of a requirement, so that e.g. the source is not hoisted out of a -- loop, which will mean it cannot be consumed. -- -- Code: -- First check the certificates and input size. mapM_ (TC.requireI [Prim Cert]) cs TC.require [Prim int32] w -- 0. let rts = lambdaReturnType lam rtsLen = length rts `div` 2 rtsI = take rtsLen rts rtsV = drop rtsLen rts -- 1. unless (rtsLen == length as) $ TC.bad $ TC.TypeError "Write: Uneven number of index types, value types, and I/O arrays." -- 2. forM_ rtsI $ \rtI -> unless (Prim int32 == rtI) $ TC.bad $ TC.TypeError "Write: Index return type must be i32." forM_ (zip rtsV as) $ \(rtV, (aw, a)) -> do -- All lengths must have type i32. TC.require [Prim int32] aw -- 3. aType <- lookupType a case (rtV, rowType aType) of (Prim pt0, Prim pt1) | pt0 == pt1 -> return () (Array pt0 _ _, Array pt1 _ _) | pt0 == pt1 -> return () _ -> TC.bad $ TC.TypeError "Write values and input arrays do not have the same primitive type" -- 4. TC.consume =<< TC.lookupAliases a typeCheckSOAC (Reduce ass size _ fun inputs) = typeCheckScanReduce ass size fun inputs typeCheckSOAC (Scan ass size fun inputs) = typeCheckScanReduce ass size fun inputs typeCheckScanReduce :: TC.Checkable lore => Certificates -> SubExp -> Lambda (Aliases lore) -> [(SubExp, VName)] -> TC.TypeM lore () typeCheckScanReduce cs size fun inputs = do let (startexps, arrexps) = unzip inputs mapM_ (TC.requireI [Prim Cert]) cs TC.require [Prim int32] size startargs <- mapM TC.checkArg startexps arrargs <- TC.checkSOACArrayArgs size arrexps TC.checkLambda fun $ map TC.noArgAliases $ startargs ++ arrargs let startt = map TC.argType startargs intupletype = map TC.argType arrargs funret = lambdaReturnType fun unless (startt == funret) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple startt ++ ", but function returns type " ++ prettyTuple funret ++ "." unless (intupletype == funret) $ TC.bad $ TC.TypeError $ "Array element value is of type " ++ prettyTuple intupletype ++ ", but function returns type " ++ prettyTuple funret ++ "." typeCheckScanomapRedomap :: TC.Checkable lore => Certificates -> SubExp -> Lambda (Aliases lore) -> Lambda (Aliases lore) -> [SubExp] -> [VName] -> TC.TypeM lore () typeCheckScanomapRedomap ass size outerfun innerfun accexps arrexps = do mapM_ (TC.requireI [Prim Cert]) ass TC.require [Prim int32] size arrargs <- TC.checkSOACArrayArgs size arrexps accargs <- mapM TC.checkArg accexps TC.checkLambda innerfun $ map TC.noArgAliases accargs ++ arrargs let innerRetType = lambdaReturnType innerfun innerAccType = take (length accexps) innerRetType asArg t = (t, mempty) TC.checkLambda outerfun $ map asArg $ innerAccType ++ innerAccType let acct = map TC.argType accargs outerRetType = lambdaReturnType outerfun unless (acct == innerAccType ) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but reduction function returns type " ++ prettyTuple innerRetType ++ "." unless (acct == outerRetType) $ TC.bad $ TC.TypeError $ "Initial value is of type " ++ prettyTuple acct ++ ", but fold function returns type " ++ prettyTuple outerRetType ++ "." -- | Get Stream's accumulators as a sub-expression list getStreamAccums :: StreamForm lore -> [SubExp] getStreamAccums (MapLike _ ) = [] getStreamAccums (RedLike _ _ _ accs) = accs getStreamAccums (Sequential accs) = accs getStreamOrder :: StreamForm lore -> StreamOrd getStreamOrder (MapLike o ) = o getStreamOrder (RedLike o _ _ _) = o getStreamOrder (Sequential _) = InOrder instance OpMetrics (Op lore) => OpMetrics (SOAC lore) where opMetrics (Map _ _ fun _) = inside "Map" $ lambdaMetrics fun opMetrics (Reduce _ _ _ fun _) = inside "Reduce" $ lambdaMetrics fun opMetrics (Scan _ _ fun _) = inside "Scan" $ lambdaMetrics fun opMetrics (Redomap _ _ _ fun1 fun2 _ _) = inside "Redomap" $ lambdaMetrics fun1 >> lambdaMetrics fun2 opMetrics (Scanomap _ _ fun1 fun2 _ _) = inside "Scanomap" $ lambdaMetrics fun1 >> lambdaMetrics fun2 opMetrics (Stream _ _ _ lam _) = inside "Stream" $ extLambdaMetrics lam opMetrics (Write _cs _len lam _ivs _as) = inside "Write" $ lambdaMetrics lam extLambdaMetrics :: OpMetrics (Op lore) => ExtLambda lore -> MetricsM () extLambdaMetrics = bodyMetrics . extLambdaBody instance PrettyLore lore => PP.Pretty (SOAC lore) where ppr (Map cs size lam as) = PP.ppCertificates' cs <> ppSOAC "map" size [lam] Nothing as ppr (Reduce cs size comm lam inputs) = PP.ppCertificates' cs <> ppSOAC s size [lam] (Just es) as where (es, as) = unzip inputs s = case comm of Noncommutative -> "reduce" Commutative -> "reduceComm" ppr (Redomap cs size comm outer inner es as) = PP.ppCertificates' cs <> text s <> parens (ppr size <> comma </> ppr outer <> comma </> ppr inner <> comma </> commasep (PP.braces (commasep $ map ppr es) : map ppr as)) where s = case comm of Noncommutative -> "redomap" Commutative -> "redomapComm" ppr (Stream cs size form lam arrs) = PP.ppCertificates' cs <> case form of MapLike o -> let ord_str = if o == Disorder then "Per" else "" in text ("streamMap"++ord_str) <> parens (ppr size <> comma </> ppr lam <> comma </> commasep (map ppr arrs) ) RedLike o comm lam0 acc -> let ord_str = if o == Disorder then "Per" else "" comm_str = case comm of Commutative -> "Comm" Noncommutative -> "" in text ("streamRed"++ord_str++comm_str) <> parens (ppr size <> comma </> ppr lam0 </> comma </> ppr lam </> commasep ( PP.braces (commasep $ map ppr acc) : map ppr arrs )) Sequential acc -> text "streamSeq" <> parens (ppr size <> comma </> ppr lam <> comma </> commasep ( PP.braces (commasep $ map ppr acc) : map ppr arrs )) ppr (Scan cs size lam inputs) = PP.ppCertificates' cs <> ppSOAC "scan" size [lam] (Just es) as where (es, as) = unzip inputs ppr (Scanomap cs size outer inner es as) = PP.ppCertificates' cs <> text "scanomap" <> parens (ppr size <> comma </> ppr outer <> comma </> ppr inner <> comma </> commasep (PP.braces (commasep $ map ppr es) : map ppr as)) ppr (Write cs len lam ivs as) = PP.ppCertificates' cs <> ppSOAC "write" len [lam] (Just (map Var ivs)) (map snd as) ppSOAC :: Pretty fn => String -> SubExp -> [fn] -> Maybe [SubExp] -> [VName] -> Doc ppSOAC name size funs es as = text name <> parens (ppr size <> comma </> ppList funs </> commasep (es' ++ map ppr as)) where es' = maybe [] ((:[]) . ppTuple') es ppList :: Pretty a => [a] -> Doc ppList as = case map ppr as of [] -> mempty a':as' -> foldl (</>) (a' <> comma) $ map (<> comma) as'
mrakgr/futhark
src/Futhark/Representation/SOACS/SOAC.hs
bsd-3-clause
28,171
19
26
7,549
8,603
4,275
4,328
542
8
{-# OPTIONS -XCPP #-} module PreventGoingBack ( preventBack) where import System.IO.Unsafe import Control.Concurrent.MVar -- #define ALONE -- to execute it alone, uncomment this #ifdef ALONE import MFlow.Wai.Blaze.Html.All main= runNavigation "" $ transientNav preventBack #else import MFlow.Wai.Blaze.Html.All hiding(page) import Menu #endif rpaid= unsafePerformIO $ newMVar (0 :: Int) preventBack= do page $ wlink "don't care" << b << "press here to pay 100000 $ " payIt paid <- liftIO $ readMVar rpaid preventGoingBack . page $ p << "You already paid 100000 before" ++> p << "you can not go back until the end of the buy process" ++> wlink () << p << "Please press here to continue" page $ p << ("you paid "++ show paid) ++> wlink () << p << "Press here to go to the menu or press the back button to verify that you can not pay again" where payIt= liftIO $ do print "paying" paid <- takeMVar rpaid putMVar rpaid $ paid + 100000 -- to run it alone, change page by ask and uncomment this: --main= runNavigation "" $ transientNav preventBack
agocorona/MFlow
Demos/PreventGoingBack.hs
bsd-3-clause
1,191
0
14
327
228
117
111
20
1
{-# LINE 1 "Data.Int.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Int -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Signed integer types -- ----------------------------------------------------------------------------- module Data.Int ( -- * Signed integer types Int, Int8, Int16, Int32, Int64, -- * Notes -- $notes ) where import GHC.Base ( Int ) import GHC.Int ( Int8, Int16, Int32, Int64 ) {- $notes * All arithmetic is performed modulo 2^n, where @n@ is the number of bits in the type. * For coercing between any two integer types, use 'Prelude.fromIntegral', which is specialized for all the common cases so should be fast enough. Coercing word types (see "Data.Word") to and from integer types preserves representation, not sign. * The rules that hold for 'Prelude.Enum' instances over a bounded type such as 'Int' (see the section of the Haskell report dealing with arithmetic sequences) also hold for the 'Prelude.Enum' instances over the various 'Int' types defined here. * Right and left shifts by amounts greater than or equal to the width of the type result in either zero or -1, depending on the sign of the value being shifted. This is contrary to the behaviour in C, which is undefined; a common interpretation is to truncate the shift count to the width of the type, for example @1 \<\< 32 == 1@ in some C implementations. -}
phischu/fragnix
builtins/base/Data.Int.hs
bsd-3-clause
1,746
0
5
367
73
54
19
8
0
{-- snippet all --} divBy :: Integral a => a -> [a] -> Maybe [a] divBy numerator denominators = mapM (numerator `safeDiv`) denominators where safeDiv _ 0 = Nothing safeDiv x y = x `div` y {-- /snippet all --}
binesiyu/ifl
examples/ch19/divby2m.hs
mit
228
0
9
59
81
44
37
5
2
{-# LANGUAGE OverloadedStrings #-} module Network.Google.Drive.SearchSpec ( main , spec ) where import SpecHelper import Data.Text (Text) main :: IO () main = hspec spec spec :: Spec spec = describe "Network.Google.Drive.Search" $ do it "can list files based on a query" $ do runApiSpec $ \folder -> do mapM_ createFile [ setParent folder $ newFile "test-file-1" Nothing , setParent folder $ newFile "test-file-2" Nothing , setParent folder $ newFile "test-file-3" Nothing , setParent folder $ newFile "test-file-4" Nothing ] files <- listFiles $ fileId folder `qIn` Parents ?&& (Title ?= ("test-file-1" :: Text) ?|| Title ?= ("test-file-3" :: Text)) map (fileTitle . fileData) files `shouldMatchList` ["test-file-1", "test-file-3"]
pbrisbin/google-drive
test/Network/Google/Drive/SearchSpec.hs
mit
952
0
21
327
233
122
111
23
1
----------------------------------------------------------------------------- -- -- Module : Transient.Move.Internals -- Copyright : -- License : MIT -- -- Maintainer : [email protected] -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable , ExistentialQuantification, OverloadedStrings ,ScopedTypeVariables, StandaloneDeriving, RecordWildCards, FlexibleContexts, CPP ,GeneralizedNewtypeDeriving #-} module Transient.Move.Internals where import Transient.Internals import Transient.Logged hiding(logged) import Transient.Indeterminism -- import Transient.Backtrack import Transient.EVars import Data.Typeable import Control.Applicative #ifndef ghcjs_HOST_OS import Network --- import Network.Info import Network.URI --import qualified Data.IP as IP import qualified Network.Socket as NS import qualified Network.BSD as BSD import qualified Network.WebSockets as NWS -- S(RequestHead(..)) import qualified Network.WebSockets.Connection as WS import Network.WebSockets.Stream hiding(parse) import qualified Data.ByteString as B(ByteString,concat) import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy.Internal as BLC import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BS import Network.Socket.ByteString as SBS(sendMany,sendAll,recv) import qualified Network.Socket.ByteString.Lazy as SBSL import Data.CaseInsensitive(mk) import Data.Char(isSpace) -- import System.Random #else import JavaScript.Web.WebSocket import qualified JavaScript.Web.MessageEvent as JM import GHCJS.Prim (JSVal) import GHCJS.Marshal(fromJSValUnchecked) import qualified Data.JSString as JS import JavaScript.Web.MessageEvent.Internal import GHCJS.Foreign.Callback.Internal (Callback(..)) import qualified GHCJS.Foreign.Callback as CB import Data.JSString (JSString(..), pack) #endif import Control.Monad.State -- import System.IO import Control.Exception hiding (onException,try) import Data.Maybe --import Data.Hashable --import System.Directory -- import Control.Monad import System.IO.Unsafe import Control.Concurrent.STM as STM import Control.Concurrent.MVar import Data.Monoid import qualified Data.Map as M import Data.List (nub,(\\)) -- ,find, insert) import Data.IORef -- import System.IO import Control.Concurrent -- import Data.Dynamic import Data.String import System.Mem.StableName import Unsafe.Coerce --import System.Random #ifdef ghcjs_HOST_OS type HostName = String newtype PortID = PortNumber Int deriving (Read, Show, Eq, Typeable) #endif data Node= Node{ nodeHost :: HostName , nodePort :: Int , connection :: Maybe (MVar Pool) , nodeServices :: Service } deriving (Typeable) instance Ord Node where compare node1 node2= compare (nodeHost node1,nodePort node1)(nodeHost node2,nodePort node2) -- The cloud monad is a thin layer over Transient in order to make sure that the type system -- forces the logging of intermediate results newtype Cloud a= Cloud {runCloud' ::TransIO a} deriving (Functor,Applicative,Monoid,Alternative, Monad, Num, MonadState EventF) -- | Execute a distributed computation inside a TransIO computation. -- All the computations in the TransIO monad that enclose the cloud computation must be `logged` runCloud :: Cloud a -> TransIO a runCloud x= do closRemote <- getSData <|> return (RemoteClosures M.empty True) runCloud' x <*** setData closRemote --instance Monoid a => Monoid (Cloud a) where -- mappend x y = mappend <$> x <*> y -- mempty= return mempty #ifndef ghcjs_HOST_OS --- empty Hooks for TLS {-# NOINLINE tlsHooks #-} tlsHooks ::IORef (SData -> BS.ByteString -> IO () ,SData -> IO B.ByteString ,NS.Socket -> BS.ByteString -> TransIO () ,String -> NS.Socket -> BS.ByteString -> TransIO ()) tlsHooks= unsafePerformIO $ newIORef ( notneeded , notneeded , \_ i -> tlsNotSupported i , \_ _ _-> return()) where notneeded= error "TLS hook function called" tlsNotSupported input = do if ((not $ BL.null input) && BL.head input == 0x16) then do conn <- getSData sendRaw conn $ BS.pack $ "HTTP/1.0 525 SSL Handshake Failed\r\nContent-Length: 0\nConnection: close\r\n\r\n" else return () (sendTLSData,recvTLSData,maybeTLSServerHandshake,maybeClientTLSHandshake)= unsafePerformIO $ readIORef tlsHooks #endif -- | Means that this computation will be executed in the current node. the result will be logged -- so the closure will be recovered if the computation is translated to other node by means of -- primitives like `beamTo`, `forkTo`, `runAt`, `teleport`, `clustered`, `mclustered` etc local :: Loggable a => TransIO a -> Cloud a local = Cloud . logged --stream :: Loggable a => TransIO a -> Cloud (StreamVar a) --stream= Cloud . transport -- #ifndef ghcjs_HOST_OS -- | Run a distributed computation inside the IO monad. Enables asynchronous -- console input (see 'keep'). runCloudIO :: Typeable a => Cloud a -> IO (Maybe a) runCloudIO (Cloud mx)= keep mx -- | Run a distributed computation inside the IO monad with no console input. runCloudIO' :: Typeable a => Cloud a -> IO (Maybe a) runCloudIO' (Cloud mx)= keep' mx -- #endif -- | alternative to `local` It means that if the computation is translated to other node -- this will be executed again if this has not been executed inside a `local` computation. -- -- > onAll foo -- > local foo' -- > local $ do -- > bar -- > runCloud $ do -- > onAll baz -- > runAt node .... -- > callTo node' ..... -- -- Here foo will be executed in node' but foo' bar and baz don't. -- -- However foo bar and baz will e executed in node. -- onAll :: TransIO a -> Cloud a onAll = Cloud -- | only executes if the result is demanded. It is useful when the conputation result is only used in -- the remote node, but it is not serializable. lazy :: TransIO a -> Cloud a lazy mx= onAll $ getCont >>= \st -> Transient $ return $ unsafePerformIO $ runStateT (runTrans mx) st >>= return .fst -- | executes a non-serilizable action in the remote node, whose result can be used by subsequent remote invocations fixRemote mx= do r <- lazy mx fixClosure return r -- | experimental: subsequent remote invocatioms will send logs to this closure. Therefore logs will be shorter. -- -- Also, non serializable statements before it will not be re-executed fixClosure= atRemote $ local $ async $ return () -- log the result a cloud computation. like `loogged`, this erases all the log produced by computations -- inside and substitute it for that single result when the computation is completed. loggedc :: Loggable a => Cloud a -> Cloud a loggedc (Cloud mx)= Cloud $ do closRemote <- getSData <|> return (RemoteClosures M.empty True) logged mx <*** setData closRemote loggedc' :: Loggable a => Cloud a -> Cloud a loggedc' (Cloud mx)= Cloud $ logged mx -- do -- return () !> ("LOGGEDC") -- r <- logged mx -- --logged $ do -- Log rec _ fulLog <- getSData -- when (not rec) $ do -- mconn <- getData -- when (isJust mconn) $ do -- let Connection{localClosures=localClosures}= fromJust mconn -- liftIO $ modifyMVar_ localClosures $ \map -> return $ M.map (\(_,cont)-> (fulLog,cont)) map --return $ M.insert closLocal (fulLog,cont) map -- return () !> ("loggedc adjusting to", length fulLog ,reverse fulLog) -- modifyState -- $ \mcls -> let RemoteClosures cls first= fromMaybe (RemoteClosures M.empty True) mcls -- len= length fulLog -- hash = sum $ map ( \x -> case x of -- Wait -> 100000; -- Exec -> 1000 -- _ -> 1) fulLog -- newMap= M.map (\(o@(cl,n)) -> if cl > hash then (cl, len) else o) cls -- in Just $ RemoteClosures newMap first -- return r logged :: Loggable a => TransIO a -> TransIO a logged mx = Transient $ do Log recover rs full <- getData `onNothing` return ( Log False [][]) runTrans $ case (recover ,rs) of -- !> ("logged enter",recover,rs) of (True, Var x: rs') -> do setData $ Log True rs' full return $ fromIDyn x -- !> ("Var:", x) (True, Exec:rs') -> do setData $ Log True rs' full r <- mx return r -- !> "Exec" (True, Wait:rs') -> do setData (Log True rs' full) -- !> "Wait" empty _ -> do -- let add= Exec: full setData $ Log False (Exec : rs) (Exec: full) -- !> ("setLog False", Exec:rs) r <- mx <** ( do -- when p1 <|> p2, to avoid the re-execution of p1 at the -- recovery when p1 is asynchronous r <- getSData <|> return NoRemote case r of WasParallel -> -- let add= Wait: full setData $ Log False (Wait: rs) (Wait: full) _ -> return ()) Log recoverAfter lognew _ <- getData `onNothing` return ( Log False [][]) let add= Var (toIDyn r): full if recoverAfter && (not $ null lognew) -- !> ("recoverAfter", recoverAfter) then (setData $ Log True lognew (reverse lognew ++ add) ) -- !> ("recover",reverse lognew ,add) else if recoverAfter && (null lognew) then setData $ Log False [] add else (setData $ Log False (Var (toIDyn r):rs) add) -- !> ("restore", (Var (toIDyn r):rs)) mconn <- getData when (isJust mconn) $ do let Connection{localClosures=localClosures}= fromJust mconn liftIO $ modifyMVar_ localClosures $ \map -> return $ M.map (\(_,cont)-> (full,cont)) map --return $ M.insert closLocal (fulLog,cont) map return () !> ("loggedc adjusting to", length full ,reverse full) modifyState $ \mcls -> let RemoteClosures cls first= fromMaybe (RemoteClosures M.empty True) mcls len= length full hash = sum $ map ( \x -> case x of Wait -> 100000; Exec -> 1000 _ -> 1) full newMap= M.map (\(o@(cl,n)) -> if cl > hash then (cl, len) else o) cls in Just $ RemoteClosures newMap first return r -- | the `Cloud` monad has no `MonadIO` instance. `lliftIO= local . liftIO` lliftIO :: Loggable a => IO a -> Cloud a lliftIO= local . liftIO -- | locally perform IO. `localIO = lliftIO` localIO :: Loggable a => IO a -> Cloud a localIO= lliftIO -- | stop the current computation and does not execute any alternative computation fullStop :: TransIO stop fullStop= setData WasRemote >> stop -- | continue the execution in a new node beamTo :: Node -> Cloud () beamTo node = wormhole node teleport -- | execute in the remote node a process with the same execution state forkTo :: Node -> Cloud () forkTo node= beamTo node <|> return() -- | open a wormhole to another node and executes an action on it. -- currently by default it keep open the connection to receive additional requests -- and responses (streaming) callTo :: Loggable a => Node -> Cloud a -> Cloud a callTo node remoteProc= wormhole node $ atRemote remoteProc -- wormhole node $ do -- relay <- local $ do -- conn <- getState <|> error ("no connection with node: " ++ show node) -- case connData conn of -- Just (Relay conn remoteNode) -> do -- setData conn !> "callTo RELAY" -- return $ Just remoteNode -- _ -> return Nothing -- case relay of -- Just remoteNode -> -- atRemote $ callTo remoteNode remoteProc -- _ -> -- atRemote remoteProc !> "callTo NO RELAY" #ifndef ghcjs_HOST_OS -- | A connectionless version of callTo for long running remote calls callTo' :: (Show a, Read a,Typeable a) => Node -> Cloud a -> Cloud a callTo' node remoteProc= do mynode <- local $ getNodes >>= return . head beamTo node r <- remoteProc beamTo mynode return r #endif -- | Within a connection to other node opened by `wormhole`, it run the computation in the remote node and return -- the result back to the original node. -- -- If `atRemote` is executed in the remote node, then the computation is executed in the original node -- -- > wormhole node2 $ do -- > t <- atRemote $ do -- > r <- foo -- executed in node2 -- > s <- atRemote bar r -- executed in the original node -- > baz s -- in node2 -- > bat t -- in the original node atRemote :: Loggable a => Cloud a -> Cloud a atRemote proc= loggedc' $ do was <- lazy $ getSData <|> return NoRemote teleport -- !> "teleport 1111" r <- Cloud $ runCloud' proc <** setData WasRemote teleport -- !> "teleport 2222" lazy $ setData was return r -- | Execute a computation in the node that initiated the connection. -- -- if the sequence of connections is n1 -> n2 -> n3 then `atCallingNode $ atCallingNode foo` in n3 -- would execute `foo` in n1, -- while `atRemote $ atRemote foo` would execute it in n3 -- atCallingNode :: Loggable a => Cloud a -> Cloud a -- atCallingNode proc= connectCaller $ atRemote proc -- | synonymous of `callTo` runAt :: Loggable a => Node -> Cloud a -> Cloud a runAt= callTo -- | run a single thread with that action for each connection created. -- When the same action is re-executed within that connection, all the threads generated by the previous execution -- are killed -- -- > box <- foo -- > r <- runAt node . local . single $ getMailbox box -- > localIO $ print r -- -- if foo return differnt mainbox indentifiers, the above code would print the -- messages of the last one. -- Without single, it would print the messages of all of them. single :: TransIO a -> TransIO a single f= do cutExceptions Connection{closChildren=rmap} <- getSData <|> error "single: only works within a wormhole" mapth <- liftIO $ readIORef rmap id <- liftIO $ f `seq` makeStableName f >>= return . hashStableName case M.lookup id mapth of Just tv -> liftIO $ killBranch' tv -- !> "JUSTTTTTTTTT" Nothing -> return () -- !> "NOTHING" tv <- get f <** do id <- liftIO $ makeStableName f >>= return . hashStableName liftIO $ modifyIORef rmap $ \mapth -> M.insert id tv mapth -- | run an unique continuation for each connection. The first thread that execute `unique` is -- executed for that connection. The rest are ignored. unique :: a -> TransIO () unique f= do Connection{closChildren=rmap} <- getSData <|> error "unique: only works within a connection. Use wormhole" mapth <- liftIO $ readIORef rmap id <- liftIO $ f `seq` makeStableName f >>= return . hashStableName let mx = M.lookup id mapth case mx of Just _ -> empty Nothing -> do tv <- get liftIO $ modifyIORef rmap $ \mapth -> M.insert id tv mapth --data ParentConnection= ParentConnection Connection (Maybe Closure) deriving Typeable -- | A wormhole opens a connection with another node anywhere in a computation. -- `teleport` uses this connection to translate the computation back and forth between the two nodes connected wormhole :: Loggable a => Node -> Cloud a -> Cloud a wormhole node (Cloud comp) = local $ Transient $ do moldconn <- getData :: StateIO (Maybe Connection) -- mclosures <- getData :: StateIO (Maybe RemoteClosures) -- when (isJust moldconn) . setState $ ParentConnection (fromJust moldconn) mclosure -- labelState $ "wormhole" ++ show node Log rec _ _ <- getData `onNothing` return (Log False [][]) if not rec then runTrans $ (do --moldcom <- getData conn <- mconnect node liftIO $ writeIORef (remoteNode conn) $ Just node setData conn{calling= True} -- setData $ (Closure 0 ) modifyState $ \mcls -> let RemoteClosures cls first= fromMaybe (RemoteClosures M.empty True) mcls in Just $ RemoteClosures cls True comp ) <*** do when (isJust moldconn) . setData $ fromJust moldconn -- when (isJust mclosure) . setData $ fromJust mclosure -- <** is not enough since comp may be reactive else do let conn = fromMaybe (error "wormhole: no connection in remote node") moldconn setData $ conn{calling= False} runTrans $ comp -- <*** do when (isJust mclosure) . setData $ fromJust mclosure -- | connect to the caller node. -- connectCaller :: Loggable a => Cloud a -> Cloud a -- connectCaller (Cloud comp)= local $ do -- conn <- getState !> "CONNECTCALLER" -- case connData conn of -- Nothing -> empty -- Just Self -> empty -- _ -> if not $ calling conn !> ("calling", calling conn) then comp else do -- ParentConnection conn mmclosure <- getState <|> error "connectCaller: No connection defined: use wormhole" -- moldconn <- getData :: TransIO (Maybe Connection) -- mclosure <- getData :: TransIO (Maybe Closure) -- -- labelState $ "wormhole" ++ show node -- Log rec _ _ <- getData `onNothing` return (Log False [][]) -- if not rec -- then do -- -- liftIO $ writeIORef (remoteNode conn) $ Just node -- setData conn{calling= True} -- setData $ if (isJust mmclosure) -- then fromJust mmclosure -- else Closure 0 -- comp -- <*** do when (isJust moldconn) . setData $ fromJust moldconn -- when (isJust mclosure) . setData $ fromJust mclosure -- -- <** is not enough since comp may be reactive -- else do -- let conn = fromMaybe (error "wormhole: no connection in remote node") moldconn -- setData $ conn{calling= False} -- comp -- <*** do when (isJust mclosure) . setData $ fromJust mclosure #ifndef ghcjs_HOST_OS type JSString= String pack= id #endif data CloudException = CloudException IdClosure String deriving (Typeable, Show, Read) instance Exception CloudException teleport :: Cloud () teleport = do local $ Transient $ do Log rec log fulLog <- getData `onNothing` return (Log False [][]) conn@Connection{connData=contype,localClosures= localClosures,calling= calling} <- getData `onNothing` error "teleport: No connection defined: use wormhole" if not rec -- !> ("teleport rec,loc fulLog=",rec,log,fulLog) -- if is not recovering in the remote node then it is active then do -- when a node call itself, there is no need of socket communications #ifndef ghcjs_HOST_OS case contype of Just Self -> runTrans $ do setData $ if (not calling) then WasRemote else WasParallel abduce -- !> "SELF" -- call himself liftIO $ do remote <- readIORef $ remoteNode conn writeIORef (myNode conn) $ fromMaybe (error "teleport: no connection?") remote _ -> do #else do #endif --read this Closure RemoteClosures cls first <- getData `onNothing` return (RemoteClosures M.empty True !> "NO CLOSURES") let (closRemote,len) = fromMaybe (0,0) $ M.lookup (idConn conn) cls let closLocal = sum $ map ( \x -> case x of Wait -> 100000; Exec -> 1000 _ -> 1) fulLog --set his own closure in his Node data -- closLocal <- liftIO $ randomRIO (0,1000000) -- node <- runTrans getMyNode -- let tosend= reverse $ if closRemote==0 then fulLog else log return () !> ("FIRST", first) tosend <- if not first then return $ reverse log else do setState $ RemoteClosures cls False -- let fragments mnext= if closRemote == 0 then reverse fulLog else -- idx ++case mnext of -- Nothing -> [] -- Just next -> let (idx',_,mnext')= fromMaybe ([],0,Nothing) $ M.lookup next cls -- in idx'++ fragments mnext' return $ (drop len $ reverse fulLog) delData NoRemote cont <- get liftIO $ modifyMVar_ localClosures $ \map -> return $ M.insert closLocal (fulLog,cont) map -- remove first idx element of the log. the log sent is in the order of execution. log is in reverse order -- send log with closure ids at head runTrans $ do msend conn $ SMore $ ClosureData closRemote closLocal (length fulLog) tosend !> ("teleport sending", SMore (unsafePerformIO $ readIORef $ remoteNode conn,closRemote,closLocal,length fulLog, tosend)) !> "--------->------>---------->" !> ("log",reverse log) setData $ if (not calling) then WasRemote else WasParallel -- !> "SET WASPAraLLEL" return Nothing else do -- runTrans $ onException $ \(e :: SomeException) -> do -- Closure closRemote <- getData `onNothing` error "teleport: no closRemote" -- msend conn $ SError $ toException $ CloudException closRemote $ show e delData WasRemote -- !> "deleting wasremote in teleport" -- it is recovering, therefore it will be the -- local, not remote return (Just ()) -- !> "TELEPORT remote" -- | copy a session data variable from the local to the remote node. -- If there is none set in the local node, The parameter is the default value. -- In this case, the default value is also set in the local node. copyData def = do r <- local getSData <|> return def onAll $ setData r return r -- | write to the mailbox -- Mailboxes are node-wide, for all processes that share the same connection data, that is, are under the -- same `listen` or `connect` -- while EVars are only visible by the process that initialized it and his children. -- Internally, the mailbox is in a well known EVar stored by `listen` in the `Connection` state. putMailbox :: Typeable a => a -> TransIO () putMailbox = putMailbox' (0::Int) -- | write to a mailbox identified by an identifier besides the type putMailbox' :: (Typeable b, Ord b, Typeable a) => b -> a -> TransIO () putMailbox' idbox dat= do let name= MailboxId idbox $ typeOf dat Connection{comEvent= mv} <- getData `onNothing` errorMailBox mbs <- liftIO $ readIORef mv let mev = M.lookup name mbs case mev of Nothing ->newMailbox name >> putMailbox' idbox dat Just ev -> writeEVar ev $ unsafeCoerce dat newMailbox :: MailboxId -> TransIO () newMailbox name= do -- return () -- !> "newMailBox" Connection{comEvent= mv} <- getData `onNothing` errorMailBox ev <- newEVar liftIO $ atomicModifyIORef mv $ \mailboxes -> (M.insert name ev mailboxes,()) errorMailBox= error "MailBox: No connection open. Use wormhole" -- | get messages from the mailbox that matches with the type expected. -- The order of reading is defined by `readTChan` -- This is reactive. it means that each new message trigger the execution of the continuation -- each message wake up all the `getMailbox` computations waiting for it. getMailbox :: Typeable a => TransIO a getMailbox = getMailbox' (0 :: Int) -- | read from a mailbox identified by an identifier besides the type getMailbox' :: (Typeable b, Ord b, Typeable a) => b -> TransIO a getMailbox' mboxid = x where x = do let name= MailboxId mboxid $ typeOf $ typeOf1 x Connection{comEvent= mv} <- getData `onNothing` errorMailBox mbs <- liftIO $ readIORef mv let mev = M.lookup name mbs case mev of Nothing ->newMailbox name >> getMailbox' mboxid Just ev ->unsafeCoerce $ readEVar ev typeOf1 :: TransIO a -> a typeOf1 = undefined -- | delete all subscriptions for that mailbox expecting this kind of data cleanMailbox :: Typeable a => a -> TransIO () cleanMailbox = cleanMailbox' 0 -- | clean a mailbox identified by an Int and the type cleanMailbox' :: Typeable a => Int -> a -> TransIO () cleanMailbox' mboxid witness= do let name= MailboxId mboxid $ typeOf witness Connection{comEvent= mv} <- getData `onNothing` error "getMailBox: accessing network events out of listen" mbs <- liftIO $ readIORef mv let mev = M.lookup name mbs case mev of Nothing -> return() Just ev -> do cleanEVar ev liftIO $ atomicModifyIORef mv $ \mbs -> (M.delete name mbs,()) -- | execute a Transient action in each of the nodes connected. -- -- The response of each node is received by the invoking node and processed by the rest of the procedure. -- By default, each response is processed in a new thread. To restrict the number of threads -- use the thread control primitives. -- -- this snippet receive a message from each of the simulated nodes: -- -- > main = keep $ do -- > let nodes= map createLocalNode [2000..2005] -- > addNodes nodes -- > (foldl (<|>) empty $ map listen nodes) <|> return () -- > -- > r <- clustered $ do -- > Connection (Just(PortNumber port, _, _, _)) _ <- getSData -- > return $ "hi from " ++ show port++ "\n" -- > liftIO $ putStrLn r -- > where -- > createLocalNode n= createNode "localhost" (PortNumber n) clustered :: Loggable a => Cloud a -> Cloud a clustered proc= callNodes (<|>) empty proc -- A variant of `clustered` that wait for all the responses and `mappend` them mclustered :: (Monoid a, Loggable a) => Cloud a -> Cloud a mclustered proc= callNodes (<>) mempty proc callNodes op init proc= loggedc' $ do nodes <- local getEqualNodes callNodes' nodes op init proc callNodes' nodes op init proc= loggedc' $ foldr op init $ map (\node -> runAt node proc) nodes ----- #ifndef ghcjs_HOST_OS sendRaw (Connection _ _ _ (Just (Node2Web sconn )) _ _ _ _ _ _) r= liftIO $ WS.sendTextData sconn r -- !> ("NOde2Web",r) sendRaw (Connection _ _ _ (Just (Node2Node _ sock _)) _ _ blocked _ _ _) r= liftIO $ withMVar blocked $ const $ SBS.sendMany sock (BL.toChunks r ) -- !> ("NOde2Node",r) sendRaw (Connection _ _ _(Just (TLSNode2Node ctx )) _ _ blocked _ _ _) r= liftIO $ withMVar blocked $ const $ sendTLSData ctx r -- !> ("TLNode2Web",r) #else sendRaw (Connection _ _ _ (Just (Web2Node sconn)) _ _ blocked _ _ _) r= liftIO $ withMVar blocked $ const $ JavaScript.Web.WebSocket.send r sconn -- !!> "MSEND SOCKET" #endif sendRaw _ _= error "No connection stablished" type LengthFulLog= Int data NodeMSG= ClosureData IdClosure IdClosure LengthFulLog CurrentPointer | RelayMSG Node Node (StreamData NodeMSG) | Control IDynamic deriving (Typeable, Read, Show) msend :: MonadIO m => Connection -> StreamData NodeMSG -> m () #ifndef ghcjs_HOST_OS msend (Connection _ _ _ (Just (Node2Node _ sock _)) _ _ blocked _ _ _) r=do liftIO $ withMVar blocked $ const $ SBS.sendAll sock $ BC.pack (show r) -- !> ("N2N SEND", r) msend (Connection _ _ _ (Just (TLSNode2Node ctx)) _ _ _ _ _ _) r= liftIO $ sendTLSData ctx $ BS.pack (show r) -- !> "TLS SEND" msend (Connection _ _ _ (Just (Node2Web sconn)) _ _ _ _ _ _) r=liftIO $ {-withMVar blocked $ const $ -} WS.sendTextData sconn $ BS.pack (show r) -- !> "websockets send" msend((Connection _ myNode _ (Just (Relay conn remote )) _ _ _ _ _ _)) r= do origin <- liftIO $ readIORef myNode -- `onNothing` error "msend: no remote node in connection" -- msend conn $ SMore (ClosureData 0 0 [Var $ IDynamic (),Var . IDynamic $ origin{nodeServices=[]} -- ,Var $ IDynamic remote{nodeServices=[]},Var $ IDynamic r]) -- writeEVar req r !> "msed relay" msend conn $ SMore $ RelayMSG origin remote r #else msend (Connection _ _ (Just (Web2Node sconn)) _ _ blocked _ _ _) r= liftIO $ withMVar blocked $ const $ JavaScript.Web.WebSocket.send (JS.pack $ show r) sconn -- !!> "MSEND SOCKET" #endif msend (Connection _ _ _ Nothing _ _ _ _ _ _) _= error "msend out of wormhole context" mread :: Loggable a => Connection -> TransIO (StreamData a) #ifdef ghcjs_HOST_OS mread (Connection _ _ (Just (Web2Node sconn)) _ _ _ _ _ _)= wsRead sconn wsRead :: Loggable a => WebSocket -> TransIO a wsRead ws= do dat <- react (hsonmessage ws) (return ()) case JM.getData dat of JM.StringData str -> return (read' $ JS.unpack str) -- !> ("Browser webSocket read", str) !> "<------<----<----<------" JM.BlobData blob -> error " blob" JM.ArrayBufferData arrBuffer -> error "arrBuffer" wsOpen :: JS.JSString -> TransIO WebSocket wsOpen url= do ws <- liftIO $ js_createDefault url -- !> ("wsopen",url) react (hsopen ws) (return ()) -- !!> "react" return ws -- !!> "AFTER ReACT" foreign import javascript safe "window.location.hostname" js_hostname :: JSVal foreign import javascript safe "window.location.protocol" js_protocol :: JSVal foreign import javascript safe "(function(){var res=window.location.href.split(':')[2];if (res === undefined){return 80} else return res.split('/')[0];})()" js_port :: JSVal foreign import javascript safe "$1.onmessage =$2;" js_onmessage :: WebSocket -> JSVal -> IO () getWebServerNode :: TransIO Node getWebServerNode = liftIO $ do h <- fromJSValUnchecked js_hostname p <- fromIntegral <$> (fromJSValUnchecked js_port :: IO Int) createNode h p hsonmessage ::WebSocket -> (MessageEvent ->IO()) -> IO () hsonmessage ws hscb= do cb <- makeCallback MessageEvent hscb js_onmessage ws cb foreign import javascript safe "$1.onopen =$2;" js_open :: WebSocket -> JSVal -> IO () newtype OpenEvent = OpenEvent JSVal deriving Typeable hsopen :: WebSocket -> (OpenEvent ->IO()) -> IO () hsopen ws hscb= do cb <- makeCallback OpenEvent hscb js_open ws cb makeCallback :: (JSVal -> a) -> (a -> IO ()) -> IO JSVal makeCallback f g = do Callback cb <- CB.syncCallback1 CB.ContinueAsync (g . f) return cb foreign import javascript safe "new WebSocket($1)" js_createDefault :: JS.JSString -> IO WebSocket #else mread (Connection _ _ _(Just (Node2Node _ _ _)) _ _ _ _ _ _) = parallelReadHandler -- !> "mread" mread (Connection _ _ _ (Just (TLSNode2Node _)) _ _ _ _ _ _) = parallelReadHandler -- parallel $ do -- s <- recvTLSData ctx -- return . read' $ BC.unpack s mread (Connection _ _ _ (Just (Node2Web sconn )) _ _ _ _ _ _)= parallel $ do s <- WS.receiveData sconn return . read' $ BS.unpack s -- !> ("WS MREAD RECEIVED ----<----<------<--------", s) mread (Connection _ _ _ (Just (Relay conn _ )) _ _ _ _ _ _)= mread conn -- !> "MREAD RELAY" parallelReadHandler :: Loggable a => TransIO (StreamData a) parallelReadHandler= do str <- giveData :: TransIO BS.ByteString r <- choose $ readStream str return r !> ("parallel read handler read", r) !> "<-------<----------<--------<----------" where readStream :: (Typeable a, Read a) => BS.ByteString -> [StreamData a] readStream s= readStream1 $ BS.unpack s where readStream1 s= let [(x,r)] = reads s in x : readStream1 r getWebServerNode :: TransIO Node getWebServerNode = getNodes >>= return . head #endif read' s= case readsPrec' 0 s of [(x,"")] -> x _ -> error $ "reading " ++ s --release (Node h p rpool _) hand= liftIO $ do ---- print "RELEASED" -- atomicModifyIORef rpool $ \ hs -> (hand:hs,()) -- -- !!> "RELEASED" mclose :: Connection -> IO () #ifndef ghcjs_HOST_OS mclose (Connection _ _ _ (Just (Node2Node _ sock _ )) _ _ _ _ _ _)= NS.close sock mclose (Connection _ _ _ (Just (Node2Web sconn )) _ _ _ _ _ _)= WS.sendClose sconn ("closemsg" :: BS.ByteString) #else mclose (Connection _ _(Just (Web2Node sconn)) _ _ blocked _ _ _)= JavaScript.Web.WebSocket.close Nothing Nothing sconn #endif mconnect :: Node -> TransIO Connection mconnect node'= do node <- fixNode node' nodes <- getNodes return () -- !> ("mconnnect", nodePort node) let fnode = filter (==node) nodes case fnode of [] -> mconnect1 node -- !> "NO NODE" [node'@(Node _ _ pool _)] -> do plist <- liftIO $ readMVar $ fromJust pool case plist of -- !> ("length", length plist,nodePort node) of (handle:_) -> do -- delData $ Closure undefined return handle !> ("REUSED!", node) _ -> mconnect1 node' where #ifndef ghcjs_HOST_OS mconnect1 (node@(Node host port _ _))= do return () !> ("MCONNECT1",host,port,nodeServices node) -- (do -- liftIO $ when (host== "192.168.99.100" && (port == 8081 || port== 8080)) $ error "connnnn" !> "detected" (conn,parseContext) <- -- checkSelf node <|> timeout 1000000 (connectNode2Node host port) <|> timeout 1000000 (connectWebSockets host port) <|> checkRelay <|> (throwt $ ConnectionError "" node) setState conn setState parseContext -- return () !> "CONNECTED AFTER TIMEOUT" -- write node connected in the connection liftIO $ writeIORef (remoteNode conn) $ Just node -- write connection in the node liftIO $ modifyMVar_ (fromJust $ connection node) . const $ return [conn] addNodes [node] watchConnection --delData $ Closure undefined return conn where checkSelf node= do node' <- getMyNode if node /= node' then empty else do conn<- case connection node of Nothing -> error "checkSelf error" Just ref -> do events <- liftIO $ newIORef M.empty rnode <- liftIO $ newIORef node conn <- defConnection >>= \c -> return c{myNode= rnode, comEvent=events,connData= Just Self} !> "DEFF1" liftIO $ withMVar ref $ const $ return [conn] return conn return (conn,(ParseContext (error "checkSelf parse error") (error "checkSelf parse error") :: ParseContext BS.ByteString)) timeout t proc=do r <- collect' 1 t proc case r of [] -> empty r:_ -> return r checkRelay= do return () !> "RELAY" myNode <- getMyNode if nodeHost node== nodeHost myNode then case lookup "localNode" $ nodeServices node of Just snode -> do con <- mconnect $ read snode cont <- getSData <|> return noParseContext return (con,cont) Nothing -> empty else do case lookup "relay" $ nodeServices node of Nothing -> empty -- !> "NO RELAY" Just relayInfo -> do let relay= read relayInfo conn <- mconnect relay -- !> ("RELAY",relay, node) rem <- liftIO $ newIORef $ Just node -- clos <- liftIO $ newMVar $ M.empty let conn'= conn{connData= Just $ Relay conn node,remoteNode=rem} --,localClosures= clos} parseContext <- getState <|> return noParseContext return (conn', parseContext) noParseContext= (ParseContext (error "relay error") (error "relay error") :: ParseContext BS.ByteString) connectSockTLS host port= do -- return () !> "connectSockTLS" let size=8192 Connection{myNode=my,comEvent= ev} <- getSData <|> error "connect: listen not set for this node" sock <- liftIO $ connectTo' size host $ PortNumber $ fromIntegral port conn' <- defConnection >>= \c -> return c{myNode=my, comEvent= ev,connData= Just $ (Node2Node u sock (error $ "addr: outgoing connection"))} !> "DEFF2" setData conn' input <- liftIO $ SBSL.getContents sock setData $ ParseContext (error "parse context: Parse error") input maybeClientTLSHandshake host sock input `catcht` \(_ :: SomeException) -> empty connectNode2Node host port= do return () !> "NODE 2 NODE" connectSockTLS host port conn <- getSData <|> error "mconnect: no connection data" sendRaw conn "CLOS a b\r\n\r\n" r <- liftIO $ readFrom conn case r of "OK" -> do parseContext <- getState return (conn,parseContext) _ -> do let Connection{connData=cdata}= conn case cdata of Just(Node2Node _ s _) -> liftIO $ NS.close s -- since the HTTP firewall closes the connection -- Just(TLSNode2Node c) -> contextClose c -- TODO empty connectWebSockets host port = do return () !> "WEBSOCKETS" connectSockTLS host port -- a new connection never <- liftIO $ newEmptyMVar :: TransIO (MVar ()) conn <- getSData <|> error "connectWebSockets: no connection" stream <- liftIO $ makeWSStreamFromConn conn wscon <- react (NWS.runClientWithStream stream (host++(':': show port)) "/" WS.defaultConnectionOptions []) (takeMVar never) return (conn{connData= Just $ (Node2Web wscon)}, noParseContext) -- noConnection= error $ show node ++ ": no connection" watchConnection= do conn <- getSData parseContext <- getSData <|> error "NO PARSE CONTEXT" :: TransIO (ParseContext BS.ByteString) chs <- liftIO $ newIORef M.empty let conn'= conn{closChildren= chs} -- liftIO $ modifyMVar_ (fromJust pool) $ \plist -> do -- if not (null plist) then print "DUPLICATE" else return () -- return $ conn':plist -- !> (node,"ADDED TO POOL") -- tell listenResponses to watch incoming responses putMailbox ((conn',parseContext,node) :: (Connection,ParseContext BS.ByteString,Node)) liftIO $ threadDelay 100000 -- give time to initialize listenResponses #else mconnect1 (node@(Node host port (Just pool) _))= do -- my <- getMyNode Connection{myNode=my,comEvent= ev} <- getSData <|> error "connect: listen not set for this node" do ws <- connectToWS host $ PortNumber $ fromIntegral port -- !> "CONNECTWS" conn <- defConnection >>= \c -> return c{comEvent= ev,connData= Just (Web2Node ws)} -- !> ("websocker CONNECION") let parseContext = ParseContext (error "parsecontext not available in the browser") ("" :: JSString) chs <- liftIO $ newIORef M.empty let conn'= conn{closChildren= chs} liftIO $ modifyMVar_ pool $ \plist -> return $ conn':plist putMailbox (conn',parseContext,node) -- tell listenResponses to watch incoming responses delData $ Closure undefined return conn #endif u= undefined data ConnectionError= ConnectionError String Node deriving Show instance Exception ConnectionError -- mconnect _ = empty #ifndef ghcjs_HOST_OS connectTo' bufSize hostname (PortNumber port) = do proto <- BSD.getProtocolNumber "tcp" bracketOnError (NS.socket NS.AF_INET NS.Stream proto) (sClose) -- only done if there's an error (\sock -> do NS.setSocketOption sock NS.RecvBuffer bufSize NS.setSocketOption sock NS.SendBuffer bufSize -- NS.setSocketOption sock NS.SendTimeOut 1000000 !> ("CONNECT",port) he <- BSD.getHostByName hostname NS.connect sock (NS.SockAddrInet port (BSD.hostAddress he)) return sock) #else connectToWS h (PortNumber p) = do protocol <- liftIO $ fromJSValUnchecked js_protocol let ps = case (protocol :: JSString)of "http:" -> "ws://"; "https:" -> "wss://" wsOpen $ JS.pack $ ps++ h++ ":"++ show p #endif type Blocked= MVar () type BuffSize = Int data ConnectionData= #ifndef ghcjs_HOST_OS Node2Node{port :: PortID ,socket ::Socket ,sockAddr :: NS.SockAddr } | TLSNode2Node{tlscontext :: SData} | Node2Web{webSocket :: WS.Connection} -- | WS2Node{webSocketNode :: WS.Connection} | Self | Relay Connection Node -- (EVar (StreamData NodeMSG)) #else Self | Web2Node{webSocket :: WebSocket} #endif -- deriving (Eq,Ord) data MailboxId = forall a .(Typeable a, Ord a) => MailboxId a TypeRep instance Eq MailboxId where id1 == id2 = id1 `compare` id2== EQ instance Ord MailboxId where MailboxId n t `compare` MailboxId n' t'= case typeOf n `compare` typeOf n' of EQ -> case n `compare` unsafeCoerce n' of EQ -> t `compare` t' LT -> LT GT -> GT other -> other data Connection= Connection{idConn :: Int ,myNode :: IORef Node ,remoteNode :: IORef (Maybe Node) ,connData :: Maybe ConnectionData ,bufferSize :: BuffSize -- Used by getMailBox, putMailBox ,comEvent :: IORef (M.Map MailboxId (EVar SData)) -- multiple wormhole/teleport use the same connection concurrently ,blocked :: Blocked ,calling :: Bool -- local localClosures with his log and his continuation ,localClosures :: MVar (M.Map IdClosure ([LogElem], EventF)) -- for each remote closure that points to local closure 0, -- a new container of child processes -- in order to treat them separately -- so that 'killChilds' do not kill unrelated processes ,closChildren :: IORef (M.Map Int EventF)} deriving Typeable defConnection :: (MonadIO m, MonadState EventF m) => m Connection -- #ifndef ghcjs_HOST_OS defConnection = do idc <- genGlobalId liftIO $ do my <- newIORef (error "node in default connection") x <- newMVar () y <- newMVar M.empty noremote <- newIORef Nothing z <- return $ error "closchildren: newIORef M.empty" return $ Connection idc my noremote Nothing 8192 (error "defConnection: accessing network events out of listen") x False y z #ifndef ghcjs_HOST_OS setBuffSize :: Int -> TransIO () setBuffSize size= Transient $ do conn<- getData `onNothing` (defConnection !> "DEFF3") setData $ conn{bufferSize= size} return $ Just () getBuffSize= (do getSData >>= return . bufferSize) <|> return 8192 -- | Setup the node to start listening for incoming connections. -- listen :: Node -> Cloud () listen (node@(Node _ port _ _ )) = onAll $ do addThreads 1 setData $ Log False [] [] conn' <- getSData <|> (defConnection !> "DEFF4") ev <- liftIO $ newIORef M.empty chs <- liftIO $ newIORef M.empty let conn= conn'{connData=Just Self, comEvent=ev,closChildren=chs} pool <- liftIO $ newMVar [conn] let node'= node{connection=Just pool} liftIO $ writeIORef (myNode conn) node' setData conn liftIO $ modifyMVar_ (fromJust $ connection node') $ const $ return [conn] addNodes [node'] mlog <- listenNew (fromIntegral port) conn <|> listenResponses :: TransIO (StreamData NodeMSG) case mlog of SMore (RelayMSG _ _ _) -> relay mlog SMore (Control ctl) -> control ctl _ -> execLog mlog `catcht` (\(e ::SomeException) -> liftIO $ print e) -- relayService :: TransIO () relay (SMore (RelayMSG origin destiny streamdata)) = do nodes <- getNodes my <- getMyNode -- !> "relayService" if destiny== my then do case filter (==origin) nodes of [node] -> do (conn: _) <- liftIO $ readMVar $ fromJust $ connection node setData conn [] -> do conn@Connection{remoteNode= rorigin} <- getState let conn'= conn{connData= Just $ Relay conn origin} -- !> ("Relay set with: ", origin, destiny) pool <- liftIO $ newMVar [conn'] addNodes [origin{connection= Just pool}] setData conn' execLog streamdata else do -- search local node name if hostname is the same -- let destiny' = if nodeHost destiny== nodeHost my -- then -- case filter (==destiny) nodes of -- [node] -> case lookup "localNode" $ nodeServices node of -- Just snode -> read snode -- Nothing -> destiny -- _ -> destiny -- else destiny -- let origin'= if nodeHost origin == "localhost" -- then case filter (==origin) nodes of -- [node] ->case lookup "externalNode" $ nodeServices node of -- Just snode -> read snode -- Nothing -> origin -- _ -> origin -- else origin let (origin',destiny')= nat origin destiny my nodes con <- mconnect destiny' msend con . SMore $ RelayMSG origin' destiny' streamdata return () !> ("SEND RELAY DATA",streamdata) fullStop relay _= empty nat origin destiny my nodes= let destiny' = if nodeHost destiny== nodeHost my then case filter (==destiny) nodes of [node] -> case lookup "localNode" $ nodeServices node of Just snode -> read snode Nothing -> destiny _ -> destiny else destiny origin'= if nodeHost origin == "localhost" then case filter (==origin) nodes of [node] ->case lookup "externalNode" $ nodeServices node of Just snode -> read snode Nothing -> origin _ -> origin else origin in (origin',destiny') -- listen incoming requests listenNew port conn'= do sock <- liftIO . listenOn $ PortNumber port let bufSize= bufferSize conn' liftIO $ do NS.setSocketOption sock NS.RecvBuffer bufSize NS.setSocketOption sock NS.SendBuffer bufSize -- wait for connections. One thread per connection (sock,addr) <- waitEvents $ NS.accept sock chs <- liftIO $ newIORef M.empty -- case addr of -- NS.SockAddrInet port host -> liftIO $ print("connection from", port, host) -- NS.SockAddrInet6 a b c d -> liftIO $ print("connection from", a, b,c,d) noNode <- liftIO $ newIORef Nothing id1 <- genId let conn= conn'{idConn=id1,closChildren=chs, remoteNode= noNode} input <- liftIO $ SBSL.getContents sock cutExceptions onException $ \(e :: SomeException) -> do -- cutExceptions liftIO $ putStr "listen: " >> print e let Connection{remoteNode=rnode,localClosures=localClosures,closChildren= rmap} = conn -- TODO How to close Connection by discriminating exceptions mnode <- liftIO $ readIORef rnode case mnode of Nothing -> return () Just node -> do liftIO $ putStr "removing1 node: " >> print node nodes <- getNodes setNodes $ nodes \\ [node] liftIO $ do modifyMVar_ localClosures $ const $ return M.empty writeIORef rmap M.empty -- topState >>= showThreads -- cutExceptions killBranch setData $ (ParseContext (NS.close sock >> error "Communication error" ) input ::ParseContext BS.ByteString) setState conn{connData=Just (Node2Node (PortNumber port) sock addr)} maybeTLSServerHandshake sock input (method,uri, headers) <- receiveHTTPHead maybeSetHost headers case method of "CLOS" -> do conn <- getSData sendRaw conn "OK" -- !> "CLOS detected" mread conn _ -> do let uri'= BC.tail $ uriPath uri if "api/" `BC.isPrefixOf` uri' then do log <- return $ Exec: (Var $ IDyns $ BS.unpack method):(map (Var . IDyns ) $ split $ BC.unpack $ BC.drop 4 uri') str <- giveData <|> error "no api data" log' <- case (method,lookup "Content-Type" headers) of ("POST",Just "application/x-www-form-urlencoded") -> do len <- read <$> BC.unpack <$> (Transient $ return (lookup "Content-Length" headers)) setData $ ParseContext (return mempty) $ BS.take len str postParams <- parsePostUrlEncoded <|> return [] return $ log ++ [(Var . IDynamic $ postParams)] _ -> return $ log -- ++ [Var $ IDynamic str] return $ SMore $ ClosureData 0 0 0 log' else do -- stay serving pages until a websocket request is received servePages (method, uri', headers) conn <- getSData sconn <- makeWebsocketConnection conn uri headers -- websockets mode let conn'= conn{connData= Just (Node2Web sconn) , closChildren=chs} setState conn' -- !> "WEBSOCKETS-----------------------------------------------" onException $ \(e :: SomeException) -> do cutExceptions liftIO $ putStr "listen websocket:" >> print e --liftIO $ mclose conn' killBranch empty -- async (return (SMore (0,0,[Exec]))) <|> do do -- return () !> "WEBSOCKET" r <- parallel $ do msg <- WS.receiveData sconn return () -- !> ("Server WebSocket msg read",msg) -- !> "<-------<---------<--------------" case reads $ BS.unpack msg of [] -> do let log =Exec: [Var $ IDynamic (msg :: BS.ByteString)] return $ SMore (ClosureData 0 0 0 log) ((x ,_):_) -> return (x :: StreamData NodeMSG) -- StreamData (Int,Int,[LogElem])) case r of SError e -> do -- liftIO $ WS.sendClose sconn ("error" :: BS.ByteString) back e -- !> "FINISH1" _ -> return r where uriPath = BC.dropWhile (/= '/') split []= [] split ('/':r)= split r split s= let (h,t) = span (/= '/') s in h: split t maybeSetHost headers= do setHost <- liftIO $ readIORef rsetHost when setHost $ do mnode <- liftIO $ do let mhost= lookup "Host" headers case mhost of Nothing -> return Nothing Just host -> atomically $ do -- set the firt node (local node) as is called from outside nodes <- readTVar nodeList let (host1,port)= BC.span (/= ':') host hostnode= (head nodes){nodeHost= BC.unpack host1 ,nodePort= if BC.null port then 80 else read $ BC.unpack $ BC.tail port} writeTVar nodeList $ hostnode : tail nodes return $ Just hostnode -- !> (host1,port) when (isJust mnode) $ do conn <- getState liftIO $ writeIORef (myNode conn) $fromJust mnode liftIO $ writeIORef rsetHost False -- !> "HOSt SET" {-#NOINLINE rsetHost #-} rsetHost= unsafePerformIO $ newIORef True --instance Read PortNumber where -- readsPrec n str= let [(n,s)]= readsPrec n str in [(fromIntegral n,s)] --deriving instance Read PortID --deriving instance Typeable PortID #endif listenResponses :: Loggable a => TransIO (StreamData a) listenResponses= do (conn, parsecontext, node) <- getMailbox labelState $ "listen from: "++ show node -- return () !> ("LISTEN",case connData conn of Just (Relay _) -> "RELAY"; _ -> "OTHER") setData conn #ifndef ghcjs_HOST_OS setData (parsecontext :: ParseContext BS.ByteString) #else setData (parsecontext :: ParseContext JSString) #endif cutExceptions onException (\(e:: SomeException) -> do liftIO $ putStr "ListenResponses: " >> print e liftIO $ putStr "removing node: " >> print node nodes <- getNodes setNodes $ nodes \\ [node] -- topState >>= showThreads killChilds let Connection{localClosures=localClosures}= conn liftIO $ modifyMVar_ localClosures $ const $ return M.empty) mread conn type IdClosure= Int -- The remote closure ids for each node connection type LogIndex = Int type CommIndex= Int type FirstMessage = Bool type IdConn= Int data RemoteClosures= RemoteClosures (M.Map IdConn (IdClosure,LogIndex)) FirstMessage -- deriving Show {- como hacer para que control acceda a variables de una closure remota? solo con variables que estan ya definidas arriba con fixRemote var <-fixremote variable pero la variable no se puede reutilizar para la siguiente interaccion por tanto mejor matar todo el thread. Por otro lado puede haber grupos que hay que matar de distitos threds por ejemplo en cloudsheell y en el chat de distribApps con resetRemote mejor que con single. hay manera de hacer mas usable resetRemote? resetRemote identifier: resetea un grupo. -} newtype DeleteClosure= DeleteClosure IdClosure deriving (Typeable, Read, Show) resetRemote= local $ noTrans $ do conn <- getData `onNothing` error "Listen: myNode not set" RemoteClosures map _ <- getData `onNothing` error "resetRemote: Closure not set, use wormhole" let (closr,_)= fromMaybe (0,0) $ M.lookup (idConn conn) map resetRemote' conn closr resetRemote' conn closr = msend conn . SMore . Control . toIDyn $ DeleteClosure closr control ctl= Transient $ case maybeFromIDyn ctl of Just (DeleteClosure clos) -> do return () !> "DELETECLOSURE" if clos==0 then return Nothing else do conn@Connection {localClosures=localClosures} <- getData `onNothing` error "Listen: myNode not set" mcont <- liftIO $ modifyMVar localClosures $ \map -> return ( {- M.delete clos-} map, M.lookup clos map) case mcont of Nothing -> error $ "closure not found: " ++ show clos Just (fulLog,cont) -> do showThreads cont liftIO $ killChildren $ children cont return Nothing _ -> return Nothing execLog :: StreamData NodeMSG -> TransIO () execLog mlog = Transient $do return () !> "EXECLOG" case mlog of SError e -> case fromException e of Just (ErrorCall str) -> do let e@(CloudException closl err) = read str process closl (error "closl not used") 0 (Left e) True SDone -> runTrans(back $ ErrorCall "SDone") >> return Nothing -- TODO remove closure? SMore (ClosureData closl closr lfull log) -> process closl closr lfull (Right log) False SLast (ClosureData closl closr lfull log) -> process closl closr lfull (Right log) True -- !> ("EXECLOG",mlog) where process :: IdClosure -> IdClosure -> LengthFulLog -> (Either CloudException CurrentPointer) -> Bool -> StateIO (Maybe ()) process closl closr lfull mlog deleteClosure= do conn@Connection {localClosures=localClosures} <- getData `onNothing` error "Listen: myNode not set" if closl== 0 then case mlog of Left _ -> empty Right log -> do return () !>("IDX1", length log) setData $ Log True log $ reverse log !> "SETLOG1" --setData $ Closure closr modifyState $ \mcls -> let RemoteClosures cls first= fromMaybe (RemoteClosures M.empty False) mcls altr Nothing= Just (closr,0) altr (Just(_,n))= Just (closr,n) in Just $ RemoteClosures (M.alter altr (idConn conn) cls) False return $ Just () -- !> "executing top level closure" else do mcont <- liftIO $ modifyMVar localClosures $ \map -> return (if deleteClosure then M.delete closl map else map, M.lookup closl map) -- !> ("localClosures=", M.size map) case mcont of Nothing -> do -- -- if closl == 0 -- add what is after execLog as closure 0 -- then do -- setData $ Log True log $ reverse log -- setData $ Closure closr -- cont <- get !> ("CLOSL","000000000") -- liftIO $ modifyMVar localClosures -- $ \map -> return (M.insert closl ([],cont) map,()) -- return $ Just () --exec what is after execLog (closure 0) -- -- else do runTrans $ msend conn $ SLast (ClosureData closr closl 0 []) -- to delete the remote closure runTrans $ liftIO $ error ("request received for non existent closure: " ++ show closl) -- execute the closure Just (fulLog,cont) -> do -- remove fulLog? liftIO $ runStateT (case mlog of Right log -> do let nlog= reverse log ++ fulLog setData $ Log True log nlog !> "SETLOG2" --setData $ Closure closr modifyState $ \mcls -> let RemoteClosures cls first= fromMaybe (RemoteClosures M.empty False) mcls altr Nothing= Just (closr,lfull) altr (Just(_,n))= Just (closr,n) in Just $ RemoteClosures (M.alter altr (idConn conn ) cls) False runContinuation cont () Left except -> do setData $ Log True [] fulLog --setData $ Closure closr modifyState $ \mcls -> let RemoteClosures cls first= fromMaybe (RemoteClosures M.empty False) mcls isExec x= case x of Exec -> True; _ -> False l= length fulLog -- $ dropWhile (isExec) fulLog in Just $ RemoteClosures (M.insert (idConn conn !> idConn conn) (closr,l) cls) False runTrans $ throwt except) cont return Nothing #ifdef ghcjs_HOST_OS listen node = onAll $ do addNodes [node] events <- liftIO $ newIORef M.empty rnode <- liftIO $ newIORef node conn <- defConnection >>= \c -> return c{myNode=rnode,comEvent=events} setData conn r <- listenResponses execLog r #endif type Pool= [Connection] type Package= String type Program= String type Service= [(Package, Program)] -------------------------------------------- data ParseContext a = IsString a => ParseContext (IO a) a deriving Typeable #ifndef ghcjs_HOST_OS -- maybeRead line= unsafePerformIO $ do -- let [(v,left)] = reads line ---- print v -- (v `seq` return [(v,left)]) -- `catch` (\(e::SomeException) -> do -- liftIO $ print $ "******readStream ERROR in: "++take 100 line -- maybeRead left) readFrom Connection{connData= Just(TLSNode2Node ctx)}= recvTLSData ctx readFrom Connection{connData= Just(Node2Node _ sock _)} = toStrict <$> loop where bufSize= 4098 loop :: IO BL.ByteString loop = unsafeInterleaveIO $ do s <- SBS.recv sock bufSize if BC.length s < bufSize then return $ BLC.Chunk s mempty else BLC.Chunk s `liftM` loop readFrom _ = error "readFrom error" toStrict= B.concat . BS.toChunks makeWSStreamFromConn conn= do let rec= readFrom conn send= sendRaw conn makeStream -- !!> "WEBSOCKETS request" (do bs <- rec -- SBS.recv sock 4098 return $ if BC.null bs then Nothing else Just bs) (\mbBl -> case mbBl of Nothing -> return () Just bl -> send bl) -- SBS.sendMany sock (BL.toChunks bl) >> return()) -- !!> show ("SOCK RESP",bl) makeWebsocketConnection conn uri headers= liftIO $ do stream <- makeWSStreamFromConn conn let pc = WS.PendingConnection { WS.pendingOptions = WS.defaultConnectionOptions , WS.pendingRequest = NWS.RequestHead uri headers False -- RequestHead (BC.pack $ show uri) -- (map parseh headers) False , WS.pendingOnAccept = \_ -> return () , WS.pendingStream = stream } sconn <- WS.acceptRequest pc -- !!> "accept request" WS.forkPingThread sconn 30 return sconn servePages (method,uri, headers) = do -- return () !> ("HTTP request",method,uri, headers) conn <- getSData <|> error " servePageMode: no connection" if isWebSocketsReq headers then return () else do let file= if BC.null uri then "index.html" else uri {- TODO rendering in server NEEDED: recodify View to use blaze-html in server. wlink to get path in server does file exist? if exist, send else do store path, execute continuation get the rendering send trough HTTP - put this logic as independent alternative programmer options serveFile dirs <|> serveApi apis <|> serveNode nodeCode -} mcontent <- liftIO $ (Just <$> BL.readFile ( "./static/out.jsexe/"++ BC.unpack file) ) `catch` (\(e:: SomeException) -> return Nothing) -- return "Not found file: index.html<br/> please compile with ghcjs<br/> ghcjs program.hs -o static/out") case mcontent of Just content -> liftIO $ sendRaw conn $ "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\nContent-Length: " <> BS.pack (show $ BL.length content) <>"\r\n\r\n" <> content Nothing ->liftIO $ sendRaw conn $ BS.pack $ "HTTP/1.0 404 Not Found\nContent-Length: 0\nConnection: close\n\n" empty --counter= unsafePerformIO $ newMVar 0 api :: TransIO BS.ByteString -> Cloud () api w= Cloud $ do conn <- getSData <|> error "api: Need a connection opened with initNode, listen, simpleWebApp" let send= sendRaw conn r <- w send r -- !> r isWebSocketsReq = not . null . filter ( (== mk "Sec-WebSocket-Key") . fst) data HTTPMethod= GET | POST deriving (Read,Show,Typeable) receiveHTTPHead = do (method, uri, vers) <- (,,) <$> getMethod <*> getUri <*> getVers headers <- manyTill paramPair (string "\r\n\r\n") -- !> (method, uri, vers) return (method, toStrict uri, headers) -- !> (method, uri, headers) where string :: BS.ByteString -> TransIO BS.ByteString string s=withData $ \str -> do let len= BS.length s ret@(s',str') = BS.splitAt len str if s == s' then return ret else empty paramPair= (,) <$> (mk <$> getParam) <*> getParamValue manyTill p end = scan where scan = do{ end; return [] } <|> do{ x <- p; xs <- scan; return (x:xs) } getMethod= getString getUri= getString getVers= getString getParam= do dropSpaces r <- tTakeWhile (\x -> x /= ':' && not (endline x)) if BS.null r || r=="\r" then empty else dropChar >> return (toStrict r) getParamValue= toStrict <$> ( dropSpaces >> tTakeWhile (\x -> not (endline x))) dropSpaces= parse $ \str ->((),BS.dropWhile isSpace str) dropChar= parse $ \r -> ((), BS.tail r) endline c= c== '\n' || c =='\r' --tGetLine= tTakeWhile . not . endline type PostParams = [(BS.ByteString, String)] parsePostUrlEncoded :: TransIO PostParams parsePostUrlEncoded= do dropSpaces many $ (,) <$> param <*> value where param= tTakeWhile' ( /= '=') value= unEscapeString <$> BS.unpack <$> tTakeWhile' ( /= '&') getString= do dropSpaces tTakeWhile (not . isSpace) tTakeWhile :: (Char -> Bool) -> TransIO BS.ByteString tTakeWhile cond= parse (BS.span cond) tTakeWhile' :: (Char -> Bool) -> TransIO BS.ByteString tTakeWhile' cond= parse ((\(h,t) -> (h, if BS.null t then t else BS.tail t)) . BS.span cond) parse :: (BS.ByteString -> (b, BS.ByteString)) -> TransIO b parse split= withData $ \str -> if str== mempty then empty else return $ split str -- | bring the data of a parse context as a lazy byteString to a parser -- and actualize the parse context with the result withData :: (BS.ByteString -> TransIO (a,BS.ByteString)) -> TransIO a withData parser= Transient $ do ParseContext readMore s <- getData `onNothing` error "parser: no context" let loop = unsafeInterleaveIO $ do r <- readMore (r <>) `liftM` loop str <- liftIO $ (s <> ) `liftM` loop mr <- runTrans $ parser str case mr of Nothing -> return Nothing Just (v,str') -> do setData $ ParseContext readMore str' return $ Just v -- | bring the data of the parse context as a lazy byteString giveData =noTrans $ do ParseContext readMore s <- getData `onNothing` error "parser: no context" :: StateIO (ParseContext BS.ByteString) -- change to strict BS let loop = unsafeInterleaveIO $ do r <- readMore (r <>) `liftM` loop liftIO $ (s <> ) `liftM` loop #endif #ifdef ghcjs_HOST_OS isBrowserInstance= True api _= empty #else -- | Returns 'True' if we are running in the browser. isBrowserInstance= False #endif {-# NOINLINE emptyPool #-} emptyPool :: MonadIO m => m (MVar Pool) emptyPool= liftIO $ newMVar [] -- | Create a node from a hostname (or IP address), port number and a list of -- services. createNodeServ :: HostName -> Int -> Service -> IO Node createNodeServ h p svs= return $ Node h p Nothing svs createNode :: HostName -> Int -> IO Node createNode h p= createNodeServ h p [] createWebNode :: IO Node createWebNode= do pool <- emptyPool return $ Node "webnode" 0 (Just pool) [("webnode","")] instance Eq Node where Node h p _ _ ==Node h' p' _ _= h==h' && p==p' instance Show Node where show (Node h p _ servs )= show (h,p, servs) instance Read Node where readsPrec n s= let r= readsPrec n s in case r of [] -> [] [((h,p,ss),s')] -> [(Node h p Nothing ss ,s')] -- inst ghc-options: -threaded -rtsopts nodeList :: TVar [Node] nodeList = unsafePerformIO $ newTVarIO [] deriving instance Ord PortID --myNode :: Int -> DBRef MyNode --myNode= getDBRef $ key $ MyNode undefined errorMyNode f= error $ f ++ ": Node not set. initialize it with connect, listen, initNode..." -- | Return the local node i.e. the node where this computation is running. getMyNode :: TransIO Node -- (MonadIO m, MonadState EventF m) => m Node getMyNode = do Connection{myNode= node} <- getSData <|> errorMyNode "getMyNode" :: TransIO Connection liftIO $ readIORef node -- | Return the list of nodes in the cluster. getNodes :: MonadIO m => m [Node] getNodes = liftIO $ atomically $ readTVar nodeList -- getEqualNodes= getNodes getEqualNodes = do nodes <- getNodes let srv= nodeServices $ head nodes case srv of [] -> return $ filter (null . nodeServices) nodes (srv:_) -> return $ filter (\n -> head (nodeServices n) == srv ) nodes matchNodes f = do nodes <- getNodes return $ map (\n -> filter f $ nodeServices n) nodes -- | Add a list of nodes to the list of existing cluster nodes. addNodes :: [Node] -> TransIO () -- (MonadIO m, MonadState EventF m) => [Node] -> m () addNodes nodes= do -- my <- getMyNode -- mynode must be first nodes' <- mapM fixNode nodes liftIO . atomically $ do prevnodes <- readTVar nodeList writeTVar nodeList $ nub $ prevnodes ++ nodes' fixNode n= case connection n of Nothing -> do pool <- emptyPool return n{connection= Just pool} Just _ -> return n -- | set the list of nodes setNodes nodes= liftIO $ atomically $ writeTVar nodeList $ nodes -- | Shuffle the list of cluster nodes and return the shuffled list. shuffleNodes :: MonadIO m => m [Node] shuffleNodes= liftIO . atomically $ do nodes <- readTVar nodeList let nodes'= tail nodes ++ [head nodes] writeTVar nodeList nodes' return nodes' --getInterfaces :: TransIO TransIO HostName --getInterfaces= do -- host <- logged $ do -- ifs <- liftIO $ getNetworkInterfaces -- liftIO $ mapM_ (\(i,n) ->putStrLn $ show i ++ "\t"++ show (ipv4 n) ++ "\t"++name n)$ zip [0..] ifs -- liftIO $ putStrLn "Select one: " -- ind <- input ( < length ifs) -- return $ show . ipv4 $ ifs !! ind -- #ifndef ghcjs_HOST_OS --instance Read NS.SockAddr where -- readsPrec _ ('[':s)= -- let (s',r1)= span (/=']') s -- [(port,r)]= readsPrec 0 $ tail $ tail r1 -- in [(NS.SockAddrInet6 port 0 (IP.toHostAddress6 $ read s') 0, r)] -- readsPrec _ s= -- let (s',r1)= span(/= ':') s -- [(port,r)]= readsPrec 0 $ tail r1 -- in [(NS.SockAddrInet port (IP.toHostAddress $ read s'),r)] -- #endif --newtype MyNode= MyNode Node deriving(Read,Show,Typeable) --instance Indexable MyNode where key (MyNode Node{nodePort=port}) = "MyNode "++ show port -- --instance Serializable MyNode where -- serialize= BS.pack . show -- deserialize= read . BS.unpack -- | Add a node (first parameter) to the cluster using a node that is already -- part of the cluster (second parameter). The added node starts listening for -- incoming connections and the rest of the computation is executed on this -- newly added node. connect :: Node -> Node -> Cloud () #ifndef ghcjs_HOST_OS connect node remotenode = do listen node <|> return () connect' remotenode -- | Reconcile the list of nodes in the cluster using a remote node already -- part of the cluster. Reconciliation end up in each node in the cluster -- having the same list of nodes. connect' :: Node -> Cloud () connect' remotenode= loggedc $ do nodes <- local getNodes localIO $ putStr "connecting to: " >> print remotenode newNodes <- runAt remotenode $ interchange nodes local $ return () !> "interchange finish" -- add the new nodes to the local nodes in all the nodes connected previously let toAdd=remotenode:tail newNodes callNodes' nodes (<>) mempty $ local $ do liftIO $ putStr "New nodes: " >> print toAdd !> "NEWNODES" addNodes toAdd where -- receive new nodes and send their own interchange nodes= do newNodes <- local $ do conn@Connection{remoteNode=rnode, connData=Just cdata} <- getSData <|> error ("connect': need to be connected to a node: use wormhole/connect/listen") -- if is a websockets node, add only this node -- let newNodes = case cdata of -- Node2Web _ -> [(head nodes){nodeServices=[("relay",show remotenode)]}] -- _ -> nodes let newNodes= map (\n -> n{nodeServices= nodeServices n ++ [("relay",show (remotenode,n))]}) nodes callingNode<- fixNode $ head newNodes liftIO $ writeIORef rnode $ Just callingNode liftIO $ modifyMVar_ (fromJust $ connection callingNode) $ const $ return [conn] -- onException $ \(e :: SomeException) -> do -- liftIO $ putStr "connect:" >> print e -- liftIO $ putStrLn "removing node: " >> print callingNode -- -- topState >>= showThreads -- nodes <- getNodes -- setNodes $ nodes \\ [callingNode] return newNodes oldNodes <- local $ getNodes mclustered . local $ do liftIO $ putStrLn "New nodes: " >> print newNodes addNodes newNodes localIO $ atomically $ do -- set the firt node (local node) as is called from outside -- return () !> "HOST2 set" nodes <- readTVar nodeList let nodes'= (head nodes){nodeHost=nodeHost remotenode ,nodePort=nodePort remotenode}:tail nodes writeTVar nodeList nodes' return oldNodes #else connect _ _= empty connect' _ = empty #endif
transient-haskell/transient-universe
src/Transient/Move/Internals.loggedmodified.hs
mit
79,528
1,056
34
27,565
12,402
7,344
5,058
1,021
12
module Sing where fstString :: [Char] -> [Char] fstString x = x ++ " in the rain" sndString :: [Char] -> [Char] sndString x = x ++ " over the rainbow" -- sing = if (x > y) then fstString x else sndString y -- where x = "Singin" -- y = "Somewhere" -- 2 sing = if (x < y) then fstString x else sndString y where x = "Singin" y = "Somewhere"
ashnikel/haskellbook
ch05/ch05fixit.hs
mit
371
0
7
106
100
58
42
8
2
{-# OPTIONS_GHC -XFlexibleInstances #-} ----------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming, 3e -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- Chapter 13 -- ----------------------------------------------------------------------- module Craft.Chapter13 where import Data.List import Craft.Chapter5 (Shape(..),area) -- Overloading and type classes -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Why overloading? -- ^^^^^^^^^^^^^^^^ -- Testing for membership of a Boolean list. elemBool :: Bool -> [Bool] -> Bool elemBool x [] = False elemBool x (y:ys) = (x == y) || elemBool x ys -- Testing for membership of a general list, with the equality function as a -- parameter. elemGen :: (a -> a -> Bool) -> a -> [a] -> Bool elemGen eqFun x [] = False elemGen eqFun x (y:ys) = (eqFun x y) || elemGen eqFun x ys -- Introducing classes -- ^^^^^^^^^^^^^^^^^^^ -- Definitions of classes cannot be hidden, so the definitions etc. here are not -- executable. -- class Eq a where -- (==) :: a -> a -> Bool -- Functions which use equality -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Testing for three values equal: more general than Int -> Int -> Int -> Bool. allEqual :: Eq a => a -> a -> a -> Bool allEqual m n p = (m==n) && (n==p) -- Erroneous expression -- error1 = allEqual suc suc suc suc = (+1) -- elem :: Eq a => a -> [a] -> Bool -- books :: Eq a => [ (a,b) ] -> a -> [b] -- It is easier to see this typing if you remane books lookupFirst: lookupFirst :: Eq a => [ (a,b) ] -> a -> [b] lookupFirst ws x = [ z | (y,z) <- ws , y==x ] -- borrowed :: Eq b => [ (a,b) ] -> b -> Bool -- numBorrowed :: Eq a => [ (a,b) ] -> a -> Int -- Signatures and Instances -- ^^^^^^^^^^^^^^^^^^^^^^^^ -- A type is made a member or instance of a class by defining -- the signature functions for the type. For example, -- instance Eq Bool where -- True == True = True -- False == False = True -- _ == _ = False -- The Info class: class Info a where examples :: [a] size :: a -> Int size _ = 1 -- Declaring instances of the Info class instance Info Int where examples = [-100..100] --size _ = 1 instance Info Char where examples = ['a','A','z','Z','0','9'] -- size _ = 1 instance Info Bool where examples = [True,False] -- size _ = 1 -- An instance declaration for a data type. instance Info Shape where examples = [ Circle 3.0, Rectangle 45.9 87.6 ] size = round . area --13.5 instance Info (Int -> Int) where examples = [(+1)] size _ = 1 instance Info (Int -> Bool) where examples = [(>0)] size _ = 3 -- Instance declaration with contexts. instance Info a => Info [a] where examples = [ [] ] ++ [ [x] | x<-examples ] ++ [ [x,y] | x<-examples , y<-examples ] size = foldr (+) 1 . map size instance (Info a,Info b) => Info (a,b) where examples = [ (x,y) | x<-examples , y<-examples ] size (x,y) = size x + size y + 1 -- Default definitions -- ^^^^^^^^^^^^^^^^^^^ -- To return to our example of equality, the Haskell equality class is in fact -- defined by -- class Eq a where -- (==), (/=) :: a -> a -> Bool -- x /= y = not (x==y) -- x == y = not (x/=y) -- Derived classes -- ^^^^^^^^^^^^^^^ -- Ordering is built on Eq. -- class Eq a => Ord a where -- (<), (<=), (>), (>=) :: a -> a -> Bool -- max, min :: a -> a -> a -- compare :: a -> a -> Ordering -- This is the same definition as in Chapter7, but now with an overloaded type. iSort :: Ord a => [a] -> [a] iSort [] = [] iSort (x:xs) = ins x (iSort xs) -- To insert an element at the right place into a sorted list. ins :: Ord a => a -> [a] -> [a] ins x [] = [x] ins x (y:ys) | x <= y = x:(y:ys) | otherwise = y : ins x ys ins' :: Ord a => a -> [a] -> [a] ins' x [] = [x] ins' x l@(y:ys) | x <= y = x:l | otherwise = y: (ins' x ys) -- Multiple constraints -- ^^^^^^^^^^^^^^^^^^^^ -- Sorting visible objects ... vSort :: (Ord a,Show a) => [a] -> String vSort = show . iSort -- Similarly, vLookupFirst :: (Eq a,Show b) => [(a,b)] -> a -> String vLookupFirst xs x = show (lookupFirst xs x) -- Multiple constraints can occur in an instance declaration, such as -- instance (Eq a,Eq b) => Eq (a,b) where -- (x,y) == (z,w) = x==z && y==w -- Multiple constraints can also occur in the definition of a class, class (Ord a,Show a) => OrdVis a -- Can then give vSort the type: -- vSort :: OrdVis a => [a] -> String -- InfoCheck. Check a property for all examples -- infoCheck :: (Info a) => (a -> Bool) -> Bool -- infoCheck property = and (map property examples) class Checkable b where infoCheck :: (Info a) => (a -> b) -> Bool instance Checkable Bool where infoCheck property = and (map property examples) instance (Info a, Checkable b) => Checkable (a -> b) where infoCheck property = and (map (infoCheck.property) examples) test0 = infoCheck (\x -> (x <=(0::Int) || x>0)) test1 = infoCheck (\x y -> (x <=(0::Int) || y <= 0 || x*y >= x)) test2 = infoCheck (\x y -> (x <=(0::Int) || y <= 0 || x*y > x)) -- A tour of the built-in Haskell classes -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- For details of the code here, please see the standard Prelude and Libraries. -- Types and Classes -- ^^^^^^^^^^^^^^^^^ -- The code in this section is not legal Haskell. -- To evaluate the type of concat . map show, type -- :type concat . map show -- to the Hugs prompt. -- Type checking and type inference -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ prodFun :: (t -> t1) -> (t -> t2) -> t -> (t1,t2) prodFun f g = \x -> (f x, g x) -- Checking types -- ^^^^^^^^^^^^^^ -- Non-type-correct definitions are included as comments. example1 = fromEnum 'c' + 3 -- example2 = fromEnum 'c' + False -- fgg n = 37+n -- fgg True = 34 -- g 0 = 37 -- g n = True -- h x -- | x>0 = True -- | otherwise = 37 -- k x = 34 -- k 0 = 35 -- Polymorphic type checking -- ^^^^^^^^^^^^^^^^^^^^^^^^^ -- Examples without their types; use Hugs to find them out. f (x,y) = (x , ['a' .. y]) g (m,zs) = m + length zs h = g . f expr :: Int expr = length ([]++[True]) + length ([]++[2,3,4]) -- The funny function does not type check. -- funny xs = length (xs++[True]) + length (xs++[2,3,4]) funny :: [a] -> [a] funny xs = (xs ++ []) ++ (xs ++ []) fzero :: [a] -> [b] -> a -> b fzero = fzero -- Type checking and classes -- ^^^^^^^^^^^^^^^^^^^^^^^^^ -- Membership on lists member :: Eq a => [a] -> a -> Bool member [] y = False member (x:xs) y = (x==y) || member xs y -- Merging ordered lists. merge :: (Ord a) => [a] -> [a] -> [a] merge (x:xs) (y:ys) | x<y = x : merge xs (y:ys) | x==y = x : merge xs ys | otherwise = y : merge (x:xs) ys merge (x:xs) [] = (x:xs) merge [] (y:ys) = (y:ys) merge [] [] = []
Numberartificial/workflow
snipets/src/Craft/Chapter13.hs
mit
6,894
7
15
1,674
1,902
1,080
822
-1
-1
-- -- -- ----------------- -- Exercise 6.62. ----------------- -- -- -- module E'6'62 where import E'6'53 ( Suit ) import E'6'55 ( Player ( North , South ) ) import E'6'56 ( TrickType ( Trick ) ) import E'6'57 ( winNT ) import E'6'58 ( winT ) data Team = NorthSouth | EastWest deriving ( Read , Show ) winnerNT :: [TrickType] -> Team -- NT; No Trump winnerNT tricks | length tricks > 13 = error "Thirteen tricks exceeded." | winsNS < winsEW = EastWest | otherwise = NorthSouth where wins :: [Player] wins = [ winNT trick | trick <- tricks ] winsNS, winsEW :: Int -- NS; North or South, EW; East or West winsNS = teamWins North South wins winsEW = 13 - winsNS winnerT :: Suit -> [TrickType] -> Team -- T; Trump winnerT trumpSuit tricks | length tricks > 13 = error "Thirteen tricks exceeded." | winsNS < winsEW = EastWest | otherwise = NorthSouth where wins :: [Player] wins = [ winT trumpSuit trick | trick <- tricks ] winsNS, winsEW :: Int -- NS; North or South, EW; East or West winsNS = teamWins North South wins winsEW = 13 - winsNS teamWins :: Player -> Player -> [Player] -> Int teamWins _ _ [] = 0 teamWins player_1 player_2 (trickWinner : remainingTrickWinners) | player_1 == trickWinner || player_2 == trickWinner = 1 + teamWins player_1 player_2 remainingTrickWinners | otherwise = teamWins player_1 player_2 remainingTrickWinners {- GHCi> :{ let northSouthWin :: TrickType ; northSouthWin = Trick North (Card Two Hearts) South (Card Two Diamonds) East (Card Two Spades) West (Card Two Clubs ) -- Just for example. :} :{ let tricks :: [TrickType] ; tricks = [ northSouthWin | _ <- [ 1 .. 13 ] ] :} winnerNT tricks winnerT Spades tricks -}
pascal-knodel/haskell-craft
_/links/E'6'62.hs
mit
1,901
0
10
554
425
232
193
37
1
module Wash.Persistent (T (), init, get, set, add, current) where import Wash.Config {- glossary A persistent entity (PE) is a named global value that evolves over time. The current value of a PE is the value that the PE has now. A handle gives access to a snapshot of a persistent entity at a particular time. -- interface data T a type of handles to a PE of type a init name initialValue creates a new PE with named name with initial value initialValue and returns the handle to the initial value. If the PE already exists, then init returns the handle to the current value. get handle retrieves the value from the handle. This value may not be current because the handle may point to a snapshot from the past. set handle newValue tries to overwrite the value of the pe pointed to by handle with newValue. Succeeds (Just handle') if the handle is a handle to the current value, in this case it returns a handle to the new value. Fails (Nothing) if the handle is not current. add handle addValue handle must point to a value of type [a] Prepends the addValue to the current value and returns a handle to the updated value. current handle returns the current handle to the PE pointed to by handle. -} import Wash.CGI hiding (head) import Prelude hiding (init) import Data.List hiding (init) import Maybe import IO import Control.Monad -- init :: (Read a, Show a) => String -> a -> CGI (T a) get :: Read a => T a -> CGI a set :: (Read a, Show a) => T a -> a -> CGI (Maybe (T a)) add :: (Read a, Show a) => T [a] -> a -> CGI (T [a]) current :: Read a => T a -> CGI (T a) -- data T a = T String Int deriving (Read, Show) data P a = P { nr :: Int, vl :: a } deriving (Read, Show) t :: String -> P a -> T a t name (P i a) = T name i trace s = -- appendFile (persistentDir ++ "TRACE") (s ++ "\n") return () init name val = io $ catch ( do trace ("init " ++ name ++ " " ++ show val) contents <- readFileStrictly fileName let pairs = read contents return $ t name $ head $ pairs) $ \ ioError -> let p = P 0 val in do writeFile fileName (show [p]) return (t name p) where fileName = persistentDir ++ name get (T name i) = unsafe_io $ do trace ("get " ++ name ++ " " ++ show i) contents <- readFileStrictly fileName return $ vl $ fromJust $ find ((== i) . nr) (read contents) where fileName = persistentDir ++ name set (T name i) val = io $ do trace ("set " ++ name ++ " " ++ show i ++ " " ++ show val) contents <- readFileStrictly fileName let pairs = read contents i' = i + 1 if nr (head pairs) == i then do writeFile fileName (show (P i' val : pairs)) return (Just (T name i')) else return Nothing where fileName = persistentDir ++ name add (T name _) val = io $ do trace ("add " ++ name ++ " " ++ show val) contents <- readFileStrictly fileName let pairs = read contents P i vals = head pairs i' = i + 1 writeFile fileName (show (P i' (val : vals) : pairs)) return (T name i') where fileName = persistentDir ++ name current (T name _) = io $ do trace ("current " ++ name) contents <- readFileStrictly fileName let pairs = read contents P i vals = head pairs return (t name (head pairs)) where fileName = persistentDir ++ name readFileStrictly filePath = do h <- openFile filePath ReadMode contents <- hGetContents h hClose (g contents h) return contents where g [] h = h g (_:rest) h = g rest h
Erdwolf/autotool-bonn
src/Wash/Persistent.hs
gpl-2.0
3,571
6
16
952
1,130
558
572
76
2
data A = A deriving (Show, Show)
roberth/uu-helium
test/parser/DerivingShowShow.hs
gpl-3.0
32
0
6
6
19
10
9
1
0
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[RnNames]{Extracting imported and top-level names in scope} -} {-# LANGUAGE CPP, NondecreasingIndentation #-} module RnNames ( rnImports, getLocalNonValBinders, newRecordSelector, rnExports, extendGlobalRdrEnvRn, gresFromAvails, calculateAvails, reportUnusedNames, checkConName ) where #include "HsVersions.h" import DynFlags import HsSyn import TcEnv import RnEnv import RnHsDoc ( rnHsDoc ) import LoadIface ( loadSrcInterface ) import TcRnMonad import PrelNames import Module import Name import NameEnv import NameSet import Avail import FieldLabel import HscTypes import RdrName import RdrHsSyn ( setRdrNameSpace ) import Outputable import Maybes import SrcLoc import BasicTypes ( TopLevelFlag(..), StringLiteral(..) ) import ErrUtils import Util import FastString import FastStringEnv import ListSetOps import Control.Monad import Data.Either ( partitionEithers, isRight, rights ) -- import qualified Data.Foldable as Foldable import Data.Map ( Map ) import qualified Data.Map as Map import Data.Ord ( comparing ) import Data.List ( partition, (\\), find, sortBy ) -- import qualified Data.Set as Set import System.FilePath ((</>)) import System.IO {- ************************************************************************ * * \subsection{rnImports} * * ************************************************************************ Note [Tracking Trust Transitively] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we import a package as well as checking that the direct imports are safe according to the rules outlined in the Note [HscMain . Safe Haskell Trust Check] we must also check that these rules hold transitively for all dependent modules and packages. Doing this without caching any trust information would be very slow as we would need to touch all packages and interface files a module depends on. To avoid this we make use of the property that if a modules Safe Haskell mode changes, this triggers a recompilation from that module in the dependcy graph. So we can just worry mostly about direct imports. There is one trust property that can change for a package though without recompliation being triggered: package trust. So we must check that all packages a module tranitively depends on to be trusted are still trusted when we are compiling this module (as due to recompilation avoidance some modules below may not be considered trusted any more without recompilation being triggered). We handle this by augmenting the existing transitive list of packages a module M depends on with a bool for each package that says if it must be trusted when the module M is being checked for trust. This list of trust required packages for a single import is gathered in the rnImportDecl function and stored in an ImportAvails data structure. The union of these trust required packages for all imports is done by the rnImports function using the combine function which calls the plusImportAvails function that is a union operation for the ImportAvails type. This gives us in an ImportAvails structure all packages required to be trusted for the module we are currently compiling. Checking that these packages are still trusted (and that direct imports are trusted) is done in HscMain.checkSafeImports. See the note below, [Trust Own Package] for a corner case in this method and how its handled. Note [Trust Own Package] ~~~~~~~~~~~~~~~~~~~~~~~~ There is a corner case of package trust checking that the usual transitive check doesn't cover. (For how the usual check operates see the Note [Tracking Trust Transitively] below). The case is when you import a -XSafe module M and M imports a -XTrustworthy module N. If N resides in a different package than M, then the usual check works as M will record a package dependency on N's package and mark it as required to be trusted. If N resides in the same package as M though, then importing M should require its own package be trusted due to N (since M is -XSafe so doesn't create this requirement by itself). The usual check fails as a module doesn't record a package dependency of its own package. So instead we now have a bool field in a modules interface file that simply states if the module requires its own package to be trusted. This field avoids us having to load all interface files that the module depends on to see if one is trustworthy. Note [Trust Transitive Property] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ So there is an interesting design question in regards to transitive trust checking. Say I have a module B compiled with -XSafe. B is dependent on a bunch of modules and packages, some packages it requires to be trusted as its using -XTrustworthy modules from them. Now if I have a module A that doesn't use safe haskell at all and simply imports B, should A inherit all the the trust requirements from B? Should A now also require that a package p is trusted since B required it? We currently say no but saying yes also makes sense. The difference is, if a module M that doesn't use Safe Haskell imports a module N that does, should all the trusted package requirements be dropped since M didn't declare that it cares about Safe Haskell (so -XSafe is more strongly associated with the module doing the importing) or should it be done still since the author of the module N that uses Safe Haskell said they cared (so -XSafe is more strongly associated with the module that was compiled that used it). Going with yes is a simpler semantics we think and harder for the user to stuff up but it does mean that Safe Haskell will affect users who don't care about Safe Haskell as they might grab a package from Cabal which uses safe haskell (say network) and that packages imports -XTrustworthy modules from another package (say bytestring), so requires that package is trusted. The user may now get compilation errors in code that doesn't do anything with Safe Haskell simply because they are using the network package. They will have to call 'ghc-pkg trust network' to get everything working. Due to this invasive nature of going with yes we have gone with no for now. -} -- | Process Import Decls. See 'rnImportDecl' for a description of what -- the return types represent. -- Note: Do the non SOURCE ones first, so that we get a helpful warning -- for SOURCE ones that are unnecessary rnImports :: [LImportDecl RdrName] -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails, AnyHpcUsage) rnImports imports = do this_mod <- getModule let (source, ordinary) = partition is_source_import imports is_source_import d = ideclSource (unLoc d) stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary stuff2 <- mapAndReportM (rnImportDecl this_mod) source -- Safe Haskell: See Note [Tracking Trust Transitively] let (decls, rdr_env, imp_avails, hpc_usage) = combine (stuff1 ++ stuff2) return (decls, rdr_env, imp_avails, hpc_usage) where combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails, AnyHpcUsage)] -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails, AnyHpcUsage) combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails, False) plus (decl, gbl_env1, imp_avails1,hpc_usage1) (decls, gbl_env2, imp_avails2,hpc_usage2) = ( decl:decls, gbl_env1 `plusGlobalRdrEnv` gbl_env2, imp_avails1 `plusImportAvails` imp_avails2, hpc_usage1 || hpc_usage2 ) -- | Given a located import declaration @decl@ from @this_mod@, -- calculate the following pieces of information: -- -- 1. An updated 'LImportDecl', where all unresolved 'RdrName' in -- the entity lists have been resolved into 'Name's, -- -- 2. A 'GlobalRdrEnv' representing the new identifiers that were -- brought into scope (taking into account module qualification -- and hiding), -- -- 3. 'ImportAvails' summarizing the identifiers that were imported -- by this declaration, and -- -- 4. A boolean 'AnyHpcUsage' which is true if the imported module -- used HPC. rnImportDecl :: Module -> LImportDecl RdrName -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails, AnyHpcUsage) rnImportDecl this_mod (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name, ideclPkgQual = mb_pkg , ideclSource = want_boot, ideclSafe = mod_safe , ideclQualified = qual_only, ideclImplicit = implicit , ideclAs = as_mod, ideclHiding = imp_details })) = setSrcSpan loc $ do when (isJust mb_pkg) $ do pkg_imports <- xoptM Opt_PackageImports when (not pkg_imports) $ addErr packageImportErr -- If there's an error in loadInterface, (e.g. interface -- file not found) we get lots of spurious errors from 'filterImports' let imp_mod_name = unLoc loc_imp_mod_name doc = ppr imp_mod_name <+> ptext (sLit "is directly imported") -- Check for self-import, which confuses the typechecker (Trac #9032) -- ghc --make rejects self-import cycles already, but batch-mode may not -- at least not until TcIface.tcHiBootIface, which is too late to avoid -- typechecker crashes. (Indirect self imports are not caught until -- TcIface, see #10337 tracking how to make this error better.) -- -- Originally, we also allowed 'import {-# SOURCE #-} M', but this -- caused bug #10182: in one-shot mode, we should never load an hs-boot -- file for the module we are compiling into the EPS. In principle, -- it should be possible to support this mode of use, but we would have to -- extend Provenance to support a local definition in a qualified location. -- For now, we don't support it, but see #10336 when (imp_mod_name == moduleName this_mod && (case mb_pkg of -- If we have import "<pkg>" M, then we should -- check that "<pkg>" is "this" (which is magic) -- or the name of this_mod's package. Yurgh! -- c.f. GHC.findModule, and Trac #9997 Nothing -> True Just (StringLiteral _ pkg_fs) -> pkg_fs == fsLit "this" || fsToUnitId pkg_fs == moduleUnitId this_mod)) (addErr (ptext (sLit "A module cannot import itself:") <+> ppr imp_mod_name)) -- Check for a missing import list (Opt_WarnMissingImportList also -- checks for T(..) items but that is done in checkDodgyImport below) case imp_details of Just (False, _) -> return () -- Explicit import list _ | implicit -> return () -- Do not bleat for implicit imports | qual_only -> return () | otherwise -> whenWOptM Opt_WarnMissingImportList $ addWarn (missingImportListWarn imp_mod_name) iface <- loadSrcInterface doc imp_mod_name want_boot (fmap sl_fs mb_pkg) -- Compiler sanity check: if the import didn't say -- {-# SOURCE #-} we should not get a hi-boot file WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) do -- Issue a user warning for a redundant {- SOURCE -} import -- NB that we arrange to read all the ordinary imports before -- any of the {- SOURCE -} imports. -- -- in --make and GHCi, the compilation manager checks for this, -- and indeed we shouldn't do it here because the existence of -- the non-boot module depends on the compilation order, which -- is not deterministic. The hs-boot test can show this up. dflags <- getDynFlags warnIf (want_boot && not (mi_boot iface) && isOneShot (ghcMode dflags)) (warnRedundantSourceImport imp_mod_name) when (mod_safe && not (safeImportsOn dflags)) $ addErr (ptext (sLit "safe import can't be used as Safe Haskell isn't on!") $+$ ptext (sLit $ "please enable Safe Haskell through either " ++ "Safe, Trustworthy or Unsafe")) let qual_mod_name = as_mod `orElse` imp_mod_name imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only, is_dloc = loc, is_as = qual_mod_name } -- filter the imports according to the import declaration (new_imp_details, gres) <- filterImports iface imp_spec imp_details let gbl_env = mkGlobalRdrEnv gres -- True <=> import M () import_all = case imp_details of Just (is_hiding, L _ ls) -> not is_hiding && null ls _ -> False -- should the import be safe? mod_safe' = mod_safe || (not implicit && safeDirectImpsReq dflags) || (implicit && safeImplicitImpsReq dflags) let imports = (calculateAvails dflags iface mod_safe' want_boot) { imp_mods = unitModuleEnv (mi_module iface) [(qual_mod_name, import_all, loc, mod_safe')] } -- Complain if we import a deprecated module whenWOptM Opt_WarnWarningsDeprecations ( case (mi_warns iface) of WarnAll txt -> addWarn $ moduleWarn imp_mod_name txt _ -> return () ) let new_imp_decl = L loc (decl { ideclSafe = mod_safe' , ideclHiding = new_imp_details }) return (new_imp_decl, gbl_env, imports, mi_hpc iface) -- | Calculate the 'ImportAvails' induced by an import of a particular -- interface, but without 'imp_mods'. calculateAvails :: DynFlags -> ModIface -> IsSafeImport -> IsBootInterface -> ImportAvails calculateAvails dflags iface mod_safe' want_boot = let imp_mod = mi_module iface orph_iface = mi_orphan iface has_finsts = mi_finsts iface deps = mi_deps iface trust = getSafeMode $ mi_trust iface trust_pkg = mi_trust_pkg iface -- If the module exports anything defined in this module, just -- ignore it. Reason: otherwise it looks as if there are two -- local definition sites for the thing, and an error gets -- reported. Easiest thing is just to filter them out up -- front. This situation only arises if a module imports -- itself, or another module that imported it. (Necessarily, -- this invoves a loop.) -- -- We do this *after* filterImports, so that if you say -- module A where -- import B( AType ) -- type AType = ... -- -- module B( AType ) where -- import {-# SOURCE #-} A( AType ) -- -- then you won't get a 'B does not export AType' message. -- Compute new transitive dependencies orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) ) imp_mod : dep_orphs deps | otherwise = dep_orphs deps finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) ) imp_mod : dep_finsts deps | otherwise = dep_finsts deps pkg = moduleUnitId (mi_module iface) -- Does this import mean we now require our own pkg -- to be trusted? See Note [Trust Own Package] ptrust = trust == Sf_Trustworthy || trust_pkg (dependent_mods, dependent_pkgs, pkg_trust_req) | pkg == thisPackage dflags = -- Imported module is from the home package -- Take its dependent modules and add imp_mod itself -- Take its dependent packages unchanged -- -- NB: (dep_mods deps) might include a hi-boot file -- for the module being compiled, CM. Do *not* filter -- this out (as we used to), because when we've -- finished dealing with the direct imports we want to -- know if any of them depended on CM.hi-boot, in -- which case we should do the hi-boot consistency -- check. See LoadIface.loadHiBootInterface ((moduleName imp_mod,want_boot):dep_mods deps,dep_pkgs deps,ptrust) | otherwise = -- Imported module is from another package -- Dump the dependent modules -- Add the package imp_mod comes from to the dependent packages ASSERT2( not (pkg `elem` (map fst $ dep_pkgs deps)) , ppr pkg <+> ppr (dep_pkgs deps) ) ([], (pkg, False) : dep_pkgs deps, False) in ImportAvails { imp_mods = emptyModuleEnv, -- this gets filled in later imp_orphs = orphans, imp_finsts = finsts, imp_dep_mods = mkModDeps dependent_mods, imp_dep_pkgs = map fst $ dependent_pkgs, -- Add in the imported modules trusted package -- requirements. ONLY do this though if we import the -- module as a safe import. -- See Note [Tracking Trust Transitively] -- and Note [Trust Transitive Property] imp_trust_pkgs = if mod_safe' then map fst $ filter snd dependent_pkgs else [], -- Do we require our own pkg to be trusted? -- See Note [Trust Own Package] imp_trust_own_pkg = pkg_trust_req } warnRedundantSourceImport :: ModuleName -> SDoc warnRedundantSourceImport mod_name = ptext (sLit "Unnecessary {-# SOURCE #-} in the import of module") <+> quotes (ppr mod_name) {- ************************************************************************ * * \subsection{importsFromLocalDecls} * * ************************************************************************ From the top-level declarations of this module produce * the lexical environment * the ImportAvails created by its bindings. Note [Top-level Names in Template Haskell decl quotes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See also: Note [Interactively-bound Ids in GHCi] in HscTypes Note [Looking up Exact RdrNames] in RnEnv Consider a Template Haskell declaration quotation like this: module M where f x = h [d| f = 3 |] When renaming the declarations inside [d| ...|], we treat the top level binders specially in two ways 1. We give them an Internal Name, not (as usual) an External one. This is done by RnEnv.newTopSrcBinder. 2. We make them *shadow* the outer bindings. See Note [GlobalRdrEnv shadowing] 3. We find out whether we are inside a [d| ... |] by testing the TH stage. This is a slight hack, because the stage field was really meant for the type checker, and here we are not interested in the fields of Brack, hence the error thunks in thRnBrack. -} extendGlobalRdrEnvRn :: [AvailInfo] -> MiniFixityEnv -> RnM (TcGblEnv, TcLclEnv) -- Updates both the GlobalRdrEnv and the FixityEnv -- We return a new TcLclEnv only because we might have to -- delete some bindings from it; -- see Note [Top-level Names in Template Haskell decl quotes] extendGlobalRdrEnvRn avails new_fixities = do { (gbl_env, lcl_env) <- getEnvs ; stage <- getStage ; isGHCi <- getIsGHCi ; let rdr_env = tcg_rdr_env gbl_env fix_env = tcg_fix_env gbl_env th_bndrs = tcl_th_bndrs lcl_env th_lvl = thLevel stage -- Delete new_occs from global and local envs -- If we are in a TemplateHaskell decl bracket, -- we are going to shadow them -- See Note [GlobalRdrEnv shadowing] inBracket = isBrackStage stage lcl_env_TH = lcl_env { tcl_rdr = delLocalRdrEnvList (tcl_rdr lcl_env) new_occs } -- See Note [GlobalRdrEnv shadowing] lcl_env2 | inBracket = lcl_env_TH | otherwise = lcl_env -- Deal with shadowing: see Note [GlobalRdrEnv shadowing] want_shadowing = isGHCi || inBracket rdr_env1 | want_shadowing = shadowNames rdr_env new_names | otherwise = rdr_env lcl_env3 = lcl_env2 { tcl_th_bndrs = extendNameEnvList th_bndrs [ (n, (TopLevel, th_lvl)) | n <- new_names ] } ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres ; let fix_env' = foldl extend_fix_env fix_env new_names gbl_env' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env' } ; traceRn (text "extendGlobalRdrEnvRn 2" <+> (pprGlobalRdrEnv True rdr_env2)) ; return (gbl_env', lcl_env3) } where new_names = concatMap availNames avails new_occs = map nameOccName new_names -- If there is a fixity decl for the gre, add it to the fixity env extend_fix_env fix_env name | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ) = extendNameEnv fix_env name (FixItem occ fi) | otherwise = fix_env where occ = nameOccName name new_gres :: [GlobalRdrElt] -- New LocalDef GREs, derived from avails new_gres = concatMap localGREsFromAvail avails add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv -- Extend the GlobalRdrEnv with a LocalDef GRE -- If there is already a LocalDef GRE with the same OccName, -- report an error and discard the new GRE -- This establishes INVARIANT 1 of GlobalRdrEnvs add_gre env gre | not (null dups) -- Same OccName defined twice = do { addDupDeclErr (gre : dups); return env } | otherwise = return (extendGlobalRdrEnv env gre) where name = gre_name gre occ = nameOccName name dups = filter isLocalGRE (lookupGlobalRdrEnv env occ) {- ********************************************************************* * * getLocalDeclBindersd@ returns the names for an HsDecl It's used for source code. *** See "THE NAMING STORY" in HsDecls **** * * ********************************************************************* -} getLocalNonValBinders :: MiniFixityEnv -> HsGroup RdrName -> RnM ((TcGblEnv, TcLclEnv), NameSet) -- Get all the top-level binders bound the group *except* -- for value bindings, which are treated separately -- Specifically we return AvailInfo for -- * type decls (incl constructors and record selectors) -- * class decls (including class ops) -- * associated types -- * foreign imports -- * value signatures (in hs-boot files only) getLocalNonValBinders fixity_env (HsGroup { hs_valds = binds, hs_tyclds = tycl_decls, hs_instds = inst_decls, hs_fords = foreign_decls }) = do { -- Process all type/class decls *except* family instances ; overload_ok <- xoptM Opt_DuplicateRecordFields ; (tc_avails, tc_fldss) <- fmap unzip $ mapM (new_tc overload_ok) (tyClGroupConcat tycl_decls) ; traceRn (text "getLocalNonValBinders 1" <+> ppr tc_avails) ; envs <- extendGlobalRdrEnvRn tc_avails fixity_env ; setEnvs envs $ do { -- Bring these things into scope first -- See Note [Looking up family names in family instances] -- Process all family instances -- to bring new data constructors into scope ; (nti_availss, nti_fldss) <- mapAndUnzipM (new_assoc overload_ok) inst_decls -- Finish off with value binders: -- foreign decls and pattern synonyms for an ordinary module -- type sigs in case of a hs-boot file only ; is_boot <- tcIsHsBootOrSig ; let val_bndrs | is_boot = hs_boot_sig_bndrs | otherwise = for_hs_bndrs ; val_avails <- mapM new_simple val_bndrs ; let avails = concat nti_availss ++ val_avails new_bndrs = availsToNameSet avails `unionNameSet` availsToNameSet tc_avails flds = concat nti_fldss ++ concat tc_fldss ; traceRn (text "getLocalNonValBinders 2" <+> ppr avails) ; (tcg_env, tcl_env) <- extendGlobalRdrEnvRn avails fixity_env -- Extend tcg_field_env with new fields (this used to be the -- work of extendRecordFieldEnv) ; let field_env = extendNameEnvList (tcg_field_env tcg_env) flds envs = (tcg_env { tcg_field_env = field_env }, tcl_env) ; return (envs, new_bndrs) } } where ValBindsIn _val_binds val_sigs = binds for_hs_bndrs :: [Located RdrName] for_hs_bndrs = hsForeignDeclsBinders foreign_decls -- In a hs-boot file, the value binders come from the -- *signatures*, and there should be no foreign binders hs_boot_sig_bndrs = [ L decl_loc (unLoc n) | L decl_loc (TypeSig ns _ _) <- val_sigs, n <- ns] -- the SrcSpan attached to the input should be the span of the -- declaration, not just the name new_simple :: Located RdrName -> RnM AvailInfo new_simple rdr_name = do{ nm <- newTopSrcBinder rdr_name ; return (Avail nm) } new_tc :: Bool -> LTyClDecl RdrName -> RnM (AvailInfo, [(Name, [FieldLabel])]) new_tc overload_ok tc_decl -- NOT for type/data instances = do { let (bndrs, flds) = hsLTyClDeclBinders tc_decl ; names@(main_name : sub_names) <- mapM newTopSrcBinder bndrs ; flds' <- mapM (newRecordSelector overload_ok sub_names) flds ; let fld_env = case unLoc tc_decl of DataDecl { tcdDataDefn = d } -> mk_fld_env d names flds' _ -> [] ; return (AvailTC main_name names flds', fld_env) } -- Calculate the mapping from constructor names to fields, which -- will go in tcg_field_env. It's convenient to do this here where -- we are working with a single datatype definition. mk_fld_env :: HsDataDefn RdrName -> [Name] -> [FieldLabel] -> [(Name, [FieldLabel])] mk_fld_env d names flds = concatMap find_con_flds (dd_cons d) where find_con_flds (L _ (ConDecl { con_names = rdrs , con_details = RecCon cdflds })) = map (\ (L _ rdr) -> ( find_con_name rdr , concatMap find_con_decl_flds (unLoc cdflds))) rdrs find_con_flds _ = [] find_con_name rdr = expectJust "getLocalNonValBinders/find_con_name" $ find (\ n -> nameOccName n == rdrNameOcc rdr) names find_con_decl_flds (L _ x) = map find_con_decl_fld (cd_fld_names x) find_con_decl_fld (L _ (FieldOcc rdr _)) = expectJust "getLocalNonValBinders/find_con_decl_fld" $ find (\ fl -> flLabel fl == lbl) flds where lbl = occNameFS (rdrNameOcc rdr) new_assoc :: Bool -> LInstDecl RdrName -> RnM ([AvailInfo], [(Name, [FieldLabel])]) new_assoc _ (L _ (TyFamInstD {})) = return ([], []) -- type instances don't bind new names new_assoc overload_ok (L _ (DataFamInstD d)) = do { (avail, flds) <- new_di overload_ok Nothing d ; return ([avail], flds) } new_assoc overload_ok (L _ (ClsInstD (ClsInstDecl { cid_poly_ty = inst_ty , cid_datafam_insts = adts }))) | Just (_, _, L loc cls_rdr, _) <- splitLHsInstDeclTy_maybe (flattenTopLevelLHsForAllTy inst_ty) = do { cls_nm <- setSrcSpan loc $ lookupGlobalOccRn cls_rdr ; (avails, fldss) <- mapAndUnzipM (new_loc_di overload_ok (Just cls_nm)) adts ; return (avails, concat fldss) } | otherwise = return ([], []) -- Do not crash on ill-formed instances -- Eg instance !Show Int Trac #3811c new_di :: Bool -> Maybe Name -> DataFamInstDecl RdrName -> RnM (AvailInfo, [(Name, [FieldLabel])]) new_di overload_ok mb_cls ti_decl = do { main_name <- lookupFamInstName mb_cls (dfid_tycon ti_decl) ; let (bndrs, flds) = hsDataFamInstBinders ti_decl ; sub_names <- mapM newTopSrcBinder bndrs ; flds' <- mapM (newRecordSelector overload_ok sub_names) flds ; let avail = AvailTC (unLoc main_name) sub_names flds' -- main_name is not bound here! fld_env = mk_fld_env (dfid_defn ti_decl) sub_names flds' ; return (avail, fld_env) } new_loc_di :: Bool -> Maybe Name -> LDataFamInstDecl RdrName -> RnM (AvailInfo, [(Name, [FieldLabel])]) new_loc_di overload_ok mb_cls (L _ d) = new_di overload_ok mb_cls d newRecordSelector :: Bool -> [Name] -> LFieldOcc RdrName -> RnM FieldLabel newRecordSelector _ [] _ = error "newRecordSelector: datatype has no constructors!" newRecordSelector overload_ok (dc:_) (L loc (FieldOcc fld _)) = do { sel_name <- newTopSrcBinder $ L loc $ mkRdrUnqual sel_occ ; return $ fl { flSelector = sel_name } } where lbl = occNameFS $ rdrNameOcc fld fl = mkFieldLabelOccs lbl (nameOccName dc) overload_ok sel_occ = flSelector fl {- Note [Looking up family names in family instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider module M where type family T a :: * type instance M.T Int = Bool We might think that we can simply use 'lookupOccRn' when processing the type instance to look up 'M.T'. Alas, we can't! The type family declaration is in the *same* HsGroup as the type instance declaration. Hence, as we are currently collecting the binders declared in that HsGroup, these binders will not have been added to the global environment yet. Solution is simple: process the type family declarations first, extend the environment, and then process the type instances. ************************************************************************ * * \subsection{Filtering imports} * * ************************************************************************ @filterImports@ takes the @ExportEnv@ telling what the imported module makes available, and filters it through the import spec (if any). Note [Dealing with imports] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ For import M( ies ), we take the mi_exports of M, and make imp_occ_env :: OccEnv (Name, AvailInfo, Maybe Name) One entry for each Name that M exports; the AvailInfo describes just that Name. The situation is made more complicated by associated types. E.g. module M where class C a where { data T a } instance C Int where { data T Int = T1 | T2 } instance C Bool where { data T Int = T3 } Then M's export_avails are (recall the AvailTC invariant from Avails.hs) C(C,T), T(T,T1,T2,T3) Notice that T appears *twice*, once as a child and once as a parent. From this we construct the imp_occ_env C -> (C, C(C,T), Nothing) T -> (T, T(T,T1,T2,T3), Just C) T1 -> (T1, T(T1,T2,T3), Nothing) -- similarly T2,T3 If we say import M( T(T1,T2) ) then we get *two* Avails: C(T), T(T1,T2) Note that the imp_occ_env will have entries for data constructors too, although we never look up data constructors. -} filterImports :: ModIface -> ImpDeclSpec -- The span for the entire import decl -> Maybe (Bool, Located [LIE RdrName]) -- Import spec; True => hiding -> RnM (Maybe (Bool, Located [LIE Name]), -- Import spec w/ Names [GlobalRdrElt]) -- Same again, but in GRE form filterImports iface decl_spec Nothing = return (Nothing, gresFromAvails (Just imp_spec) (mi_exports iface)) where imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll } filterImports iface decl_spec (Just (want_hiding, L l import_items)) = do -- check for errors, convert RdrNames to Names items1 <- mapM lookup_lie import_items let items2 :: [(LIE Name, AvailInfo)] items2 = concat items1 -- NB the AvailInfo may have duplicates, and several items -- for the same parent; e.g N(x) and N(y) names = availsToNameSet (map snd items2) keep n = not (n `elemNameSet` names) pruned_avails = filterAvails keep all_avails hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll } gres | want_hiding = gresFromAvails (Just hiding_spec) pruned_avails | otherwise = concatMap (gresFromIE decl_spec) items2 return (Just (want_hiding, L l (map fst items2)), gres) where all_avails = mi_exports iface -- See Note [Dealing with imports] imp_occ_env :: OccEnv (Name, -- the name AvailInfo, -- the export item providing the name Maybe Name) -- the parent of associated types imp_occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing)) | a <- all_avails, n <- availNames a] where -- See example in Note [Dealing with imports] -- 'combine' is only called for associated types which appear twice -- in the all_avails. In the example, we combine -- T(T,T1,T2,T3) and C(C,T) to give (T, T(T,T1,T2,T3), Just C) combine (name1, a1@(AvailTC p1 _ []), mp1) (name2, a2@(AvailTC p2 _ []), mp2) = ASSERT( name1 == name2 && isNothing mp1 && isNothing mp2 ) if p1 == name1 then (name1, a1, Just p2) else (name1, a2, Just p1) combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y) lookup_name :: RdrName -> IELookupM (Name, AvailInfo, Maybe Name) lookup_name rdr | isQual rdr = failLookupWith (QualImportError rdr) | Just succ <- mb_success = return succ | otherwise = failLookupWith BadImport where mb_success = lookupOccEnv imp_occ_env (rdrNameOcc rdr) lookup_lie :: LIE RdrName -> TcRn [(LIE Name, AvailInfo)] lookup_lie (L loc ieRdr) = do (stuff, warns) <- setSrcSpan loc $ liftM (fromMaybe ([],[])) $ run_lookup (lookup_ie ieRdr) mapM_ emit_warning warns return [ (L loc ie, avail) | (ie,avail) <- stuff ] where -- Warn when importing T(..) if T was exported abstractly emit_warning (DodgyImport n) = whenWOptM Opt_WarnDodgyImports $ addWarn (dodgyImportWarn n) emit_warning MissingImportList = whenWOptM Opt_WarnMissingImportList $ addWarn (missingImportListItem ieRdr) emit_warning BadImportW = whenWOptM Opt_WarnDodgyImports $ addWarn (lookup_err_msg BadImport) run_lookup :: IELookupM a -> TcRn (Maybe a) run_lookup m = case m of Failed err -> addErr (lookup_err_msg err) >> return Nothing Succeeded a -> return (Just a) lookup_err_msg err = case err of BadImport -> badImportItemErr iface decl_spec ieRdr all_avails IllegalImport -> illegalImportItemErr QualImportError rdr -> qualImportItemErr rdr -- For each import item, we convert its RdrNames to Names, -- and at the same time construct an AvailInfo corresponding -- to what is actually imported by this item. -- Returns Nothing on error. -- We return a list here, because in the case of an import -- item like C, if we are hiding, then C refers to *both* a -- type/class and a data constructor. Moreover, when we import -- data constructors of an associated family, we need separate -- AvailInfos for the data constructors and the family (as they have -- different parents). See Note [Dealing with imports] lookup_ie :: IE RdrName -> IELookupM ([(IE Name, AvailInfo)], [IELookupWarning]) lookup_ie ie = handle_bad_import $ do case ie of IEVar (L l n) -> do (name, avail, _) <- lookup_name n return ([(IEVar (L l name), trimAvail avail name)], []) IEThingAll (L l tc) -> do (name, avail, mb_parent) <- lookup_name tc let warns = case avail of Avail {} -- e.g. f(..) -> [DodgyImport tc] AvailTC _ subs fs | null (drop 1 subs) && null fs -- e.g. T(..) where T is a synonym -> [DodgyImport tc] | not (is_qual decl_spec) -- e.g. import M( T(..) ) -> [MissingImportList] | otherwise -> [] renamed_ie = IEThingAll (L l name) sub_avails = case avail of Avail {} -> [] AvailTC name2 subs fs -> [(renamed_ie, AvailTC name2 (subs \\ [name]) fs)] case mb_parent of Nothing -> return ([(renamed_ie, avail)], warns) -- non-associated ty/cls Just parent -> return ((renamed_ie, AvailTC parent [name] []) : sub_avails, warns) -- associated type IEThingAbs (L l tc) | want_hiding -- hiding ( C ) -- Here the 'C' can be a data constructor -- *or* a type/class, or even both -> let tc_name = lookup_name tc dc_name = lookup_name (setRdrNameSpace tc srcDataName) in case catIELookupM [ tc_name, dc_name ] of [] -> failLookupWith BadImport names -> return ([mkIEThingAbs l name | name <- names], []) | otherwise -> do nameAvail <- lookup_name tc return ([mkIEThingAbs l nameAvail], []) IEThingWith (L l rdr_tc) rdr_ns rdr_fs -> ASSERT2(null rdr_fs, ppr rdr_fs) do (name, AvailTC _ ns subflds, mb_parent) <- lookup_name rdr_tc -- Look up the children in the sub-names of the parent let subnames = case ns of -- The tc is first in ns, [] -> [] -- if it is there at all -- See the AvailTC Invariant in Avail.hs (n1:ns1) | n1 == name -> ns1 | otherwise -> ns case lookupChildren (map Left subnames ++ map Right subflds) rdr_ns of Nothing -> failLookupWith BadImport Just (childnames, childflds) -> case mb_parent of -- non-associated ty/cls Nothing -> return ([(IEThingWith (L l name) childnames childflds, AvailTC name (name:map unLoc childnames) (map unLoc childflds))], []) -- associated ty Just parent -> return ([(IEThingWith (L l name) childnames childflds, AvailTC name (map unLoc childnames) (map unLoc childflds)), (IEThingWith (L l name) childnames childflds, AvailTC parent [name] [])], []) _other -> failLookupWith IllegalImport -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed -- all errors. where mkIEThingAbs l (n, av, Nothing ) = (IEThingAbs (L l n), trimAvail av n) mkIEThingAbs l (n, _, Just parent) = (IEThingAbs (L l n), AvailTC parent [n] []) handle_bad_import m = catchIELookup m $ \err -> case err of BadImport | want_hiding -> return ([], [BadImportW]) _ -> failLookupWith err type IELookupM = MaybeErr IELookupError data IELookupWarning = BadImportW | MissingImportList | DodgyImport RdrName -- NB. use the RdrName for reporting a "dodgy" import data IELookupError = QualImportError RdrName | BadImport | IllegalImport failLookupWith :: IELookupError -> IELookupM a failLookupWith err = Failed err catchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a catchIELookup m h = case m of Succeeded r -> return r Failed err -> h err catIELookupM :: [IELookupM a] -> [a] catIELookupM ms = [ a | Succeeded a <- ms ] {- ************************************************************************ * * \subsection{Import/Export Utils} * * ************************************************************************ -} plusAvail :: AvailInfo -> AvailInfo -> AvailInfo plusAvail a1 a2 | debugIsOn && availName a1 /= availName a2 = pprPanic "RnEnv.plusAvail names differ" (hsep [ppr a1,ppr a2]) plusAvail a1@(Avail {}) (Avail {}) = a1 plusAvail (AvailTC _ [] []) a2@(AvailTC {}) = a2 plusAvail a1@(AvailTC {}) (AvailTC _ [] []) = a1 plusAvail (AvailTC n1 (s1:ss1) fs1) (AvailTC n2 (s2:ss2) fs2) = case (n1==s1, n2==s2) of -- Maintain invariant the parent is first (True,True) -> AvailTC n1 (s1 : (ss1 `unionLists` ss2)) (fs1 `unionLists` fs2) (True,False) -> AvailTC n1 (s1 : (ss1 `unionLists` (s2:ss2))) (fs1 `unionLists` fs2) (False,True) -> AvailTC n1 (s2 : ((s1:ss1) `unionLists` ss2)) (fs1 `unionLists` fs2) (False,False) -> AvailTC n1 ((s1:ss1) `unionLists` (s2:ss2)) (fs1 `unionLists` fs2) plusAvail (AvailTC n1 ss1 fs1) (AvailTC _ [] fs2) = AvailTC n1 ss1 (fs1 `unionLists` fs2) plusAvail (AvailTC n1 [] fs1) (AvailTC _ ss2 fs2) = AvailTC n1 ss2 (fs1 `unionLists` fs2) plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2]) -- | trims an 'AvailInfo' to keep only a single name trimAvail :: AvailInfo -> Name -> AvailInfo trimAvail (Avail n) _ = Avail n trimAvail (AvailTC n ns fs) m = case find ((== m) . flSelector) fs of Just x -> AvailTC n [] [x] Nothing -> ASSERT( m `elem` ns ) AvailTC n [m] [] -- | filters 'AvailInfo's by the given predicate filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo] filterAvails keep avails = foldr (filterAvail keep) [] avails -- | filters an 'AvailInfo' by the given predicate filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo] filterAvail keep ie rest = case ie of Avail n | keep n -> ie : rest | otherwise -> rest AvailTC tc ns fs -> let ns' = filter keep ns fs' = filter (keep . flSelector) fs in if null ns' && null fs' then rest else AvailTC tc ns' fs' : rest -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's. gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt] gresFromIE decl_spec (L loc ie, avail) = gresFromAvail prov_fn avail where is_explicit = case ie of IEThingAll (L _ name) -> \n -> n == name _ -> \_ -> True prov_fn name = Just (ImpSpec { is_decl = decl_spec, is_item = item_spec }) where item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc } {- Note [Children for duplicate record fields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the module {-# LANGUAGE DuplicateRecordFields #-} module M (F(foo, MkFInt, MkFBool)) where data family F a data instance F Int = MkFInt { foo :: Int } data instance F Bool = MkFBool { foo :: Bool } The `foo` in the export list refers to *both* selectors! For this reason, lookupChildren builds an environment that maps the FastString to a list of items, rather than a single item. -} mkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt] mkChildEnv gres = foldr add emptyNameEnv gres where add gre env = case gre_par gre of FldParent p _ -> extendNameEnv_Acc (:) singleton env p gre ParentIs p -> extendNameEnv_Acc (:) singleton env p gre NoParent -> env findChildren :: NameEnv [a] -> Name -> [a] findChildren env n = lookupNameEnv env n `orElse` [] lookupChildren :: [Either Name FieldLabel] -> [Located RdrName] -> Maybe ([Located Name], [Located FieldLabel]) -- (lookupChildren all_kids rdr_items) maps each rdr_item to its -- corresponding Name all_kids, if the former exists -- The matching is done by FastString, not OccName, so that -- Cls( meth, AssocTy ) -- will correctly find AssocTy among the all_kids of Cls, even though -- the RdrName for AssocTy may have a (bogus) DataName namespace -- (Really the rdr_items should be FastStrings in the first place.) lookupChildren all_kids rdr_items = do xs <- mapM doOne rdr_items return (fmap concat (partitionEithers xs)) where doOne (L l r) = case (lookupFsEnv kid_env . occNameFS . rdrNameOcc) r of Just [Left n] -> Just (Left (L l n)) Just rs | all isRight rs -> Just (Right (map (L l) (rights rs))) _ -> Nothing -- See Note [Children for duplicate record fields] kid_env = extendFsEnvList_C (++) emptyFsEnv [(either (occNameFS . nameOccName) flLabel x, [x]) | x <- all_kids] classifyGREs :: [GlobalRdrElt] -> ([Name], [FieldLabel]) classifyGREs = partitionEithers . map classifyGRE classifyGRE :: GlobalRdrElt -> Either Name FieldLabel classifyGRE gre = case gre_par gre of FldParent _ Nothing -> Right (FieldLabel (occNameFS (nameOccName n)) False n) FldParent _ (Just lbl) -> Right (FieldLabel lbl True n) _ -> Left n where n = gre_name gre -- | Combines 'AvailInfo's from the same family -- 'avails' may have several items with the same availName -- E.g import Ix( Ix(..), index ) -- will give Ix(Ix,index,range) and Ix(index) -- We want to combine these; addAvail does that nubAvails :: [AvailInfo] -> [AvailInfo] nubAvails avails = nameEnvElts (foldl add emptyNameEnv avails) where add env avail = extendNameEnv_C plusAvail env (availName avail) avail {- ************************************************************************ * * \subsection{Export list processing} * * ************************************************************************ Processing the export list. You might think that we should record things that appear in the export list as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong. We do check (here) that they are in scope, but there is no need to slurp in their actual declaration (which is what @addOccurrenceName@ forces). Indeed, doing so would big trouble when compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@, whose type includes @ConcBase.StateAndSynchVar#@, and so on... Note [Exports of data families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose you see (Trac #5306) module M where import X( F ) data instance F Int = FInt What does M export? AvailTC F [FInt] or AvailTC F [F,FInt]? The former is strictly right because F isn't defined in this module. But then you can never do an explicit import of M, thus import M( F( FInt ) ) because F isn't exported by M. Nor can you import FInt alone from here import M( FInt ) because we don't have syntax to support that. (It looks like an import of the type FInt.) At one point I implemented a compromise: * When constructing exports with no export list, or with module M( module M ), we add the parent to the exports as well. * But not when you see module M( f ), even if f is a class method with a parent. * Nor when you see module M( module N ), with N /= M. But the compromise seemed too much of a hack, so we backed it out. You just have to use an explicit export list: module M( F(..) ) where ... -} type ExportAccum -- The type of the accumulating parameter of -- the main worker function in rnExports = ([LIE Name], -- Export items with Names ExportOccMap, -- Tracks exported occurrence names [AvailInfo]) -- The accumulated exported stuff -- Not nub'd! emptyExportAccum :: ExportAccum emptyExportAccum = ([], emptyOccEnv, []) type ExportOccMap = OccEnv (Name, IE RdrName) -- Tracks what a particular exported OccName -- in an export list refers to, and which item -- it came from. It's illegal to export two distinct things -- that have the same occurrence name rnExports :: Bool -- False => no 'module M(..) where' header at all -> Maybe (Located [LIE RdrName]) -- Nothing => no explicit export list -> TcGblEnv -> RnM TcGblEnv -- Complains if two distinct exports have same OccName -- Warns about identical exports. -- Complains about exports items not in scope rnExports explicit_mod exports tcg_env@(TcGblEnv { tcg_mod = this_mod, tcg_rdr_env = rdr_env, tcg_imports = imports }) = unsetWOptM Opt_WarnWarningsDeprecations $ -- Do not report deprecations arising from the export -- list, to avoid bleating about re-exporting a deprecated -- thing (especially via 'module Foo' export item) do { -- If the module header is omitted altogether, then behave -- as if the user had written "module Main(main) where..." -- EXCEPT in interactive mode, when we behave as if he had -- written "module Main where ..." -- Reason: don't want to complain about 'main' not in scope -- in interactive mode ; dflags <- getDynFlags ; let real_exports | explicit_mod = exports | ghcLink dflags == LinkInMemory = Nothing | otherwise = Just (noLoc [noLoc (IEVar (noLoc main_RDR_Unqual))]) -- ToDo: the 'noLoc' here is unhelpful if 'main' -- turns out to be out of scope ; (rn_exports, avails) <- exports_from_avail real_exports rdr_env imports this_mod ; traceRn (ppr avails) ; let final_avails = nubAvails avails -- Combine families final_ns = availsToNameSetWithSelectors final_avails ; traceRn (text "rnExports: Exports:" <+> ppr final_avails) ; return (tcg_env { tcg_exports = final_avails, tcg_rn_exports = case tcg_rn_exports tcg_env of Nothing -> Nothing Just _ -> rn_exports, tcg_dus = tcg_dus tcg_env `plusDU` usesOnly final_ns }) } exports_from_avail :: Maybe (Located [LIE RdrName]) -- Nothing => no explicit export list -> GlobalRdrEnv -> ImportAvails -> Module -> RnM (Maybe [LIE Name], [AvailInfo]) exports_from_avail Nothing rdr_env _imports _this_mod = -- The same as (module M) where M is the current module name, -- so that's how we handle it. let avails = [ availFromGRE gre | gre <- globalRdrEnvElts rdr_env , isLocalGRE gre ] in return (Nothing, avails) exports_from_avail (Just (L _ rdr_items)) rdr_env imports this_mod = do (ie_names, _, exports) <- foldlM do_litem emptyExportAccum rdr_items return (Just ie_names, exports) where do_litem :: ExportAccum -> LIE RdrName -> RnM ExportAccum do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie) -- Maps a parent to its in-scope children kids_env :: NameEnv [GlobalRdrElt] kids_env = mkChildEnv (globalRdrEnvElts rdr_env) imported_modules = [ qual_name | xs <- moduleEnvElts $ imp_mods imports, (qual_name, _, _, _) <- xs ] exports_from_item :: ExportAccum -> LIE RdrName -> RnM ExportAccum exports_from_item acc@(ie_names, occs, exports) (L loc (IEModuleContents (L lm mod))) | let earlier_mods = [ mod | (L _ (IEModuleContents (L _ mod))) <- ie_names ] , mod `elem` earlier_mods -- Duplicate export of M = do { warn_dup_exports <- woptM Opt_WarnDuplicateExports ; warnIf warn_dup_exports (dupModuleExport mod) ; return acc } | otherwise = do { warnDodgyExports <- woptM Opt_WarnDodgyExports ; let { exportValid = (mod `elem` imported_modules) || (moduleName this_mod == mod) ; gre_prs = pickGREsModExp mod (globalRdrEnvElts rdr_env) ; new_exports = map (availFromGRE . fst) gre_prs ; names = map (gre_name . fst) gre_prs ; all_gres = foldr (\(gre1,gre2) gres -> gre1 : gre2 : gres) [] gre_prs } ; checkErr exportValid (moduleNotImported mod) ; warnIf (warnDodgyExports && exportValid && null gre_prs) (nullModuleExport mod) ; traceRn (text "efa" <+> (ppr mod $$ ppr all_gres)) ; addUsedGREs all_gres ; occs' <- check_occs (IEModuleContents (noLoc mod)) occs names -- This check_occs not only finds conflicts -- between this item and others, but also -- internally within this item. That is, if -- 'M.x' is in scope in several ways, we'll have -- several members of mod_avails with the same -- OccName. ; traceRn (vcat [ text "export mod" <+> ppr mod , ppr new_exports ]) ; return (L loc (IEModuleContents (L lm mod)) : ie_names, occs', new_exports ++ exports) } exports_from_item acc@(lie_names, occs, exports) (L loc ie) | isDoc ie = do new_ie <- lookup_doc_ie ie return (L loc new_ie : lie_names, occs, exports) | otherwise = do (new_ie, avail) <- lookup_ie ie if isUnboundName (ieName new_ie) then return acc -- Avoid error cascade else do occs' <- check_occs ie occs (availNames avail) return (L loc new_ie : lie_names, occs', avail : exports) ------------- lookup_ie :: IE RdrName -> RnM (IE Name, AvailInfo) lookup_ie (IEVar (L l rdr)) = do (name, avail) <- lookupGreAvailRn rdr return (IEVar (L l name), avail) lookup_ie (IEThingAbs (L l rdr)) = do (name, avail) <- lookupGreAvailRn rdr return (IEThingAbs (L l name), avail) lookup_ie ie@(IEThingAll (L l rdr)) = do name <- lookupGlobalOccRn rdr let gres = findChildren kids_env name (non_flds, flds) = classifyGREs gres addUsedKids rdr gres warnDodgyExports <- woptM Opt_WarnDodgyExports when (null gres) $ if isTyConName name then when warnDodgyExports $ addWarn (dodgyExportWarn name) else -- This occurs when you export T(..), but -- only import T abstractly, or T is a synonym. addErr (exportItemErr ie) return ( IEThingAll (L l name) , AvailTC name (name:non_flds) flds ) lookup_ie ie@(IEThingWith (L l rdr) sub_rdrs sub_flds) = ASSERT2(null sub_flds, ppr sub_flds) do name <- lookupGlobalOccRn rdr let gres = findChildren kids_env name if isUnboundName name then return ( IEThingWith (L l name) [] [] , AvailTC name [name] [] ) else case lookupChildren (map classifyGRE gres) sub_rdrs of Nothing -> do addErr (exportItemErr ie) return ( IEThingWith (L l name) [] [] , AvailTC name [name] [] ) Just (non_flds, flds) -> do addUsedKids rdr gres return ( IEThingWith (L l name) non_flds flds , AvailTC name (name:map unLoc non_flds) (map unLoc flds) ) lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier ------------- lookup_doc_ie :: IE RdrName -> RnM (IE Name) lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc return (IEGroup lev rn_doc) lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc return (IEDoc rn_doc) lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str) lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier -- In an export item M.T(A,B,C), we want to treat the uses of -- A,B,C as if they were M.A, M.B, M.C -- Happily pickGREs does just the right thing addUsedKids :: RdrName -> [GlobalRdrElt] -> RnM () addUsedKids parent_rdr kid_gres = addUsedGREs (pickGREs parent_rdr kid_gres) isDoc :: IE RdrName -> Bool isDoc (IEDoc _) = True isDoc (IEDocNamed _) = True isDoc (IEGroup _ _) = True isDoc _ = False ------------------------------- check_occs :: IE RdrName -> ExportOccMap -> [Name] -> RnM ExportOccMap check_occs ie occs names -- 'names' are the entities specifed by 'ie' = foldlM check occs names where check occs name = case lookupOccEnv occs name_occ of Nothing -> return (extendOccEnv occs name_occ (name, ie)) Just (name', ie') | name == name' -- Duplicate export -- But we don't want to warn if the same thing is exported -- by two different module exports. See ticket #4478. -> do unless (dupExport_ok name ie ie') $ do warn_dup_exports <- woptM Opt_WarnDuplicateExports warnIf warn_dup_exports (dupExportWarn name_occ ie ie') return occs | otherwise -- Same occ name but different names: an error -> do { global_env <- getGlobalRdrEnv ; addErr (exportClashErr global_env name' name ie' ie) ; return occs } where name_occ = nameOccName name dupExport_ok :: Name -> IE RdrName -> IE RdrName -> Bool -- The Name is exported by both IEs. Is that ok? -- "No" iff the name is mentioned explicitly in both IEs -- or one of the IEs mentions the name *alone* -- "Yes" otherwise -- -- Examples of "no": module M( f, f ) -- module M( fmap, Functor(..) ) -- module M( module Data.List, head ) -- -- Example of "yes" -- module M( module A, module B ) where -- import A( f ) -- import B( f ) -- -- Example of "yes" (Trac #2436) -- module M( C(..), T(..) ) where -- class C a where { data T a } -- instace C Int where { data T Int = TInt } -- -- Example of "yes" (Trac #2436) -- module Foo ( T ) where -- data family T a -- module Bar ( T(..), module Foo ) where -- import Foo -- data instance T Int = TInt dupExport_ok n ie1 ie2 = not ( single ie1 || single ie2 || (explicit_in ie1 && explicit_in ie2) ) where explicit_in (IEModuleContents _) = False -- module M explicit_in (IEThingAll r) = nameOccName n == rdrNameOcc (unLoc r) -- T(..) explicit_in _ = True single (IEVar {}) = True single (IEThingAbs {}) = True single _ = False {- ********************************************************* * * \subsection{Unused names} * * ********************************************************* -} reportUnusedNames :: Maybe (Located [LIE RdrName]) -- Export list -> TcGblEnv -> RnM () reportUnusedNames _export_decls gbl_env = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env))) ; warnUnusedImportDecls gbl_env ; warnUnusedTopBinds unused_locals } where used_names :: NameSet used_names = findUses (tcg_dus gbl_env) emptyNameSet -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used -- Hence findUses -- Collect the defined names from the in-scope environment defined_names :: [GlobalRdrElt] defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env) -- Note that defined_and_used, defined_but_not_used -- are both [GRE]; that's why we need defined_and_used -- rather than just used_names _defined_and_used, defined_but_not_used :: [GlobalRdrElt] (_defined_and_used, defined_but_not_used) = partition (gre_is_used used_names) defined_names kids_env = mkChildEnv defined_names -- This is done in mkExports too; duplicated work gre_is_used :: NameSet -> GlobalRdrElt -> Bool gre_is_used used_names (GRE {gre_name = name}) = name `elemNameSet` used_names || any (\ gre -> gre_name gre `elemNameSet` used_names) (findChildren kids_env name) -- A use of C implies a use of T, -- if C was brought into scope by T(..) or T(C) -- Filter out the ones that are -- (a) defined in this module, and -- (b) not defined by a 'deriving' clause -- The latter have an Internal Name, so we can filter them out easily unused_locals :: [GlobalRdrElt] unused_locals = filter is_unused_local defined_but_not_used is_unused_local :: GlobalRdrElt -> Bool is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre) {- ********************************************************* * * \subsection{Unused imports} * * ********************************************************* This code finds which import declarations are unused. The specification and implementation notes are here: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports -} type ImportDeclUsage = ( LImportDecl Name -- The import declaration , [AvailInfo] -- What *is* used (normalised) , [Name] ) -- What is imported but *not* used warnUnusedImportDecls :: TcGblEnv -> RnM () warnUnusedImportDecls gbl_env = do { uses <- readMutVar (tcg_used_gres gbl_env) ; let user_imports = filterOut (ideclImplicit . unLoc) (tcg_rn_imports gbl_env) -- This whole function deals only with *user* imports -- both for warning about unnecessary ones, and for -- deciding the minimal ones rdr_env = tcg_rdr_env gbl_env fld_env = mkFieldEnv rdr_env ; let usage :: [ImportDeclUsage] usage = findImportUsage user_imports uses ; traceRn (vcat [ ptext (sLit "Uses:") <+> ppr uses , ptext (sLit "Import usage") <+> ppr usage]) ; whenWOptM Opt_WarnUnusedImports $ mapM_ (warnUnusedImport fld_env) usage ; whenGOptM Opt_D_dump_minimal_imports $ printMinimalImports usage } {- Note [The ImportMap] ~~~~~~~~~~~~~~~~~~~~ The ImportMap is a short-lived intermediate data struture records, for each import declaration, what stuff brought into scope by that declaration is actually used in the module. The SrcLoc is the location of the END of a particular 'import' declaration. Why *END*? Because we don't want to get confused by the implicit Prelude import. Consider (Trac #7476) the module import Foo( foo ) main = print foo There is an implicit 'import Prelude(print)', and it gets a SrcSpan of line 1:1 (just the point, not a span). If we use the *START* of the SrcSpan to identify the import decl, we'll confuse the implicit import Prelude with the explicit 'import Foo'. So we use the END. It's just a cheap hack; we could equally well use the Span too. The AvailInfos are the things imported from that decl (just a list, not normalised). -} type ImportMap = Map SrcLoc [AvailInfo] -- See [The ImportMap] findImportUsage :: [LImportDecl Name] -> [GlobalRdrElt] -> [ImportDeclUsage] findImportUsage imports used_gres = map unused_decl imports where import_usage :: ImportMap import_usage = foldr extendImportMap Map.empty used_gres unused_decl decl@(L loc (ImportDecl { ideclHiding = imps })) = (decl, nubAvails used_avails, nameSetElems unused_imps) where used_avails = Map.lookup (srcSpanEnd loc) import_usage `orElse` [] -- srcSpanEnd: see Note [The ImportMap] used_names = availsToNameSetWithSelectors used_avails used_parents = mkNameSet [n | AvailTC n _ _ <- used_avails] unused_imps -- Not trivial; see eg Trac #7454 = case imps of Just (False, L _ imp_ies) -> foldr (add_unused . unLoc) emptyNameSet imp_ies _other -> emptyNameSet -- No explicit import list => no unused-name list add_unused :: IE Name -> NameSet -> NameSet add_unused (IEVar (L _ n)) acc = add_unused_name n acc add_unused (IEThingAbs (L _ n)) acc = add_unused_name n acc add_unused (IEThingAll (L _ n)) acc = add_unused_all n acc add_unused (IEThingWith (L _ p) ns fs) acc = add_unused_with p xs acc where xs = map unLoc ns ++ map (flSelector . unLoc) fs add_unused _ acc = acc add_unused_name n acc | n `elemNameSet` used_names = acc | otherwise = acc `extendNameSet` n add_unused_all n acc | n `elemNameSet` used_names = acc | n `elemNameSet` used_parents = acc | otherwise = acc `extendNameSet` n add_unused_with p ns acc | all (`elemNameSet` acc1) ns = add_unused_name p acc1 | otherwise = acc1 where acc1 = foldr add_unused_name acc ns -- If you use 'signum' from Num, then the user may well have -- imported Num(signum). We don't want to complain that -- Num is not itself mentioned. Hence the two cases in add_unused_with. extendImportMap :: GlobalRdrElt -> ImportMap -> ImportMap -- For each of a list of used GREs, find all the import decls that brought -- it into scope; choose one of them (bestImport), and record -- the RdrName in that import decl's entry in the ImportMap extendImportMap gre imp_map = add_imp gre (bestImport (gre_imp gre)) imp_map where add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap add_imp gre (ImpSpec { is_decl = imp_decl_spec }) imp_map = Map.insertWith add decl_loc [avail] imp_map where add _ avails = avail : avails -- add is really just a specialised (++) decl_loc = srcSpanEnd (is_dloc imp_decl_spec) -- For srcSpanEnd see Note [The ImportMap] avail = availFromGRE gre warnUnusedImport :: NameEnv (FieldLabelString, Name) -> ImportDeclUsage -> RnM () warnUnusedImport fld_env (L loc decl, used, unused) | Just (False,L _ []) <- ideclHiding decl = return () -- Do not warn for 'import M()' | Just (True, L _ hides) <- ideclHiding decl , not (null hides) , pRELUDE_NAME == unLoc (ideclName decl) = return () -- Note [Do not warn about Prelude hiding] | null used = addWarnAt loc msg1 -- Nothing used; drop entire decl | null unused = return () -- Everything imported is used; nop | otherwise = addWarnAt loc msg2 -- Some imports are unused where msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used, nest 2 (ptext (sLit "except perhaps to import instances from") <+> quotes pp_mod), ptext (sLit "To import instances alone, use:") <+> ptext (sLit "import") <+> pp_mod <> parens Outputable.empty ] msg2 = sep [pp_herald <+> quotes sort_unused, text "from module" <+> quotes pp_mod <+> pp_not_used] pp_herald = text "The" <+> pp_qual <+> text "import of" pp_qual | ideclQualified decl = text "qualified" | otherwise = Outputable.empty pp_mod = ppr (unLoc (ideclName decl)) pp_not_used = text "is redundant" ppr_possible_field n = case lookupNameEnv fld_env n of Just (fld, p) -> ppr p <> parens (ppr fld) Nothing -> ppr n -- Print unused names in a deterministic (lexicographic) order sort_unused = pprWithCommas ppr_possible_field $ sortBy (comparing nameOccName) unused {- Note [Do not warn about Prelude hiding] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We do not warn about import Prelude hiding( x, y ) because even if nothing else from Prelude is used, it may be essential to hide x,y to avoid name-shadowing warnings. Example (Trac #9061) import Prelude hiding( log ) f x = log where log = () Note [Printing minimal imports] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To print the minimal imports we walk over the user-supplied import decls, and simply trim their import lists. NB that * We do *not* change the 'qualified' or 'as' parts! * We do not disard a decl altogether; we might need instances from it. Instead we just trim to an empty import list -} printMinimalImports :: [ImportDeclUsage] -> RnM () -- See Note [Printing minimal imports] printMinimalImports imports_w_usage = do { imports' <- mapM mk_minimal imports_w_usage ; this_mod <- getModule ; dflags <- getDynFlags ; liftIO $ do { h <- openFile (mkFilename dflags this_mod) WriteMode ; printForUser dflags h neverQualify (vcat (map ppr imports')) } -- The neverQualify is important. We are printing Names -- but they are in the context of an 'import' decl, and -- we never qualify things inside there -- E.g. import Blag( f, b ) -- not import Blag( Blag.f, Blag.g )! } where mkFilename dflags this_mod | Just d <- dumpDir dflags = d </> basefn | otherwise = basefn where basefn = moduleNameString (moduleName this_mod) ++ ".imports" mk_minimal (L l decl, used, unused) | null unused , Just (False, _) <- ideclHiding decl = return (L l decl) | otherwise = do { let ImportDecl { ideclName = L _ mod_name , ideclSource = is_boot , ideclPkgQual = mb_pkg } = decl ; iface <- loadSrcInterface doc mod_name is_boot (fmap sl_fs mb_pkg) ; let lies = map (L l) (concatMap (to_ie iface) used) ; return (L l (decl { ideclHiding = Just (False, L l lies) })) } where doc = text "Compute minimal imports for" <+> ppr decl to_ie :: ModIface -> AvailInfo -> [IE Name] -- The main trick here is that if we're importing all the constructors -- we want to say "T(..)", but if we're importing only a subset we want -- to say "T(A,B,C)". So we have to find out what the module exports. to_ie _ (Avail n) = [IEVar (noLoc n)] to_ie _ (AvailTC n [m] []) | n==m = [IEThingAbs (noLoc n)] to_ie iface (AvailTC n ns fs) = case [(xs,gs) | AvailTC x xs gs <- mi_exports iface , x == n , x `elem` xs -- Note [Partial export] ] of [xs] | all_used xs -> [IEThingAll (noLoc n)] | otherwise -> [IEThingWith (noLoc n) (map noLoc (filter (/= n) ns)) (map noLoc fs)] -- Note [Overloaded field import] _other | all_non_overloaded fs -> map (IEVar . noLoc) $ ns ++ map flSelector fs | otherwise -> [IEThingWith (noLoc n) (map noLoc (filter (/= n) ns)) (map noLoc fs)] where fld_lbls = map flLabel fs all_used (avail_occs, avail_flds) = all (`elem` ns) avail_occs && all (`elem` fld_lbls) (map flLabel avail_flds) all_non_overloaded = all (not . flIsOverloaded) {- Note [Partial export] ~~~~~~~~~~~~~~~~~~~~~ Suppose we have module A( op ) where class C a where op :: a -> a module B where import A f = ..op... Then the minimal import for module B is import A( op ) not import A( C( op ) ) which we would usually generate if C was exported from B. Hence the (x `elem` xs) test when deciding what to generate. Note [Overloaded field import] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On the other hand, if we have {-# LANGUAGE DuplicateRecordFields #-} module A where data T = MkT { foo :: Int } module B where import A f = ...foo... then the minimal import for module B must be import A ( T(foo) ) because when DuplicateRecordFields is enabled, field selectors are not in scope without their enclosing datatype. ************************************************************************ * * \subsection{Errors} * * ************************************************************************ -} qualImportItemErr :: RdrName -> SDoc qualImportItemErr rdr = hang (ptext (sLit "Illegal qualified name in import item:")) 2 (ppr rdr) badImportItemErrStd :: ModIface -> ImpDeclSpec -> IE RdrName -> SDoc badImportItemErrStd iface decl_spec ie = sep [ptext (sLit "Module"), quotes (ppr (is_mod decl_spec)), source_import, ptext (sLit "does not export"), quotes (ppr ie)] where source_import | mi_boot iface = ptext (sLit "(hi-boot interface)") | otherwise = Outputable.empty badImportItemErrDataCon :: OccName -> ModIface -> ImpDeclSpec -> IE RdrName -> SDoc badImportItemErrDataCon dataType_occ iface decl_spec ie = vcat [ ptext (sLit "In module") <+> quotes (ppr (is_mod decl_spec)) <+> source_import <> colon , nest 2 $ quotes datacon <+> ptext (sLit "is a data constructor of") <+> quotes dataType , ptext (sLit "To import it use") , nest 2 $ quotes (ptext (sLit "import")) <+> ppr (is_mod decl_spec) <> parens_sp (dataType <> parens_sp datacon) , ptext (sLit "or") , nest 2 $ quotes (ptext (sLit "import")) <+> ppr (is_mod decl_spec) <> parens_sp (dataType <> ptext (sLit "(..)")) ] where datacon_occ = rdrNameOcc $ ieName ie datacon = parenSymOcc datacon_occ (ppr datacon_occ) dataType = parenSymOcc dataType_occ (ppr dataType_occ) source_import | mi_boot iface = ptext (sLit "(hi-boot interface)") | otherwise = Outputable.empty parens_sp d = parens (space <> d <> space) -- T( f,g ) badImportItemErr :: ModIface -> ImpDeclSpec -> IE RdrName -> [AvailInfo] -> SDoc badImportItemErr iface decl_spec ie avails = case find checkIfDataCon avails of Just con -> badImportItemErrDataCon (availOccName con) iface decl_spec ie Nothing -> badImportItemErrStd iface decl_spec ie where checkIfDataCon (AvailTC _ ns _) = case find (\n -> importedFS == nameOccNameFS n) ns of Just n -> isDataConName n Nothing -> False checkIfDataCon _ = False availOccName = nameOccName . availName nameOccNameFS = occNameFS . nameOccName importedFS = occNameFS . rdrNameOcc $ ieName ie illegalImportItemErr :: SDoc illegalImportItemErr = ptext (sLit "Illegal import item") dodgyImportWarn :: RdrName -> SDoc dodgyImportWarn item = dodgyMsg (ptext (sLit "import")) item dodgyExportWarn :: Name -> SDoc dodgyExportWarn item = dodgyMsg (ptext (sLit "export")) item dodgyMsg :: (OutputableBndr n, HasOccName n) => SDoc -> n -> SDoc dodgyMsg kind tc = sep [ ptext (sLit "The") <+> kind <+> ptext (sLit "item") <+> quotes (ppr (IEThingAll (noLoc tc))) <+> ptext (sLit "suggests that"), quotes (ppr tc) <+> ptext (sLit "has (in-scope) constructors or class methods,"), ptext (sLit "but it has none") ] exportItemErr :: IE RdrName -> SDoc exportItemErr export_item = sep [ ptext (sLit "The export item") <+> quotes (ppr export_item), ptext (sLit "attempts to export constructors or class methods that are not visible here") ] exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE RdrName -> IE RdrName -> MsgDoc exportClashErr global_env name1 name2 ie1 ie2 = vcat [ ptext (sLit "Conflicting exports for") <+> quotes (ppr occ) <> colon , ppr_export ie1' name1' , ppr_export ie2' name2' ] where occ = nameOccName name1 ppr_export ie name = nest 3 (hang (quotes (ppr ie) <+> ptext (sLit "exports") <+> quotes (ppr name)) 2 (pprNameProvenance (get_gre name))) -- get_gre finds a GRE for the Name, so that we can show its provenance get_gre name = case lookupGRE_Name global_env name of (gre:_) -> gre [] -> pprPanic "exportClashErr" (ppr name) get_loc name = greSrcSpan (get_gre name) (name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2 then (name1, ie1, name2, ie2) else (name2, ie2, name1, ie1) addDupDeclErr :: [GlobalRdrElt] -> TcRn () addDupDeclErr [] = panic "addDupDeclErr: empty list" addDupDeclErr gres@(gre : _) = addErrAt (getSrcSpan (last sorted_names)) $ -- Report the error at the later location vcat [ptext (sLit "Multiple declarations of") <+> quotes (ppr (nameOccName name)), -- NB. print the OccName, not the Name, because the -- latter might not be in scope in the RdrEnv and so will -- be printed qualified. ptext (sLit "Declared at:") <+> vcat (map (ppr . nameSrcLoc) sorted_names)] where name = gre_name gre sorted_names = sortWith nameSrcLoc (map gre_name gres) dupExportWarn :: OccName -> IE RdrName -> IE RdrName -> SDoc dupExportWarn occ_name ie1 ie2 = hsep [quotes (ppr occ_name), ptext (sLit "is exported by"), quotes (ppr ie1), ptext (sLit "and"), quotes (ppr ie2)] dupModuleExport :: ModuleName -> SDoc dupModuleExport mod = hsep [ptext (sLit "Duplicate"), quotes (ptext (sLit "Module") <+> ppr mod), ptext (sLit "in export list")] moduleNotImported :: ModuleName -> SDoc moduleNotImported mod = ptext (sLit "The export item `module") <+> ppr mod <> ptext (sLit "' is not imported") nullModuleExport :: ModuleName -> SDoc nullModuleExport mod = ptext (sLit "The export item `module") <+> ppr mod <> ptext (sLit "' exports nothing") missingImportListWarn :: ModuleName -> SDoc missingImportListWarn mod = ptext (sLit "The module") <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list") missingImportListItem :: IE RdrName -> SDoc missingImportListItem ie = ptext (sLit "The import item") <+> quotes (ppr ie) <+> ptext (sLit "does not have an explicit import list") moduleWarn :: ModuleName -> WarningTxt -> SDoc moduleWarn mod (WarningTxt _ txt) = sep [ ptext (sLit "Module") <+> quotes (ppr mod) <> ptext (sLit ":"), nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ] moduleWarn mod (DeprecatedTxt _ txt) = sep [ ptext (sLit "Module") <+> quotes (ppr mod) <+> ptext (sLit "is deprecated:"), nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ] packageImportErr :: SDoc packageImportErr = ptext (sLit "Package-qualified imports are not enabled; use PackageImports") -- This data decl will parse OK -- data T = a Int -- treating "a" as the constructor. -- It is really hard to make the parser spot this malformation. -- So the renamer has to check that the constructor is legal -- -- We can get an operator as the constructor, even in the prefix form: -- data T = :% Int Int -- from interface files, which always print in prefix form checkConName :: RdrName -> TcRn () checkConName name = checkErr (isRdrDataCon name) (badDataCon name) badDataCon :: RdrName -> SDoc badDataCon name = hsep [ptext (sLit "Illegal data constructor name"), quotes (ppr name)]
AlexanderPankiv/ghc
compiler/rename/RnNames.hs
bsd-3-clause
82,670
8
31
25,621
15,590
8,049
7,541
-1
-1
{-# LANGUAGE DeriveGeneric #-} module ModifiersSpec where import Data.List import Test.Hspec import System.Console.GetOpt.Generics import System.Console.GetOpt.GenericsSpec import Util spec :: Spec spec = do describe "AddShortOption" $ do it "allows modifiers for short options" $ do modsParse [AddShortOption "camelCase" 'x'] "-x foo" `shouldBe` Success (CamelCaseOptions "foo") it "allows modifiers in camelCase" $ do modsParse [AddShortOption "camelCase" 'x'] "-x foo" `shouldBe` Success (CamelCaseOptions "foo") let parse' :: String -> Result CamelCaseOptions parse' = modsParse [AddShortOption "camelCase" 'x'] it "includes the short option in the help" $ do let OutputAndExit output = parse' "--help" output `shouldContain` "-x STRING" describe "RenameOption" $ do it "allows to rename options" $ do modsParse [RenameOption "camelCase" "bla"] "--bla foo" `shouldBe` Success (CamelCaseOptions "foo") context "when shadowing earlier modifiers with later modifiers" $ do let parse' = modsParse [RenameOption "camelCase" "foo", RenameOption "camelCase" "bar"] it "uses the later renaming" $ do parse' "--bar foo" `shouldBe` Success (CamelCaseOptions "foo") it "disregards the earlier renaming" $ do let Errors errs = parse' "--foo foo" errs `shouldContain` ["unrecognized option `--foo'\n"] it "contains renamed options in error messages" $ do let Errors errs = modsParse [RenameOption "camelCase" "foo"] "" :: Result CamelCaseOptions -- _ <- error $ show errs show errs `shouldNotContain` "camelCase" show errs `shouldNotContain` "camel-case" show errs `shouldContain` "foo" it "" $ do modsParse [RenameOption "bar" "one", RenameOption "baz" "two"] "--one 1 --two foo" `shouldBe` Success (Foo (Just 1) "foo" False) describe "AddVersionFlag" $ do it "implements --version" $ do let OutputAndExit output = modsParse [AddVersionFlag "1.0.0"] "--version" :: Result Foo output `shouldBe` "prog-name version 1.0.0" it "--help takes precedence over --version" $ do let OutputAndExit output = modsParse [AddVersionFlag "1.0.0"] "--version --help" :: Result Foo output `shouldSatisfy` ("show help and exit" `isInfixOf`) it "--version shows up in help output" $ do let OutputAndExit output = modsParse [AddVersionFlag "1.0.0"] "--help" :: Result Foo output `shouldSatisfy` ("show version and exit" `isInfixOf`)
kosmikus/getopt-generics
test/ModifiersSpec.hs
bsd-3-clause
2,638
0
19
644
666
316
350
53
1
{- | Module : $Header$ Description : OWL reserved keywords and printing Copyright : (c) Christian Maeder DFKI Bremen 2008, Felix Mance, 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable String constants for keywords to be used for parsing and printing plus owl, xsd, rdf and rdfs reserved keywords. All identifiers are mixed case -} module OWL2.Keywords where import Common.Keywords keywords :: [String] keywords = [ digitsS , exactlyS , fractionS , functionalS , hasS , inverseS , lengthS , maxLengthS , maxS , minLengthS , minS , oS , onlyS , onlysomeS , orS , patternS , selfS , someS , thatS , valueS , xorS ] ++ datatypeKeys base64BinaryS :: String base64BinaryS = "base64Binary" booleanS :: String booleanS = "boolean" byteS :: String byteS = "byte" dATAS :: String dATAS = "DATA" decimalS :: String decimalS = "decimal" doubleS :: String doubleS = "double" digitsS :: String digitsS = "totalDigits" exactlyS :: String exactlyS = "exactly" floatS :: String floatS = "float" fractionS :: String fractionS = "fractionDigits" functionalS :: String functionalS = "Functional" hasS :: String hasS = "has" hexBinaryS :: String hexBinaryS = "hexBinary" intS :: String intS = "int" integerS :: String integerS = "integer" inverseS :: String inverseS = "inverse" langRangeS :: String langRangeS = "langRange" lengthS :: String lengthS = "length" longS :: String longS = "long" maxLengthS :: String maxLengthS = "maxLength" maxS :: String maxS = "max" minLengthS :: String minLengthS = "minLength" minS :: String minS = "min" negativeIntegerS :: String negativeIntegerS = "negativeInteger" nonNegativeIntegerS :: String nonNegativeIntegerS = "nonNegativeInteger" nonPositiveIntegerS :: String nonPositiveIntegerS = "nonPositiveInteger" oS :: String oS = "o" onlyS :: String onlyS = "only" onlysomeS :: String onlysomeS = "onlysome" orS :: String orS = "or" patternS :: String patternS = "pattern" positiveIntegerS :: String positiveIntegerS = "positiveInteger" rationalS :: String rationalS = "rational" realS :: String realS = "real" selfS :: String selfS = "Self" shortS :: String shortS = "short" someS :: String someS = "some" thatS :: String thatS = "that" rdfsLiteral :: String rdfsLiteral = "Literal" unsignedByteS :: String unsignedByteS = "unsignedByte" unsignedIntS :: String unsignedIntS = "unsignedInt" unsignedLongS :: String unsignedLongS = "unsignedLongS" unsignedShortS :: String unsignedShortS = "unsignedShort" valueS :: String valueS = "value" xorS :: String xorS = "xor" dateTimeS :: String dateTimeS = "dateTime" dateTimeStampS :: String dateTimeStampS = "dateTimeStamp" anyURI :: String anyURI = "anyURI" xmlLiteral :: String xmlLiteral = "XMLLiteral" ncNameS :: String ncNameS = "NCName" nameS :: String nameS = "Name" nmTokenS :: String nmTokenS = "NMTOKEN" tokenS :: String tokenS = "token" languageS :: String languageS = "language" normalizedStringS :: String normalizedStringS = "normalizedString" thingS :: String thingS = "Thing" nothingS :: String nothingS = "Nothing" topObjProp :: String topObjProp = "topObjectProperty" bottomObjProp :: String bottomObjProp = "bottomObjectProperty" topDataProp :: String topDataProp = "topDataProperty" bottomDataProp :: String bottomDataProp = "bottomDataProperty" label :: String label = "label" comment :: String comment = "comment" seeAlso :: String seeAlso = "seeAlso" isDefinedBy :: String isDefinedBy = "isDefinedBy" deprecated :: String deprecated = "deprecated" versionInfo :: String versionInfo = "versionInfo" priorVersion :: String priorVersion = "priorVersion" backwardCompatibleWith :: String backwardCompatibleWith = "backwardCompatibleWith" incompatibleWith :: String incompatibleWith = "incompatibleWith" implied :: String implied = "Implied" predefClass :: [String] predefClass = [thingS, nothingS] predefObjProp :: [String] predefObjProp = [topObjProp, bottomObjProp] predefDataProp :: [String] predefDataProp = [topDataProp, bottomDataProp] predefRDFSAnnoProps :: [String] predefRDFSAnnoProps = [label, comment, seeAlso, isDefinedBy] predefOWLAnnoProps :: [String] predefOWLAnnoProps = [deprecated, versionInfo, priorVersion, backwardCompatibleWith, incompatibleWith, implied] xsdNumbers :: [String] xsdNumbers = [integerS, negativeIntegerS, nonNegativeIntegerS, nonPositiveIntegerS, positiveIntegerS, decimalS, doubleS, floatS, longS, intS, shortS, byteS, unsignedLongS, unsignedIntS, unsignedShortS, unsignedByteS] owlNumbers :: [String] owlNumbers = [realS, rationalS] xsdStrings :: [String] xsdStrings = [stringS, ncNameS, "QName", nameS, nmTokenS, "NMTOKENS", tokenS , languageS, normalizedStringS, "NOTATION", "ENTITY", "ENTITIES" , "ID", "IDREF", "IDREFS" ] xsdKeys :: [String] xsdKeys = [booleanS, dATAS, hexBinaryS, base64BinaryS, "date", "time" , "gYearMonth", "gYear", "gMonthDay", "gDay", "gMonth", "duration" , dateTimeS, dateTimeStampS, anyURI] ++ xsdNumbers ++ xsdStrings nonXSDKeys :: [String] nonXSDKeys = owlNumbers ++ [xmlLiteral, rdfsLiteral] datatypeKeys :: [String] datatypeKeys = xsdKeys ++ nonXSDKeys data DatatypeFacet = LENGTH | MINLENGTH | MAXLENGTH | PATTERN | LANGRANGE | MININCLUSIVE | MINEXCLUSIVE | MAXINCLUSIVE | MAXEXCLUSIVE | TOTALDIGITS | FRACTIONDIGITS deriving (Show, Eq, Ord) showFacet :: DatatypeFacet -> String showFacet df = case df of LENGTH -> lengthS MINLENGTH -> minLengthS MAXLENGTH -> maxLengthS PATTERN -> patternS LANGRANGE -> langRangeS MININCLUSIVE -> lessEq MINEXCLUSIVE -> lessS MAXINCLUSIVE -> greaterEq MAXEXCLUSIVE -> greaterS TOTALDIGITS -> digitsS FRACTIONDIGITS -> fractionS facetList :: [DatatypeFacet] facetList = [LENGTH, MINLENGTH, MAXLENGTH, PATTERN, LANGRANGE, MININCLUSIVE, MINEXCLUSIVE, MAXINCLUSIVE, MAXEXCLUSIVE, TOTALDIGITS, FRACTIONDIGITS]
keithodulaigh/Hets
OWL2/Keywords.hs
gpl-2.0
6,036
0
7
1,025
1,344
820
524
227
11
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElastiCache.CreateCacheSubnetGroup -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | The /CreateCacheSubnetGroup/ action creates a new cache subnet group. -- -- Use this parameter only when you are creating a cluster in an Amazon Virtual -- Private Cloud (VPC). -- -- <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CreateCacheSubnetGroup.html> module Network.AWS.ElastiCache.CreateCacheSubnetGroup ( -- * Request CreateCacheSubnetGroup -- ** Request constructor , createCacheSubnetGroup -- ** Request lenses , ccsgCacheSubnetGroupDescription , ccsgCacheSubnetGroupName , ccsgSubnetIds -- * Response , CreateCacheSubnetGroupResponse -- ** Response constructor , createCacheSubnetGroupResponse -- ** Response lenses , ccsgrCacheSubnetGroup ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ElastiCache.Types import qualified GHC.Exts data CreateCacheSubnetGroup = CreateCacheSubnetGroup { _ccsgCacheSubnetGroupDescription :: Text , _ccsgCacheSubnetGroupName :: Text , _ccsgSubnetIds :: List "member" Text } deriving (Eq, Ord, Read, Show) -- | 'CreateCacheSubnetGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ccsgCacheSubnetGroupDescription' @::@ 'Text' -- -- * 'ccsgCacheSubnetGroupName' @::@ 'Text' -- -- * 'ccsgSubnetIds' @::@ ['Text'] -- createCacheSubnetGroup :: Text -- ^ 'ccsgCacheSubnetGroupName' -> Text -- ^ 'ccsgCacheSubnetGroupDescription' -> CreateCacheSubnetGroup createCacheSubnetGroup p1 p2 = CreateCacheSubnetGroup { _ccsgCacheSubnetGroupName = p1 , _ccsgCacheSubnetGroupDescription = p2 , _ccsgSubnetIds = mempty } -- | A description for the cache subnet group. ccsgCacheSubnetGroupDescription :: Lens' CreateCacheSubnetGroup Text ccsgCacheSubnetGroupDescription = lens _ccsgCacheSubnetGroupDescription (\s a -> s { _ccsgCacheSubnetGroupDescription = a }) -- | A name for the cache subnet group. This value is stored as a lowercase string. -- -- Constraints: Must contain no more than 255 alphanumeric characters or -- hyphens. -- -- Example: 'mysubnetgroup' ccsgCacheSubnetGroupName :: Lens' CreateCacheSubnetGroup Text ccsgCacheSubnetGroupName = lens _ccsgCacheSubnetGroupName (\s a -> s { _ccsgCacheSubnetGroupName = a }) -- | A list of VPC subnet IDs for the cache subnet group. ccsgSubnetIds :: Lens' CreateCacheSubnetGroup [Text] ccsgSubnetIds = lens _ccsgSubnetIds (\s a -> s { _ccsgSubnetIds = a }) . _List newtype CreateCacheSubnetGroupResponse = CreateCacheSubnetGroupResponse { _ccsgrCacheSubnetGroup :: Maybe CacheSubnetGroup } deriving (Eq, Read, Show) -- | 'CreateCacheSubnetGroupResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ccsgrCacheSubnetGroup' @::@ 'Maybe' 'CacheSubnetGroup' -- createCacheSubnetGroupResponse :: CreateCacheSubnetGroupResponse createCacheSubnetGroupResponse = CreateCacheSubnetGroupResponse { _ccsgrCacheSubnetGroup = Nothing } ccsgrCacheSubnetGroup :: Lens' CreateCacheSubnetGroupResponse (Maybe CacheSubnetGroup) ccsgrCacheSubnetGroup = lens _ccsgrCacheSubnetGroup (\s a -> s { _ccsgrCacheSubnetGroup = a }) instance ToPath CreateCacheSubnetGroup where toPath = const "/" instance ToQuery CreateCacheSubnetGroup where toQuery CreateCacheSubnetGroup{..} = mconcat [ "CacheSubnetGroupDescription" =? _ccsgCacheSubnetGroupDescription , "CacheSubnetGroupName" =? _ccsgCacheSubnetGroupName , "SubnetIds" =? _ccsgSubnetIds ] instance ToHeaders CreateCacheSubnetGroup instance AWSRequest CreateCacheSubnetGroup where type Sv CreateCacheSubnetGroup = ElastiCache type Rs CreateCacheSubnetGroup = CreateCacheSubnetGroupResponse request = post "CreateCacheSubnetGroup" response = xmlResponse instance FromXML CreateCacheSubnetGroupResponse where parseXML = withElement "CreateCacheSubnetGroupResult" $ \x -> CreateCacheSubnetGroupResponse <$> x .@? "CacheSubnetGroup"
kim/amazonka
amazonka-elasticache/gen/Network/AWS/ElastiCache/CreateCacheSubnetGroup.hs
mpl-2.0
5,178
0
10
1,053
568
347
221
71
1
module Trace.Hpc.Coveralls.Config where import Trace.Hpc.Coveralls.Types (CoverageMode) data Config = Config { excludedDirs :: ![FilePath], coverageMode :: !CoverageMode, cabalFile :: !(Maybe FilePath), serviceName :: !(Maybe String), repoToken :: !(Maybe String), testSuites :: ![String] }
jdnavarro/hpc-coveralls
src/Trace/Hpc/Coveralls/Config.hs
bsd-3-clause
330
0
11
72
95
56
39
21
0
-- | Saves the version module Version where import Data.Version {-# noinline nikkiVersion #-} nikkiVersion :: Version nikkiVersion = Version version tags where version = 999 : [] tags = ["fakeFuture"]
geocurnoff/nikki
src/FakeFutureVersion.hs
lgpl-3.0
216
0
8
46
47
28
19
7
1
module VersionTest where import Data.Int import Data.Vector import Test.QuickCheck import Thrift.Protocol.Binary import Thrift.Protocol.Compact import Thrift.Protocol.JSON import Thrift.Protocol.SimpleJSON import Thrift.Transport import Thrift.Transport.Empty import Version_Types import Util prop_roundtrip :: (Transport t, Protocol p) => p t -> Int32 -> Vector (Vector Int32) -> Bool prop_roundtrip p x y = Foo1 x == decode_Foo1 p (encode_Foo2 p $ Foo2 x y) main :: IO () main = aggregateResults $ quickCheckResult <$> [ prop_roundtrip $ BinaryProtocol EmptyTransport , prop_roundtrip $ SimpleJSONProtocol EmptyTransport , prop_roundtrip $ JSONProtocol EmptyTransport , prop_roundtrip $ CompactProtocol EmptyTransport ]
getyourguide/fbthrift
thrift/lib/hs/tests/VersionTest.hs
apache-2.0
762
0
11
129
206
111
95
20
1
module D2 where {- generalise function 'f' on the sub-expression '(y+1)' with a new parameter 'z'. This refactoring only affects the current module -} y=0 f z x =x + z f_gen = (y + 1) sumFun xs = sum $ map (f (y + 1)) xs
kmate/HaRe
old/testing/generaliseDef/D2_TokOut.hs
bsd-3-clause
231
0
10
57
66
36
30
5
1
-- -- Adapted from the program "infer", believed to have been originally -- authored by Philip Wadler, and used in the nofib benchmark suite -- since at least the late 90s. -- module InferMonad (Infer, returnI, eachI, thenI, guardI, useI, getSubI, substituteI, unifyI, freshI, freshesI) where import Control.Applicative import Control.Monad import MaybeM import StateX (StateX, returnSX, eachSX, thenSX, toSX, putSX, getSX, useSX) import Type import Substitution type Counter = Int data Infer x = MkI (StateX Sub (StateX Counter (Maybe ((x, Sub), Counter)))) rep (MkI xJ) = xJ returnI :: x -> Infer x returnI x = MkI (returnSX (returnSX returnM) x) eachI :: Infer x -> (x -> y) -> Infer y xI `eachI` f = MkI (eachSX (eachSX eachM) (rep xI) f) thenI :: Infer x -> (x -> Infer y) -> Infer y xI `thenI` kI = MkI (thenSX (thenSX thenM) (rep xI) (rep . kI)) failI :: Infer x failI = MkI (toSX (eachSX eachM) (toSX eachM failM)) useI :: x -> Infer x -> x useI xfail = useM xfail . useSX eachM 0 . useSX (eachSX eachM) emptySub . rep guardI :: Bool -> Infer x -> Infer x guardI b xI = if b then xI else failI putSubI :: Sub -> Infer () putSubI s = MkI (putSX (returnSX returnM) s) getSubI :: Infer Sub getSubI = MkI (getSX (returnSX returnM)) putCounterI :: Counter -> Infer () putCounterI c = MkI (toSX (eachSX eachM) (putSX returnM c)) getCounterI :: Infer Counter getCounterI = MkI (toSX (eachSX eachM) (getSX returnM)) substituteI :: MonoType -> Infer MonoType substituteI t = getSubI `thenI` (\ s -> returnI (applySub s t)) unifyI :: MonoType -> MonoType -> Infer () unifyI t u = getSubI `thenI` (\ s -> let sM = unifySub t u s in existsM sM `guardI` ( putSubI (theM sM) `thenI` (\ () -> returnI ()))) freshI :: Infer MonoType freshI = getCounterI `thenI` (\c -> putCounterI (c+1) `thenI` (\() -> returnI (TVar ("a" ++ show c)))) freshesI :: Int -> Infer [MonoType] freshesI 0 = returnI [] freshesI n = freshI `thenI` (\x -> freshesI (n-1) `thenI` (\xs -> returnI (x:xs))) instance Applicative Infer where pure = return (<*>) = ap instance Monad Infer where return = returnI (>>=) = thenI instance Functor Infer where fmap f x = x >>= return . f
jasonzoladz/parconc-examples
parinfer/InferMonad.hs
bsd-3-clause
3,090
2
16
1,338
982
525
457
60
2
module Tests.Unit ( runTests ) where import System.Directory import Test.HUnit import Control.Monad import Control.Applicative ((<$>)) import Control.Exception import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Certificate.X509 import Data.List (isPrefixOf) -- FIXME : make unit tests portable to run on osX and windows import System.Certificate.X509 import Data.CertificateStore checkCert (X509 c mraw rawCert sigalg sigbits) = do let errs = (checkSigAlg $ certSignatureAlg c) ++ (checkPubKey $ certPubKey c) ++ (checkExtensions $ certExtensions c) ++ (checkBodyRaw rawCert mraw) when (errs /= []) $ do putStrLn ("error decoding") mapM_ (putStrLn . (" " ++)) errs where checkExtensions ext = [] checkSigAlg (SignatureALG_Unknown oid) = ["unknown signature algorithm " ++ show oid] checkSigAlg _ = [] checkPubKey (PubKeyUnknown oid _) = ["unknown public key alg " ++ show (certPubKey c)] checkPubKey _ = [] checkBodyRaw (Just x) (Just y) = if findsubstring y x then [] else ["cannot find body cert in original raw file"] checkBodyRaw _ _ = [] findsubstring a b | L.null b = False | a `L.isPrefixOf` b = True | otherwise = findsubstring a (L.drop 1 b) runTests :: IO () runTests = getSystemCertificateStore >>= mapM_ checkCert . listCertificates
theeternalsw0rd/ports-2012
dev-haskell/certificate/files/certificate-1.3.6/Tests/Unit.hs
gpl-2.0
1,401
12
15
307
456
240
216
35
5
module Oops where main = print ((f 1) 2, gaga True) where f x y = g + y where g = x gaga h = ("g: " ++) (show h)
kmate/HaRe
old/testing/introNewDef/Oops_AstOut.hs
bsd-3-clause
132
0
9
50
74
39
35
5
1
module Main where main :: IO () main = putStrLn "This is foo from has-exe-foo"
AndreasPK/stack
test/integration/tests/1198-multiple-exes-with-same-name/files/app/Main.hs
bsd-3-clause
80
0
6
16
22
12
10
3
1
-- Test for trac #322 module ShouldCompile where instance (Num a) => Num (Maybe a) where (Just a) + (Just b) = Just (a + b) _ + _ = Nothing (Just a) - (Just b) = Just (a - b) _ - _ = Nothing (Just a) * (Just b) = Just (a * b) _ * _ = Nothing negate (Just a) = Just (negate a) negate _ = Nothing abs (Just a) = Just (abs a) abs _ = Nothing signum (Just a) = Just (signum a) signum _ = Nothing fromInteger = Just . fromInteger f :: Maybe Int -> Int f 1 = 1 f Nothing = 2 -- Gives bogus "Warning: Pattern match(es) are overlapped" f _ = 3
urbanslug/ghc
testsuite/tests/deSugar/should_compile/ds060.hs
bsd-3-clause
593
0
8
181
299
148
151
19
1
module Main where import Data.Text (Text) import qualified Data.Text as T import Graphics.QML factorial :: Integer -> Integer factorial n = product [1..n] main :: IO () main = do clazz <- newClass [ defMethod' "factorial" (\_ txt -> let n = read $ T.unpack txt :: Integer in return . T.pack . show $ product [1..n] :: IO Text)] ctx <- newObject clazz () runEngineLoop defaultEngineConfig { initialDocument = fileDocument "factorial1.qml", contextObject = Just $ anyObjRef ctx }
fredmorcos/attic
snippets/haskell/QML/Main_2.hs
isc
637
0
19
238
190
99
91
15
1
module Morph.Phonology ( phonologicalChange ) where import ClassyPrelude hiding ((\\)) import Data.RVar import Data.Random.Extras import Data.List (nub, (\\)) import Data.Language import Data.Word import Data.Phoneme import Data.Inflection import Data.Soundchange import Constants import HelperFunctions -- Given a phonological rule, change some phonemes into previously-not-existing ones phonologicalChange :: Int -> Language -> RVar Language phonologicalChange 50 lang = return lang --give up after 50 attempts --trace "Gave up on sound change" phonologicalChange i lang = do rule <- generateRule lang let (langN, changes) = executeRuleOnLanguage rule lang if changes < 2 then phonologicalChange (i+1) lang else return langN executeRuleOnLanguage :: Rule -> Language -> (Language, Int) executeRuleOnLanguage rule lang = (langN, rootChanges + derivChanges + inflChanges) where -- Execute rule on each (valid) phoneme in the lexicon and inflection system inflMorphs = getInflMorphemes lang lemmaMorphs = getLemmaMorphemes lang derivMorphs = getDerivMorphemes lang compoundMorphs = getCompoundMorphemes lang rootMorphs = getRootMorphemes lang (inflMorphsN, inflChanges) = second sum $ unzip $ map (executeRuleOnMorpheme rule) inflMorphs :: ([Morpheme], Int) (lemmaMorphsN, lemmaChanges) = second sum $ unzip $ map (executeRuleOnMorpheme rule) lemmaMorphs :: ([Morpheme], Int) (derivMorphsN, derivChanges) = second sum $ unzip $ map (executeRuleOnMorpheme rule) derivMorphs :: ([Morpheme], Int) (compoundMorphsN, compoundChanges) = second sum $ unzip $ map (executeRuleOnMorpheme rule) compoundMorphs :: ([Morpheme], Int) (rootMorphsN, rootChanges) = second sum $ unzip $ map (executeRuleOnMorpheme rule) rootMorphs :: ([Morpheme], Int) -- Take a new survey of which phonemes exist in the lexicon -- Update inventories and maps inflPhonemes = concatMap morphToPhonemes inflMorphsN lemmaPhonemes = concatMap morphToPhonemes lemmaMorphsN derivPhonemes = concatMap morphToPhonemes derivMorphsN compoundPhonemes = concatMap morphToPhonemes compoundMorphsN rootPhonemes = concatMap morphToPhonemes rootMorphsN allPhonemes = nub $ inflPhonemes ++ lemmaPhonemes ++ derivPhonemes ++ compoundPhonemes ++ rootPhonemes cInvN = filter isConsonant allPhonemes vInvN = filter isVowel allPhonemes cMapN = updateCMap cInvN vMapN = updateVMap vInvN -- Need to update valid CC lists -- Need to use rescueSyllables langN = lang{getCMap = cMapN, getCInv = cInvN, getVMap = vMapN, getVInv = vInvN, getInflMorphemes = inflMorphsN, getLemmaMorphemes = lemmaMorphsN, getDerivMorphemes = derivMorphsN, getCompoundMorphemes = compoundMorphsN, getRootMorphemes = rootMorphsN, getRules = rule : getRules lang} -- Creates a new vMap from a given vowel inventory updateVMap :: [Phoneme] -> ([Height], [Backness], [Roundedness], [Length]) updateVMap vInv = (hs, bs, rs, ls) where hs = nub (map getHeight vInv) bs = nub (map getBackness vInv) rs = nub (map getRoundedness vInv) ls = nub (map getLength vInv) -- Creates a new cMap from a given consonant inventory updateCMap :: [Phoneme] -> ([Place], [Manner], [Phonation], [Airstream]) updateCMap cInv = (ps, ms, hs, as) where ps = nub (map getPlace cInv) ms = nub (map getManner cInv) hs = nub (map getVoice cInv) as = nub (map getAirstream cInv) -- Applies rule to a morpheme executeRuleOnMorpheme :: Rule -> Morpheme -> (Morpheme, Int) executeRuleOnMorpheme rule (MorphemeS m t y) = first (MorphemeS m t) (executeRuleOnSyllWord 0 rule [] y) executeRuleOnMorpheme rule (MorphemeC m t y) = (MorphemeC m t y, 0) --simple rules should probably execute executeRuleOnMorpheme rule (MorphemeV m t y) = (MorphemeV m t y, 0) --simple rules should probably execute -- Applies a rule to each phoneme in multiple syllables executeRuleOnSyllWord :: Int -> Rule -> [Syllable] -> [Syllable] -> ([Syllable], Int) executeRuleOnSyllWord _ NoChange _ xs = (xs, 0) executeRuleOnSyllWord i _ ys [] = (ys, i) executeRuleOnSyllWord i rule@Rule{} ys (x:xs) = executeRuleOnSyllWord (i+j) rule (ys++[syllN]) xs where (syllN, j) = executeRuleOnSyllable rule x (lastMay ys, headMay xs) -- Applies a phonological rule to each phoneme in a syllable -- Applying the rule can result in new phonemes (though not impossible ones) executeRuleOnSyllable :: Rule -> Syllable -> (Maybe Syllable, Maybe Syllable) -> (Syllable, Int) executeRuleOnSyllable NoChange syll _ = (syll, 0) executeRuleOnSyllable rule@Rule{} (Syllable onset nuc coda tone stress) (prev, next) = (Syllable onsetN nucN codaN tone stress, i+j+k) where (onsetN, i) = executeRuleOnOnset 0 rule [] onset (prevP, nuc) (nucN, j) = executeRuleOnNucleus rule nuc (prevP, onset, coda, nextP) (codaN, k) = executeRuleOnCoda 0 rule [] coda (nuc, nextP) prevP = syllToPhonemes <$> prev nextP = syllToPhonemes <$> next morphToPhonemes :: Morpheme -> [Phoneme] morphToPhonemes (MorphemeS _ _ y) = nub $ concatMap syllToPhonemes y morphToPhonemes (MorphemeP _ _ y) = nub y morphToPhonemes (MorphemeC _ _ y) = nub $ concat y morphToPhonemes (MorphemeV _ _ y) = nub $ concatMap syllToPhonemes y syllToPhonemes :: Syllable -> [Phoneme] syllToPhonemes (Syllable o n c _ _) = nub $ o ++ [n] ++ c executeRuleOnOnset :: Int -> Rule -> [Phoneme] -> [Phoneme] -> (Maybe [Phoneme], Phoneme) -> ([Phoneme], Int) executeRuleOnOnset _ NoChange _ xs _ = (xs, 0) executeRuleOnOnset i _ ys [] _ = (ys, i) executeRuleOnOnset i rule@(Rule a b p f) [] [x] (prev, nucleus) -- if only one phoneme in onset, compare using the nucleus and phoneme in previous syll | and [ comparePhonemeR p (join $ lastMay <$> prev) || comparePhonemeR2 p (join $ lastMay <$> prev) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (Just nucleus) , not $ impConsonants (applyRule b x) ] = executeRuleOnOnset (i+1) (Rule a b p f) [applyRule b x] [] (prev, nucleus) | otherwise = executeRuleOnOnset i (Rule a b p f) [x] [] (prev, nucleus) executeRuleOnOnset i rule@(Rule a b p f) ys [x] (prev, nucleus) -- for the last phoneme in the onset, compare using the nucleus | and [ comparePhonemeR p (lastMay ys) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (Just nucleus) , not $ impConsonants (applyRule b x) ] = executeRuleOnOnset (i+1) (Rule a b p f) (ys++[applyRule b x]) [] (prev, nucleus) | otherwise = executeRuleOnOnset i (Rule a b p f) (ys++[x]) [] (prev, nucleus) executeRuleOnOnset i rule@(Rule a b p f) [] (x:xs) (prev, nucleus) -- for the first phoneme in the onset, compare using the phonemes of the previous syllable | and [ comparePhonemeR p (join $ lastMay <$> prev) || comparePhonemeR2 p (join $ lastMay <$> prev) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (headMay xs) , not $ impConsonants (applyRule b x) ] = executeRuleOnOnset (i+1) (Rule a b p f) [applyRule b x] xs (prev, nucleus) | otherwise = executeRuleOnOnset i (Rule a b p f) [x] xs (prev, nucleus) executeRuleOnOnset i rule@(Rule a b p f) ys (x:xs) s -- this looks at inter-onset phonemes | and [ comparePhonemeR p (lastMay ys) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (headMay xs) , not $ impConsonants (applyRule b x) ] = executeRuleOnOnset (i+1) (Rule a b p f) (ys++[applyRule b x]) xs s | otherwise = executeRuleOnOnset i (Rule a b p f) (ys++[x]) xs s executeRuleOnCoda :: Int -> Rule -> [Phoneme] -> [Phoneme] -> (Phoneme, Maybe [Phoneme]) -> ([Phoneme], Int) executeRuleOnCoda _ NoChange _ xs _ = (xs, 0) executeRuleOnCoda i _ ys [] _ = (ys, i) executeRuleOnCoda i rule@(Rule a b p f) [] [x] (nucleus, next) | and [ comparePhonemeR p (Just nucleus) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (join $ headMay <$> next) || comparePhonemeR2 f (join $ headMay <$> next) , not $ impConsonants (applyRule b x) ] = executeRuleOnCoda (i+1) (Rule a b p f) [applyRule b x] [] (nucleus, next) | otherwise = executeRuleOnCoda i (Rule a b p f) [x] [] (nucleus, next) executeRuleOnCoda i rule@(Rule a b p f) ys [x] (nucleus, next) | and [ comparePhonemeR p (Just nucleus) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (headMay ys) , not $ impConsonants (applyRule b x) ] = executeRuleOnCoda (i+1) (Rule a b p f) (ys++[applyRule b x]) [] (nucleus, next) | otherwise = executeRuleOnCoda i (Rule a b p f) (ys++[x]) [] (nucleus, next) executeRuleOnCoda i rule@(Rule a b p f) [] (x:xs) (nucleus, next) | and [ comparePhonemeR p (lastMay xs) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (join $ headMay <$> next) || comparePhonemeR2 f (join $ headMay <$> next) , not $ impConsonants (applyRule b x) ] = executeRuleOnCoda (i+1) (Rule a b p f) [applyRule b x] xs (nucleus, next) | otherwise = executeRuleOnCoda i (Rule a b p f) [x] xs (nucleus, next) executeRuleOnCoda i rule@(Rule a b p f) ys (x:xs) s | and [ comparePhonemeR f (headMay ys) , comparePhonemeR (Just a) (Just x) , comparePhonemeR p (lastMay xs) , not $ impConsonants (applyRule b x) ] = executeRuleOnCoda (i+1) (Rule a b p f) (ys++[applyRule b x]) xs s | otherwise = executeRuleOnCoda i (Rule a b p f) (ys++[x]) xs s executeRuleOnNucleus :: Rule -> Phoneme -> (Maybe [Phoneme], [Phoneme], [Phoneme], Maybe [Phoneme]) -> (Phoneme, Int) executeRuleOnNucleus NoChange nuc _ = (nuc, 0) executeRuleOnNucleus rule@(Rule a b p f) nuc (prev, [], [], next) | and [ comparePhonemeR p (join $ lastMay <$> prev) || comparePhonemeR2 p (join $ lastMay <$> prev) , comparePhonemeR (Just a) (Just nuc) , comparePhonemeR f (join $ headMay <$> next) || comparePhonemeR2 f (join $ headMay <$> next) , not $ impConsonants (applyRule b nuc) ] = (applyRule b nuc, 1) | otherwise = (nuc, 0) executeRuleOnNucleus rule@(Rule a b p f) nuc (_, onset, [], next) | and [ comparePhonemeR p (lastMay onset) , comparePhonemeR (Just a) (Just nuc) , comparePhonemeR f (join $ headMay <$> next) || comparePhonemeR2 f (join $ headMay <$> next) , not $ impConsonants (applyRule b nuc) ] = (applyRule b nuc, 1) | otherwise = (nuc, 0) executeRuleOnNucleus rule@(Rule a b p f) nuc (prev, [], coda, _) | and [ comparePhonemeR p (join $ lastMay <$> prev) || comparePhonemeR2 p (join $ lastMay <$> prev) , comparePhonemeR (Just a) (Just nuc) , comparePhonemeR f (headMay coda) , not $ impConsonants (applyRule b nuc) ] = (applyRule b nuc, 1) | otherwise = (nuc, 0) executeRuleOnNucleus rule@(Rule a b p f) nuc (_, onset, coda, _) | and [ comparePhonemeR p (lastMay onset) , comparePhonemeR (Just a) (Just nuc) , comparePhonemeR f (headMay coda) , not $ impConsonants (applyRule b nuc) ] = (applyRule b nuc, 1) | otherwise = (nuc, 0) -- Applies a phonological rule to each phoneme in a word/morpheme -- Applying the rule can result in new phonemes (though not impossible ones) executeRuleOnMorphWord :: Int -> Rule -> [Phoneme] -> [Phoneme] -> ([Phoneme], Int) executeRuleOnMorphWord i _ ys [] = (ys, i) executeRuleOnMorphWord i (Rule a b p f) ys (x:xs) | and [ comparePhonemeR p (lastMay ys) , comparePhonemeR (Just a) (Just x) , comparePhonemeR f (headMay xs) , not $ impConsonants (applyRule b x) ] = executeRuleOnMorphWord (i+1) (Rule a b p f) (ys++[applyRule b x]) xs | otherwise = executeRuleOnMorphWord i (Rule a b p f) (ys++[x]) xs executeRuleOnMorphWord _ NoChange _ xs = (xs, 0) -- Might need someone here if i do semivowel <-> vowel applyRule :: PhonemeR -> Phoneme -> Phoneme applyRule (ConsonantR pr mr hr ar) (Consonant p m h a) = Consonant (fromMaybe p pr) (fromMaybe m mr) (fromMaybe h hr) (fromMaybe a ar) applyRule (VowelR hr br rr lr) (Vowel h b r l) = Vowel (fromMaybe h hr) (fromMaybe b br) (fromMaybe r rr) (fromMaybe l lr) applyRule _ pho = pho --this should never happen -- First argument refers to the Rule's pattern-phonemes -- Nothing means "undefined" and matches everything -- Second argument refres to the actual phoneme in the word -- Nothing there means "Word Boundary" basically -- This function only compares the phonemes themselves though -- comparePhonemeR2 takes care of Syllable and Word Boundaries comparePhonemeR :: Maybe PhonemeR -> Maybe Phoneme -> Bool comparePhonemeR (Just (ConsonantR pr mr hr ar)) (Just (Consonant p m h a)) = fromMaybe True ((p ==) <$> pr) && fromMaybe True ((m ==) <$> mr) && fromMaybe True ((h ==) <$> hr) && fromMaybe True ((a ==) <$> ar) comparePhonemeR (Just (VowelR hr br rr lr)) (Just (Vowel h b r l)) = fromMaybe True ((h ==) <$> hr) && fromMaybe True ((b ==) <$> br) && fromMaybe True ((r ==) <$> rr) && fromMaybe True ((l ==) <$> lr) comparePhonemeR Nothing _ = True --undefined matches everything comparePhonemeR _ _ = False -- Special compare for Word and Syllable Boundaries comparePhonemeR2 :: Maybe PhonemeR -> Maybe Phoneme -> Bool comparePhonemeR2 (Just SyllableBoundary) _ = True -- if your using this function, you're comparing across syllable boundaries comparePhonemeR2 (Just WordBoundary) Nothing = True -- finding nothing = you're looking at a word boundary comparePhonemeR2 (Just WordBoundary) (Just _) = False -- finding anything = you're not looking at a word boundary comparePhonemeR2 _ _ = False -- Generate phonological Rule generateRule :: Language -> RVar Rule generateRule lang = do -- Phoneme A changes into Phoneme B... (soundA, soundB) <- join $ choice [ createCChangePattern lang , createCChangePattern2 lang , createVChangePattern lang , createVChangePattern2 lang ] -- ...preceding Phoneme P and following Phoneme F. (soundP, soundF) <- join $ choice [ createCEnvironmentPattern lang , createVEnvironmentPattern lang ] return $ Rule soundA soundB soundP soundF -- [+consonant]__[+consonant] environment (only existing phonemes, of course) createCEnvironmentPattern :: Language -> RVar (Maybe PhonemeR, Maybe PhonemeR) createCEnvironmentPattern lang = do let (places, manners, phonations, airstreams) = getCMap lang prp <- join $ choice_ 1 Nothing <$> choice (map Just places) mrp <- join $ choice_ 1 Nothing <$> choice (map Just manners) hrp <- join $ choice_ 1 Nothing <$> choice (map Just phonations) arp <- join $ choice_ 1 Nothing <$> choice (map Just airstreams) prf <- join $ choice_ 1 Nothing <$> choice (map Just places) mrf <- join $ choice_ 1 Nothing <$> choice (map Just manners) hrf <- join $ choice_ 1 Nothing <$> choice (map Just phonations) arf <- join $ choice_ 1 Nothing <$> choice (map Just airstreams) p <- choice_ 4 (Just $ ConsonantR prp mrp hrp arp) (Just WordBoundary) f <- choice_ 4 (Just $ ConsonantR prf mrf hrf arf) (Just WordBoundary) return (p, f) -- [+consonant] -> [+consonant] change (only uses existing p/m/h/a's) createCChangePattern :: Language -> RVar (PhonemeR, PhonemeR) createCChangePattern lang = do let (places, manners, phonations, airstreams) = getCMap lang pra <- join $ choice_ 1 Nothing <$> choice (map Just places) mra <- join $ choice_ 1 Nothing <$> choice (map Just manners) hra <- join $ choice_ 1 Nothing <$> choice (map Just phonations) ara <- join $ choice_ 1 Nothing <$> choice (map Just airstreams) prb <- join $ choice_ 1 Nothing <$> choice (Nothing : delete pra (map Just places)) mrb <- join $ choice_ 1 Nothing <$> choice (Nothing : delete mra (map Just manners)) hrb <- join $ choice_ 1 Nothing <$> choice (Nothing : delete hra (map Just phonations)) arb <- join $ choice_ 1 Nothing <$> choice (Nothing : delete ara (map Just airstreams)) if ConsonantR prb mrb hrb arb == ConsonantR Nothing Nothing Nothing Nothing then createCChangePattern lang else return (ConsonantR pra mra hra ara, ConsonantR prb mrb hrb arb) -- [+consonant] -> [+consonant] change (only uses unused p/m/h/a's) createCChangePattern2 :: Language -> RVar (PhonemeR, PhonemeR) createCChangePattern2 lang = do let (places, manners, phonations, airstreams) = getCMap lang pra <- join $ choice_ 1 Nothing <$> choice (map Just places) mra <- join $ choice_ 1 Nothing <$> choice (map Just manners) hra <- join $ choice_ 1 Nothing <$> choice (map Just phonations) ara <- join $ choice_ 1 Nothing <$> choice (map Just airstreams) let place | null ([BILABIAL .. GLOTTAL] \\ places) = return Nothing | otherwise = choice (map Just ([BILABIAL .. GLOTTAL] \\ places)) prb <- join $ choice_ 1 Nothing <$> place let manner | null ([NASAL .. LFLAP] \\ manners) = return Nothing | otherwise = choice (map Just ([NASAL .. LFLAP] \\ manners)) mrb <- join $ choice_ 1 Nothing <$> manner let phonation | null ([VOICELESS .. ASPIRATED] \\ phonations) = return Nothing | otherwise = choice (map Just ([VOICELESS .. ASPIRATED] \\ phonations)) hrb <- join $ choice_ 1 Nothing <$> phonation let airstream | null ([PULMONIC .. LINGUAL] \\ airstreams) = return Nothing | otherwise = choice (map Just ([PULMONIC .. LINGUAL] \\ airstreams)) arb <- join $ choice_ 1 Nothing <$> airstream if ConsonantR prb mrb hrb arb == ConsonantR Nothing Nothing Nothing Nothing then createCChangePattern2 lang else return (ConsonantR pra mra hra ara, ConsonantR prb mrb hrb arb) -- [+vowel]__[+vowel] environment (only existing phonemes, of course) createVEnvironmentPattern :: Language -> RVar (Maybe PhonemeR, Maybe PhonemeR) createVEnvironmentPattern lang = do let (heights, backs, rounds, lengths) = getVMap lang hrp <- join $ choice_ 2 Nothing <$> choice (map Just heights) brp <- join $ choice_ 2 Nothing <$> choice (map Just backs) rrp <- join $ choice_ 2 Nothing <$> choice (map Just rounds) lrp <- join $ choice_ 2 Nothing <$> choice (map Just lengths) hrf <- join $ choice_ 2 Nothing <$> choice (map Just heights) brf <- join $ choice_ 2 Nothing <$> choice (map Just backs) rrf <- join $ choice_ 2 Nothing <$> choice (map Just rounds) lrf <- join $ choice_ 2 Nothing <$> choice (map Just lengths) p <- choice_ 4 (Just $ VowelR hrp brp rrp lrp) (Just WordBoundary) f <- choice_ 4 (Just $ VowelR hrf brf rrf lrf) (Just WordBoundary) return (p, f) -- [+vowel] -> [+vowel] change (only uses existing p/m/h's) createVChangePattern :: Language -> RVar (PhonemeR, PhonemeR) createVChangePattern lang = do let (heights, backs, rounds, lengths) = getVMap lang hra <- join $ choice_ 2 Nothing <$> choice (map Just heights) bra <- join $ choice_ 2 Nothing <$> choice (map Just backs) rra <- join $ choice_ 2 Nothing <$> choice (map Just rounds) lra <- join $ choice_ 2 Nothing <$> choice (map Just lengths) hrb <- join $ choice_ 2 Nothing <$> choice (Nothing : delete hra (map Just heights)) brb <- join $ choice_ 2 Nothing <$> choice (Nothing : delete bra (map Just backs)) rrb <- join $ choice_ 2 Nothing <$> choice (Nothing : delete rra (map Just rounds)) lrb <- join $ choice_ 2 Nothing <$> choice (Nothing : delete lra (map Just lengths)) if VowelR hrb brb rrb lrb == VowelR Nothing Nothing Nothing Nothing then createVChangePattern lang else return (VowelR hra bra rra lra, VowelR hrb brb rrb lrb) -- [+vowel] -> [+vowel] change (only uses unused h/b/r/l/t's) createVChangePattern2 :: Language -> RVar (PhonemeR, PhonemeR) createVChangePattern2 lang = do let (heights, backs, rounds, lengths) = getVMap lang hra <- join $ choice_ 2 Nothing <$> choice (map Just heights) bra <- join $ choice_ 2 Nothing <$> choice (map Just backs) rra <- join $ choice_ 2 Nothing <$> choice (map Just rounds) lra <- join $ choice_ 2 Nothing <$> choice (map Just lengths) let height | null ([CLOSE .. OPEN] \\ heights) = return Nothing | otherwise = choice (map Just ([CLOSE .. OPEN] \\ heights)) hrb <- join $ choice_ 2 Nothing <$> height let back | null ([BACK .. FRONT] \\ backs) = return Nothing | otherwise = choice (map Just ([BACK .. FRONT] \\ backs)) brb <- join $ choice_ 2 Nothing <$> back let rnd | null ([ROUNDED .. UNROUNDED] \\ rounds) = return Nothing | otherwise = choice (map Just ([ROUNDED .. UNROUNDED] \\ rounds)) rrb <- join $ choice_ 2 Nothing <$> rnd let lngth | null ([SHORT .. LONG] \\ lengths) = return Nothing | otherwise = choice (map Just ([SHORT .. LONG] \\ lengths)) lrb <- join $ choice_ 2 Nothing <$> lngth if VowelR hrb brb rrb lrb == VowelR Nothing Nothing Nothing Nothing then createVChangePattern2 lang else return (VowelR hra bra rra lra, VowelR hrb brb rrb lrb) -- Shelved -- this should clean up any improper contrasts -- like having short/long vowels, one of them needs to be redefined to 'normal' -- maybe having only one of [LAMINALALVEOLAR, APICOALVEOLAR] should result in it redefining to ALVEOLAR -- same with POSTALVEOLAR -- having NEAROPEN without OPEN or NEARCLOSE without CLOSE seems like it should be impossible -- same with NEARBACK and BACK and NEARFRONT and FRONT -- so basically once a rule is applied and the cmap and vmaps are updated -- check if there are "improper contrasts", and then go back through the lexicon and redefine shit {- cleanUpRuleC :: Language -> RVar Rule cleanUpRuleC lang = langN where (ps, ms, hs) = getCMap langN action | LAMINALALVEOLAR `elem` ps && APICOALVEOLAR `notElem` ps = --LAMINALALVEOLAR -> ALVEOLAR | APICOALVEOLAR `elem` ps && LAMINALALVEOLAR `notElem` ps = --APICOALVEOLAR -> ALVEOLAR | ALVEOLAR `elem` ps && LAMINALALVEOLAR `elem` ps && APICOALVEOLAR `elem` ps = --ALVEOLAR -> LAMINALALVEOLAR or APICOALVEOLAR? | PALATOALVEOLAR `elem` ps && APICALRETROFLEX `notElem` ps && ALVEOLOPALATAL `notElem` ps = --PALATOALVEOLAR -> POSTALVEOLAR | APICALRETROFLEX `elem` ps && PALATOALVEOLAR `notElem` ps && ALVEOLOPALATAL `notElem` ps = --APICALRETROFLEX -> POSTALVEOLAR | ALVEOLOPALATAL `elem` ps && APICALRETROFLEX `notElem` ps && PALATOALVEOLAR `notElem` ps = --ALVEOLOPALATAL -> POSTALVEOLAR | POSTALVEOLAR `elem` ps && PALATOALVEOLAR `elem` ps && APICALRETROFLEX `notElem` ps && ALVEOLOPALATAL `notElem` ps = --POSTALVEOLAR -> APICALRETROFLEX or ALVEOLOPALATAL | POSTALVEOLAR `elem` ps && PALATOALVEOLAR `elem` ps && APICALRETROFLEX `elem` && ALVEOLOPALATAL `notElem` ps = --POSTALVEOLAR -> ALVEOLOPALATAL | POSTALVEOLAR `elem` ps && APICALRETROFLEX `elem` ps && PALATOALVEOLAR `notElem` ps && ALVEOLOPALATAL `notElem` ps = --POSTALVEOLAR -> PALATOALVEOLAR or ALVEOLOPALATAL | POSTALVEOLAR `elem` ps && APICALRETROFLEX `elem` ps && PALATOALVEOLAR `notElem` ps && ALVEOLOPALATAL `elem` ps = --POSTALVEOLAR -> PALATOALVEOLAR | POSTALVEOLAR `elem` ps && ALVEOLOPALATAL `elem` ps && PALATOALVEOLAR `notElem` ps && APICALRETROFLEX `notElem` ps = --POSTALVEOLAR -> PALATOALVEOLAR or APICALRETROFLEX | POSTALVEOLAR `elem` ps && ALVEOLOPALATAL `elem` ps && PALATOALVEOLAR `elem` ps && APICALRETROFLEX `notElem` ps = --POSTALVEOLAR -> APICALRETROFLEX | POSTALVEOLAR `elem` ps && ALVEOLOPALATAL `elem` ps && PALATOALVEOLAR `elem` ps && APICALRETROFLEX `elem` ps = --POSTALVEOLAR -> ANY return $ Rule soundA soundB soundP soundF cleanUpRuleV :: Language -> RVar Rule cleanUpRuleV lang = do (hs, bs, rs, ls, ts) = getVMap lanN actionV | LONG `elem` ls && SHORT `elem` ls && NORMAL `notElem` ls = --LONG or SHORT -> NORMAL | NEAROPEN `elem` hs && OPEN `notElem` hs = --NEAROPEN -> OPEN | NEARCLOSE `elem` hs && CLOSE `notElem` hs = --NEARCLOSE -> CLOSE | NEARBACK `elem` bs && BACK `notElem` bs = --NEARBACK -> BACK | NEARFRONT `elem` bs && FRONT `notElem` bs = --NEARFRONT -> FRONT | CLOSEMID `elem` hs && MID `notElem` hs && OPENMID `notElem` hs = --CLOSEMID -> MID | OPENMID `elem` hs && MID `notElem` hs && CLOSEMID `notElem` hs = --CLOSEMID -> MID | HRISET `elem` ts && LRISET `notElem` ts && RISET `notElem` ts = --HRISET -> RISET | LRISET `elem` ts && HRISET `notElem` ts && RISET `notElem` ts = --LRISET -> RISET | HFALLT `elem` ts && LFALLT `notElem` ts && FALLT `notElem` ts = --HFALLT -> FALLT | LFALLT `elem` ts && HFALLT `notElem` ts && FALLT `notElem` ts = --LFALLT -> FALLT return $ Rule soundA soundB soundP soundF -}
Brightgalrs/con-lang-gen
src/Morph/Phonology.hs
mit
24,898
0
16
5,462
8,049
4,097
3,952
309
2
{- HAAP: Haskell Automated Assessment Platform This module provides the @CmdArgs@ plugin (<https://hackage.haskell.org/package/cmdargs>) for command-line argument support. -} {-# LANGUAGE DeriveDataTypeable, TypeOperators, FlexibleInstances, UndecidableInstances, FlexibleContexts, TypeFamilies, MultiParamTypeClasses, ConstraintKinds #-} module HAAP.CmdArgs where import HAAP.Core import HAAP.Plugin import HAAP.IO import System.Environment import System.Console.CmdArgs hiding (CmdArgs,def,Default(..)) import Data.Default import Data.Proxy import Data.Typeable import Control.Monad.Reader as Reader import Control.Monad.Catch import Control.Monad.Trans.Compose import Control.Monad.Morph data CmdArgs args = CmdArgs args deriving (Data,Typeable) type HasCmdArgs args t m = HasPlugin (CmdArgs args) t m instance (Data args) => HaapPlugin (CmdArgs args) where type PluginI (CmdArgs args) = CmdArgs args type PluginO (CmdArgs args) = () type PluginT (CmdArgs args) = ReaderT (CmdArgs args) type PluginK (CmdArgs args) t m = (MonadIO m,Data args) usePlugin getArgs m = do CmdArgs argsDef <- getArgs args <- runBaseIO $ cmdArgs argsDef x <- mapHaapMonad (flip Reader.runReaderT (CmdArgs args) . getComposeT) m return (x,()) useCmdArgs :: (HaapStack t m,PluginK (CmdArgs args) t m) => args -> Haap (PluginT (CmdArgs args) :..: t) m a -> Haap t m a useCmdArgs argsDef = usePlugin_ (return $ CmdArgs argsDef) instance (HaapMonad m) => HasPlugin (CmdArgs args) (ReaderT (CmdArgs args)) m where liftPlugin = id instance (HaapStack t2 m) => HasPlugin (CmdArgs args) (ComposeT (ReaderT (CmdArgs args)) t2) m where liftPlugin m = ComposeT $ hoist' lift m readCmdArgs :: HasPlugin (CmdArgs args) t m => Haap t m args readCmdArgs = do CmdArgs args <- liftHaap $ liftPluginProxy (Proxy::Proxy (CmdArgs args)) $ Reader.ask return args
hpacheco/HAAP
src/HAAP/CmdArgs.hs
mit
1,905
0
14
328
607
319
288
37
1
module Data.List.Util ( deletions, splits, shuffle ) where import Control.Arrow (second) import Control.Monad (forM) import Data.Array.IO.Safe (IOArray, newListArray, readArray, writeArray) import System.Random (randomRIO) deletions :: [a] -> [(a, [a])] deletions [] = [] deletions (x:xs) = (x, xs) : map (second (x :)) (deletions xs) splits :: [a] -> [([a], a, [a])] splits [] = [] splits (x:xs) = ([], x, xs) : map (\(l, c, r) -> (x:l, c, r)) (splits xs) shuffle :: [a] -> IO [a] shuffle xs = do let n = length xs ar <- newArray n xs forM [1 .. n] $ \i -> do j <- randomRIO (i, n) vi <- readArray ar i vj <- readArray ar j writeArray ar j vi return vj newArray :: Int -> [a] -> IO (IOArray Int a) newArray n = newListArray (1, n)
YellPika/Hannel
src/Data/List/Util.hs
mit
793
0
13
199
435
238
197
24
1
module Tamien.Core (module X) where import Tamien.Core.Language as X import Tamien.Core.Parser as X import Tamien.Core.Printer as X
cpettitt/tamien
Tamien/Core.hs
mit
133
0
4
18
36
26
10
4
0
-- Church Numbers - Add, Multiply, Exponents -- http://www.codewars.com/kata/55c0c452de0056d7d800004d/ module Haskell.Codewars.Church where type Lambda a = (a -> a) type Cnum a = Lambda a -> Lambda a churchAdd :: Cnum a -> Cnum a -> Cnum a churchAdd c1 c2 f = c1 f . c2 f churchMul :: Cnum a -> Cnum a -> Cnum a churchMul c1 c2 = c1 . c2 churchPow :: Cnum a -> (Cnum a -> Cnum a) -> Cnum a churchPow cb ce = ce cb
gafiatulin/codewars
src/3 kyu/Church.hs
mit
419
0
9
89
165
83
82
9
1
{- H-99 Problems Copyright 2015 (c) Adrian Nwankwo (Arcaed0x) Problem : 8 Description : Eliminate consecutive duplicates of list elements. License : MIT (See LICENSE file) -} unique :: (Eq a) => [a] -> [a] unique [] = [] unique (x:xs) = reverse $ foldl uniqueFilter [x] xs where uniqueFilter acc x = if (head acc) == x then acc else x:acc
Arcaed0x/H-99-Solutions
src/prob8.hs
mit
432
0
10
155
101
54
47
6
2
sum [1..10] take (double 2) [1, 2, 3, 4, 5, 6] head [1,2,3,4,5] tail [1,2,3,4,5] [1,2,3,4,5] !! 2 //Not a constant time operation take 3 [1,2,3,4,5] drop 3 [1,2,3,4,5] length [1,2,3,4,5] [1,2,3] ++ [4,5] sum [1,2,3,4,5] product [1,2,3,4,5] reverse [1,2,3,4,5] /*f [] = [] f (x:xs) = f ys ++ [x] + f zs where ys = [a | a <- xs, a <=x ] zs = [b | b <- xs, b > x]*/
jugalps/edX
FP101x/week1/week1.hs
mit
407
3
8
119
370
205
165
-1
-1
module DataModels( Queue, Stack, createQueue, createStack, queuePush, stackPush, queuePop, stackPop, queueSize, stackSize, getQueueList ) where -- Defining a generic queue data structure -- Can be a queue of any type -- This isn't performance focused data Queue a = Queue [a] deriving(Show) data Stack a = Stack [a] deriving(Show) -- ------------ Queue Operations -------------------- createQueue :: [a] -> Queue a createQueue item = Queue item queuePush :: a -> Queue a -> Queue a queuePush item (Queue items) = Queue (items ++ [item]) -- Makes pop operation and returns a tuple -- Output: (popItem, queueWithoutPopItem) queuePop :: Queue a -> (a, Queue a) queuePop (Queue items) = (head items, Queue (tail items)) queueSize :: Queue a -> Int queueSize (Queue x) = length x getQueueList :: Queue a -> [a] getQueueList (Queue x) = x -- ------------ Stack Operations -------------------- createStack :: [a] -> Stack a createStack item = Stack item stackPush :: a -> Stack a -> Stack a stackPush item (Stack items) = Stack ([item] ++ items) stackPop :: Stack a -> (a, Stack a) stackPop (Stack items) = (head items, Stack(tail items)) stackSize :: Stack a -> Int stackSize (Stack x) = length x
MFire30/haskellPresidentCardgame
app/src/DataModels.hs
mit
1,230
0
8
236
427
228
199
34
1
{-# LANGUAGE TemplateHaskell, NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Mezzo.Compose.Chords -- Description : Harmonic composition units -- Copyright : (c) Dima Szamozvancev -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Literals for chords and progressions. -- ----------------------------------------------------------------------------- module Mezzo.Compose.Chords where import Mezzo.Model import Mezzo.Compose.Types import Mezzo.Compose.Builder import Mezzo.Compose.Templates import Mezzo.Compose.Basic -- * Atomic literals -- ** Scale degree literals scaleDegreeLits -- ** Mode literals modeLits -- ** Dyad type literals dyaTyLits -- ** Triad type literals triTyLits -- ** Tetrad type literals tetTyLits _dbl :: TriType t -> TetType (DoubledT t) _dbl t = TetType -- ** Inversion literals invLits -- ** Constructors -- | Create a new key from a pitch class, accidental and mode. key :: PC p -> Acc a -> Mod m -> KeyS (Key p a m) key p a m = KeyS -- | Create a triad from a root, a triad type and an inversion. triad :: Root r -> TriType t -> Inv i -> Cho (Triad r t i) triad r t i = Cho -- | Create a seventh chord from a root, a triad type and an inversion. seventh :: Root r -> TetType t -> Inv i -> Cho (Tetrad r t i) seventh r t i = Cho -- * Chord builders -- ** Dyad converters mkDyaConvs -- ** Triad converters mkTriConvs -- ** Doubled dyad converters mkDoubledDConvs -- ** Tetrad converters mkTetConvs -- ** Doubled triad converters mkDoubledTConvs -- ** Inversion mutators inv :: ChorM c (InvertChord c) inv = constConv Cho
DimaSamoz/mezzo
src/Mezzo/Compose/Chords.hs
mit
1,719
0
10
312
308
166
142
28
1
coins = [1,2,5,10,20,50,100,200] coinMaxCombo = map (\x -> 200 `div` x) coins coin_vals = zip coins coinMaxCombo --coins = [(1,200),(2,100),(5,40),(10,20),(20,10),(50,4),(100,2),(200,1)] effective (c,n) = c*n is_valid xs = sum xs == 200 coin_func (c,n) = [effective (c,n) | n <- [0..n]] ec = map coin_func coin_vals combos = [ [a,b,c,d,e,f,g,h] | a <- ec !! 0, b <- ec !! 1, c <- ec !! 2, d <- ec !! 3, e <- ec !! 4, f <- ec !! 5, g <- ec !! 6, h <- ec !! 7, a+b+c+d+e+f+g+h == 200] withcoins 1 x = [[x]] withcoins n x = concatMap addCoin [0 .. x `div` coins!!(n-1)] where addCoin k = map (++[k]) (withcoins (n-1) (x - k*coins!!(n-1)) ) effective_combo = map (\xs -> zipWith (*) coins xs) $ withcoins (length coins) 200 --combos2 = zipWith (*) coins $ withcoins (length coins) 200 ans2 = length $ effective_combo
stefan-j/ProjectEuler
q31.hs
mit
881
4
14
218
479
261
218
15
1
module Worksheet where data DayOfWeek = Mon | Tue | Weds | Thu | Fri | Sat | Sun deriving(Show, Eq) -- deriving (Ord, Show, Eq) -- If you need to automatically implement Ord, this is the way to go. instance Ord DayOfWeek where compare Fri Fri = EQ compare Fri _ = GT compare _ Fri = LT compare _ _ = EQ
raventid/coursera_learning
haskell/chapter6/ord_worksheet.hs
mit
331
0
6
92
90
51
39
9
0
{-# LANGUAGE DeriveGeneric #-} module Abalone ( Game(..) , Outcome(..) , Board(Board) , Player(White, Black) , Position , gameOver , winner , numPieces , futures , isValid , Direction , Segment , segments , adjacent , start ) where import Data.Ord import Data.List import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Aeson import GHC.Generics import Control.Applicative import Control.Monad import Player data Outcome = WhiteWins | BlackWins | TieGame deriving (Eq, Show, Read, Generic) data Game = Game { board :: Board , nextPlayer :: Player , movesRemaining :: Int , marblesPerMove :: Int , lossThreshold :: Int -- if pieces <= threshold, loss occurs } deriving (Eq, Show, Read, Generic) instance FromJSON Game instance ToJSON Game data Board = Board { whitePositions :: Set Position , blackPositions :: Set Position , boardRadius :: Int } deriving (Eq, Show, Read, Generic) instance FromJSON Board instance ToJSON Board getPieces :: Board -> Player -> Set Position getPieces b White = whitePositions b getPieces b Black = blackPositions b start :: Game start = Game standardBoard White 200 3 8 standardBoard :: Board standardBoard = Board whitePos blackPos 5 where whitePos = Set.fromList $ [(-4,0,4),(-4,1,3),(-2,0,2)] >>= \(q,q',r) -> map (flip (,) r) [q..q'] blackPos = Set.map (\(q, r) -> (-q, -r)) whitePos {-- Chas: that code might make more sense if you replace(list) >>= function with (flip concatmap) (list) (function) Then flip the function args so it's set $ concatMap (function) [list] --} -- Position / Grid Functions -- type Position = (Int, Int) dist2 :: Position -> Position -> Int -- distance * 2 (to avoid fractional types) dist2 (q1,r1) (q2,r2) = abs (q1 - q2) + abs (r1 - r2) + abs (q1 + r1 - q2 - r2) data Direction = TopRight | MidRight | BotRight | TopLeft | MidLeft | BotLeft deriving (Eq, Show, Read, Ord, Bounded, Enum, Generic) instance FromJSON Direction instance ToJSON Direction adjacent :: Direction -> Position -> Position adjacent TopRight (q, r) = (q+1, r-1) adjacent MidRight (q, r) = (q+1, r ) adjacent BotRight (q, r) = (q , r+1) adjacent BotLeft (q, r) = (q-1, r+1) adjacent MidLeft (q, r) = (q-1, r ) adjacent TopLeft (q, r) = (q , r-1) (|>) = flip adjacent opposite :: Direction -> Direction opposite TopRight = BotLeft opposite MidRight = MidLeft opposite BotRight = TopLeft opposite BotLeft = TopRight opposite MidLeft = MidRight opposite TopLeft = BotRight colinear :: Direction -> Direction -> Bool colinear d1 d2 = d1 == d2 || d1 == opposite d2 -- Moves are internal-only representation of a move - external API is just game states data Move = Move { segment :: Segment , direction :: Direction } deriving (Eq, Show, Read, Generic) inline, broadside :: Move -> Bool inline m@(Move s _) | isNothing $ orientation s = False | otherwise = colinear (direction m) (fromJust $ orientation s) broadside m = not (inline m) -- A segment is a linear group of marbles that could move. data Segment = Segment { basePos :: Position -- The start position of the segment , orientation :: Maybe Direction -- The direction the segment grows in (Nothing if len is 1) , segLength :: Int -- The length of the segment , player :: Player -- The controlling player } deriving (Eq, Show, Read, Generic) segPieces :: Segment -> [Position] segPieces (Segment pos orient len _) = maybe [pos] safeGetPieces orient where safeGetPieces orient = take len $ iterate (|> orient) pos gameOver :: Game -> Bool gameOver g = movesRemaining g <= 0 || any (\p -> numPieces g p <= lossThreshold g) [White, Black] winner :: Game -> Maybe Outcome winner g | gameOver g = Just advantage | otherwise = Nothing where advantage = case comparing (numPieces g) White Black of GT -> WhiteWins LT -> BlackWins EQ -> TieGame numPieces :: Game -> Player -> Int numPieces g p = Set.size $ getPieces (board g) p -- this function will recieve new game states from client and verify validity isValid :: Game -> Game -> Bool isValid g0 g1 = g1 `elem` futures g0 -- very inefficient impl but that should be fine since occurs once per turn onBoard :: Board -> Position -> Bool -- is a piece on the board still? onBoard board pos = dist2 pos (0, 0) <= boardRadius board * 2 owner :: Board -> Position -> Maybe Player owner b x | x `Set.member` getPieces b White = Just White | x `Set.member` getPieces b Black = Just Black | otherwise = Nothing -- Take a board and a proposed inline move, and return Just the moved enemy pieces if it is valid inlineMoved :: Board -> Move -> Maybe [Position] inlineMoved b m@(Move s@(Segment pos orient len player) dir) | inline m = let front = if fromJust orient == dir then last else head attacked = (|> dir) . front $ segPieces s attackedPieces x force | isNothing $ owner b x = Just [] | owner b x == Just player || force == 0 = Nothing | otherwise = (:) x <$> attackedPieces (x |> dir) (force - 1) in attackedPieces attacked (len - 1) | otherwise = Nothing update :: Game -> Move -> Game update (Game b p remaining perMove lossThreshold) m@(Move s dir) = newGame where -- Pieces to move ownPieces = segPieces s enemyPieces | broadside m = [] | inline m = fromJust $ inlineMoved b m -- New game state updated = filter (onBoard b) . map (|> dir) (whiteMoved, blackMoved) | p == White = (ownPieces, enemyPieces) | p == Black = (enemyPieces, ownPieces) newWhitePos = (whitePositions b \\ whiteMoved) \/ updated whiteMoved newBlackPos = (blackPositions b \\ blackMoved) \/ updated blackMoved s \\ l = Set.difference s (Set.fromList l) s \/ l = Set.union s (Set.fromList l) newBoard = Board newWhitePos newBlackPos (boardRadius b) newGame = Game newBoard (next p) (remaining - 1) perMove lossThreshold futures :: Game -> [Game] -- find all valid future states of this board (1 move) futures g = map (update g) (possibleMoves g) {- Algorithm: - find all segments (distinct groupings that can move) - take cartesian product with all directions - see if that direction is a valid move for given segment - if orientation is aligned with direction, attempt a "forward" move - might push off opponent so more complex computation - if orientation is not aligned with direction, attempt a "broadside" - just check that all destination spaces are free -} possibleMoves :: Game -> [Move] possibleMoves g@(Game b p _ _ _) = do move <- Move <$> segments g <*> [minBound .. maxBound] guard $ valid move return move where free x = isNothing $ owner b x valid m@(Move s dir) | broadside m = all free $ map (|> dir) (segPieces s) | inline m = isJust $ inlineMoved b m -- get every segment (distinct linear grouping) for current player in game -- handle singletons seperately because otherwise they could be triple-counted segments :: Game -> [Segment] segments (Game b p _ maxlen _) = singletons ++ lengthTwoOrMore where pieces = Set.toList $ getPieces b p singletons = [Segment x Nothing 1 p | x <- pieces] lengthTwoOrMore = do pos <- pieces orient <- [TopRight, MidRight, BotRight] len <- [2..maxlen] let seg = Segment pos (Just orient) len p guard $ valid seg return seg where valid = all (`Set.member` getPieces b p) . segPieces
danmane/abalone
unsupported/hs/src/abalone.hs
mit
7,930
0
16
2,114
2,491
1,318
1,173
165
3
module Hanoi where type Peg = String type Move = (Peg, Peg) hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi 0 _ _ _ = [] hanoi n t1 t2 t3 = hanoi (n-1) t1 t3 t2 ++ [(t1, t2)] ++ hanoi (n-1) t3 t2 t1
tomwadeson/cis194
week1/Hanoi.hs
mit
210
0
9
55
125
69
56
6
1
-- Haskell Anagram Library -- Copyright (c) Ryan Kadwell <[email protected]> -- -- For the full copyright and license information, please view the LICENSE -- file that was distributed with this source code. -- -- Author: Ryan Kadwell <[email protected]> module Main (main) where import Control.Monad (when) import Data.Char (toLower) import Data.Function (on) import Data.List (sortBy, nub) import Data.Maybe (fromMaybe) import Hanagram (getMatches, getMatchesDups) import Hanagram.Presentation (showResults, sayResults, showAndSayResults) import System.Console.GetOpt import System.Environment (getArgs) import System.Exit (exitWith, ExitCode(..)) -- | Return the hanagram version string versionString :: String versionString = "\nHanagram v1.0\nCopyright (c) Ryan Kadwell 2013 <[email protected]>\n" -- | Returns the hanagram usage information usageString :: [OptDescr (Options -> Options)] -> String usageString options = usageInfo header options where header = "\nUsage: hanagram [options...] [dictionary files...]" data Options = Options { optVersion :: Bool , optHelp :: Bool , optOrdered :: Bool , optSpeech :: Bool , optDups :: Bool , optLength :: Maybe String , optLetters :: String } deriving (Show) defaultOptions = Options { optVersion = False , optHelp = False , optOrdered = False , optSpeech = False , optDups = False , optLength = Nothing , optLetters = [] } options :: [OptDescr (Options -> Options)] options = [ Option "v" ["version"] (NoArg (\ opts -> opts { optVersion = True })) "Display version" , Option "h?" ["help"] (NoArg (\ opts -> opts { optHelp = True })) "Display help message" , Option "o" ["ordered"] (NoArg (\ opts -> opts { optOrdered = True })) "Display the output sorted based on word length" , Option "s" ["say"] (NoArg (\ opts -> opts { optSpeech = True })) "Enable text to speech processing" , Option [] ["dups"] (NoArg (\ opts -> opts { optDups = True })) "When finding words that match allow letters to be used more than once" , Option "n" ["length"] (OptArg ((\ f opts -> opts { optLength = Just f }) . fromMaybe "0" ) "INTEGER") "Limit results to words of a specific length" , Option "l" ["letters"] (ReqArg (\ l opts -> opts { optLetters = l }) "STRING") "The available letters" ] -- | parse the options from passed array into the opts object parseOpts :: [String] -> IO (Options, [String]) parseOpts argv = case getOpt Permute options argv of (o, n, []) -> return (foldl (flip id) defaultOptions o, n) (_, _, errs) -> ioError (userError (concat errs ++ usageString options)) -- | Read an array of files and return all the lines that are contained. -- This allows us to pass dict files where it contains one word per line or -- just regular space delimited files parseFiles :: [FilePath] -> IO [String] parseFiles [] = return [] parseFiles (x:xs) = do contents <- readFile x let returnLines = lines contents rest <- parseFiles xs return $ returnLines ++ rest -- converts a maybe string into the length limit or 0 if we dont care about -- the length fixLength :: Maybe String -> Int fixLength Nothing = 0 fixLength (Just x) = (read x :: Int) main :: IO (ExitCode) main = do args <- getArgs (opts, files) <- parseOpts args when (optHelp opts) $ do putStrLn $ versionString ++ (usageString options) exitWith ExitSuccess when (optVersion opts) $ do putStrLn versionString exitWith ExitSuccess words <- parseFiles files when (words == []) $ do putStrLn "hanagram: error: No words to check against. \nEnsure you have provided a path to a usable dictionary file" exitWith $ ExitFailure 1 let getMatchesFunction = if optDups opts then getMatchesDups else getMatches -- need case insesitive searching let filteredWords = [ map toLower word | word <- words ] let searchLength = fixLength (optLength opts) let matches = if searchLength == 0 then [ word | word <- getMatchesFunction (optLetters opts) filteredWords] else [ word | word <- getMatchesFunction (optLetters opts) filteredWords, length word == searchLength] let sortedMatches = if optOrdered opts then sortBy (compare `on` length) matches else matches -- show results omiting any duplicates. We filter duplicates at this -- point because its not a cheap process... let filteredResults = nub sortedMatches if optSpeech opts then showAndSayResults filteredResults else showResults filteredResults return ExitSuccess
ryakad/hanagram
main.hs
mit
4,737
0
16
1,132
1,224
661
563
99
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-fieldtomatch.html module Stratosphere.ResourceProperties.WAFRegionalByteMatchSetFieldToMatch where import Stratosphere.ResourceImports -- | Full data type definition for WAFRegionalByteMatchSetFieldToMatch. See -- 'wafRegionalByteMatchSetFieldToMatch' for a more convenient constructor. data WAFRegionalByteMatchSetFieldToMatch = WAFRegionalByteMatchSetFieldToMatch { _wAFRegionalByteMatchSetFieldToMatchData :: Maybe (Val Text) , _wAFRegionalByteMatchSetFieldToMatchType :: Val Text } deriving (Show, Eq) instance ToJSON WAFRegionalByteMatchSetFieldToMatch where toJSON WAFRegionalByteMatchSetFieldToMatch{..} = object $ catMaybes [ fmap (("Data",) . toJSON) _wAFRegionalByteMatchSetFieldToMatchData , (Just . ("Type",) . toJSON) _wAFRegionalByteMatchSetFieldToMatchType ] -- | Constructor for 'WAFRegionalByteMatchSetFieldToMatch' containing required -- fields as arguments. wafRegionalByteMatchSetFieldToMatch :: Val Text -- ^ 'wafrbmsftmType' -> WAFRegionalByteMatchSetFieldToMatch wafRegionalByteMatchSetFieldToMatch typearg = WAFRegionalByteMatchSetFieldToMatch { _wAFRegionalByteMatchSetFieldToMatchData = Nothing , _wAFRegionalByteMatchSetFieldToMatchType = typearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-fieldtomatch.html#cfn-wafregional-bytematchset-fieldtomatch-data wafrbmsftmData :: Lens' WAFRegionalByteMatchSetFieldToMatch (Maybe (Val Text)) wafrbmsftmData = lens _wAFRegionalByteMatchSetFieldToMatchData (\s a -> s { _wAFRegionalByteMatchSetFieldToMatchData = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-fieldtomatch.html#cfn-wafregional-bytematchset-fieldtomatch-type wafrbmsftmType :: Lens' WAFRegionalByteMatchSetFieldToMatch (Val Text) wafrbmsftmType = lens _wAFRegionalByteMatchSetFieldToMatchType (\s a -> s { _wAFRegionalByteMatchSetFieldToMatchType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/WAFRegionalByteMatchSetFieldToMatch.hs
mit
2,203
0
13
212
265
151
114
28
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordformat.html module Stratosphere.ResourceProperties.KinesisAnalyticsApplicationRecordFormat where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.KinesisAnalyticsApplicationMappingParameters -- | Full data type definition for KinesisAnalyticsApplicationRecordFormat. -- See 'kinesisAnalyticsApplicationRecordFormat' for a more convenient -- constructor. data KinesisAnalyticsApplicationRecordFormat = KinesisAnalyticsApplicationRecordFormat { _kinesisAnalyticsApplicationRecordFormatMappingParameters :: Maybe KinesisAnalyticsApplicationMappingParameters , _kinesisAnalyticsApplicationRecordFormatRecordFormatType :: Val Text } deriving (Show, Eq) instance ToJSON KinesisAnalyticsApplicationRecordFormat where toJSON KinesisAnalyticsApplicationRecordFormat{..} = object $ catMaybes [ fmap (("MappingParameters",) . toJSON) _kinesisAnalyticsApplicationRecordFormatMappingParameters , (Just . ("RecordFormatType",) . toJSON) _kinesisAnalyticsApplicationRecordFormatRecordFormatType ] -- | Constructor for 'KinesisAnalyticsApplicationRecordFormat' containing -- required fields as arguments. kinesisAnalyticsApplicationRecordFormat :: Val Text -- ^ 'kaarfRecordFormatType' -> KinesisAnalyticsApplicationRecordFormat kinesisAnalyticsApplicationRecordFormat recordFormatTypearg = KinesisAnalyticsApplicationRecordFormat { _kinesisAnalyticsApplicationRecordFormatMappingParameters = Nothing , _kinesisAnalyticsApplicationRecordFormatRecordFormatType = recordFormatTypearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordformat.html#cfn-kinesisanalytics-application-recordformat-mappingparameters kaarfMappingParameters :: Lens' KinesisAnalyticsApplicationRecordFormat (Maybe KinesisAnalyticsApplicationMappingParameters) kaarfMappingParameters = lens _kinesisAnalyticsApplicationRecordFormatMappingParameters (\s a -> s { _kinesisAnalyticsApplicationRecordFormatMappingParameters = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordformat.html#cfn-kinesisanalytics-application-recordformat-recordformattype kaarfRecordFormatType :: Lens' KinesisAnalyticsApplicationRecordFormat (Val Text) kaarfRecordFormatType = lens _kinesisAnalyticsApplicationRecordFormatRecordFormatType (\s a -> s { _kinesisAnalyticsApplicationRecordFormatRecordFormatType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/KinesisAnalyticsApplicationRecordFormat.hs
mit
2,709
0
13
212
260
150
110
29
1
-- GenI surface realiser -- Copyright (C) 2005 Carlos Areces and Eric Kow -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- | This module provides some very generic, non-GenI specific functions on strings, -- trees and other miscellaneous odds and ends. Whenever possible, one should try -- to replace these functions with versions that are available in the standard -- libraries, or the Haskell platform ones, or on hackage. {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} module NLP.GenI.General ( -- * IO ePutStr, ePutStrLn, eFlush, -- * Strings isGeniIdentLetter, dropTillIncluding, trim, toUpperHead, toLowerHead, toAlphaNum, quoteString, quoteText, maybeQuoteText, clumpBy, -- * Triples first3, second3, third3, fst3, snd3, thd3, -- * Lists map', buckets, isEmptyIntersect, groupByFM, insertToListMap, histogram, combinations, mapMaybeM, repList, -- * Trees mapTree', filterTree, treeLeaves, preTerminals, repNode, repAllNode, listRepNode, repNodeByNode, -- * Intervals Interval, (!+!), ival, showInterval, -- * Bit vectors BitVector, showBitVector, -- * Errors, logging and exceptions geniBug, prettyException, mkLogname, ) where import Control.Arrow (first) import Control.Exception (IOException) import Control.Monad (liftM) import Data.Binary import Data.Bits (shiftR, (.&.)) import Data.Char (isAlphaNum, isDigit, isSpace, toLower, toUpper) import Data.Function (on) import Data.List (foldl', groupBy, inits, intersect, intersperse, sortBy) import qualified Data.Map as Map import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Tree import Data.Typeable (Typeable, typeOf) import Prelude hiding (catch) import System.IO (hFlush, hPutStr, hPutStrLn, stderr) import System.IO.Error (ioeGetErrorString, isUserError) import Text.JSON -- ---------------------------------------------------------------------- -- IO -- ---------------------------------------------------------------------- -- | putStr on stderr ePutStr :: String -> IO () ePutStr = hPutStr stderr ePutStrLn :: String -> IO() ePutStrLn = hPutStrLn stderr eFlush :: IO() eFlush = hFlush stderr -- ---------------------------------------------------------------------- -- Strings -- ---------------------------------------------------------------------- instance Binary Text where put = put . T.encodeUtf8 get = liftM T.decodeUtf8 get isGeniIdentLetter :: Char -> Bool isGeniIdentLetter x = isAlphaNum x || x `elem` "_'+-." trim :: String -> String trim = reverse . (dropWhile isSpace) . reverse . (dropWhile isSpace) -- | Drop all characters up to and including the one in question dropTillIncluding :: Char -> String -> String dropTillIncluding c = drop 1 . (dropWhile (/= c)) -- | Make the first character of a string upper case toUpperHead :: String -> String toUpperHead [] = [] toUpperHead (h:t) = (toUpper h):t -- | Make the first character of a string lower case toLowerHead :: String -> String toLowerHead [] = [] toLowerHead(h:t) = (toLower h):t quoteString :: String -> String quoteString xs = "\"" ++ concatMap helper xs ++ "\"" where helper '"' = [ '\\', '\"' ] helper '\\' = [ '\\', '\\' ] helper x = [ x ] -- | 'quoteText' but only if it contains characters that are not -- used in GenI identifiers maybeQuoteText :: Text -> Text maybeQuoteText x | T.null x = quoteText "" | "-" `T.isPrefixOf` x = quoteText x -- could be interpreted as | "+" `T.isPrefixOf` x = quoteText x -- semantic polarities | T.any naughty x = quoteText x | otherwise = x where naughty c = not (isGeniIdentLetter c) || c `elem` "_?/" quoteText :: Text -> Text quoteText t = q `T.append` escape t `T.append` q where escape = T.replace q escQ . T.replace s escS q = "\"" s = "\\" escQ = s `T.append` q escS = s `T.append` s -- | break a list of items into sublists of length < the clump -- size, taking into consideration that each item in the clump -- will have a single gap of padding interspersed -- -- any item whose length is greater than the clump size -- is put into a clump by itself -- -- given a length function -- @clumpBy (length.show) 8 ["hello", "this", "is", "a", "list"]@ clumpBy :: (a -> Int) -> Int -> [a] -> [[a]] clumpBy f l items = iter [] items where iter acc [] = reverse acc iter acc cs = case break toobig (drop 1 $ inits cs) of ([],_) -> next 1 -- first too big (_,[]) -> iter (cs:acc) [] -- none too big (_,(x:_)) -> next (length x - 1) where next n = iter (take n cs : acc) (drop n cs) toobig x = (sum . intersperse 1 . map f) x > l -- ---------------------------------------------------------------------- -- Alphanumeric sort -- ---------------------------------------------------------------------- -- | Intermediary type used for alphanumeric sort data AlphaNum = A String | N Int deriving Eq -- we don't derive this, because we want num < alpha instance Ord AlphaNum where compare (A s1) (A s2) = compare s1 s2 compare (N s1) (N s2) = compare s1 s2 compare (A _) (N _) = GT compare (N _) (A _) = LT -- | An alphanumeric sort is one where you treat the numbers in the string -- as actual numbers. An alphanumeric sort would put x2 before x100, -- because 2 < 10, wheraeas a naive sort would put it the other way -- around because the characters 1 < 2. To sort alphanumerically, just -- 'sortBy (comparing toAlphaNum)' toAlphaNum :: String -> [AlphaNum] toAlphaNum = map readOne . groupBy ((==) `on` isDigit) where readOne s | all isDigit s = N (read s) | otherwise = A s -- ---------------------------------------------------------------------- -- Triples -- ---------------------------------------------------------------------- first3 :: (a -> a2) -> (a, b, c) -> (a2, b, c) first3 f (x,y,z) = (f x, y, z) second3 :: (b -> b2) -> (a, b, c) -> (a, b2, c) second3 f (x,y,z) = (x, f y, z) third3 :: (c -> c2) -> (a, b, c) -> (a, b, c2) third3 f (x,y,z) = (x, y, f z) fst3 :: (a,b,c) -> a fst3 (x,_,_) = x snd3 :: (a,b,c) -> b snd3 (_,x,_) = x thd3 :: (a,b,c) -> c thd3 (_,_,x) = x -- ---------------------------------------------------------------------- -- Lists -- ---------------------------------------------------------------------- -- | A strict version of 'map' map' :: (a->b) -> [a] -> [b] map' _ [] = [] map' f (x:xs) = let a = f x in a `seq` (a:(map' f xs)) -- | True if the intersection of two lists is empty. isEmptyIntersect :: (Eq a) => [a] -> [a] -> Bool isEmptyIntersect a b = null $ intersect a b -- ---------------------------------------------------------------------- -- Grouping -- ---------------------------------------------------------------------- -- | Serves the same function as 'Data.List.groupBy'. It groups together -- items by some property they have in common. The difference is that the -- property is used as a key to a Map that you can lookup. groupByFM :: (Ord b) => (a -> b) -> [a] -> (Map.Map b [a]) groupByFM fn list = let addfn x acc key = insertToListMap key x acc helper acc x = addfn x acc (fn x) in foldl' helper Map.empty list {-# INLINE insertToListMap #-} insertToListMap :: (Ord b) => b -> a -> Map.Map b [a] -> Map.Map b [a] insertToListMap k i m = case Map.lookup k m of Nothing -> Map.insert k [i] m Just p -> Map.insert k (i:p) m histogram :: Ord a => [a] -> Map.Map a Int histogram xs = Map.fromListWith (+) $ zip xs (repeat 1) buckets :: Ord b => (a -> b) -> [a] -> [ (b,[a]) ] buckets f = map (first head . unzip) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . map (\x -> (f x, x)) -- Given a list of lists, return all lists such that one item from each sublist is chosen. -- If returns the empty list if there are any empty sublists. combinations :: [[a]] -> [[a]] combinations = sequence mapMaybeM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM _ [] = return [] mapMaybeM f (x:xs) = f x >>= (\my -> case my of Nothing -> mapMaybeM f xs Just y -> liftM (y:) (mapMaybeM f xs)) -- | Return the list, modifying only the first matching item. repList :: (a->Bool) -> (a->a) -> [a] -> [a] repList _ _ [] = [] repList pr fn (x:xs) | pr x = fn x : xs | otherwise = x : (repList pr fn xs) -- ---------------------------------------------------------------------- -- Trees -- ---------------------------------------------------------------------- -- | Strict version of 'mapTree' (for non-strict, just use fmap) mapTree' :: (a->b) -> Tree a -> Tree b mapTree' fn (Node a []) = let b = fn a in b `seq` Node b [] mapTree' fn (Node a l) = let b = fn a bs = map' (mapTree' fn) l in b `seq` bs `seq` Node b bs -- | Like 'filter', except on Trees. Filter might not be a good name, though, -- because we return a list of nodes, not a tree. filterTree :: (a->Bool) -> Tree a -> [a] filterTree fn = (filter fn) . flatten -- | The leaf nodes of a Tree treeLeaves :: Tree a -> [a] treeLeaves (Node n []) = [n] treeLeaves (Node _ l ) = concatMap treeLeaves l -- | Return pairs of (parent, terminal) preTerminals :: Tree a -> [(a,a)] preTerminals (Node r xs) = concatMap (helper r) xs where helper p (Node k []) = [ (p,k) ] helper _ (Node p ys) = concatMap (helper p) ys -- | 'repNode' @fn filt t@ returns a version of @t@ in which the first -- node which @filt@ matches is transformed using @fn@. repNode :: (Tree a -> Tree a) -- ^ replacement function -> (Tree a -> Bool) -- ^ filtering function -> Tree a -> Maybe (Tree a) repNode fn filt t = case listRepNode fn filt [t] of (_, False) -> Nothing ([t2], True) -> Just t2 _ -> geniBug "Either repNode or listRepNode are broken" -- | Like 'repNode' except that it performs the operations on -- all nodes that match and doesn't care if any nodes match -- or not repAllNode :: (Tree a -> Tree a) -> (Tree a -> Bool) -> Tree a -> Tree a repAllNode fn filt n | filt n = fn n repAllNode fn filt (Node p ks) = Node p $ map (repAllNode fn filt) ks -- | Like 'repNode' but on a list of tree nodes listRepNode :: (Tree a -> Tree a) -- ^ replacement function -> (Tree a -> Bool) -- ^ filtering function -> [Tree a] -- ^ nodes -> ([Tree a], Bool) listRepNode _ _ [] = ([], False) listRepNode fn filt (n:l2) | filt n = (fn n : l2, True) listRepNode fn filt ((n@(Node a l1)):l2) = case listRepNode fn filt l1 of (lt1, True) -> ((Node a lt1):l2, True) _ -> case listRepNode fn filt l2 of (lt2, flag2) -> (n:lt2, flag2) -- | Replace a node in the tree in-place with another node; keep the -- children the same. If the node is not found in the tree, or if -- there are multiple instances of the node, this is treated as an -- error. repNodeByNode :: (a -> Bool) -- ^ which node? -> a -> Tree a -> Tree a repNodeByNode nfilt rep t = let tfilt (Node n _) = nfilt n replaceFn (Node _ k) = Node rep k in case listRepNode replaceFn tfilt [t] of ([t2], True) -> t2 (_ , False) -> geniBug "Node not found in repNode" _ -> geniBug "Unexpected result in repNode" -- ---------------------------------------------------------------------- -- Errors, exceptions and logging -- ---------------------------------------------------------------------- -- | errors specifically in GenI, which is very likely NOT the user's fault. geniBug :: String -> a geniBug s = error $ "Bug in GenI!\n" ++ s ++ "\nPlease file a report on http://trac.haskell.org/GenI/newticket" -- stolen from Darcs prettyException :: IOException -> String prettyException e | isUserError e = ioeGetErrorString e prettyException e = show e -- | The module name for an arbitrary data type mkLogname :: Typeable a => a -> String mkLogname = reverse . drop 1 . dropWhile (/= '.') . reverse . show . typeOf -- ---------------------------------------------------------------------- -- Intervals -- ---------------------------------------------------------------------- type Interval = (Int,Int) -- | Add two intervals (!+!) :: Interval -> Interval -> Interval (!+!) (a1,a2) (b1,b2) = (a1+b1, a2+b2) -- | 'ival' @x@ builds a trivial interval from 'x' to 'x' ival :: Int -> Interval ival i = (i,i) showInterval :: Interval -> String showInterval (x,y) = let sign i = if i > 0 then "+" else "" -- in if (x==y) then (sign x) ++ (show x) else show (x,y) -- ---------------------------------------------------------------------- -- Bit vectors -- ---------------------------------------------------------------------- type BitVector = Integer -- | displays a bit vector, using a minimum number of bits showBitVector :: Int -> BitVector -> String showBitVector min_ 0 = replicate min_ '0' showBitVector min_ x = showBitVector (min_ - 1) (shiftR x 1) ++ (show $ x .&. 1) -- ---------------------------------------------------------------------- -- JSON -- ---------------------------------------------------------------------- instance JSON Text where readJSON = fmap T.pack . readJSON showJSON = showJSON . T.unpack
kowey/GenI
src/NLP/GenI/General.hs
gpl-2.0
14,629
1
13
3,538
3,997
2,196
1,801
239
4