code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE MagicHash #-} module Main (main) where import GHC.Exts (Double(D#), Float(F#), word2Double#, word2Float#) main :: IO () main = do print (D# (word2Double# 0##)) -- 9007199254740992 is 2^53, which is the largest integer which -- can be stored in a 64-bit IEEE floating-point value without -- loss of precision. -- print (D# (word2Double# 9007199254740992##)) -- disabled, overflows 32 bit Word print (D# (word2Double# 4294967295##)) print (D# (word2Double# 2147483647##)) print (F# (word2Float# 0##)) -- 16777216 is 2^24, which is the largest integer which can be -- stored in a 32-bit IEEE floating-point value without loss of -- precision print (F# (word2Float# 16777216##))
beni55/ghcjs
test/ghc/codeGen/word2Float64.hs
Haskell
mit
738
-- | -- Module: BigE.Model -- Copyright: (c) 2017 Patrik Sandahl -- Licence: MIT -- Maintainer: Patrik Sandahl <patrik.sandahl@gmail.com> -- Stability: experimental -- Portability: portable -- Utilities to read Wavefront model files and produce vectors that can be -- used to create meshes. module BigE.Model ( vertPFromFile , vertPNFromFile , vertPNTxFromFile ) where import qualified BigE.Attribute.Vert_P as Vert_P import qualified BigE.Attribute.Vert_P_N as Vert_P_N import qualified BigE.Attribute.Vert_P_N_Tx as Vert_P_N_Tx import BigE.Model.Assembler (assembleVertP, assembleVertPN, assembleVertPNTx) import BigE.Model.Parser (FilePart, fromFile) import Control.Monad.IO.Class (MonadIO) import Data.Vector.Storable (Vector, fromList) import Foreign (Storable) import Graphics.GL (GLuint) -- | Read a model from the given file. Only use the position attribute. All -- valid model files shall be able to read. vertPFromFile :: MonadIO m => FilePath -> m (Either String (Vector Vert_P.Vertex, Vector GLuint)) vertPFromFile = readIt assembleVertP -- | Read a model from the given file. The model file must have the attributes -- position and normal to be able to load. vertPNFromFile :: MonadIO m => FilePath -> m (Either String (Vector Vert_P_N.Vertex, Vector GLuint)) vertPNFromFile = readIt assembleVertPN -- | Read a model from the given file. The model file must have the attributes -- position, normal and texture coordinate to be able to load. vertPNTxFromFile :: MonadIO m => FilePath -> m (Either String (Vector Vert_P_N_Tx.Vertex, Vector GLuint)) vertPNTxFromFile = readIt assembleVertPNTx readIt :: (Storable a, Storable b, MonadIO m) => ([FilePart] -> Maybe ([a], [b])) -> FilePath -> m (Either String (Vector a, Vector b)) readIt assemble file = do eParts <- fromFile file case eParts of Right parts -> case assemble parts of Just (xs, ys) -> return $ Right (fromList xs, fromList ys) Nothing -> return $ Left "Cannot assemble model parts" Left err -> return $ Left err
psandahl/big-engine
src/BigE/Model.hs
Haskell
mit
2,315
{-# LANGUAGE OverloadedStrings #-} module Model.InitDB ( initDBSpecs ) where import TestImport import qualified Data.List as L initDBSpecs :: Spec initDBSpecs = ydescribe "Initial DB should be empty" $ do -- user/article/comment/image tables are empty when initial. yit "leaves the article table empty" $ do articles <- runDB $ selectList ([] :: [Filter Article]) [] assertEqual "article table empty" 0 $ L.length articles yit "leaves the comment table empty" $ do comments <- runDB $ selectList ([] :: [Filter Comment]) [] assertEqual "comment table empty" 0 $ L.length comments yit "leaves the image table empty" $ do image <- runDB $ selectList ([] :: [Filter Image]) [] assertEqual "image table empty" 0 $ L.length image yit "leaves the tag table empty" $ do tag <- runDB $ selectList ([] :: [Filter Tag]) [] assertEqual "tag table empty" 0 $ L.length tag yit "leaves the user table empty" $ do users <- runDB $ selectList ([] :: [Filter User]) [] assertEqual "user table empty" 0 $ L.length users
cosmo0920/Ahblog
tests/Model/InitDB.hs
Haskell
mit
1,102
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-} {-# LANGUAGE PartialTypeSignatures , OverloadedStrings , RecordWildCards #-} module XMonad.Javran.Config ( myConfig ) where -- TODO: xmonad restarter import Data.Monoid import System.IO import XMonad import XMonad.Layout.Fullscreen import XMonad.Hooks.ManageDocks import XMonad.Util.Run import Data.Time.Clock import qualified XMonad.Util.ExtensibleState as XS import XMonad.Hooks.EwmhDesktops hiding (fullscreenEventHook) import XMonad.Javran.Config.Workspace import XMonad.Javran.Config.State import XMonad.Javran.Config.LogHook import qualified XMonad.Javran.Config.Keys as ConfKeys import qualified XMonad.Javran.Config.LayoutHook as LyH import qualified XMonad.Javran.Config.ManageHook as MgmH -- TODO: fullscreen without frame? myConfig :: Handle -> XConfig _ myConfig dzenHandle = def { modMask = mod3Mask , terminal = "xfce4-terminal" , keys = ConfKeys.keys , manageHook = fullscreenManageHook <> manageDocks <> MgmH.manageHook , handleEventHook = fullscreenEventHook <> docksEventHook -- <> myEwmhDesktopsEventHook , layoutHook = LyH.layoutHook , logHook = mkLogHook dzenHandle <> ewmhDesktopsLogHook , focusedBorderColor = "cyan" , workspaces = workspaceIds , startupHook = myStartupHook <> ewmhDesktopsStartup } myStartupHook :: X () myStartupHook = do StartupTime <$> liftIO getCurrentTime >>= XS.put safeSpawn "/bin/bash" ["/home/javran/.xmonad/on-startup.sh"] myEwmhDesktopsEventHook :: Event -> X All myEwmhDesktopsEventHook e@ClientMessageEvent{..} = do a_aw <- getAtom "_NET_ACTIVE_WINDOW" curTime <- liftIO getCurrentTime StartupTime starupTime <- XS.get -- prevernt ewmh for the first 5 sec window after startup. if ev_message_type == a_aw && curTime `diffUTCTime` starupTime <= 5.0 then pure (All True) else ewmhDesktopsEventHook e myEwmhDesktopsEventHook e = ewmhDesktopsEventHook e
Javran/xmonad-javran
src/XMonad/Javran/Config.hs
Haskell
mit
1,960
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {- | Module : Control.SIArrow Description : Categories of reversible computations. Copyright : (c) Paweł Nowak License : MIT Maintainer : Paweł Nowak <pawel834@gmail.com> Stability : experimental Categories of reversible computations. -} module Control.SIArrow ( -- * Arrow. SIArrow(..), (^>>), (>>^), (^<<), (<<^), (#>>), (>>#), (#<<), (<<#), -- * Functor and applicative. (/$/), (/*/), (/*), (*/), -- * Signaling errors. sifail, (/?/), -- * Combinators. sisequence, sisequence_, sireplicate, sireplicate_ ) where import Control.Arrow (Kleisli(..)) import Control.Category import Control.Category.Structures import Control.Lens.Cons import Control.Lens.Empty import Control.Lens.Iso import Control.Lens.SemiIso import Control.Monad import Data.Semigroupoid.Dual import Prelude hiding (id, (.)) infixr 1 ^>>, ^<<, #>>, #<< infixr 1 >>^, <<^, >>#, <<# infixl 4 /$/ infixl 5 /*/, */, /* infixl 3 /?/ -- | A category equipped with an embedding 'siarr' from @SemiIso@ into @cat@ and some -- additional structure. -- -- SIArrow abstracts categories of reversible computations -- (with reversible side effects). -- -- The category @cat@ should contain @SemiIso@ as a sort of -- \"subcategory of pure computations\". class (Products cat, Coproducts cat, CatPlus cat) => SIArrow cat where -- | Allows you to lift a SemiIso into @cat@. The resulting arrow should be -- in some sense minimal or \"pure\", similiar to 'pure', 'return' and -- 'arr' from "Control.Category". siarr :: ASemiIso' a b -> cat a b siarr = sipure . rev -- | Reversed version of 'siarr'. -- -- Use this where you would use 'pure'. sipure :: ASemiIso' b a -> cat a b sipure = siarr . rev -- | Allows a computation to depend on a its input value. -- -- I am not sure if this is the right way to get that ArrowApply or Monad -- like power. It seems quite easy to break the parser/pretty-printer inverse -- guarantee using this. On the other hand we have to be careful only when -- constructing the SemiIso using 'iso'/'semiIso' - and with an invalid SemiIso -- we could break everything anyway using 'siarr'. sibind :: ASemiIso a (cat a b) (cat a b) b -> cat a b -- | @sisome v@ repeats @v@ as long as possible, but no less then once. sisome :: cat () b -> cat () [b] sisome v = _Cons /$/ v /*/ simany v -- | @simany v@ repeats @v@ as long as possible. simany :: cat () b -> cat () [b] simany v = sisome v /+/ sipure _Empty {-# MINIMAL (siarr | sipure), sibind #-} instance MonadPlus m => SIArrow (Kleisli m) where siarr ai = Kleisli $ either fail return . apply ai sibind ai = Kleisli $ \a -> either fail (($ a) . runKleisli) $ apply ai a instance SIArrow cat => SIArrow (Dual cat) where siarr = Dual . sipure sibind ai = Dual $ sibind (iso id getDual . rev ai . iso getDual id) instance SIArrow ReifiedSemiIso' where siarr = reifySemiIso sibind ai = ReifiedSemiIso' $ semiIso (\a -> apply ai a >>= flip apply a . runSemiIso) (\b -> unapply ai b >>= flip unapply b . runSemiIso) -- | Composes a SemiIso with an arrow. (^>>) :: SIArrow cat => ASemiIso' a b -> cat b c -> cat a c f ^>> a = a . siarr f -- | Composes an arrow with a SemiIso. (>>^) :: SIArrow cat => cat a b -> ASemiIso' b c -> cat a c a >>^ f = siarr f . a -- | Composes a SemiIso with an arrow, backwards. (^<<) :: SIArrow cat => ASemiIso' b c -> cat a b -> cat a c f ^<< a = siarr f . a -- | Composes an arrow with a SemiIso, backwards. (<<^) :: SIArrow cat => cat b c -> ASemiIso' a b -> cat a c a <<^ f = a . siarr f -- | Composes a reversed SemiIso with an arrow. (#>>) :: SIArrow cat => ASemiIso' b a -> cat b c -> cat a c f #>> a = a . sipure f -- | Composes an arrow with a reversed SemiIso. (>>#) :: SIArrow cat => cat a b -> ASemiIso' c b -> cat a c a >># f = sipure f . a -- | Composes a reversed SemiIso with an arrow, backwards. (#<<) :: SIArrow cat => ASemiIso' c b -> cat a b -> cat a c f #<< a = sipure f . a -- | Composes an arrow with a reversed SemiIso, backwards. (<<#) :: SIArrow cat => cat b c -> ASemiIso' b a -> cat a c a <<# f = a . sipure f -- | Postcomposes an arrow with a reversed SemiIso. -- The analogue of '<$>' and synonym for '#<<'. (/$/) :: SIArrow cat => ASemiIso' b' b -> cat a b -> cat a b' (/$/) = (#<<) -- | The product of two arrows with duplicate units removed. Side effect are -- sequenced from left to right. -- -- The uncurried analogue of '<*>'. (/*/) :: SIArrow cat => cat () b -> cat () c -> cat () (b, c) a /*/ b = unit ^>> (a *** b) -- | The product of two arrows, where the second one has no input and no output -- (but can have side effects), with duplicate units removed. Side effect are -- sequenced from left to right. -- -- The uncurried analogue of '<*'. (/*) :: SIArrow cat => cat () a -> cat () () -> cat () a f /* g = unit /$/ f /*/ g -- | The product of two arrows, where the first one has no input and no output -- (but can have side effects), with duplicate units removed. Side effect are -- sequenced from left to right. -- -- The uncurried analogue of '*>'. (*/) :: SIArrow cat => cat () () -> cat () a -> cat () a f */ g = unit . swapped /$/ f /*/ g -- | An arrow that fails with an error message. sifail :: SIArrow cat => String -> cat a b sifail = siarr . alwaysFailing -- | Provides an error message in the case of failure. (/?/) :: SIArrow cat => cat a b -> String -> cat a b f /?/ msg = f /+/ sifail msg -- | Equivalent of 'sequence'. sisequence :: SIArrow cat => [cat () a] -> cat () [a] sisequence [] = sipure _Empty sisequence (x:xs) = _Cons /$/ x /*/ sisequence xs -- | Equivalent of 'sequence_', restricted to units. sisequence_ :: SIArrow cat => [cat () ()] -> cat () () sisequence_ [] = sipure _Empty sisequence_ (x:xs) = unit /$/ x /*/ sisequence_ xs -- | Equivalent of 'replicateM'. sireplicate :: SIArrow cat => Int -> cat () a -> cat () [a] sireplicate n f = sisequence (replicate n f) -- | Equivalent of 'replicateM_', restricted to units. sireplicate_ :: SIArrow cat => Int -> cat () () -> cat () () sireplicate_ n f = sisequence_ (replicate n f)
pawel-n/semi-iso
Control/SIArrow.hs
Haskell
mit
6,380
module SimpleNoun where import ClassyPrelude import Numeric.Natural import qualified Urbit.Noun as N type Atom = Natural type Noun = Tree Atom data Tree a = A !a | C !(Tree a) !(Tree a) deriving (Eq, Ord, Read, Functor, Generic) instance Hashable a => Hashable (Tree a) data Fern a = FernA !a | FernF [Fern a] toFern :: Tree a -> Fern a toFern = \case A a -> FernA a C h t -> case toFern t of a@FernA{} -> FernF [toFern h, a] FernF fs -> FernF (toFern h : fs) instance Show a => Show (Fern a) where show = \case FernA a -> show a FernF xs -> "[" <> intercalate " " (map show xs) <> "]" instance Show a => Show (Tree a) where show = show . toFern yes, no :: Noun yes = A 0 no = A 1 loob :: Bool -> Noun loob = \case True -> yes False -> no textToAtom :: Text -> Atom textToAtom t = case N.textToUtf8Atom t of N.A a -> a N.C _ _ -> error "textToAtom: nani!?" showA :: Atom -> String showA a = show (N.A a) tshowA :: Atom -> Text tshowA = pack . showA -- | Tree address type Axis = Atom data Dir = L | R deriving (Eq, Ord, Enum, Read, Show) type Path = [Dir] -- some stuff from hoon.hoon cap :: Axis -> Dir cap = \case 2 -> L 3 -> R a | a <= 1 -> error "cap: bad axis" | otherwise -> cap (div a 2) mas :: Axis -> Axis mas = \case 2 -> 1 3 -> 1 a | a <= 1 -> error "mas: bad axis" | otherwise -> (mod a 2) + 2 * mas (div a 2) capMas :: Axis -> (Dir, Axis) capMas = \case 2 -> (L, 1) 3 -> (R, 1) a | a <= 1 -> error "capMas: bad axis" | otherwise -> (d, (mod a 2) + 2 * r) where (d, r) = capMas (div a 2) peg :: Axis -> Axis -> Axis peg a = \case 1 -> a 2 -> a * 2 3 -> a * 2 + 1 b -> (mod b 2) + 2 * peg a (div b 2) axis :: Axis -> Tree a -> Tree a axis 1 n = n axis (capMas -> (d, r)) (C n m) = case d of L -> axis r n R -> axis r m axis a _ = error ("bad axis: " ++ show a) edit :: Axis -> Tree a -> Tree a -> Tree a edit 1 v n = v edit (capMas -> (d, r)) v (C n m) = case d of L -> C (edit r v n) m R -> C n (edit r v m) edit a _ _ = error ("bad edit: " ++ show a) -- Write an axis as a binary number; e.g. 5 as 101. -- The rule is: after droping the 1 in the msb, you read from left to right. -- 0 becomes L and 1 becomes R. So 5 becomes [L,R] toPath :: Axis -> Path toPath = \case 1 -> [] (capMas -> (d, r)) -> d : toPath r toAxis :: Path -> Axis toAxis = foldl' step 1 where step r = \case L -> 2 * r R -> 2 * r + 1
urbit/urbit
pkg/hs/proto/lib/SimpleNoun.hs
Haskell
mit
2,478
{-# LANGUAGE OverloadedStrings #-} module Engine.Probing where import Control.Monad.IO.Class import Data.Carthage.TargetPlatform import Data.List ( intersect ) import Data.Romefile ( _frameworkPlatforms ) import Types hiding ( version ) import Utils import qualified Turtle import System.FilePath ( (</>) ) -- | Probes a `FilePath` to check if each `FrameworkVersion` exists for each `TargetPlatform` probeEngineForFrameworks :: MonadIO m => FilePath -- ^ The `FilePath` to the engine -> CachePrefix -- ^ The top level directory prefix. -> InvertedRepositoryMap -- ^ The map used to resolve `FrameworkName`s to `GitRepoName`s. -> [FrameworkVersion] -- ^ A list of `FrameworkVersion` to probe for. -> [TargetPlatform] -- ^ A list target platforms restricting the scope of this action. -> m [FrameworkAvailability] probeEngineForFrameworks lCacheDir cachePrefix reverseRomeMap frameworkVersions = sequence . probeForEachFramework where probeForEachFramework = mapM (probeEngineForFramework lCacheDir cachePrefix reverseRomeMap) frameworkVersions -- | Probes the engine at `FilePath` to check if a `FrameworkVersion` exists for each `TargetPlatform` probeEngineForFramework :: MonadIO m => FilePath -- ^ The `FilePath` to the engine -> CachePrefix -- ^ The top level directory prefix. -> InvertedRepositoryMap -- ^ The map used to resolve `FrameworkName`s to `GitRepoName`s. -> FrameworkVersion -- ^ The `FrameworkVersion` to probe for. -> [TargetPlatform] -- ^ A list target platforms restricting the scope of this action. -> m FrameworkAvailability probeEngineForFramework lCacheDir cachePrefix reverseRomeMap frameworkVersion platforms = fmap (FrameworkAvailability frameworkVersion) probeForEachPlatform where probeForEachPlatform = mapM (probeEngineForFrameworkOnPlatform lCacheDir cachePrefix reverseRomeMap frameworkVersion) (platforms `intersect` (_frameworkPlatforms . _framework $ frameworkVersion)) -- | Probes the engine at `FilePath` to check if a `FrameworkVersion` exists for a given `TargetPlatform` probeEngineForFrameworkOnPlatform :: MonadIO m => FilePath -- ^ The `FilePath` to the engine -> CachePrefix -- ^ The top level directory prefix. -> InvertedRepositoryMap -- ^ The map used to resolve `FrameworkName`s to `GitRepoName`s. -> FrameworkVersion -- ^ The `FrameworkVersion` to probe for. -> TargetPlatform -- ^ A target platforms restricting the scope of this action. -> m PlatformAvailability probeEngineForFrameworkOnPlatform enginePath (CachePrefix prefix) reverseRomeMap (FrameworkVersion fwn version) platform = do let cmd = Turtle.fromString enginePath exitCode <- Turtle.proc cmd ["list", Turtle.fromString (prefix </> remoteFrameworkUploadPath)] (return $ Turtle.unsafeTextToLine "") case exitCode of -- If engine exits with success, we assume the framework exists. Turtle.ExitSuccess -> return (PlatformAvailability platform True) Turtle.ExitFailure _ -> return (PlatformAvailability platform False) where remoteFrameworkUploadPath = remoteFrameworkPath platform reverseRomeMap fwn version
blender/Rome
src/Engine/Probing.hs
Haskell
mit
3,364
{-# LANGUAGE BangPatterns, RecordWildCards, FlexibleContexts #-} module AI.Funn.Optimizer.SGD (SGDState, initSGD, extractSGD, updateSGD) where import Control.Monad import Data.Foldable import AI.Funn.Space type LearningRate = Double type Momentum = Double data SGDState m d p = SGDState { sgdStepSize :: LearningRate, sgdMomentumWeight :: Momentum, sgdScale :: Double -> d -> m d, sgdAddDP :: d -> p -> m p, sgdAddDD :: d -> d -> m d, sgdValue :: p, sgdMoment :: d } initSGD :: (Monad m, VectorSpace m Double d) => LearningRate -> Momentum -> (d -> p -> m p) -> p -> m (SGDState m d p) initSGD lr mr add x0 = do d0 <- zero return $ SGDState { sgdStepSize = lr, sgdMomentumWeight = mr, sgdScale = scale, sgdAddDP = add, sgdAddDD = plus, sgdValue = x0, sgdMoment = d0 } extractSGD :: SGDState m d p -> p extractSGD = sgdValue updateSGD :: (Monad m) => d -> SGDState m d p -> m (SGDState m d p) updateSGD d (SGDState{..}) = do newMoment <- join $ sgdAddDD <$> sgdScale sgdMomentumWeight sgdMoment <*> sgdScale (-sgdStepSize) d newValue <- sgdAddDP newMoment sgdValue return $ SGDState { sgdStepSize = sgdStepSize, sgdMomentumWeight = sgdMomentumWeight, sgdScale = sgdScale, sgdAddDP = sgdAddDP, sgdAddDD = sgdAddDD, sgdValue = newValue, sgdMoment = newMoment }
nshepperd/funn
AI/Funn/Optimizer/SGD.hs
Haskell
mit
1,355
{-# LANGUAGE OverloadedStrings #-} module Database.Hasqueue.Store.SimpleSpec ( spec ) where import Control.Concurrent.STM.Class import Control.Monad import Database.Hasqueue import Data.List (sort) import Pipes import qualified Pipes.Prelude as P import Pipes.Concurrent import Test.Hspec spec :: Spec spec = do let withSimple :: (Simple -> IO ()) -> IO () withSimple f = do simple <- startService f simple stopService simple describe "listing all buckets" $ do let buckets = ["bucket-one", "bucket-two", "bucket-three"] commands = map CreateBucket buckets ++ [ListBuckets] it "returns a list of buckets" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output forM_ buckets $ \bid -> do result <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result <- liftSTM $ recv input case result of Just (Right (Buckets bids)) -> sort bids `shouldBe` sort buckets _ -> fail "Could not list buckets." describe "creating a bucket" $ do let bid = "test-bucket" context "when the bucket does not exist" $ do let commands = [CreateBucket bid, ListBuckets] it "creates the bucket" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right (Buckets [bid])) context "when the bucket does exist" $ do let commands = [CreateBucket bid, CreateBucket bid, ListBuckets] it "throws an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Left (BucketExists bid)) result'' `shouldBe` Just (Right (Buckets [bid])) describe "deleting a bucket" $ do let bid = "sample-bucket" context "when the bucket does not exist" $ do let commands = [DeleteBucket bid, ListBuckets] it "does nothing" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result `shouldBe` Just (Right Empty) result' `shouldBe` Just (Right (Buckets [])) context "when the bucket does exist" $ do let commands = [CreateBucket bid, ListBuckets, DeleteBucket bid, ListBuckets] it "deletes that bucket" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result''' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right (Buckets [bid])) result'' `shouldBe` Just (Right Empty) result''' `shouldBe` Just (Right (Buckets [])) describe "renaming a bucket" $ do let old = "old-bid" new = "new-bid" context "when the original bucket does not exist" $ do let commands = [RenameBucket old new] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result `shouldBe` Just (Left (NoSuchBucket old)) context "when the original bucket exists" $ do context "but the target bucket exists" $ do let commands = [CreateBucket old, CreateBucket new, RenameBucket old new] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket old)) result' `shouldBe` Just (Right (Bucket new)) result'' `shouldBe` Just (Left (BucketExists new)) context "and the target bucket does not exist" $ do let value = String "test" valueID = "test-value-id" commands = [CreateBucket old, PutValue old valueID value, RenameBucket old new] it "moves the bucket" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket old)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Bucket new)) describe "listing the contents of a bucket" $ do let bid = "tmp-bid" context "when the bucket is does not exist" $ do let commands = [ListBucket bid] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result `shouldBe` Just (Left (NoSuchBucket bid)) context "when the bucket exists" $ do let vid = "tmp-vid" value = Int 1 commands = [CreateBucket bid, PutValue bid vid value, ListBucket bid] it "lists the keys" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Values [vid])) describe "accessing a value" $ do let bid = "my-bid" vid = "my-vid" context "when the value's bucket does not exist" $ do let commands = [GetValue bid vid] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result `shouldBe` Just (Left (NoSuchBucket bid)) context "when the value's bucket exists" $ do context "when the value does not exist" $ do let commands = [CreateBucket bid, GetValue bid vid] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Left (NoSuchValue bid vid)) context "when the value does exists" $ do let value = Double 1.2 commands = [CreateBucket bid, PutValue bid vid value, GetValue bid vid] it "returns that value" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Value value)) describe "deleting a value" $ do let bid = "sample-bid" vid = "sample-vid" context "when the bucket does not exist" $ do let commands = [DeleteValue bid vid] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result `shouldBe` Just (Left (NoSuchBucket bid)) context "when the bucket does exists" $ do context "but the value doesn't exist" $ do let commands = [CreateBucket bid, ListBucket bid, DeleteValue bid vid, ListBucket bid] it "does nothing" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result''' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right (Values [])) result'' `shouldBe` Just (Right Empty) result''' `shouldBe` Just (Right (Values [])) context "and the value exists" $ do let value = Null commands = [CreateBucket bid, PutValue bid vid value, ListBucket bid, DeleteValue bid vid, ListBucket bid] it "deletes that value" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result''' <- liftSTM $ recv input result'''' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Values [vid])) result''' `shouldBe` Just (Right Empty) result'''' `shouldBe` Just (Right (Values [])) describe "putting a value" $ do let bid = "put-bucket" vid = "put-value" value = Int 2 context "when the bucket does not exist" $ do let commands = [PutValue bid vid value] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result `shouldBe` Just (Left (NoSuchBucket bid)) context "when the bucket does exist" $ do context "when the value doesn't exist" $ do let commands = [ CreateBucket bid , PutValue bid vid value , GetValue bid vid ] it "puts the value" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Value value)) context "when the value already exists" $ do let value' = Null commands = [ CreateBucket bid , PutValue bid vid value' , GetValue bid vid , PutValue bid vid value , GetValue bid vid ] it "puts the value" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result''' <- liftSTM $ recv input result'''' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket bid)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Value value')) result''' `shouldBe` Just (Right Empty) result'''' `shouldBe` Just (Right (Value value)) describe "renaming a value" $ do let oldBID = "old-bid" oldVID = "old-vid" newBID = "new-bid" newVID = "new-vid" old = (oldBID, oldVID) new = (newBID, newVID) value = String "hello" context "when the source bucket does not exist" $ do let commands = [RenameValue old new] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result `shouldBe` Just (Left (NoSuchBucket oldBID)) context "when the source bucket exists" $ do context "when the source value does not exist" $ do let commands = [CreateBucket oldBID, RenameValue old new] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket oldBID)) result' `shouldBe` Just (Left (NoSuchValue oldBID oldVID)) context "when the source value exists" $ do context "when the target bucket does not exist" $ do let commands = [CreateBucket oldBID, PutValue oldBID oldVID value, RenameValue old new] it "returns an error" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket oldBID)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Left (NoSuchBucket newBID)) context "when the target bucket exists" $ do context "when the target value does not exist" $ do let commands = [ CreateBucket oldBID , PutValue oldBID oldVID value , CreateBucket newBID , RenameValue old new , uncurry GetValue new ] it "renames the value" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result''' <- liftSTM $ recv input result'''' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket oldBID)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Bucket newBID)) result''' `shouldBe` Just (Right Empty) result'''' `shouldBe` Just (Right (Value value)) context "when the target value exists" $ do let value' = Null commands = [ CreateBucket oldBID , PutValue oldBID oldVID value , CreateBucket newBID , PutValue newBID newVID value' , uncurry GetValue new , RenameValue old new , uncurry GetValue new ] it "clobbers the old value" $ do (output, input) <- spawn Unbounded withSimple $ \simple -> runEffect $ each commands >-> toPipe simple >-> toOutput output result <- liftSTM $ recv input result' <- liftSTM $ recv input result'' <- liftSTM $ recv input result''' <- liftSTM $ recv input result'''' <- liftSTM $ recv input result''''' <- liftSTM $ recv input result'''''' <- liftSTM $ recv input result `shouldBe` Just (Right (Bucket oldBID)) result' `shouldBe` Just (Right Empty) result'' `shouldBe` Just (Right (Bucket newBID)) result''' `shouldBe` Just (Right Empty) result'''' `shouldBe` Just (Right (Value value')) result''''' `shouldBe` Just (Right Empty) result'''''' `shouldBe` Just (Right (Value value)) describe "shutting down" $ do let commands = [CreateBucket "test-bucket"] it "does not respond after a shutdown" $ do pending (output, input) <- spawn Unbounded putStrLn "pre start" simple <- startService :: IO Simple stopService simple putStrLn "pre stop" runEffect $ each commands >-> toPipe simple >-> toOutput output putStrLn "post stop" exhausted <- P.null $ fromInput input unless exhausted $ fail "Output should be closed"
nahiluhmot/hasqueue
spec/Database/Hasqueue/Store/SimpleSpec.hs
Haskell
mit
20,475
{-# LANGUAGE Arrows #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Auto import Data.Profunctor import Data.Serialize import Data.Traversable import Debug.Trace import Linear.Matrix import Linear.Metric import Linear.V1 import Linear.V2 import Linear.V3 import Linear.V4 import Linear.Vector import Prelude hiding ((.), id) import System.Random import qualified Data.List as L type Neural m i o = Auto m (Either (i, o) i) o type UNeural m i o = Auto m i o type TNeural m i o = Auto m (i, o) o fromU :: Monad m => UNeural m i o -> Neural m i o fromU = lmap (either fst id) fromT :: (Monad m, Additive o, Num a) => TNeural m i (o a) -> Neural m i (o a) fromT = lmap (either id (, zero)) logistic :: Floating a => a -> a -> a -> a logistic x0 k x = 1 / (1 + exp (-k * (x - x0))) -- for weights: outer layer is each output, nested/inner layer is the -- weights for each input. trainNodeFrom :: forall m vi vo. ( Monad vi , Applicative vi , Metric vi , Additive vi , Traversable vi , Num (vi Double) , Monad vo , Applicative vo , Metric vo , Additive vo , Traversable vo -- , Num (vo Double) , Serialize (vo (vi Double)) , Show (vo (vi Double)) , Monad m ) => (vo Double -> vo Double) -- map before exit -> vo (vi Double) -- inner: by-input weights -- outer: by-output weight sets -> Neural m (vi Double) (vo Double) trainNodeFrom outFunc = mkState f where dw :: Double dw = 0.05 wStep :: Double wStep = 1 -- the types work out :| nudges :: vo (vi (vo (vi Double))) nudges = fmap (outer (scaled (pure dw))) (scaled (pure (pure dw))) f :: Either (vi Double, vo Double) (vi Double) -> vo (vi Double) -> (vo Double, vo (vi Double)) f (Left (input, expected)) weights = -- traceShow weights' (outFunc $ weights' !* input, weights') where result = outFunc $ weights !* input resultErr = result `qd` expected weights' :: vo (vi Double) weights' = do nudgeRow <- nudges :: vo (vi (vo (vi Double))) row <- weights :: vo (vi Double) return $ do -- nudgeEl : matrix with a 1 only at the row of this column nudgeEl <- nudgeRow :: vi (vo (vi Double)) weight <- row :: vi Double let nudged = weights !+! nudgeEl resNudged = outFunc $ nudged !* input nudgedErr = resNudged `qd` expected dErrdW = (nudgedErr - resultErr) / dw return (weight - dErrdW * wStep) f (Right input) weights = (outFunc $ weights !* input, weights) testPoints :: [(V4 Double, V3 Double)] testPoints = map (\[a,b,c,d] -> (V4 a b c d, ws !* V4 a b c d)) . L.transpose . map (randoms . mkStdGen) $ [25645,45764,1354,75673] where -- ws = V1 (V4 0.05 0.6 0.2 0.15) ws = V3 (V4 0.05 0.6 0.2 0.15) (V4 0 0.1 0.2 0.7 ) (V4 0.4 0.4 0.1 0.1 ) asTest :: (Additive vo, Monad m) => Neural m (vi Double) (vo Double) -> Neural m (vi Double) (vo Double) asTest = liftA2 (^-^) (arr (either snd (const zero))) testNudge :: V2 (V3 (V2 (V3 Double))) testNudge = V2 (V3 (V2 (V3 1 0 0) (V3 0 0 0)) (V2 (V3 0 1 0) (V3 0 0 0)) (V2 (V3 0 0 1) (V3 0 0 0))) (V3 (V2 (V3 0 0 0) (V3 1 0 0)) (V2 (V3 0 0 0) (V3 0 1 0)) (V2 (V3 0 0 0) (V3 0 0 1))) main :: IO () main = mapM_ print $ streamAuto' (quadrance <$> asTest (trainNodeFrom id w0)) (take 1000 $ map Left testPoints) where -- w0 = V1 (V4 0.25 0.25 0.25 0.25) w0 = V3 (V4 0.25 0.25 0.25 0.25) (V4 0.25 0.25 0.25 0.25) (V4 0.25 0.25 0.25 0.25)
mstksg/auto-examples
src/Experimental/Neural.hs
Haskell
mit
4,299
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE OverloadedStrings #-} module Yesod.Content ( -- * Content Content (..) , emptyContent , ToContent (..) -- * Mime types -- ** Data type , ContentType , typeHtml , typePlain , typeJson , typeXml , typeAtom , typeRss , typeJpeg , typePng , typeGif , typeSvg , typeJavascript , typeCss , typeFlv , typeOgv , typeOctet -- * Utilities , simpleContentType -- * Representations , ChooseRep , HasReps (..) , defChooseRep -- ** Specific content types , RepHtml (..) , RepJson (..) , RepHtmlJson (..) , RepPlain (..) , RepXml (..) -- * Utilities , formatW3 , formatRFC1123 , formatRFC822 ) where import Data.Maybe (mapMaybe) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Text.Lazy (Text, pack) import qualified Data.Text as T import Data.Time import System.Locale import qualified Data.Text.Encoding import qualified Data.Text.Lazy.Encoding import Blaze.ByteString.Builder (Builder, fromByteString, fromLazyByteString) import Data.Monoid (mempty) import Text.Hamlet (Html) import Text.Blaze.Renderer.Utf8 (renderHtmlBuilder) import Data.String (IsString (fromString)) import Network.Wai (FilePart) import Data.Conduit (Source, Flush) data Content = ContentBuilder Builder (Maybe Int) -- ^ The content and optional content length. | ContentSource (Source IO (Flush Builder)) | ContentFile FilePath (Maybe FilePart) -- | Zero-length enumerator. emptyContent :: Content emptyContent = ContentBuilder mempty $ Just 0 instance IsString Content where fromString = toContent -- | Anything which can be converted into 'Content'. Most of the time, you will -- want to use the 'ContentBuilder' constructor. An easier approach will be to use -- a pre-defined 'toContent' function, such as converting your data into a lazy -- bytestring and then calling 'toContent' on that. -- -- Please note that the built-in instances for lazy data structures ('String', -- lazy 'L.ByteString', lazy 'Text' and 'Html') will not automatically include -- the content length for the 'ContentBuilder' constructor. class ToContent a where toContent :: a -> Content instance ToContent Builder where toContent = flip ContentBuilder Nothing instance ToContent B.ByteString where toContent bs = ContentBuilder (fromByteString bs) $ Just $ B.length bs instance ToContent L.ByteString where toContent = flip ContentBuilder Nothing . fromLazyByteString instance ToContent T.Text where toContent = toContent . Data.Text.Encoding.encodeUtf8 instance ToContent Text where toContent = toContent . Data.Text.Lazy.Encoding.encodeUtf8 instance ToContent String where toContent = toContent . pack instance ToContent Html where toContent bs = ContentBuilder (renderHtmlBuilder bs) Nothing -- | A function which gives targetted representations of content based on the -- content-types the user accepts. type ChooseRep = [ContentType] -- ^ list of content-types user accepts, ordered by preference -> IO (ContentType, Content) -- | Any type which can be converted to representations. class HasReps a where chooseRep :: a -> ChooseRep -- | A helper method for generating 'HasReps' instances. -- -- This function should be given a list of pairs of content type and conversion -- functions. If none of the content types match, the first pair is used. defChooseRep :: [(ContentType, a -> IO Content)] -> a -> ChooseRep defChooseRep reps a ts = do let (ct, c) = case mapMaybe helper ts of (x:_) -> x [] -> case reps of [] -> error "Empty reps to defChooseRep" (x:_) -> x c' <- c a return (ct, c') where helper ct = do c <- lookup ct reps return (ct, c) instance HasReps ChooseRep where chooseRep = id instance HasReps () where chooseRep = defChooseRep [(typePlain, const $ return $ toContent B.empty)] instance HasReps (ContentType, Content) where chooseRep = const . return instance HasReps [(ContentType, Content)] where chooseRep a cts = return $ case filter (\(ct, _) -> go ct `elem` map go cts) a of ((ct, c):_) -> (ct, c) _ -> case a of (x:_) -> x _ -> error "chooseRep [(ContentType, Content)] of empty" where go = simpleContentType newtype RepHtml = RepHtml Content instance HasReps RepHtml where chooseRep (RepHtml c) _ = return (typeHtml, c) newtype RepJson = RepJson Content instance HasReps RepJson where chooseRep (RepJson c) _ = return (typeJson, c) data RepHtmlJson = RepHtmlJson Content Content instance HasReps RepHtmlJson where chooseRep (RepHtmlJson html json) = chooseRep [ (typeHtml, html) , (typeJson, json) ] newtype RepPlain = RepPlain Content instance HasReps RepPlain where chooseRep (RepPlain c) _ = return (typePlain, c) newtype RepXml = RepXml Content instance HasReps RepXml where chooseRep (RepXml c) _ = return (typeXml, c) type ContentType = B.ByteString -- FIXME Text? typeHtml :: ContentType typeHtml = "text/html; charset=utf-8" typePlain :: ContentType typePlain = "text/plain; charset=utf-8" typeJson :: ContentType typeJson = "application/json; charset=utf-8" typeXml :: ContentType typeXml = "text/xml" typeAtom :: ContentType typeAtom = "application/atom+xml" typeRss :: ContentType typeRss = "application/rss+xml" typeJpeg :: ContentType typeJpeg = "image/jpeg" typePng :: ContentType typePng = "image/png" typeGif :: ContentType typeGif = "image/gif" typeSvg :: ContentType typeSvg = "image/svg+xml" typeJavascript :: ContentType typeJavascript = "text/javascript; charset=utf-8" typeCss :: ContentType typeCss = "text/css; charset=utf-8" typeFlv :: ContentType typeFlv = "video/x-flv" typeOgv :: ContentType typeOgv = "video/ogg" typeOctet :: ContentType typeOctet = "application/octet-stream" -- | Removes \"extra\" information at the end of a content type string. In -- particular, removes everything after the semicolon, if present. -- -- For example, \"text/html; charset=utf-8\" is commonly used to specify the -- character encoding for HTML data. This function would return \"text/html\". simpleContentType :: ContentType -> ContentType simpleContentType = fst . B.breakByte 59 -- 59 == ; -- | Format a 'UTCTime' in W3 format. formatW3 :: UTCTime -> T.Text formatW3 = T.pack . formatTime defaultTimeLocale "%FT%X-00:00" -- | Format as per RFC 1123. formatRFC1123 :: UTCTime -> T.Text formatRFC1123 = T.pack . formatTime defaultTimeLocale "%a, %d %b %Y %X %Z" -- | Format as per RFC 822. formatRFC822 :: UTCTime -> T.Text formatRFC822 = T.pack . formatTime defaultTimeLocale "%a, %d %b %Y %H:%M:%S %z"
chreekat/yesod
yesod-core/Yesod/Content.hs
Haskell
bsd-2-clause
7,002
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts, DeriveDataTypeable, StandaloneDeriving #-} module HEP.Automation.MadGraph.Model.ZpH where import Data.Typeable import Data.Data import Text.Printf import Text.Parsec import Control.Monad.Identity import Text.StringTemplate import Text.StringTemplate.Helpers import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Model.Common data ZpH = ZpH deriving (Show, Typeable, Data) instance Model ZpH where data ModelParam ZpH = ZpHParam { massZp :: Double, gRZp :: Double } deriving Show briefShow ZpH = "Zp" madgraphVersion _ = MadGraph4 modelName ZpH = "zHorizontal_MG" modelFromString str = case str of "zHorizontal_MG" -> Just ZpH _ -> Nothing paramCard4Model ZpH = "param_card_zHorizontal.dat" paramCardSetup tpath ZpH (ZpHParam m g) = do templates <- directoryGroup tpath return $ ( renderTemplateGroup templates [ ("masszp" , (printf "%.4e" m :: String)) , ("gRoverSqrtTwo" , (printf "%.4e" (g / (sqrt 2.0)) :: String)) , ("widthzp" , (printf "%.4e" (gammaWpZp m g) :: String)) ] (paramCard4Model ZpH) ) ++ "\n\n\n" briefParamShow (ZpHParam m g) = "M"++show m++"G"++show g interpreteParam str = let r = parse zphparse "" str in case r of Right param -> param Left err -> error (show err) zphparse :: ParsecT String () Identity (ModelParam ZpH) zphparse = do char 'M' massstr <- many1 (oneOf "+-0123456789.") char 'G' gstr <- many1 (oneOf "+-0123456789.") return (ZpHParam (read massstr) (read gstr)) gammaWpZp :: Double -> Double -> Double gammaWpZp mass coup = let r = mtop^(2 :: Int)/ mass^(2 :: Int) in coup^(2 :: Int) / (16.0 * pi) *mass*( 1.0 - 1.5 * r + 0.5 * r^(3 :: Int)) zpHTr :: TypeRep zpHTr = mkTyConApp (mkTyCon "HEP.Automation.MadGraph.Model.ZpH.ZpH") [] instance Typeable (ModelParam ZpH) where typeOf _ = mkTyConApp modelParamTc [zpHTr] deriving instance Data (ModelParam ZpH)
wavewave/madgraph-auto-model
src/HEP/Automation/MadGraph/Model/ZpH.hs
Haskell
bsd-2-clause
2,229
----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com> -- Stability : experimental -- Portability : portable ---------------------------------------------------------------------------- module Graphics.Luminance.Shader.Program where import Control.Applicative ( liftA2 ) import Control.Monad.Except ( MonadError(throwError) ) import Control.Monad.IO.Class ( MonadIO(..) ) import Control.Monad.Trans.Resource ( MonadResource, register ) import Data.Foldable ( traverse_ ) import Foreign.C ( peekCString, withCString ) import Foreign.Marshal.Alloc ( alloca ) import Foreign.Marshal.Array ( allocaArray ) import Foreign.Ptr ( castPtr, nullPtr ) import Foreign.Storable ( peek ) import Graphics.Luminance.Shader.Stage ( Stage(..) ) import Graphics.Luminance.Shader.Uniform ( U, Uniform(..) ) import Graphics.GL import Numeric.Natural ( Natural ) newtype Program = Program { programID :: GLuint } data ProgramError = LinkFailed String | InactiveUniform String deriving (Eq,Show) class HasProgramError a where fromProgramError :: ProgramError -> a createProgram :: (HasProgramError e,MonadError e m,MonadIO m,MonadResource m) => [Stage] -> ((forall a. (Uniform a) => Either String Natural -> m (U a)) -> m i) -> m (Program,i) createProgram stages buildIface = do (pid,linked,cl) <- liftIO $ do pid <- glCreateProgram traverse_ (glAttachShader pid . stageID) stages glLinkProgram pid linked <- isLinked pid ll <- clogLength pid cl <- clog ll pid pure (pid,linked,cl) if | linked -> do _ <- register $ glDeleteProgram pid let prog = Program pid iface <- buildIface $ ifaceWith prog pure (prog,iface) | otherwise -> throwError . fromProgramError $ LinkFailed cl createProgram_ :: (HasProgramError e,MonadError e m,MonadIO m,MonadResource m) => [Stage] -> m Program createProgram_ stages = fmap fst $ createProgram stages (\_ -> pure ()) isLinked :: GLuint -> IO Bool isLinked pid = do ok <- alloca $ liftA2 (*>) (glGetProgramiv pid GL_LINK_STATUS) peek pure $ ok == GL_TRUE clogLength :: GLuint -> IO Int clogLength pid = fmap fromIntegral . alloca $ liftA2 (*>) (glGetProgramiv pid GL_INFO_LOG_LENGTH) peek clog :: Int -> GLuint -> IO String clog l pid = allocaArray l $ liftA2 (*>) (glGetProgramInfoLog pid (fromIntegral l) nullPtr) (peekCString . castPtr) ifaceWith :: (HasProgramError e,MonadError e m,MonadIO m,Uniform a) => Program -> Either String Natural -> m (U a) ifaceWith prog access = case access of Left name -> do location <- liftIO . withCString name $ glGetUniformLocation pid if | isActive location -> pure $ toU pid location | otherwise -> throwError . fromProgramError $ InactiveUniform name Right sem | isActive sem -> pure $ toU pid (fromIntegral sem) | otherwise -> throwError . fromProgramError $ InactiveUniform (show sem) where pid = programID prog isActive :: (Ord a,Num a) => a -> Bool isActive = (> -1)
apriori/luminance
src/Graphics/Luminance/Shader/Program.hs
Haskell
bsd-3-clause
3,276
{-# LANGUAGE CPP #-} module Text.Search.Sphinx.Types ( module Text.Search.Sphinx.Types , ByteString ) where import Data.ByteString.Lazy (ByteString) import Data.Int (Int64) import Data.Maybe (Maybe, isJust) import Data.Text (Text,empty) -- | Data structure representing one query. It can be sent with 'runQueries' -- or 'runQueries'' to the server in batch mode. data Query = Query { queryString :: Text -- ^ The actual query string , queryIndexes :: Text -- ^ The indexes, \"*\" means every index , queryComment :: Text -- ^ A comment string. } deriving (Show) -- | Search commands data SearchdCommand = ScSearch | ScExcerpt | ScUpdate | ScKeywords deriving (Show, Enum) searchdCommand :: SearchdCommand -> Int searchdCommand = fromEnum -- | Current client-side command implementation versions data VerCommand = VcSearch | VcExcerpt | VcUpdate | VcKeywords deriving (Show) #ifdef ONE_ONE_BETA -- | Important! only 1.1 compatible, not 9.9.x verCommand VcSearch = 0x117 verCommand VcExcerpt = 0x102 #else -- | Important! 2.0 compatible verCommand VcSearch = 0x118 verCommand VcExcerpt = 0x103 #endif verCommand VcUpdate = 0x101 verCommand VcKeywords = 0x100 -- | Searchd status codes data Status = OK | RETRY | WARNING | ERROR Int deriving (Show) -- | status from an individual query data QueryStatus = QueryOK | QueryWARNING | QueryERROR Int deriving (Show) toQueryStatus 0 = QueryOK toQueryStatus 3 = QueryWARNING toQueryStatus 2 = error "Didn't think retry was possible" toQueryStatus n = QueryERROR n toStatus 0 = OK toStatus 2 = RETRY toStatus 3 = WARNING toStatus n = ERROR n -- | Match modes data MatchMode = All | Any | Phrase | Boolean | Extended | Fullscan | Extended2 -- extended engine V2 (TEMPORARY, WILL BE REMOVED) deriving (Show, Enum) -- | Ranking modes (ext2 only) data Rank = ProximityBm25 -- default mode, phrase proximity major factor and BM25 minor one | Bm25 -- statistical mode, BM25 ranking only (faster but worse quality) | None -- no ranking, all matches get a weight of 1 | WordCount -- simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts | Proximity -- internally used to emulate SPH_MATCH_ALL queries | MatchAny -- internaly used to emulate SPHINX_MATCH_ANY searching mode | Fieldmask -- ? | Sph04 -- like ProximityBm25, but more weight given to matches at beginning or end of field | Total deriving (Show, Enum) -- | Sort modes data Sort = Relevance | AttrDesc | AttrAsc | TimeSegments | SortExtended -- constructor already existed | Expr deriving (Show, Enum) -- | Filter types data Filter = ExclusionFilter Filter | FilterValues String [Int64] | FilterRange String Int64 Int64 | FilterFloatRange String Float Float deriving (Show) -- | shortcut for creating an exclusion filter exclude filter = ExclusionFilter filter fromEnumFilter (FilterValues _ _) = 0 fromEnumFilter (FilterRange _ _ _) = 1 fromEnumFilter (FilterFloatRange _ _ _) = 2 -- | Attribute types data AttrT = AttrTUInt -- unsigned 32-bit integer | AttrTTimestamp -- timestamp | AttrTStr2Ordinal -- ordinal string number (integer at search time, specially handled at indexing time) | AttrTBool -- boolean bit field | AttrTFloat -- floating point number (IEEE 32-bit) | AttrTBigInt -- signed 64-bit integer | AttrTString -- string (binary; in-memory) | AttrTWordCount -- string word count (integer at search time,tokenized and counted at indexing time) | AttrTMulti AttrT -- multiple values (0 or more) deriving (Show) instance Enum AttrT where toEnum = toAttrT fromEnum = attrT toAttrT 1 = AttrTUInt toAttrT 2 = AttrTTimestamp toAttrT 3 = AttrTStr2Ordinal toAttrT 4 = AttrTBool toAttrT 5 = AttrTFloat toAttrT 6 = AttrTBigInt toAttrT 7 = AttrTString toAttrT 8 = AttrTWordCount toAttrT 0x40000001 = AttrTMulti AttrTUInt attrMultiMask = 0x40000000 attrT AttrTUInt = 1 attrT AttrTTimestamp = 2 attrT AttrTStr2Ordinal = 3 attrT AttrTBool = 4 attrT AttrTFloat = 5 attrT AttrTBigInt = 6 attrT AttrTString = 7 attrT AttrTWordCount = 8 attrT (AttrTMulti AttrTUInt) = 0x40000001 -- | Grouping functions data GroupByFunction = Day | Week | Month | Year | Attr | AttrPair deriving (Show, Enum) -- | The result of a query data QueryResult = QueryResult { -- | The matches matches :: [Match] -- | Total amount of matches retrieved on server by this query. , total :: Int -- | Total amount of matching documents in index. , totalFound :: Int -- | processed words with the number of docs and the number of hits. , words :: [(Text, Int, Int)] -- | List of attribute names returned in the result. -- | The Match will contain just the attribute values in the same order. , attributeNames :: [ByteString] } deriving Show -- | a single query result, runQueries returns a list of these data SingleResult = QueryOk QueryResult | QueryWarning Text QueryResult | QueryError Int Text deriving (Show) -- | a result returned from searchd data Result a = Ok a | Warning Text a | Error Int Text | Retry Text deriving (Show) data Match = Match { -- Document ID documentId :: Int64 -- Document weight , documentWeight :: Int -- Attribute values , attributeValues :: [Attr] } deriving Show instance Eq Match where d1 == d2 = documentId d1 == documentId d2 data Attr = AttrMulti [Attr] | AttrUInt Int | AttrBigInt Int64 | AttrString Text | AttrFloat Float deriving (Show)
gregwebs/haskell-sphinx-client
Text/Search/Sphinx/Types.hs
Haskell
bsd-3-clause
6,681
{-#LANGUAGE MultiParamTypeClasses #-} {-#LANGUAGE OverloadedStrings #-} {-#LANGUAGE ViewPatterns #-} module Twilio.Transcription ( -- * Resource Transcription(..) , Twilio.Transcription.get -- * Types , PriceUnit(..) , TranscriptionStatus(..) ) where import Control.Applicative import Control.Error.Safe import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types {- Resource -} data Transcription = Transcription { sid :: !TranscriptionSID , dateCreated :: !UTCTime , dateUpdated :: !UTCTime , accountSID :: !AccountSID , status :: !TranscriptionStatus , recordingSID :: !RecordingSID , duration :: !(Maybe Int) , transcriptionText :: !Text , price :: !(Maybe Double) , priceUnit :: !PriceUnit , apiVersion :: !APIVersion , uri :: !URI } deriving (Show, Eq) instance FromJSON Transcription where parseJSON (Object v) = Transcription <$> v .: "sid" <*> (v .: "date_created" >>= parseDateTime) <*> (v .: "date_updated" >>= parseDateTime) <*> v .: "account_sid" <*> v .: "status" <*> v .: "recording_sid" <*> (v .: "duration" <&> fmap readZ >>= maybeReturn') <*> v .: "transcription_text" <*> (v .: "price" <&> fmap readZ >>= maybeReturn') <*> v .: "price_unit" <*> v .: "api_version" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) parseJSON _ = mzero instance Get1 TranscriptionSID Transcription where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Transcriptions/" <> sid <> ".json") -- | Get a 'Transcription' by 'TranscriptionSID'. get :: MonadThrow m => TranscriptionSID -> TwilioT m Transcription get = Resource.get {- Types -} data TranscriptionStatus = InProgress | Completed | Failed deriving Eq instance Show TranscriptionStatus where show InProgress = "in-progress" show Completed = "completed" show Failed = "failed" instance FromJSON TranscriptionStatus where parseJSON (String "in-progress") = return InProgress parseJSON (String "completed") = return Completed parseJSON (String "failed") = return Failed parseJSON _ = mzero
seagreen/twilio-haskell
src/Twilio/Transcription.hs
Haskell
bsd-3-clause
2,632
{-# LANGUAGE GADTs, TypeOperators, PolyKinds, RankNTypes, CPP #-} #include "macros.h" LANGUAGE_TRUSTWORTHY LANGUAGE_AUTODERIVETYPEABLE {-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-orphans #-} -- | Kind-polymorphic functions for manipulating type equality evidence. -- -- This module is available only if @PolyKinds@ are available (GHC 7.6+). module Type.Eq.Poly (module Type.Eq, module Type.Eq.Poly) where import Control.Applicative ((<$>)) import Control.Category ((.)) -- for haddock import Data.Typeable (Typeable1, typeOf1, Typeable2, typeOf2, Typeable3, typeOf3, Typeable4, typeOf4, Typeable5, typeOf5, Typeable6, typeOf6, Typeable7, typeOf7) import Type.Eq import Type.Eq.Higher ((::~::)(..), (:::~:::)(..), OuterEq1(..), InnerEq1(..)) import Type.Eq.Unsafe import Prelude hiding ((.)) import Unsafe.Coerce {- INSTANCE_TYPEABLE(1,:~:,f,g,"Type.Eq",":~:",()) INSTANCE_TYPEABLE(2,:~:,m,n,"Type.Eq",":~:",() ()) INSTANCE_TYPEABLE(3,:~:,x,y,"Type.Eq",":~:",() () ()) INSTANCE_TYPEABLE(4,:~:,x,y,"Type.Eq",":~:",() () () ()) INSTANCE_TYPEABLE(5,:~:,x,y,"Type.Eq",":~:",() () () () ()) INSTANCE_TYPEABLE(6,:~:,x,y,"Type.Eq",":~:",() () () () () ()) INSTANCE_TYPEABLE(7,:~:,x,y,"Type.Eq",":~:",() () () () () () ()) -} -- | Synonym for @'composeEq'@. Kind-polymorphic, unlike @('.')@. (|.|) :: b :~: c -> a :~: b -> a :~: c (|.|) = composeEq -- | Congruence? applyEq, (|$|) :: f :~: g -> a :~: b -> f a :~: g b applyEq = withEq (withEq Eq) (|$|) = applyEq -- | Type constructors are generative constructorEq :: f a :~: g b -> f :~: g constructorEq = withEq BUG_5591(Eq) DYNAMIC_EQ(1,,:~:,f,g,()) DYNAMIC_EQ(2,,:~:,n,m,() ()) DYNAMIC_EQ(3,,:~:,x,y,() () ()) DYNAMIC_EQ(4,,:~:,x,y,() () () ()) DYNAMIC_EQ(5,,:~:,x,y,() () () () ()) DYNAMIC_EQ(6,,:~:,x,y,() () () () () ()) DYNAMIC_EQ(7,,:~:,x,y,() () () () () () ()) sameOuterEq :: OuterEq f a -> OuterEq g a -> f :~: g sameOuterEq OuterEq OuterEq = BUG_5591(Eq) -- * Compatibility with Type.Eq.Higher fromEq1 :: f ::~:: g -> f :~: g fromEq1 Eq1 = Eq toEq1 :: f :~: g -> f ::~:: g toEq1 Eq = Eq1 fromEq2 :: n :::~::: m -> n :~: m fromEq2 Eq2 = Eq toEq2 :: n :~: m -> n :::~::: m toEq2 Eq = Eq2 fromOuterEq1 :: OuterEq1 m f -> OuterEq m f fromOuterEq1 OuterEq1 = BUG_5591(OuterEq) toOuterEq1 :: OuterEq m f -> OuterEq1 m f toOuterEq1 OuterEq = OuterEq1 fromInnerEq1 :: InnerEq1 a f -> InnerEq a f fromInnerEq1 InnerEq1 = BUG_5591(InnerEq) toInnerEq1 :: InnerEq a f -> InnerEq1 a f toInnerEq1 InnerEq = InnerEq1
glaebhoerl/type-eq
Type/Eq/Poly.hs
Haskell
bsd-3-clause
2,487
module Database.Algebra.Rewrite.Traversal ( preOrder , postOrder , applyToAll , topologically , iteratively , sequenceRewrites ) where import Control.Monad import qualified Data.IntMap as M import qualified Data.Set as S import qualified Database.Algebra.Dag as Dag import Database.Algebra.Dag.Common import Database.Algebra.Rewrite.DagRewrite import Database.Algebra.Rewrite.Rule applyToAll :: Rewrite o e (NodeMap p) -> RuleSet o p e -> Rewrite o e Bool applyToAll inferProps rules = iterateRewrites False 0 where iterateRewrites anyChanges offset = do -- drop the first nodes, assuming that we already visited them nodes <- drop offset <$> M.keys <$> Dag.nodeMap <$> exposeDag -- re-infer properties props <- inferProps extras <- getExtras -- try to apply the rewrites, beginning with node at position offset matchedOffset <- traverseNodes offset props extras rules nodes case matchedOffset of -- A rewrite applied at offset o -> we continue at this offset Just o -> iterateRewrites True o -- No rewrite applied -> report if any changes occured at all Nothing -> return anyChanges traverseNodes :: Int -> NodeMap p -> e -> RuleSet o p e -> [AlgNode] -> Rewrite o e (Maybe Int) traverseNodes offset props extras rules nodes = case nodes of n : ns -> do changed <- applyRuleSet extras props rules n if changed then return $ Just offset else traverseNodes (offset + 1) props extras rules ns [] -> return Nothing -- | Infer properties, then traverse the DAG in preorder fashion and apply the rule set -- at every node. Properties are re-inferred after every change. preOrder :: Dag.Operator o => Rewrite o e (NodeMap p) -> RuleSet o p e -> Rewrite o e Bool preOrder inferAction rules = let traversePre (changedPrev, mProps, visited) q = if q `S.member` visited then return (changedPrev, mProps, visited) else do props <- case mProps of Just ps -> return ps Nothing -> inferAction e <- getExtras changedSelf <- applyRuleSet e props rules q -- Have to be careful here: With garbage collection, the current node 'q' -- might no longer be present after a rewrite. mop <- operatorSafe q case mop of Just op -> do -- the node still seems to be around, so we need to look after its children let mProps' = if changedSelf then Nothing else Just props let cs = Dag.opChildren op (changedChild, mProps'', visited') <- foldM descend (changedSelf, mProps', visited) cs let visited'' = S.insert q visited' if changedChild then return (True, Nothing, visited'') else return (changedPrev || (changedSelf || changedChild), mProps'', visited'') Nothing -> return (True, Nothing, visited) -- The node has been collected -> do nothing descend (changedPrev, mProps, visited) c = do props <- case mProps of Just ps -> return ps Nothing -> inferAction traversePre (changedPrev, Just props, visited) c in do pm <- inferAction rs <- rootNodes (changed, _, _) <- foldM traversePre (False, Just pm, S.empty) rs return changed {- | Map a ruleset over the nodes of a DAG in topological order. This function assumes that the structur of the DAG is not changed during the rewrites. Properties are only inferred once. -} topologically :: Rewrite o e (NodeMap p) -> RuleSet o p e -> Rewrite o e Bool topologically inferAction rules = do topoOrdering <- topsort props <- inferAction let rewriteNode changedPrev q = do e <- getExtras changed <- applyRuleSet e props rules q return $ changed || changedPrev foldM rewriteNode False topoOrdering where -- | Infer properties, then traverse the DAG in a postorder fashion and apply the rule set at -- every node. Properties are re-inferred after every change. postOrder :: Dag.Operator o => Rewrite o e (NodeMap p) -> RuleSet o p e -> Rewrite o e Bool postOrder inferAction rules = let traversePost (changedPrev, props, visited) q = if q `S.member` visited then return (changedPrev, props, visited) else do op <- operator q let cs = Dag.opChildren op (changedChild, mProps, visited') <- foldM descend (False, props, visited) cs props' <- case mProps of Just ps -> return ps Nothing -> inferAction e <- getExtras -- Check if the current node is still around after its children -- have been rewritten. This should not happen regularly, but -- better safe than sorry. mop <- operatorSafe q case mop of Just _ -> do changedSelf <- applyRuleSet e props' rules q let visited'' = S.insert q visited' if changedSelf then return (True, Nothing, visited'') else return (changedChild || changedPrev, Just props', visited'') Nothing -> return (True, Nothing, visited) descend (changedPrev, mProps, visited) c = do props <- case mProps of Just ps -> return ps Nothing -> inferAction traversePost (changedPrev, Just props, visited) c in do pm <- inferAction rs <- rootNodes (changed, _, _) <- foldM traversePost (False, Just pm, S.empty) rs return changed -- | Iteratively apply a rewrite, until no further changes occur. iteratively :: Rewrite o e Bool -> Rewrite o e Bool iteratively rewrite = aux False where aux b = do changed <- rewrite if changed then logGeneral ">>> Iterate" >> aux True else return b -- | Sequence a list of rewrites and propagate information about -- wether one of them applied. sequenceRewrites :: [Rewrite o e Bool] -> Rewrite o e Bool sequenceRewrites rewrites = or <$> sequence rewrites
ulricha/algebra-dag
src/Database/Algebra/Rewrite/Traversal.hs
Haskell
bsd-3-clause
6,370
{-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} -- | Implementation of the @dhall to-directory-tree@ subcommand module Dhall.DirectoryTree ( -- * Filesystem toDirectoryTree , FilesystemError(..) ) where import Control.Applicative (empty) import Control.Exception (Exception) import Data.Void (Void) import Dhall.Syntax (Chunks (..), Expr (..), RecordField (..)) import System.FilePath ((</>)) import qualified Control.Exception as Exception import qualified Data.Foldable as Foldable import qualified Data.Text as Text import qualified Data.Text.IO as Text.IO import qualified Dhall.Map as Map import qualified Dhall.Pretty import qualified Dhall.Util as Util import qualified Prettyprinter.Render.String as Pretty import qualified System.Directory as Directory import qualified System.FilePath as FilePath {-| Attempt to transform a Dhall record into a directory tree where: * Records are translated into directories * @Map@s are also translated into directories * @Text@ values or fields are translated into files * @Optional@ values are omitted if @None@ For example, the following Dhall record: > { dir = { `hello.txt` = "Hello\n" } > , `goodbye.txt`= Some "Goodbye\n" > , `missing.txt` = None Text > } ... should translate to this directory tree: > $ tree result > result > ├── dir > │ └── hello.txt > └── goodbye.txt > > $ cat result/dir/hello.txt > Hello > > $ cat result/goodbye.txt > Goodbye Use this in conjunction with the Prelude's support for rendering JSON/YAML in "pure Dhall" so that you can generate files containing JSON. For example: > let JSON = > https://prelude.dhall-lang.org/v12.0.0/JSON/package.dhall sha256:843783d29e60b558c2de431ce1206ce34bdfde375fcf06de8ec5bf77092fdef7 > > in { `example.json` = > JSON.render (JSON.array [ JSON.number 1.0, JSON.bool True ]) > , `example.yaml` = > JSON.renderYAML > (JSON.object (toMap { foo = JSON.string "Hello", bar = JSON.null })) > } ... which would generate: > $ cat result/example.json > [ 1.0, true ] > > $ cat result/example.yaml > ! "bar": null > ! "foo": "Hello" This utility does not take care of type-checking and normalizing the provided expression. This will raise a `FilesystemError` exception upon encountering an expression that cannot be converted as-is. -} toDirectoryTree :: FilePath -> Expr Void Void -> IO () toDirectoryTree path expression = case expression of RecordLit keyValues -> Map.unorderedTraverseWithKey_ process $ recordFieldValue <$> keyValues ListLit (Just (Record [ ("mapKey", recordFieldValue -> Text), ("mapValue", _) ])) [] -> return () ListLit _ records | not (null records) , Just keyValues <- extract (Foldable.toList records) -> Foldable.traverse_ (uncurry process) keyValues TextLit (Chunks [] text) -> Text.IO.writeFile path text Some value -> toDirectoryTree path value App (Field (Union _) _) value -> toDirectoryTree path value App None _ -> return () _ -> die where extract [] = return [] extract (RecordLit [ ("mapKey", recordFieldValue -> TextLit (Chunks [] key)) , ("mapValue", recordFieldValue -> value)] : records) = fmap ((key, value) :) (extract records) extract _ = empty process key value = do if Text.isInfixOf (Text.pack [ FilePath.pathSeparator ]) key then die else return () Directory.createDirectoryIfMissing False path toDirectoryTree (path </> Text.unpack key) value die = Exception.throwIO FilesystemError{..} where unexpectedExpression = expression {- | This error indicates that you supplied an invalid Dhall expression to the `toDirectoryTree` function. The Dhall expression could not be translated to a directory tree. -} newtype FilesystemError = FilesystemError { unexpectedExpression :: Expr Void Void } instance Show FilesystemError where show FilesystemError{..} = Pretty.renderString (Dhall.Pretty.layout message) where message = Util._ERROR <> ": Not a valid directory tree expression \n\ \ \n\ \Explanation: Only a subset of Dhall expressions can be converted to a directory \n\ \tree. Specifically, record literals or maps can be converted to directories, \n\ \❰Text❱ literals can be converted to files, and ❰Optional❱ values are included if \n\ \❰Some❱ and omitted if ❰None❱. Values of union types can also be converted if \n\ \they are an alternative which has a non-nullary constructor whose argument is of \n\ \an otherwise convertible type. No other type of value can be translated to a \n\ \directory tree. \n\ \ \n\ \For example, this is a valid expression that can be translated to a directory \n\ \tree: \n\ \ \n\ \ \n\ \ ┌──────────────────────────────────┐ \n\ \ │ { `example.json` = \"[1, true]\" } │ \n\ \ └──────────────────────────────────┘ \n\ \ \n\ \ \n\ \In contrast, the following expression is not allowed due to containing a \n\ \❰Natural❱ field, which cannot be translated in this way: \n\ \ \n\ \ \n\ \ ┌───────────────────────┐ \n\ \ │ { `example.txt` = 1 } │ \n\ \ └───────────────────────┘ \n\ \ \n\ \ \n\ \Note that key names cannot contain path separators: \n\ \ \n\ \ \n\ \ ┌─────────────────────────────────────┐ \n\ \ │ { `directory/example.txt` = \"ABC\" } │ Invalid: Key contains a forward slash\n\ \ └─────────────────────────────────────┘ \n\ \ \n\ \ \n\ \Instead, you need to refactor the expression to use nested records instead: \n\ \ \n\ \ \n\ \ ┌───────────────────────────────────────────┐ \n\ \ │ { directory = { `example.txt` = \"ABC\" } } │ \n\ \ └───────────────────────────────────────────┘ \n\ \ \n\ \ \n\ \You tried to translate the following expression to a directory tree: \n\ \ \n\ \" <> Util.insert unexpectedExpression <> "\n\ \ \n\ \... which is not an expression that can be translated to a directory tree. \n" instance Exception FilesystemError
Gabriel439/Haskell-Dhall-Library
dhall/src/Dhall/DirectoryTree.hs
Haskell
bsd-3-clause
9,987
-- | Usage: http-bench <total> <concurrent> module Main where import Control.Concurrent import Control.Monad import Network.HTTP import Text.Printf import System.Exit import System.Environment import Control.Exception as E import Debug.Trace data Stats = Stats {hits :: Int, prevHits :: Int} deriving (Show) data Interval = Interval {} deriving (Show) interval = 10 * 1000 * 1000 -- ten seconds main = do args <- getArgs when (length args /= 3) (fail usage) let [url, minConcStr, maxConcStr] = args minConc <- readIO minConcStr :: IO Int maxConc <- readIO maxConcStr :: IO Int currentConcurrent <- newMVar minConc stats <- newMVar $ Stats {hits = 0, prevHits = 0} flip E.catch (handleInterrupts stats) $ do -- create initial set of threads threads <- forM [1 .. minConc] $ \_ -> forkIO $ go url stats -- spawn thread for pool control forkIO $ poolControl threads (go url stats) currentConcurrent -- main thread does stat control statControl minConc maxConc currentConcurrent stats handleInterrupts stats e | e /= UserInterrupt = E.throwIO e | otherwise = do s <- readMVar stats putStr "\n\n" print s error "Exiting..." poolControl :: [ThreadId] -> IO () -> MVar Int -> IO () poolControl threads action currentConcurrent = do -- maintain a list of type [ThreadId] that represents a threadpool threadDelay interval let currentThreads = length threads wantedThreads <- readMVar currentConcurrent -- periodically spawn or kill threads as needed to keep the pool at the size specified by an mvar case compare wantedThreads currentThreads of GT -> do let newThreads = wantedThreads - currentThreads tids <- forM [1 .. newThreads] $ \_ -> forkIO action poolControl (tids ++ threads) action currentConcurrent LT -> do let removeThreads = currentThreads - wantedThreads (remove, keep) = splitAt removeThreads threads forM_ remove $ \tid -> killThread tid poolControl keep action currentConcurrent EQ -> poolControl threads action currentConcurrent statControl :: Int -> Int -> MVar Int -> MVar Stats -> IO () statControl minConc maxConc currentConcurrent statsRef = forever $ do threadDelay interval -- read current stats information stats <- readMVar statsRef conc <- readMVar currentConcurrent -- use information from stats to update concurrency level, if necessary -- if we end up unable to rise above the minimum concurrency level, print message let wanted = case (prevHits stats `compare` hits stats) of EQ -> conc LT -> min maxConc (conc + 1) GT -> max minConc (conc - 1) -- if we end up stable at the maximum concurrency level, print message printf "Hits: %i - Concurrent: %i\n" (hits stats) wanted -- reset stats for current interval modifyMVar_ statsRef (return . reset) modifyMVar_ currentConcurrent (return . const wanted) return () reset :: Stats -> Stats reset s = s {hits = 0, prevHits = hits s} go :: String -> MVar Stats -> IO () go url stats = forever $ do result <- simpleHTTP (getRequest url) let success = case result of (Right response) | rspCode response == (2, 0, 0) -> True _ -> False modifyMVar_ stats $ \s -> return s {hits = hits s + 1} usage = "\n\ \Usage: http-bench <url> <min-concurrent> <max-concurrent>\n\ \ Benchmark a website by requesting a URL many times concurrently.\n\ \ http-bench will begin at the minimum number of concurrent requests,\n\ \ and slowly scale to the speed of your webserver, or the upper\n\ \ concurrency limit parameter.\n"
headprogrammingczar/http-bench
Main.hs
Haskell
bsd-3-clause
3,858
{-- Another instance of Applicative is (->) r, so functions. They are rarely used with the applicative style outside of code golf, but they're still interesting as applicatives, so let's take a look at how the function instance is implemented. instance Applicative ((->) r) where pure x = (\_ -> x) f <*> g = \x -> f x (g x) When we wrap a value into an applicative functor with pure, the result it yields always has to be that value. A minimal default context that still yields that value as a result. That's why in the function instance implementation, pure takes a value and creates a function that ignores its parameter and always returns that value. If we look at the type for pure, but specialized for the (->) r instance: it's pure :: a -> (r -> a). ghci> (pure 3) "blah" 3 Because of currying, function application is left-associative, so we can omit the parentheses. ghci> pure 3 "blah" 3 ghci> :t (+) <$> (+3) <*> (*100) (+) <$> (+3) <*> (*100) :: (Num a) => a -> a ghci> (+) <$> (+3) <*> (*100) $ 5 508 When we do (+) <$> (+3) <*> (*100), we're making a function that will use + on the results of (+3) and (*100) and return that. To demonstrate on a real example, when we did (+) <$> (+3) <*> (*100) $ 5, the 5 first got applied to (+3) and (*100), resulting in 8 and 500. Then, + gets called with 8 and 500, resulting in 508. --} {-- review of ((->) r) in <*>, <$> we know fmap f g :: (a -> b) -> z a -> z b so f :: (a ->b), g :: z a and in ((->) r) higer-kinded type this is defined as: z a :: ((->) r) a fmap f g :: (a -> b) -> ((->) r) a -> ((->) r) b as infix: (a -> b) -> (r -> a) -> (r -> b) Note that f a must be concrete type! so it is ((->) r) a Then rewrite it as infix operator: r -> a <$> :: (functor f) => (a -> b) -> f a -> f b f <$> g = fmap f g so output of <$> for ((->) r) is as: ((->) r) b which is equivalent to ((->) r) (f (g r)) , rewrite it to lambda: r -> (f a) == r -> z b then: fmap f g = \r -> f (g r) or as \x -> f (g x) <*> :: f (a -> b) -> f a -> f b the same as: ((-> r) a -> b) -> ((-> r) a) -> ((-> r) b) == (r -> (a -> b)) -> (r -> a) -> (r -> b) f <*> g => then we know f r == (a -> b) so f <*> g = \x -> f x (g x), since here x or r is the same type In here we can fnd that f should be a "binary" higer-kinded type, ex: (+), (-) In here we can fnd that g should be a "unary" higer-kinded type, ex: (+ 3), (- 2) so (+) <$> (+3) <*> (*100) $ 5 => fmap (+) (+3) ... => (\x -> (+ ((+) 3 x))) <*> (* 100) ... ^ as z => (\r -> z r (* 100 r)) $ 5 => z 5 (* 100 5) => z 5 (500) => (+ ((+) 3 5)) 500 => (+ 8) 500 => 508 pure f <*> x <*> y ... == fmap f x <*> y ... == f <$> x <*> y ... --} {-- by type signature. we might have different impl for [], ex: [(+3),(*2)] <*> [1,2] could result to [4,5,2,4] or [1 + 3, 2 * 2] In order to distinguish this, haskell provide a ZipList applicative functor: instance Applicative ZipList where pure x = ZipList (repeat x) ZipList fs <*> ZipList xs = ZipList (zipWith (\f x -> f x) fs xs) for all cases like [1 + 3, 2 * 2] So how do zip lists work in an applicative style? Let's see. Oh, the ZipList a type doesn't have a Show instance, so we have to use the "getZipList" function to extract a raw list out of a zip list. --} getZipList $ (,,) <$> ZipList "dog" <*> ZipList "cat" <*> ZipList "rat" -- [('d','c','r'),('o','a','a'),('g','t','t')] {-- The (,,) function is the same as \x y z -> (x,y,z). Also, the (,) function is the same as \x y -> (x,y). Control.Applicative defines a function that's called liftA2, which has a type of liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c It's defined like this: liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c liftA2 f a b = f <$> a <*> b It's also interesting to look at this function's type as: (a -> b -> c) -> (f a -> f b -> f c) When we look at it like this, we can say that liftA2 takes a normal binary function and promotes it to a function that operates on two functors. ghci> liftA2 (:) (Just 3) (Just [4]) Just [3,4] ghci> (:) <$> Just 3 <*> Just [4] Just [3,4] It seems that we can combine any amount of applicatives into one applicative that has a list of the results of those applicatives inside it. Let's try implementing a function that takes a list of applicatives and returns an applicative that has a list as its result value. We'll call it sequenceA. sequenceA :: (Applicative f) => [f a] -> f [a] sequenceA [] = pure [] sequenceA (x:xs) = (:) <$> x <*> sequenceA xs Another way to implement sequenceA is with a fold. Remember, pretty much any function where we go over a list element by element and accumulate a result along the way can be implemented with a fold. sequenceA :: (Applicative f) => [f a] -> f [a] sequenceA = foldr (liftA2 (:)) (pure []) ghci> sequenceA [Just 3, Just 2, Just 1] Just [3,2,1] ghci> sequenceA [Just 3, Nothing, Just 1] Nothing ghci> sequenceA [(+3),(+2),(+1)] 3 [6,5,4] ghci> sequenceA [[1,2,3],[4,5,6]] [[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]] ghci> sequenceA [[1,2,3],[4,5,6],[3,4,4],[]] [] sequenceA [[1], []] => (:) <$> [1] <*> sequenceA [[]] => (:) <$> [1] <*> ((:) <$> [] <*> sequenceA []) => (:) <$> [1] <*> ((:) <$> [] <*> [[]]) => (:) <$> [1] <*> [] => [((:) 1)] <*> [] => fmap ((:) 1) [] => by defintion we know fmap f [] = [] => [] => or => [f x | f <- ((:) 1), x <- []] by fs <*> xs = [f x | f <- fs, x <- xs] => or => do f <- fs x <- xs f x => fs >>= (\f -> xs >>= (\x -> f x)) => since [] >>= (\x -> [(+ 1) x]) = [] => fs >>= (\f -> []) => and xs >>= k = join (fmap k xs) => join (fmap (\f -> []) fs) => [] instance Functor [] where fmap = map -- https://hackage.haskell.org/package/base-4.10.0.0/docs/src/GHC.Base.html#fmap map _ [] = [] map f (x:xs) = f x : map f xs -- http://hackage.haskell.org/package/base-4.10.0.0/docs/src/GHC.Base.html#map --} {-- ghci> map (\f -> f 7) [(>4),(<10),odd] [True,True,True] ghci> and $ map (\f -> f 7) [(>4),(<10),odd] True ghci> sequenceA [(>4),(<10),odd] 7 [True,True,True] ghci> and $ sequenceA [(>4),(<10),odd] 7 True --}
jamesyang124/haskell-playground
src/Chp111.hs
Haskell
bsd-3-clause
6,133
-- | -- Functions for constructing and parsing Atom feeds for use in the -- request and response bodies of the various web methods. -- module Network.TableStorage.Atom ( atomNamespace, dataServicesNamespace, metadataNamespace, qualifyAtom, qualifyDataServices, qualifyMetadata, atomElement, atomAttr, wrapContent ) where import Network.TableStorage.XML ( qualify, cDataText, namespaceAttr ) import Network.TableStorage.Format ( atomDate ) import Text.XML.Light ( Element(elAttribs, elContent, elName), Content(Elem), QName, CDataKind(..), Content(..), CData(..), Attr(..), blank_element, unqual ) import Data.Maybe (fromMaybe) atomNamespace :: String atomNamespace = "http://www.w3.org/2005/Atom" dataServicesNamespace :: String dataServicesNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices" metadataNamespace :: String metadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" qualifyAtom :: String -> QName qualifyAtom = qualify (Just atomNamespace) Nothing qualifyDataServices :: String -> QName qualifyDataServices = qualify (Just dataServicesNamespace) (Just "d") qualifyMetadata :: String -> QName qualifyMetadata = qualify (Just metadataNamespace) (Just "m") -- | -- An element in the Atom namespace with the provided attributes and child elements -- atomElement :: String -> Maybe String -> [Attr] -> [Element] -> Element atomElement name content attrs els = blank_element { elName = qualifyAtom name, elAttribs = attrs, elContent = map Elem els ++ maybe [] cDataText content } -- | -- An attribute in the Atom namespace -- atomAttr :: String -> String -> Attr atomAttr name value = Attr { attrKey = qualifyAtom name, attrVal = value } -- | -- Create an Atom entry using the specified element as the content element -- wrapContent :: Maybe String -> Element -> IO Element wrapContent entityID content = do date <- atomDate return $ atomElement "entry" Nothing [ Attr { attrKey = unqual "xmlns", attrVal = atomNamespace } , namespaceAttr "d" dataServicesNamespace , namespaceAttr "m" metadataNamespace ] [ atomElement "category" Nothing [ atomAttr "scheme" "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" , atomAttr "term" "clio.cookies" ] [] , atomElement "title" Nothing [] [] , atomElement "author" Nothing [] [ atomElement "name" Nothing [] [] ] , atomElement "updated" (Just date) [] [] , blank_element { elName = qualifyAtom "id" , elAttribs = [] , elContent = [Text CData { cdVerbatim = CDataRaw, cdData = fromMaybe "" entityID, cdLine = Nothing }] } , atomElement "content" Nothing [ atomAttr "type" "application/xml" ] [ content ] ]
paf31/tablestorage
src/Network/TableStorage/Atom.hs
Haskell
bsd-3-clause
2,878
-- | State monad for the linear register allocator. -- Here we keep all the state that the register allocator keeps track -- of as it walks the instructions in a basic block. {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module RegAlloc.Linear.State ( RA_State(..), RegM, runR, spillR, loadR, getFreeRegsR, setFreeRegsR, getAssigR, setAssigR, getBlockAssigR, setBlockAssigR, setDeltaR, getDeltaR, getUniqueR, recordSpill ) where import RegAlloc.Linear.Stats import RegAlloc.Linear.StackMap import RegAlloc.Linear.Base import RegAlloc.Liveness import Instruction import Reg import Platform import Unique import UniqSupply -- | The RegM Monad instance Monad (RegM freeRegs) where m >>= k = RegM $ \s -> case unReg m s of { (# s, a #) -> unReg (k a) s } return a = RegM $ \s -> (# s, a #) -- | Run a computation in the RegM register allocator monad. runR :: BlockAssignment freeRegs -> freeRegs -> RegMap Loc -> StackMap -> UniqSupply -> RegM freeRegs a -> (BlockAssignment freeRegs, StackMap, RegAllocStats, a) runR block_assig freeregs assig stack us thing = case unReg thing (RA_State { ra_blockassig = block_assig , ra_freeregs = freeregs , ra_assig = assig , ra_delta = 0{-???-} , ra_stack = stack , ra_us = us , ra_spills = [] }) of (# state'@RA_State { ra_blockassig = block_assig , ra_stack = stack' } , returned_thing #) -> (block_assig, stack', makeRAStats state', returned_thing) -- | Make register allocator stats from its final state. makeRAStats :: RA_State freeRegs -> RegAllocStats makeRAStats state = RegAllocStats { ra_spillInstrs = binSpillReasons (ra_spills state) } spillR :: Instruction instr => Platform -> Reg -> Unique -> RegM freeRegs (instr, Int) spillR platform reg temp = RegM $ \ s@RA_State{ra_delta=delta, ra_stack=stack} -> let (stack',slot) = getStackSlotFor stack temp instr = mkSpillInstr platform reg delta slot in (# s{ra_stack=stack'}, (instr,slot) #) loadR :: Instruction instr => Platform -> Reg -> Int -> RegM freeRegs instr loadR platform reg slot = RegM $ \ s@RA_State{ra_delta=delta} -> (# s, mkLoadInstr platform reg delta slot #) getFreeRegsR :: RegM freeRegs freeRegs getFreeRegsR = RegM $ \ s@RA_State{ra_freeregs = freeregs} -> (# s, freeregs #) setFreeRegsR :: freeRegs -> RegM freeRegs () setFreeRegsR regs = RegM $ \ s -> (# s{ra_freeregs = regs}, () #) getAssigR :: RegM freeRegs (RegMap Loc) getAssigR = RegM $ \ s@RA_State{ra_assig = assig} -> (# s, assig #) setAssigR :: RegMap Loc -> RegM freeRegs () setAssigR assig = RegM $ \ s -> (# s{ra_assig=assig}, () #) getBlockAssigR :: RegM freeRegs (BlockAssignment freeRegs) getBlockAssigR = RegM $ \ s@RA_State{ra_blockassig = assig} -> (# s, assig #) setBlockAssigR :: BlockAssignment freeRegs -> RegM freeRegs () setBlockAssigR assig = RegM $ \ s -> (# s{ra_blockassig = assig}, () #) setDeltaR :: Int -> RegM freeRegs () setDeltaR n = RegM $ \ s -> (# s{ra_delta = n}, () #) getDeltaR :: RegM freeRegs Int getDeltaR = RegM $ \s -> (# s, ra_delta s #) getUniqueR :: RegM freeRegs Unique getUniqueR = RegM $ \s -> case takeUniqFromSupply (ra_us s) of (uniq, us) -> (# s{ra_us = us}, uniq #) -- | Record that a spill instruction was inserted, for profiling. recordSpill :: SpillReason -> RegM freeRegs () recordSpill spill = RegM $ \s -> (# s { ra_spills = spill : ra_spills s}, () #)
nomeata/ghc
compiler/nativeGen/RegAlloc/Linear/State.hs
Haskell
bsd-3-clause
3,775
module Data.Persist.Compile (compile) where import Data.Persist.AST import Language.Haskell.Exts.Syntax import Data.Either (partitionEithers) compile :: [Either Decl Relationship] -> Module compile input = Module noLoc (ModuleName "Model") pragmas Nothing Nothing imports (compileDecls input) where imports = map mkImport ["Data.Persist.Interface", "Generics.Regular"] pragmas = [LanguagePragma noLoc $ map Ident ["TemplateHaskell", "EmptyDataDecls", "TypeFamilies"]] mkImport nm = ImportDecl noLoc (ModuleName nm) False False Nothing Nothing Nothing compileDecls :: [Either Decl Relationship] -> [Decl] compileDecls input = let (decls, relationships) = partitionEithers input relationshipsBothDirections = relationships ++ (map reverseRelationship relationships) dbClass = UnQual (Ident "Persistent") in concat [ decls , concatMap derivingRegular decls , concatMap (compileRelationship decls) relationships , concatMap (createMethod dbClass relationshipsBothDirections) decls , createSchema dbClass decls relationships ] compileRelationship :: [Decl] -> Relationship -> [Decl] compileRelationship _ r = [ TypeSig noLoc [funName] (relType `TyApp` from `TyApp` to) , FunBind [Match noLoc funName [] Nothing rhs (BDecls [])] ] where funName = Ident $ relName r rhs = UnGuardedRhs $ Con (UnQual (Ident "Relation")) `App` (Lit $ String $ relName r) from = TyCon (UnQual (Ident (relFromName r))) to = TyCon (UnQual (Ident (relToName r))) createMethod :: QName -> [Relationship] -> Decl -> [Decl] createMethod dbClass rs d = [ TypeSig noLoc [funName] (TyForall Nothing ctx $ TyFun (typ d) (f (TyApp monad (TyApp refType (typ d))))) , FunBind [Match noLoc funName ((PVar (Ident "value")):(map (PVar . Ident . snd) relArgs)) Nothing (UnGuardedRhs (rhs relArgs) ) (BDecls [])] ] where ctx = [ClassA dbClass [monad]] monad = TyVar (Ident "db") funName = Ident $ "create" ++ datatypeName relArgs = zip rels (map relVarName [1..]) relVarName x = "x" ++ show x datatypeName = name d rels = involvedRelationships datatypeName rs f = relationshipsToFun rels rhs relArgs = Do $ concat [ [ Generator noLoc (PVar (Ident "i")) (App (var "create_") (var "value")) ] , concatMap relCreate relArgs , [ Qualifier $ App (var "return") (var "i") ] ] where relCreate :: (Relationship, String) -> [Stmt] relCreate (r,s) = [ addRelation r s ] addRelation r s | reversed r == False = Qualifier $ App (App (var "addRelation") (var "i")) (var s) | otherwise = Qualifier $ var "addRelation" `App` var s `App` var "i" `App` var (relName r) createSchema :: QName -> [Decl] -> [Relationship] -> [Decl] createSchema dbClass decls rels = [ TypeSig noLoc [funName] (TyForall Nothing ctx $ monad `TyApp` unit_tycon) , FunBind [Match noLoc funName [] Nothing (UnGuardedRhs (schemaRhs decls rels)) (BDecls []) ] ] where ctx = [ClassA dbClass [monad]] monad = TyVar (Ident "db") schemaRhs decls rels = Do (map entSchema decls ++ map relSchema rels) funName = Ident "createSchema" entSchema ent = Qualifier $ App (var "createSchemaEntity_") (ExpTypeSig noLoc (var "undefined") (TyCon (UnQual (Ident $ name ent)))) relSchema rel = Qualifier $ App (var "createSchemaRelationship_") (var $ relName rel) var :: String -> Exp var = Var . UnQual . Ident relationshipsToFun :: [Relationship] -> (Type -> Type) relationshipsToFun [] = id relationshipsToFun (x:xs) = TyFun (TyApp refType $ TyCon (UnQual (Ident (relToName x)))) . relationshipsToFun xs derivingRegular :: Decl -> [Decl] derivingRegular x = [ SpliceDecl noLoc $ SpliceExp $ ParenSplice $ var "deriveAll" `App` TypQuote typeName `App` (Lit $ String pfName) , TypeInsDecl noLoc (TyCon pFType `TyApp` TyCon typeName) (TyCon $ UnQual $ Ident pfName) ] where nm = name x pfName = "PF" ++ nm typeName = UnQual $ Ident nm involvedRelationships :: String -> [Relationship] -> [Relationship] involvedRelationships d = filter (\r -> relFromName r == d && isToOne r) typ :: Decl -> Type typ (DataDecl _ _ _ nm _ _ _) = TyCon (UnQual nm) typ _ = error "Compile.typ" pFType :: QName pFType = (UnQual (Ident "PF")) relType :: Type relType = TyCon (UnQual (Ident "Relation")) refType :: Type refType = TyCon (UnQual (Ident "Ref")) name :: Decl -> String name (DataDecl _ _ _ (Ident nm) _ _ _) = nm name s = error $ "Compile.name" ++ show s noLoc :: SrcLoc noLoc = SrcLoc "" 0 0
chriseidhof/persist
src/Data/Persist/Compile.hs
Haskell
bsd-3-clause
4,882
{-- snippet all --} import System.IO import System.Directory(getTemporaryDirectory, removeFile) import System.IO.Error(catch) import Control.Exception(finally) -- The main entry point. Work with a temp file in myAction. main :: IO () main = withTempFile "mytemp.txt" myAction {- The guts of the program. Called with the path and handle of a temporary file. When this function exits, that file will be closed and deleted because myAction was called from withTempFile. -} myAction :: FilePath -> Handle -> IO () myAction tempname temph = do -- Start by displaying a greeting on the terminal putStrLn "Welcome to tempfile.hs" putStrLn $ "I have a temporary file at " ++ tempname -- Let's see what the initial position is pos <- hTell temph putStrLn $ "My initial position is " ++ show pos -- Now, write some data to the temporary file let tempdata = show [1..10] putStrLn $ "Writing one line containing " ++ show (length tempdata) ++ " bytes: " ++ tempdata hPutStrLn temph tempdata -- Get our new position. This doesn't actually modify pos -- in memory, but makes the name "pos" correspond to a different -- value for the remainder of the "do" block. pos <- hTell temph putStrLn $ "After writing, my new position is " ++ show pos -- Seek to the beginning of the file and display it putStrLn $ "The file content is: " hSeek temph AbsoluteSeek 0 -- hGetContents performs a lazy read of the entire file c <- hGetContents temph -- Copy the file byte-for-byte to stdout, followed by \n putStrLn c -- Let's also display it as a Haskell literal putStrLn $ "Which could be expressed as this Haskell literal:" print c {- This function takes two parameters: a filename pattern and another function. It will create a temporary file, and pass the name and Handle of that file to the given function. The temporary file is created with openTempFile. The directory is the one indicated by getTemporaryDirectory, or, if the system has no notion of a temporary directory, "." is used. The given pattern is passed to openTempFile. After the given function terminates, even if it terminates due to an exception, the Handle is closed and the file is deleted. -} withTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a withTempFile pattern func = do -- The library ref says that getTemporaryDirectory may raise on -- exception on systems that have no notion of a temporary directory. -- So, we run getTemporaryDirectory under catch. catch takes -- two functions: one to run, and a different one to run if the -- first raised an exception. If getTemporaryDirectory raised an -- exception, just use "." (the current working directory). tempdir <- catch (getTemporaryDirectory) (\_ -> return ".") (tempfile, temph) <- openTempFile tempdir pattern -- Call (func tempfile temph) to perform the action on the temporary -- file. finally takes two actions. The first is the action to run. -- The second is an action to run after the first, regardless of -- whether the first action raised an exception. This way, we ensure -- the temporary file is always deleted. The return value from finally -- is the first action's return value. finally (func tempfile temph) (do hClose temph removeFile tempfile) {-- /snippet all --}
binesiyu/ifl
examples/ch07/tempfile.hs
Haskell
mit
3,603
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-SP"> <title>Import Urls | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/importurls/src/main/javahelp/org/zaproxy/zap/extension/importurls/resources/help_sr_SP/helpset_sr_SP.hs
Haskell
apache-2.0
972
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Export Report | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/exportreport/src/main/javahelp/org/zaproxy/zap/extension/exportreport/resources/help_ur_PK/helpset_ur_PK.hs
Haskell
apache-2.0
975
----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.EwmhDesktops -- Copyright : (c) 2007, 2008 Joachim Breitner <mail@joachim-breitner.de> -- License : BSD -- -- Maintainer : Joachim Breitner <mail@joachim-breitner.de> -- Stability : unstable -- Portability : unportable -- -- Makes xmonad use the EWMH hints to tell panel applications about its -- workspaces and the windows therein. It also allows the user to interact -- with xmonad by clicking on panels and window lists. ----------------------------------------------------------------------------- module XMonad.Hooks.EwmhDesktops ( -- * Usage -- $usage ewmh, ewmhDesktopsStartup, ewmhDesktopsLogHook, ewmhDesktopsLogHookCustom, ewmhDesktopsEventHook, ewmhDesktopsEventHookCustom, fullscreenEventHook ) where import Codec.Binary.UTF8.String (encode) import Data.List import Data.Maybe import Data.Monoid import XMonad import Control.Monad import qualified XMonad.StackSet as W import XMonad.Hooks.SetWMName import XMonad.Util.XUtils (fi) import XMonad.Util.WorkspaceCompare import XMonad.Util.WindowProperties (getProp32) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad -- > import XMonad.Hooks.EwmhDesktops -- > -- > main = xmonad $ ewmh def{ handleEventHook = -- > handleEventHook def <+> fullscreenEventHook } -- -- You may also be interested in 'avoidStruts' from "XMonad.Hooks.ManageDocks". -- | Add EWMH functionality to the given config. See above for an example. ewmh :: XConfig a -> XConfig a ewmh c = c { startupHook = startupHook c +++ ewmhDesktopsStartup , handleEventHook = handleEventHook c +++ ewmhDesktopsEventHook , logHook = logHook c +++ ewmhDesktopsLogHook } where x +++ y = mappend x y -- | -- Initializes EwmhDesktops and advertises EWMH support to the X -- server ewmhDesktopsStartup :: X () ewmhDesktopsStartup = setSupported -- | -- Notifies pagers and window lists, such as those in the gnome-panel -- of the current state of workspaces and windows. ewmhDesktopsLogHook :: X () ewmhDesktopsLogHook = ewmhDesktopsLogHookCustom id -- | -- Generalized version of ewmhDesktopsLogHook that allows an arbitrary -- user-specified function to transform the workspace list (post-sorting) ewmhDesktopsLogHookCustom :: ([WindowSpace] -> [WindowSpace]) -> X () ewmhDesktopsLogHookCustom f = withWindowSet $ \s -> do sort' <- getSortByIndex let ws = f $ sort' $ W.workspaces s -- Number of Workspaces setNumberOfDesktops (length ws) -- Names thereof setDesktopNames (map W.tag ws) -- all windows, with focused windows last let wins = nub . concatMap (maybe [] (\(W.Stack x l r)-> reverse l ++ r ++ [x]) . W.stack) $ ws setClientList wins -- Current desktop case (elemIndex (W.currentTag s) $ map W.tag ws) of Nothing -> return () Just curr -> do setCurrentDesktop curr -- Per window Desktop -- To make gnome-panel accept our xinerama stuff, we display -- all visible windows on the current desktop. forM_ (W.current s : W.visible s) $ \x -> forM_ (W.integrate' (W.stack (W.workspace x))) $ \win -> do setWindowDesktop win curr forM_ (W.hidden s) $ \w -> case elemIndex (W.tag w) (map W.tag ws) of Nothing -> return () Just wn -> forM_ (W.integrate' (W.stack w)) $ \win -> do setWindowDesktop win wn setActiveWindow return () -- | -- Intercepts messages from pagers and similar applications and reacts on them. -- Currently supports: -- -- * _NET_CURRENT_DESKTOP (switching desktops) -- -- * _NET_WM_DESKTOP (move windows to other desktops) -- -- * _NET_ACTIVE_WINDOW (activate another window, changing workspace if needed) ewmhDesktopsEventHook :: Event -> X All ewmhDesktopsEventHook = ewmhDesktopsEventHookCustom id -- | -- Generalized version of ewmhDesktopsEventHook that allows an arbitrary -- user-specified function to transform the workspace list (post-sorting) ewmhDesktopsEventHookCustom :: ([WindowSpace] -> [WindowSpace]) -> Event -> X All ewmhDesktopsEventHookCustom f e = handle f e >> return (All True) handle :: ([WindowSpace] -> [WindowSpace]) -> Event -> X () handle f (ClientMessageEvent { ev_window = w, ev_message_type = mt, ev_data = d }) = withWindowSet $ \s -> do sort' <- getSortByIndex let ws = f $ sort' $ W.workspaces s a_cd <- getAtom "_NET_CURRENT_DESKTOP" a_d <- getAtom "_NET_WM_DESKTOP" a_aw <- getAtom "_NET_ACTIVE_WINDOW" a_cw <- getAtom "_NET_CLOSE_WINDOW" a_ignore <- mapM getAtom ["XMONAD_TIMER"] if mt == a_cd then do let n = head d if 0 <= n && fi n < length ws then windows $ W.view (W.tag (ws !! fi n)) else trace $ "Bad _NET_CURRENT_DESKTOP with data[0]="++show n else if mt == a_d then do let n = head d if 0 <= n && fi n < length ws then windows $ W.shiftWin (W.tag (ws !! fi n)) w else trace $ "Bad _NET_DESKTOP with data[0]="++show n else if mt == a_aw then do windows $ W.focusWindow w else if mt == a_cw then do killWindow w else if mt `elem` a_ignore then do return () else do -- The Message is unknown to us, but that is ok, not all are meant -- to be handled by the window manager return () handle _ _ = return () -- | -- An event hook to handle applications that wish to fullscreen using the -- _NET_WM_STATE protocol. This includes users of the gtk_window_fullscreen() -- function, such as Totem, Evince and OpenOffice.org. -- -- Note this is not included in 'ewmh'. fullscreenEventHook :: Event -> X All fullscreenEventHook (ClientMessageEvent _ _ _ dpy win typ (action:dats)) = do wmstate <- getAtom "_NET_WM_STATE" fullsc <- getAtom "_NET_WM_STATE_FULLSCREEN" wstate <- fromMaybe [] `fmap` getProp32 wmstate win let isFull = fromIntegral fullsc `elem` wstate -- Constants for the _NET_WM_STATE protocol: remove = 0 add = 1 toggle = 2 ptype = 4 -- The atom property type for changeProperty chWstate f = io $ changeProperty32 dpy win wmstate ptype propModeReplace (f wstate) when (typ == wmstate && fi fullsc `elem` dats) $ do when (action == add || (action == toggle && not isFull)) $ do chWstate (fi fullsc:) windows $ W.float win $ W.RationalRect 0 0 1 1 when (action == remove || (action == toggle && isFull)) $ do chWstate $ delete (fi fullsc) windows $ W.sink win return $ All True fullscreenEventHook _ = return $ All True setNumberOfDesktops :: (Integral a) => a -> X () setNumberOfDesktops n = withDisplay $ \dpy -> do a <- getAtom "_NET_NUMBER_OF_DESKTOPS" c <- getAtom "CARDINAL" r <- asks theRoot io $ changeProperty32 dpy r a c propModeReplace [fromIntegral n] setCurrentDesktop :: (Integral a) => a -> X () setCurrentDesktop i = withDisplay $ \dpy -> do a <- getAtom "_NET_CURRENT_DESKTOP" c <- getAtom "CARDINAL" r <- asks theRoot io $ changeProperty32 dpy r a c propModeReplace [fromIntegral i] setDesktopNames :: [String] -> X () setDesktopNames names = withDisplay $ \dpy -> do -- Names thereof r <- asks theRoot a <- getAtom "_NET_DESKTOP_NAMES" c <- getAtom "UTF8_STRING" let names' = map fromIntegral $ concatMap ((++[0]) . encode) names io $ changeProperty8 dpy r a c propModeReplace names' setClientList :: [Window] -> X () setClientList wins = withDisplay $ \dpy -> do -- (What order do we really need? Something about age and stacking) r <- asks theRoot c <- getAtom "WINDOW" a <- getAtom "_NET_CLIENT_LIST" io $ changeProperty32 dpy r a c propModeReplace (fmap fromIntegral wins) a' <- getAtom "_NET_CLIENT_LIST_STACKING" io $ changeProperty32 dpy r a' c propModeReplace (fmap fromIntegral wins) setWindowDesktop :: (Integral a) => Window -> a -> X () setWindowDesktop win i = withDisplay $ \dpy -> do a <- getAtom "_NET_WM_DESKTOP" c <- getAtom "CARDINAL" io $ changeProperty32 dpy win a c propModeReplace [fromIntegral i] setSupported :: X () setSupported = withDisplay $ \dpy -> do r <- asks theRoot a <- getAtom "_NET_SUPPORTED" c <- getAtom "ATOM" supp <- mapM getAtom ["_NET_WM_STATE_HIDDEN" ,"_NET_NUMBER_OF_DESKTOPS" ,"_NET_CLIENT_LIST" ,"_NET_CLIENT_LIST_STACKING" ,"_NET_CURRENT_DESKTOP" ,"_NET_DESKTOP_NAMES" ,"_NET_ACTIVE_WINDOW" ,"_NET_WM_DESKTOP" ,"_NET_WM_STRUT" ] io $ changeProperty32 dpy r a c propModeReplace (fmap fromIntegral supp) setWMName "xmonad" setActiveWindow :: X () setActiveWindow = withWindowSet $ \s -> withDisplay $ \dpy -> do let w = fromMaybe none (W.peek s) r <- asks theRoot a <- getAtom "_NET_ACTIVE_WINDOW" c <- getAtom "WINDOW" io $ changeProperty32 dpy r a c propModeReplace [fromIntegral w]
eb-gh-cr/XMonadContrib1
XMonad/Hooks/EwmhDesktops.hs
Haskell
bsd-3-clause
9,444
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes (module PointTypes ,decodePTID ,fetchPointType ,pt0 ,pt1 ,pt2 ,pt3 ,pt4 ,pt5 ,pt6 ,pt7 ,pt8 ,pt9 ,pt10 ,pt12 ,pt13 ,pt14 ,pt15 ,pt16 ,pt17 ,pt18 ,pt19 ,pt20 ,pt21 ,pt40 ,pt41 ,pt42 ,pt43 ,pt44 ,pt45 ,pt46 ,pt47 ,pt48 ,pt52 ,pt53 ,pt54 ,pt55 ,pt56 ,pt57 ,pt58 ,pt59 ,pt80 ,pt81 ,pt85 ,pt86 ,pt88 ,pt89 ,pt93 ,pt94 ,pt98 ,pt117 ,pt118 ,pt120 ,pt121 ,pt122 ,pt172 ,pt173 ,pt174 ,pt175 ,pt176 ,pt177 ,PointTypes (..) ) where import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as C8 import Data.Word import Data.Binary.Get import Protocol.ROC.PointTypes.PointType0 as PointTypes import Protocol.ROC.PointTypes.PointType1 as PointTypes import Protocol.ROC.PointTypes.PointType2 as PointTYpes import Protocol.ROC.PointTypes.PointType3 as PointTYpes import Protocol.ROC.PointTypes.PointType4 as PointTYpes import Protocol.ROC.PointTypes.PointType5 as PointTypes import Protocol.ROC.PointTypes.PointType6 as PointTypes import Protocol.ROC.PointTypes.PointType7 as PointTypes import Protocol.ROC.PointTypes.PointType8 as PointTypes import Protocol.ROC.PointTypes.PointType9 as PointTypes import Protocol.ROC.PointTypes.PointType10 as PointTypes import Protocol.ROC.PointTypes.PointType12 as PointTYpes import Protocol.ROC.PointTypes.PointType13 as PointTYpes import Protocol.ROC.PointTypes.PointType14 as PointTypes import Protocol.ROC.PointTypes.PointType15 as PointTypes import Protocol.ROC.PointTypes.PointType16 as PointTypes import Protocol.ROC.PointTypes.PointType17 as PointTypes import Protocol.ROC.PointTypes.PointType18 as PointTypes import Protocol.ROC.PointTypes.PointType19 as PointTypes import Protocol.ROC.PointTypes.PointType20 as PointTYpes import Protocol.ROC.PointTypes.PointType21 as PointTYpes import Protocol.ROC.PointTypes.PointType40 as PointTYpes import Protocol.ROC.PointTypes.PointType41 as PointTypes import Protocol.ROC.PointTypes.PointType42 as PointTypes import Protocol.ROC.PointTypes.PointType43 as PointTypes import Protocol.ROC.PointTypes.PointType44 as PointTYpes import Protocol.ROC.PointTypes.PointType45 as PointTypes import Protocol.ROC.PointTypes.PointType46 as PointTypes import Protocol.ROC.PointTypes.PointType47 as PointTypes import Protocol.ROC.PointTypes.PointType48 as PointTYpes import Protocol.ROC.PointTypes.PointType52 as PointTypes import Protocol.ROC.PointTypes.PointType53 as PointTypes import Protocol.ROC.PointTypes.PointType54 as PointTypes import Protocol.ROC.PointTypes.PointType55 as PointTypes import Protocol.ROC.PointTypes.PointType56 as PointTypes import Protocol.ROC.PointTypes.PointType57 as PointTypes import Protocol.ROC.PointTypes.PointType58 as PointTypes import Protocol.ROC.PointTypes.PointType59 as PointTypes import Protocol.ROC.PointTypes.PointType80 as PointTypes import Protocol.ROC.PointTypes.PointType81 as PointTYpes import Protocol.ROC.PointTypes.PointType85 as PointTypes import Protocol.ROC.PointTypes.PointType86 as PointTypes import Protocol.ROC.PointTypes.PointType88 as PointTypes import Protocol.ROC.PointTypes.PointType89 as PointTypes import Protocol.ROC.PointTypes.PointType93 as PointTypes import Protocol.ROC.PointTypes.PointType94 as PointTypes import Protocol.ROC.PointTypes.PointType98 as PointTypes import Protocol.ROC.PointTypes.PointType117 as PointTypes import Protocol.ROC.PointTypes.PointType118 as PointTypes import Protocol.ROC.PointTypes.PointType120 as PointTypes import Protocol.ROC.PointTypes.PointType121 as PointTypes import Protocol.ROC.PointTypes.PointType122 as PointTypes import Protocol.ROC.PointTypes.PointType172 as PointTypes import Protocol.ROC.PointTypes.PointType173 as PointTypes import Protocol.ROC.PointTypes.PointType174 as PointTypes import Protocol.ROC.PointTypes.PointType175 as PointTypes import Protocol.ROC.PointTypes.PointType176 as PointTypes import Protocol.ROC.PointTypes.PointType177 as PointTypes data PointTypes a = PTID0 (Either a PointType0) | PTID1 (Either a PointType1) | PTID2 (Either a PointType2) | PTID3 (Either a PointType3) | PTID4 (Either a PointType4) | PTID5 (Either a PointType5) | PTID6 (Either a PointType6) | PTID7 (Either a PointType7) | PTID8 (Either a PointType8) | PTID9 (Either a PointType9) | PTID10 (Either a PointType10) | PTID12 (Either a PointType12) | PTID13 (Either a PointType13) | PTID14 (Either a PointType14) | PTID15 (Either a PointType15) | PTID16 (Either a PointType16) | PTID17 (Either a PointType17) | PTID18 (Either a PointType18) | PTID19 (Either a PointType19) | PTID20 (Either a PointType20) | PTID21 (Either a PointType21) | PTID40 (Either a PointType40) | PTID41 (Either a PointType41) | PTID42 (Either a PointType42) | PTID43 (Either a PointType43) | PTID44 (Either a PointType44) | PTID45 (Either a PointType45) | PTID46 (Either a PointType46) | PTID47 (Either a PointType47) | PTID48 (Either a PointType48) | PTID52 (Either a PointType52) | PTID53 (Either a PointType53) | PTID54 (Either a PointType54) | PTID55 (Either a PointType55) | PTID56 (Either a PointType56) | PTID57 (Either a PointType57) | PTID58 (Either a PointType58) | PTID59 (Either a PointType59) | PTID80 (Either a PointType80) | PTID81 (Either a PointType81) | PTID85 (Either a PointType85) | PTID86 (Either a PointType86) | PTID88 (Either a PointType88) | PTID89 (Either a PointType89) | PTID93 (Either a PointType93) | PTID94 (Either a PointType94) | PTID98 (Either a PointType98) | PTID117 (Either a PointType117) | PTID118 (Either a PointType118) | PTID120 (Either a PointType120) | PTID121 (Either a PointType121) | PTID122 (Either a PointType122) | PTID172 (Either a PointType172) | PTID173 (Either a PointType173) | PTID174 (Either a PointType174) | PTID175 (Either a PointType175) | PTID176 (Either a PointType176) | PTID177 (Either a PointType177) deriving (Eq,Show) pt0 :: PointTypes () pt0 = PTID0 $ Left () pt1 :: PointTypes () pt1 = PTID1 $ Left () pt2 :: PointTypes () pt2 = PTID2 $ Left () pt3 :: PointTypes () pt3 = PTID3 $ Left () pt4 :: PointTypes () pt4 = PTID4 $ Left () pt5 :: PointTypes () pt5 = PTID5 $ Left () pt6 :: PointTypes () pt6 = PTID6 $ Left () pt7 :: PointTypes () pt7 = PTID7 $ Left () pt8 :: PointTypes () pt8 = PTID8 $ Left () pt9 :: PointTypes () pt9 = PTID9 $ Left () pt10 :: PointTypes () pt10 = PTID10 $ Left () pt12 :: PointTypes () pt12 = PTID12 $ Left () pt13 :: PointTypes () pt13 = PTID13 $ Left () pt14 :: PointTypes () pt14 = PTID14 $ Left () pt15 :: PointTypes () pt15 = PTID15 $ Left () pt16 :: PointTypes () pt16 = PTID16 $ Left () pt17 :: PointTypes () pt17 = PTID17 $ Left () pt18 :: PointTypes () pt18 = PTID18 $ Left () pt19 :: PointTypes () pt19 = PTID19 $ Left () pt20 :: PointTypes () pt20 = PTID20 $ Left () pt21 :: PointTypes () pt21 = PTID21 $ Left () pt40 :: PointTypes () pt40 = PTID40 $ Left () pt41 :: PointTypes () pt41 = PTID41 $ Left () pt42 :: PointTypes () pt42 = PTID42 $ Left () pt43 :: PointTypes () pt43 = PTID43 $ Left () pt44 :: PointTypes () pt44 = PTID44 $ Left () pt45 :: PointTypes () pt45 = PTID45 $ Left () pt46 :: PointTypes () pt46 = PTID46 $ Left () pt47 :: PointTypes () pt47 = PTID47 $ Left () pt48 :: PointTypes () pt48 = PTID48 $ Left () pt52 :: PointTypes () pt52 = PTID52 $ Left () pt53 :: PointTypes () pt53 = PTID53 $ Left () pt54 :: PointTypes () pt54 = PTID54 $ Left () pt55 :: PointTypes () pt55 = PTID55 $ Left () pt56 :: PointTypes () pt56 = PTID56 $ Left () pt57 :: PointTypes () pt57 = PTID57 $ Left () pt58 :: PointTypes () pt58 = PTID58 $ Left () pt59 :: PointTypes () pt59 = PTID59 $ Left () pt80 :: PointTypes () pt80 = PTID80 $ Left () pt81 :: PointTypes () pt81 = PTID81 $ Left () pt85 :: PointTypes () pt85 = PTID85 $ Left () pt86 :: PointTypes () pt86 = PTID86 $ Left () pt88 :: PointTypes () pt88 = PTID88 $ Left () pt89 :: PointTypes () pt89 = PTID89 $ Left () pt93 :: PointTypes () pt93 = PTID93 $ Left () pt94 :: PointTypes () pt94 = PTID94 $ Left () pt98 :: PointTypes () pt98 = PTID98 $ Left () pt117 :: PointTypes () pt117 = PTID117 $ Left () pt118 :: PointTypes () pt118 = PTID118 $ Left () pt120 :: PointTypes () pt120 = PTID120 $ Left () pt121 :: PointTypes () pt121 = PTID121 $ Left () pt122 :: PointTypes () pt122 = PTID122 $ Left () pt172 :: PointTypes () pt172 = PTID172 $ Left () pt173 :: PointTypes () pt173 = PTID173 $ Left () pt174 :: PointTypes () pt174 = PTID174 $ Left () pt175 :: PointTypes () pt175 = PTID175 $ Left () pt176 :: PointTypes () pt176 = PTID176 $ Left () pt177 :: PointTypes () pt177 = PTID177 $ Left () decodePTID :: PointTypes a -> Word8 decodePTID (PTID0 _) = 0 decodePTID (PTID1 _) = 1 decodePTID (PTID2 _) = 2 decodePTID (PTID3 _) = 3 decodePTID (PTID4 _) = 4 decodePTID (PTID5 _) = 5 decodePTID (PTID6 _) = 6 decodePTID (PTID7 _) = 7 decodePTID (PTID8 _) = 8 decodePTID (PTID9 _) = 9 decodePTID (PTID10 _) = 10 decodePTID (PTID12 _) = 12 decodePTID (PTID13 _) = 13 decodePTID (PTID14 _) = 14 decodePTID (PTID15 _) = 15 decodePTID (PTID16 _) = 16 decodePTID (PTID17 _) = 17 decodePTID (PTID18 _) = 18 decodePTID (PTID19 _) = 19 decodePTID (PTID20 _) = 20 decodePTID (PTID21 _) = 21 decodePTID (PTID40 _) = 40 decodePTID (PTID41 _) = 41 decodePTID (PTID42 _) = 42 decodePTID (PTID43 _) = 43 decodePTID (PTID44 _) = 44 decodePTID (PTID45 _) = 45 decodePTID (PTID46 _) = 46 decodePTID (PTID47 _) = 47 decodePTID (PTID48 _) = 48 decodePTID (PTID52 _) = 52 decodePTID (PTID53 _) = 53 decodePTID (PTID54 _) = 54 decodePTID (PTID55 _) = 55 decodePTID (PTID56 _) = 56 decodePTID (PTID57 _) = 57 decodePTID (PTID58 _) = 58 decodePTID (PTID59 _) = 59 decodePTID (PTID80 _) = 80 decodePTID (PTID81 _) = 81 decodePTID (PTID85 _) = 85 decodePTID (PTID86 _) = 86 decodePTID (PTID88 _) = 88 decodePTID (PTID89 _) = 89 decodePTID (PTID93 _) = 93 decodePTID (PTID94 _) = 94 decodePTID (PTID98 _) = 98 decodePTID (PTID117 _) = 117 decodePTID (PTID118 _) = 118 decodePTID (PTID120 _) = 120 decodePTID (PTID121 _) = 121 decodePTID (PTID122 _) = 122 decodePTID (PTID172 _) = 172 decodePTID (PTID173 _) = 173 decodePTID (PTID174 _) = 174 decodePTID (PTID175 _) = 175 decodePTID (PTID176 _) = 176 decodePTID (PTID177 _) = 177 ----------------------------------------------------------------------------------- --data PointTypeTest = PointTypeTest { --pointTypeTestLowRead :: !PointTypeTestLowRead --} --type PointTypeTestLowRead = Float --pointTypeTestParser :: Get PointTypeTestLowRead --pointTypeTestParser = get --fetchPointTypeTest :: LB.ByteString -> Decoder PointTypeTestLowRead --fetchPointTypeTest bs = runGetIncremental pointTypeTestParser `pushChunks` bs ------------------------------------------------------------------------------------ fetchPointType :: PointTypes a -> LB.ByteString -> PointTypes LB.ByteString fetchPointType (PTID0 _ ) bs = PTID0 $ decodeToEither $ runGetIncremental pointType0Parser `pushChunks` bs fetchPointType (PTID1 _ ) bs = PTID1 $ decodeToEither $ runGetIncremental pointType1Parser `pushChunks` bs fetchPointType (PTID2 _ ) bs = PTID2 $ decodeToEither $ runGetIncremental pointType2Parser `pushChunks` bs fetchPointType (PTID3 _ ) bs = PTID3 $ decodeToEither $ runGetIncremental pointType3Parser `pushChunks` bs fetchPointType (PTID4 _ ) bs = PTID4 $ decodeToEither $ runGetIncremental pointType4Parser `pushChunks` bs fetchPointType (PTID5 _ ) bs = PTID5 $ decodeToEither $ runGetIncremental pointType5Parser `pushChunks` bs fetchPointType (PTID6 _ ) bs = PTID6 $ decodeToEither $ runGetIncremental pointType6Parser `pushChunks` bs fetchPointType (PTID7 _ ) bs = PTID7 $ decodeToEither $ runGetIncremental pointType7Parser `pushChunks` bs fetchPointType (PTID8 _ ) bs = PTID8 $ decodeToEither $ runGetIncremental pointType8Parser `pushChunks` bs fetchPointType (PTID9 _ ) bs = PTID9 $ decodeToEither $ runGetIncremental pointType9Parser `pushChunks` bs fetchPointType (PTID10 _ ) bs = PTID10 $ decodeToEither $ runGetIncremental pointType10Parser `pushChunks` bs fetchPointType (PTID12 _ ) bs = PTID12 $ decodeToEither $ runGetIncremental pointType12Parser `pushChunks` bs fetchPointType (PTID13 _ ) bs = PTID13 $ decodeToEither $ runGetIncremental pointType13Parser `pushChunks` bs fetchPointType (PTID14 _ ) bs = PTID14 $ decodeToEither $ runGetIncremental pointType14Parser `pushChunks` bs fetchPointType (PTID15 _ ) bs = PTID15 $ decodeToEither $ runGetIncremental pointType15Parser `pushChunks` bs fetchPointType (PTID16 _ ) bs = PTID16 $ decodeToEither $ runGetIncremental pointType16Parser `pushChunks` bs fetchPointType (PTID17 _ ) bs = PTID17 $ decodeToEither $ runGetIncremental pointType17Parser `pushChunks` bs fetchPointType (PTID18 _ ) bs = PTID18 $ decodeToEither $ runGetIncremental pointType18Parser `pushChunks` bs fetchPointType (PTID19 _ ) bs = PTID19 $ decodeToEither $ runGetIncremental pointType19Parser `pushChunks` bs fetchPointType (PTID20 _ ) bs = PTID20 $ decodeToEither $ runGetIncremental pointType20Parser `pushChunks` bs fetchPointType (PTID21 _ ) bs = PTID21 $ decodeToEither $ runGetIncremental pointType21Parser `pushChunks` bs fetchPointType (PTID40 _ ) bs = PTID40 $ decodeToEither $ runGetIncremental pointType40Parser `pushChunks` bs fetchPointType (PTID41 _ ) bs = PTID41 $ decodeToEither $ runGetIncremental pointType41Parser `pushChunks` bs fetchPointType (PTID42 _ ) bs = PTID42 $ decodeToEither $ runGetIncremental pointType42Parser `pushChunks` bs fetchPointType (PTID43 _ ) bs = PTID43 $ decodeToEither $ runGetIncremental pointType43Parser `pushChunks` bs fetchPointType (PTID44 _ ) bs = PTID44 $ decodeToEither $ runGetIncremental pointType44Parser `pushChunks` bs fetchPointType (PTID45 _ ) bs = PTID45 $ decodeToEither $ runGetIncremental pointType45Parser `pushChunks` bs fetchPointType (PTID46 _ ) bs = PTID46 $ decodeToEither $ runGetIncremental pointType46Parser `pushChunks` bs fetchPointType (PTID47 _ ) bs = PTID47 $ decodeToEither $ runGetIncremental pointType47Parser `pushChunks` bs fetchPointType (PTID48 _ ) bs = PTID48 $ decodeToEither $ runGetIncremental pointType48Parser `pushChunks` bs fetchPointType (PTID52 _ ) bs = PTID52 $ decodeToEither $ runGetIncremental pointType52Parser `pushChunks` bs fetchPointType (PTID53 _ ) bs = PTID53 $ decodeToEither $ runGetIncremental pointType53Parser `pushChunks` bs fetchPointType (PTID54 _ ) bs = PTID54 $ decodeToEither $ runGetIncremental pointType54Parser `pushChunks` bs fetchPointType (PTID55 _ ) bs = PTID55 $ decodeToEither $ runGetIncremental pointType55Parser `pushChunks` bs fetchPointType (PTID56 _ ) bs = PTID56 $ decodeToEither $ runGetIncremental pointType56Parser `pushChunks` bs fetchPointType (PTID57 _ ) bs = PTID57 $ decodeToEither $ runGetIncremental pointType57Parser `pushChunks` bs fetchPointType (PTID58 _ ) bs = PTID58 $ decodeToEither $ runGetIncremental pointType58Parser `pushChunks` bs fetchPointType (PTID59 _ ) bs = PTID59 $ decodeToEither $ runGetIncremental pointType59Parser `pushChunks` bs fetchPointType (PTID80 _ ) bs = PTID80 $ decodeToEither $ runGetIncremental pointType80Parser `pushChunks` bs fetchPointType (PTID81 _ ) bs = PTID81 $ decodeToEither $ runGetIncremental pointType81Parser `pushChunks` bs fetchPointType (PTID85 _ ) bs = PTID85 $ decodeToEither $ runGetIncremental pointType85Parser `pushChunks` bs fetchPointType (PTID86 _ ) bs = PTID86 $ decodeToEither $ runGetIncremental pointType86Parser `pushChunks` bs fetchPointType (PTID88 _ ) bs = PTID88 $ decodeToEither $ runGetIncremental pointType88Parser `pushChunks` bs fetchPointType (PTID89 _ ) bs = PTID89 $ decodeToEither $ runGetIncremental pointType89Parser `pushChunks` bs fetchPointType (PTID93 _ ) bs = PTID93 $ decodeToEither $ runGetIncremental pointType93Parser `pushChunks` bs fetchPointType (PTID94 _ ) bs = PTID94 $ decodeToEither $ runGetIncremental pointType94Parser `pushChunks` bs fetchPointType (PTID98 _ ) bs = PTID98 $ decodeToEither $ runGetIncremental pointType98Parser `pushChunks` bs fetchPointType (PTID117 _ ) bs = PTID117 $ decodeToEither $ runGetIncremental pointType117Parser `pushChunks` bs fetchPointType (PTID118 _ ) bs = PTID118 $ decodeToEither $ runGetIncremental pointType118Parser `pushChunks` bs fetchPointType (PTID120 _ ) bs = PTID120 $ decodeToEither $ runGetIncremental pointType120Parser `pushChunks` bs fetchPointType (PTID121 _ ) bs = PTID121 $ decodeToEither $ runGetIncremental pointType121Parser `pushChunks` bs fetchPointType (PTID122 _ ) bs = PTID122 $ decodeToEither $ runGetIncremental pointType122Parser `pushChunks` bs fetchPointType (PTID172 _ ) bs = PTID172 $ decodeToEither $ runGetIncremental pointType172Parser `pushChunks` bs fetchPointType (PTID173 _ ) bs = PTID173 $ decodeToEither $ runGetIncremental pointType173Parser `pushChunks` bs fetchPointType (PTID174 _ ) bs = PTID174 $ decodeToEither $ runGetIncremental pointType174Parser `pushChunks` bs fetchPointType (PTID175 _ ) bs = PTID175 $ decodeToEither $ runGetIncremental pointType175Parser `pushChunks` bs fetchPointType (PTID176 _ ) bs = PTID176 $ decodeToEither $ runGetIncremental pointType176Parser `pushChunks` bs fetchPointType (PTID177 _ ) bs = PTID177 $ decodeToEither $ runGetIncremental pointType177Parser `pushChunks` bs decodeToEither :: (Show a) => Decoder a -> Either LB.ByteString a decodeToEither (Fail _ _ s) = Left $ C8.append "decoder Failed with" (C8.pack s) decodeToEither (Done _ _ a) = Right a decodeToEither _ = Left "incomplete parsing SHOULD NOT HAPPEN!" --debugDecoderPointType :: (Show a) => Decoder a -> IO () --debugDecoderPointType (Fail _ _ s) = print $ "decoder Failed with" ++ s --debugDecoderPointType (Done _ _ pt) = print "Point type finished" >> print pt --debugDecoderPointType _ = print "incomplete parsing SHOULD NOT HAPPEN!"
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes.hs
Haskell
bsd-3-clause
21,145
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} module Modal.Code where import Prelude hiding (readFile, sequence, mapM, foldr1, concat, concatMap) import Control.Applicative import Control.Monad.Except hiding (mapM, sequence) import Control.Monad.State hiding (mapM, sequence, state) import Data.Map (Map) import Data.Maybe (mapMaybe, maybeToList) import Data.Monoid ((<>)) import Data.Foldable import Data.Traversable import Modal.CompilerBase hiding (main) import Modal.Display import Modal.Formulas (ModalFormula, (%^), (%|)) import Modal.Parser hiding (main) import Modal.Programming import Modal.Statement hiding (main) import Modal.Utilities import Text.Parsec hiding ((<|>), optional, many, State) import Text.Parsec.Expr import Text.Parsec.Text (Parser) import Text.Printf (printf) import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Text as Text import qualified Modal.Formulas as F ------------------------------------------------------------------------------- data CodeConfig = CodeConfig { actionKw :: String , actionsKw :: String , outcomeKw :: String , outcomesKw :: String } deriving (Eq, Ord, Read, Show) ------------------------------------------------------------------------------- data SimpleExpr = Num (Ref Int) | Add SimpleExpr SimpleExpr | Sub SimpleExpr SimpleExpr | Mul SimpleExpr SimpleExpr | Exp SimpleExpr SimpleExpr deriving Eq instance Show SimpleExpr where show (Num v) = show v show (Add x y) = show x ++ "+" ++ show y show (Sub x y) = show x ++ "-" ++ show y show (Mul x y) = show x ++ "*" ++ show y show (Exp x y) = show x ++ "^" ++ show y instance Parsable SimpleExpr where parser = buildExpressionParser lTable term where lTable = [ [Infix (try $ symbol "+" $> Add) AssocRight] , [Infix (try $ symbol "-" $> Sub) AssocRight] , [Infix (try $ symbol "*" $> Mul) AssocRight] , [Infix (try $ symbol "^" $> Exp) AssocRight] ] term = parens parser <|> try (Num <$> (parser :: Parser (Ref Int))) <?> "a math expression" compileExpr :: MonadCompile m => SimpleExpr -> m Int compileExpr (Num v) = lookupN v compileExpr (Add x y) = (+) <$> compileExpr x <*> compileExpr y compileExpr (Sub x y) = (-) <$> compileExpr x <*> compileExpr y compileExpr (Mul x y) = (*) <$> compileExpr x <*> compileExpr y compileExpr (Exp x y) = (^) <$> compileExpr x <*> compileExpr y ------------------------------------------------------------------------------- data Range x = EnumRange (Ref x) (Maybe (Ref x)) (Maybe (Ref Int)) | ListRange [Ref x] | TotalRange deriving Eq instance Show x => Show (Range x) where show (EnumRange sta msto mste) = printf "%s..%s%s" (show sta) x y where x = maybe ("" :: String) show msto y = maybe ("" :: String) (printf " by %s" . show) mste show (ListRange xs) = printf "[%s]" (List.intercalate ", " $ map show xs) show TotalRange = "[...]" instance Parsable x => Parsable (Range x) where parser = rangeParser "[...]" parser rangeParser :: String -> Parser x -> Parser (Range x) rangeParser allname x = try rEnum <|> try rList <|> try rAll <?> "a range" where rEnum = EnumRange <$> (symbol "[" *> refParser x <* symbol "..") <*> (optional (refParser x) <* symbol "]") <*> optional (try $ keyword "by" *> parser) rList = ListRange <$> listParser (refParser x) rAll = keyword allname $> TotalRange _testRangeParser :: IO () _testRangeParser = do let succeeds = verifyParser (parser :: Parser (Range Int)) let fails = verifyParserFails (parser :: Parser (Range Int)) succeeds "[1..]" (EnumRange (Lit 1) Nothing Nothing) succeeds "[ 1 ..]" (EnumRange (Lit 1) Nothing Nothing) succeeds "[ 1 .. 2 ]" (EnumRange (Lit 1) (Just (Lit 2)) Nothing) succeeds "[&n..]" (EnumRange (Ref "n") Nothing Nothing) succeeds "[&n..3]" (EnumRange (Ref "n") (Just (Lit 3)) Nothing) succeeds "[&n..3] by 2" (EnumRange (Ref "n") (Just (Lit 3)) (Just (Lit 2))) fails "[1..2..3]" succeeds "[1, 2, &three]" (ListRange [Lit 1, Lit 2, Ref "three"]) succeeds "[...]" TotalRange succeeds "[ ]" (ListRange []) fails "[ " boundedRange :: Parsable x => Parser (Range x) boundedRange = try rBoundedEnum <|> try rList <?> "a bounded range" where rBoundedEnum = EnumRange <$> (symbol "[" *> parser <* symbol "..") <*> (Just <$> parser <* symbol "]") <*> optional (try $ keyword "by" *> parser) rList = ListRange <$> parser _testBoundedRangeParser :: IO () _testBoundedRangeParser = do let succeeds = verifyParser (boundedRange :: Parser (Range Int)) let fails = verifyParserFails (boundedRange :: Parser (Range Int)) fails "[1..]" succeeds "[1 .. 2]" (EnumRange (Lit 1) (Just (Lit 2)) Nothing) succeeds "[&n .. 2] by 10" (EnumRange (Ref "n") (Just (Lit 2)) (Just (Lit 10))) succeeds "[1, 2, &three]" (ListRange [Lit 1, Lit 2, Ref "three"]) fails "[...]" rangeLitValues :: Range x -> [x] rangeLitValues (EnumRange sta sto _) = maybeToList (lit sta) ++ maybe [] (maybeToList . lit) sto rangeLitValues (ListRange refs) = mapMaybe lit refs rangeLitValues _ = [] compileRange :: (Eq x, MonadCompile m) => m [x] -> (Ref x -> m x) -> Range x -> m [x] compileRange getXs _ TotalRange = getXs compileRange _ getX (ListRange xs) = mapM getX xs compileRange getXs getX (EnumRange sta msto mste) = renum msto mste where renum Nothing Nothing = dropWhile . (/=) <$> getX sta <*> getXs renum (Just sto) Nothing = takeWhile . (/=) <$> getX sto <*> renum Nothing Nothing renum _ (Just ste) = every <$> lookupN ste <*> renum msto Nothing ------------------------------------------------------------------------------- data CodeFragment = For ClaimType Name (Range Value) [CodeFragment] | ForN Name (Range Int) [CodeFragment] | LetN Name SimpleExpr | If Statement [CodeFragment] | IfElse Statement [CodeFragment] [CodeFragment] | Return (Maybe (Ref Value)) | Pass deriving Eq instance Blockable CodeFragment where blockLines (For t n r cs) = [(0, Text.pack $ printf "for %s %s in %s" (show t) n (show r))] <> increaseIndent (concatMap blockLines cs) blockLines (ForN n r cs) = [(0, Text.pack $ printf "for number %s in %s" n (show r))] <> increaseIndent (concatMap blockLines cs) blockLines (LetN n x) = [(0, Text.pack $ printf "let %s = %s" n (show x))] blockLines (If s xs) = [(0, Text.pack $ printf "if %s" $ show s)] <> increaseIndent (concatMap blockLines xs) blockLines (IfElse s xs ys) = [(0, Text.pack $ printf "if %s" $ show s)] <> increaseIndent (concatMap blockLines xs) <> [(0, "else")] <> increaseIndent (concatMap blockLines ys) blockLines (Return Nothing) = [(0, "return")] blockLines (Return (Just x)) = [(0, Text.pack $ printf "return %s" (show x))] blockLines (Pass) = [(0, "pass")] instance Show CodeFragment where show = Text.unpack . renderBlock data CodeFragConfig = CodeFragConfig { indentLevel :: Int , codeConfig :: CodeConfig } deriving (Eq, Ord, Read, Show) eatIndent :: CodeFragConfig -> Parser () eatIndent conf = void (count (indentLevel conf) (char '\t')) <?> printf "%d tabs" (indentLevel conf) codeFragmentParser :: CodeFragConfig -> Parser CodeFragment codeFragmentParser conf = try indent *> pFrag where indent = (many $ try ignoredLine) *> eatIndent conf pFrag = try pForA <|> try pForO <|> try pForN <|> try pLetN <|> try pIfElse <|> try pIf <|> try pReturn <|> try pPass pForA = pFor ActionT action actions pForO = pFor OutcomeT outcome outcomes pFor t x xs = For t <$> (keyword "for" *> keyword x *> varname) <*> (keyword "in" *> rangeParser xs parser <* w <* endOfLine) <*> pBlock pForN = ForN <$> (keyword "for" *> keyword "number" *> varname) <*> (keyword "in" *> boundedRange <* w <* endOfLine) <*> pBlock pLetN = LetN <$> (keyword "let" *> varname <* symbol "=") <*> parser <* eols pIf = If <$> (keyword "if" *> parser <* w <* endOfLine) <*> pBlock pIfElse = IfElse <$> (keyword "if" *> parser <* w <* endOfLine) <*> pBlock <*> (indent *> keyword "else" *> w *> endOfLine *> pBlock) pBlock = many1 $ try $ codeFragmentParser conf{indentLevel=succ $ indentLevel conf} pPass = symbol "pass" $> Pass <* w <* eol pReturn = try returnThing <|> returnNothing <?> "a return statement" returnNothing :: Parser CodeFragment returnThing = symbol "return " *> (Return . Just <$> parser) <* w <* eol returnNothing = symbol "return" $> Return Nothing <* w <* eol action = actionKw $ codeConfig conf outcome = outcomeKw $ codeConfig conf actions = actionsKw $ codeConfig conf outcomes = outcomesKw $ codeConfig conf varname = char '&' *> name compileCodeFragment :: MonadCompile m => CodeFragment -> m (PartialProgram Value CompiledClaim) compileCodeFragment code = case code of For ActionT n r x -> loop (withA n) x =<< compileRange (gets actionList) lookupA r For OutcomeT n r x -> loop (withO n) x =<< compileRange (gets outcomeList) lookupO r ForN n r x -> loop (withN n) x =<< compileRange (return [0..]) lookupN r LetN n x -> compileExpr x >>= modify . withN n >> return id If s block -> compileCodeFragment (IfElse s block [Pass]) IfElse s tblock eblock -> do cond <- compileStatement compileClaim s thens <- mapM compileCodeFragment tblock elses <- mapM compileCodeFragment eblock let yes = foldr1 (.) thens let no = foldr1 (.) elses return (\continue act -> (cond %^ yes continue act) %| (F.Neg cond %^ no continue act)) Return (Just v) -> (\a -> const $ F.Val . (a ==)) <$> lookupA v Return Nothing -> (\a -> const $ F.Val . (a ==)) <$> defaultAction Pass -> return id where loop update block xs | null xs = return id | otherwise = foldr1 (.) . concat <$> mapM doFragment xs where doFragment x = modify (update x) >> mapM compileCodeFragment block ------------------------------------------------------------------------------- data Code = Code [CodeFragment] | ActionMap (Map Value Statement) deriving Eq instance Blockable Code where blockLines (Code frags) = concatMap blockLines frags blockLines (ActionMap a2s) = [ (0, Text.pack $ printf "%s ↔ %s" (show a) (show s)) | (a, s) <- Map.toList a2s] instance Show Code where show = Text.unpack . renderBlock codeParser :: CodeConfig -> Parser Code codeParser conf = Code <$> many1 (codeFragmentParser $ CodeFragConfig 1 conf) _testCodeParser :: IO () _testCodeParser = testAllSamples where sample1 = Text.unlines ["\tlet &step = 0" ,"\tfor action &a in actions" ,"\t\t-- This is a comment about the inner loop." ,"\t\tfor outcome &u in utilities" ,"\t\t\tif [&step][A()=&a -> U()=&u]" ,"\t\t\t\treturn &a" ,"\t\t\tlet &step = &step + 1" ,"\treturn"] sample2 = Text.unlines ["\tif {- IGNORE THIS COMMENT -} [][Them(Me)=C]" ,"\t\treturn C -- Ignore this one too." ,"" ,"\telse" ,"\t\treturn D"] sample3 = Text.unlines [" -- Sample 3:" ,"\tfor number &n in [0, 1, 2, 3]" ,"\t\tif Possible(&n)[Them(Me)=C]" ,"\t\t\treturn C" ," \t " ,"" ,"\treturn D"] sample4 = Text.unlines ["\tfor number &n in [...]" ,"\t\treturn &n"] sample5 = Text.unlines ["\tif ⊤" ,"\treturn 0"] sample6 = Text.unlines ["\tif ⊤" ,"\t return 0"] sample7 = Text.unlines ["\tif ⊤" ,"\t\t\treturn 0"] conf = CodeConfig "action" "actions" "outcome" "utilities" testAllSamples = do verifyParser (codeParser conf) sample1 (Code [ LetN "step" (Num (Lit 0)) , For ActionT "a" TotalRange [ For OutcomeT "u" TotalRange [ If (Provable (Ref "step") (Imp (Var $ ParsedClaim "A" Nothing (Equals (Ref "a"))) (Var $ ParsedClaim "U" Nothing (Equals (Ref "u"))))) [ Return (Just (Ref "a")) ] , LetN "step" (Add (Num $ Ref "step") (Num $ Lit 1)) ] ] , Return Nothing ]) verifyParser (codeParser conf) sample2 (Code [ IfElse (Provable (Lit 0) (Var $ ParsedClaim "Them" (Just $ Call "Me" [] Map.empty [] []) (Equals $ Lit "C"))) [ Return (Just (Lit "C")) ] [ Return (Just (Lit "D")) ] ]) verifyParser (codeParser conf) sample3 (Code [ ForN "n" (ListRange [Lit 0, Lit 1, Lit 2, Lit 3]) [ If (Possible (Ref "n") (Var $ ParsedClaim "Them" (Just $ Call "Me" [] Map.empty [] []) (Equals $ Lit "C"))) [ Return (Just (Lit "C")) ] ] , Return (Just (Lit "D")) ]) verifyParserFails (codeParser conf) sample4 verifyParserFails (codeParser conf) sample5 verifyParserFails (codeParser conf) sample6 verifyParserFails (codeParser conf) sample7 codeMapParser :: Parser Code codeMapParser = ActionMap . Map.fromList <$> many1 assignment where indent = (many (w *> endOfLine)) *> char '\t' iffParsers = [symbol "↔", symbol "<->", keyword "iff"] pIff = void $ choice $ map try iffParsers assignment = (,) <$> (indent *> parser <* pIff) <*> (parser <* eols) _testCodeMapParser :: IO () _testCodeMapParser = testAllSamples where sample1 = Text.unlines ["\tC ↔ [][Them(Me)=C]" ,"\tD ↔ ~[][Them(Me)=C]"] sample2 = Text.unlines ["\tCD iff A1()=C and A2()=D" ,"\tCC iff A1()=C and A2()=C" ,"\tDD iff A1()=D and A2()=D" ,"\tDC iff A1()=D and A2()=C"] sample3 = Text.unlines ["\tC ↔ [][Them(Me)=C]" ,"\t\tD ↔ ~[][Them(Me)=C]"] sample4 = Text.unlines ["\tC ↔ [][Them(Me)=C]" ," D ↔ ~[][Them(Me)=C]"] testAllSamples = do verifyParser codeMapParser sample1 (ActionMap $ Map.fromList [ ("C", Provable (Lit 0) (Var $ ParsedClaim "Them" (Just $ Call "Me" [] Map.empty [] []) (Equals $ Lit "C"))) , ("D", Neg $ Provable (Lit 0) (Var $ ParsedClaim "Them" (Just $ Call "Me" [] Map.empty [] []) (Equals $ Lit "C"))) ]) verifyParser codeMapParser sample2 (ActionMap $ Map.fromList [ ("CD", (And (Var $ ParsedClaim "A1" Nothing (Equals $ Lit "C")) (Var $ ParsedClaim "A2" Nothing (Equals $ Lit "D")))) , ("CC", (And (Var $ ParsedClaim "A1" Nothing (Equals $ Lit "C")) (Var $ ParsedClaim "A2" Nothing (Equals $ Lit "C")))) , ("DD", (And (Var $ ParsedClaim "A1" Nothing (Equals $ Lit "D")) (Var $ ParsedClaim "A2" Nothing (Equals $ Lit "D")))) , ("DC", (And (Var $ ParsedClaim "A1" Nothing (Equals $ Lit "D")) (Var $ ParsedClaim "A2" Nothing (Equals $ Lit "C")))) ]) verifyParserFails codeMapParser sample3 verifyParserFails codeMapParser sample4 compileCode :: MonadCompile m => Code -> m (ModalProgram Value CompiledClaim) compileCode (Code frags) = do prog <- foldM (\f c -> (f .) <$> compileCodeFragment c) id frags dflt <- defaultAction return $ prog (F.Val . (dflt ==)) compileCode (ActionMap a2smap) = do let a2slist = Map.toList a2smap formulas <- mapM (compileStatement compileClaim . snd) a2slist let a2flist = zip (map fst a2slist) formulas return $ \a -> let Just f = List.lookup a a2flist in f -- Note: Code not dead; just not yet used. actionsMentioned :: Code -> [Value] actionsMentioned (ActionMap m) = Map.keys m actionsMentioned (Code frags) = concatMap fragRets frags where fragRets (For ActionT _ range fs) = rangeLitValues range ++ concatMap fragRets fs fragRets (For OutcomeT _ _ fs) = concatMap fragRets fs fragRets (ForN _ _ fs) = concatMap fragRets fs fragRets (If _ fs) = concatMap fragRets fs fragRets (IfElse _ fs gs) = concatMap fragRets fs ++ concatMap fragRets gs fragRets (Return (Just v)) = maybeToList $ lit v fragRets (Return _) = [] fragRets (LetN _ _) = [] fragRets Pass = [] -- Note: Code not dead; just not yet used. outcomesMentioned :: Code -> [Value] outcomesMentioned (ActionMap _) = [] outcomesMentioned (Code frags) = concatMap fragRets frags where fragRets (For ActionT _ _ fs) = concatMap fragRets fs fragRets (For OutcomeT _ range fs) = rangeLitValues range ++ concatMap fragRets fs fragRets (ForN _ _ fs) = concatMap fragRets fs fragRets (If _ fs) = concatMap fragRets fs fragRets (IfElse _ fs gs) = concatMap fragRets fs ++ concatMap fragRets gs fragRets (Return _) = [] fragRets (LetN _ _) = [] fragRets Pass = [] -- Note: Code not dead; just not yet used. claimsMade :: Code -> [ParsedClaim] claimsMade (ActionMap m) = concatMap claimsParsed $ Map.elems m claimsMade (Code frags) = concatMap fragClaims frags where fragClaims (For _ _ _ fs) = concatMap fragClaims fs fragClaims (ForN _ _ fs) = concatMap fragClaims fs fragClaims (If s fs) = claimsParsed s ++ concatMap fragClaims fs fragClaims (IfElse s fs gs) = claimsParsed s ++ concatMap fragClaims fs ++ concatMap fragClaims gs fragClaims (LetN _ _) = [] fragClaims (Return _) = [] fragClaims Pass = [] ------------------------------------------------------------------------------- type CompiledAgent = Map Value (ModalFormula CompiledClaim) codeToProgram :: MonadError CompileError m => CompileContext -> Code -> m CompiledAgent codeToProgram context code = do (prog, state) <- runStateT (compileCode code) context return $ Map.fromList [(a, prog a) | a <- actionList state] ------------------------------------------------------------------------------- -- Testing main :: IO () main = do _testRangeParser _testBoundedRangeParser _testCodeParser _testCodeMapParser putStrLn ""
daniel-ziegler/provability
src/Modal/Code.hs
Haskell
bsd-3-clause
17,712
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE CPP #-} module Network.Wai.Handler.Warp.Response ( sendResponse , sanitizeHeaderValue -- for testing , warpVersion , hasBody , replaceHeader ) where #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 1 #endif #ifndef MIN_VERSION_http_types #define MIN_VERSION_http_types(x,y,z) 1 #endif import Blaze.ByteString.Builder.HTTP (chunkedTransferEncoding, chunkedTransferTerminator) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative #endif import qualified Control.Exception as E import Control.Monad (unless, when) import Data.Array ((!)) import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.ByteString.Builder (byteString, Builder) import Data.ByteString.Builder.Extra (flush) import qualified Data.CaseInsensitive as CI import Data.Function (on) import Data.List (deleteBy) import Data.Maybe #if MIN_VERSION_base(4,5,0) # if __GLASGOW_HASKELL__ < 709 import Data.Monoid (mempty) # endif import Data.Monoid ((<>)) #else import Data.Monoid (mappend, mempty) #endif import Data.Streaming.Blaze (newBlazeRecv, reuseBufferStrategy) import Data.Version (showVersion) import Data.Word8 (_cr, _lf) import qualified Network.HTTP.Types as H #if MIN_VERSION_http_types(0,9,0) import qualified Network.HTTP.Types.Header as H #endif import Network.Wai import Network.Wai.Handler.Warp.Buffer (toBuilderBuffer) import qualified Network.Wai.Handler.Warp.Date as D import Network.Wai.Handler.Warp.File import Network.Wai.Handler.Warp.Header import Network.Wai.Handler.Warp.IO (toBufIOWith) import Network.Wai.Handler.Warp.ResponseHeader import Network.Wai.Handler.Warp.Settings import qualified Network.Wai.Handler.Warp.Timeout as T import Network.Wai.Handler.Warp.Types import Network.Wai.Internal import qualified Paths_warp #if !MIN_VERSION_base(4,5,0) (<>) :: Monoid m => m -> m -> m (<>) = mappend #endif -- $setup -- >>> :set -XOverloadedStrings ---------------------------------------------------------------- -- | Sending a HTTP response to 'Connection' according to 'Response'. -- -- Applications/middlewares MUST provide a proper 'H.ResponseHeaders'. -- so that inconsistency does not happen. -- No header is deleted by this function. -- -- Especially, Applications/middlewares MUST provide a proper -- Content-Type. They MUST NOT provide -- Content-Length, Content-Range, and Transfer-Encoding -- because they are inserted, when necessary, -- regardless they already exist. -- This function does not insert Content-Encoding. It's middleware's -- responsibility. -- -- The Date and Server header is added if not exist -- in HTTP response header. -- -- There are three basic APIs to create 'Response': -- -- ['responseBuilder' :: 'H.Status' -> 'H.ResponseHeaders' -> 'Builder' -> 'Response'] -- HTTP response body is created from 'Builder'. -- Transfer-Encoding: chunked is used in HTTP/1.1. -- -- ['responseStream' :: 'H.Status' -> 'H.ResponseHeaders' -> 'StreamingBody' -> 'Response'] -- HTTP response body is created from 'Builder'. -- Transfer-Encoding: chunked is used in HTTP/1.1. -- -- ['responseRaw' :: ('IO' 'ByteString' -> ('ByteString' -> 'IO' ()) -> 'IO' ()) -> 'Response' -> 'Response'] -- No header is added and no Transfer-Encoding: is applied. -- -- ['responseFile' :: 'H.Status' -> 'H.ResponseHeaders' -> 'FilePath' -> 'Maybe' 'FilePart' -> 'Response'] -- HTTP response body is sent (by sendfile(), if possible) for GET method. -- HTTP response body is not sent by HEAD method. -- Content-Length and Content-Range are automatically -- added into the HTTP response header if necessary. -- If Content-Length and Content-Range exist in the HTTP response header, -- they would cause inconsistency. -- \"Accept-Ranges: bytes\" is also inserted. -- -- Applications are categorized into simple and sophisticated. -- Sophisticated applications should specify 'Just' to -- 'Maybe' 'FilePart'. They should treat the conditional request -- by themselves. A proper 'Status' (200 or 206) must be provided. -- -- Simple applications should specify 'Nothing' to -- 'Maybe' 'FilePart'. The size of the specified file is obtained -- by disk access or from the file infor cache. -- If-Modified-Since, If-Unmodified-Since, If-Range and Range -- are processed. Since a proper status is chosen, 'Status' is -- ignored. Last-Modified is inserted. sendResponse :: Settings -> Connection -> InternalInfo -> Request -- ^ HTTP request. -> IndexedHeader -- ^ Indexed header of HTTP request. -> IO ByteString -- ^ source from client, for raw response -> Response -- ^ HTTP response including status code and response header. -> IO Bool -- ^ Returing True if the connection is persistent. sendResponse settings conn ii req reqidxhdr src response = do hs <- addServerAndDate hs0 if hasBody s then do -- The response to HEAD does not have body. -- But to handle the conditional requests defined RFC 7232 and -- to generate appropriate content-length, content-range, -- and status, the response to HEAD is processed here. -- -- See definition of rsp below for proper body stripping. (ms, mlen) <- sendRsp conn ii ver s hs rsp case ms of Nothing -> return () Just realStatus -> logger req realStatus mlen T.tickle th return ret else do _ <- sendRsp conn ii ver s hs RspNoBody logger req s Nothing T.tickle th return isPersist where defServer = settingsServerName settings logger = settingsLogger settings ver = httpVersion req s = responseStatus response hs0 = sanitizeHeaders $ responseHeaders response rspidxhdr = indexResponseHeader hs0 th = threadHandle ii getdate = getDate ii addServerAndDate = addDate getdate rspidxhdr . addServer defServer rspidxhdr (isPersist,isChunked0) = infoFromRequest req reqidxhdr isChunked = not isHead && isChunked0 (isKeepAlive, needsChunked) = infoFromResponse rspidxhdr (isPersist,isChunked) isHead = requestMethod req == H.methodHead rsp = case response of ResponseFile _ _ path mPart -> RspFile path mPart reqidxhdr isHead (T.tickle th) ResponseBuilder _ _ b | isHead -> RspNoBody | otherwise -> RspBuilder b needsChunked ResponseStream _ _ fb | isHead -> RspNoBody | otherwise -> RspStream fb needsChunked th ResponseRaw raw _ -> RspRaw raw src (T.tickle th) ret = case response of ResponseFile {} -> isPersist ResponseBuilder {} -> isKeepAlive ResponseStream {} -> isKeepAlive ResponseRaw {} -> False ---------------------------------------------------------------- sanitizeHeaders :: H.ResponseHeaders -> H.ResponseHeaders sanitizeHeaders = map (sanitize <$>) where sanitize v | containsNewlines v = sanitizeHeaderValue v -- slow path | otherwise = v -- fast path {-# INLINE containsNewlines #-} containsNewlines :: ByteString -> Bool containsNewlines = S.any (\w -> w == _cr || w == _lf) {-# INLINE sanitizeHeaderValue #-} sanitizeHeaderValue :: ByteString -> ByteString sanitizeHeaderValue v = case S8.lines $ S.filter (/= _cr) v of [] -> "" x : xs -> S8.intercalate "\r\n" (x : mapMaybe addSpaceIfMissing xs) where addSpaceIfMissing line = case S8.uncons line of Nothing -> Nothing Just (first, _) | first == ' ' || first == '\t' -> Just line | otherwise -> Just $ " " <> line ---------------------------------------------------------------- data Rsp = RspNoBody | RspFile FilePath (Maybe FilePart) IndexedHeader Bool (IO ()) | RspBuilder Builder Bool | RspStream StreamingBody Bool T.Handle | RspRaw (IO ByteString -> (ByteString -> IO ()) -> IO ()) (IO ByteString) (IO ()) ---------------------------------------------------------------- sendRsp :: Connection -> InternalInfo -> H.HttpVersion -> H.Status -> H.ResponseHeaders -> Rsp -> IO (Maybe H.Status, Maybe Integer) ---------------------------------------------------------------- sendRsp conn _ ver s hs RspNoBody = do -- Not adding Content-Length. -- User agents treats it as Content-Length: 0. composeHeader ver s hs >>= connSendAll conn return (Just s, Nothing) ---------------------------------------------------------------- sendRsp conn _ ver s hs (RspBuilder body needsChunked) = do header <- composeHeaderBuilder ver s hs needsChunked let hdrBdy | needsChunked = header <> chunkedTransferEncoding body <> chunkedTransferTerminator | otherwise = header <> body buffer = connWriteBuffer conn size = connBufferSize conn toBufIOWith buffer size (connSendAll conn) hdrBdy return (Just s, Nothing) -- fixme: can we tell the actual sent bytes? ---------------------------------------------------------------- sendRsp conn _ ver s hs (RspStream streamingBody needsChunked th) = do header <- composeHeaderBuilder ver s hs needsChunked (recv, finish) <- newBlazeRecv $ reuseBufferStrategy $ toBuilderBuffer (connWriteBuffer conn) (connBufferSize conn) let send builder = do popper <- recv builder let loop = do bs <- popper unless (S.null bs) $ do sendFragment conn th bs loop loop sendChunk | needsChunked = send . chunkedTransferEncoding | otherwise = send send header streamingBody sendChunk (sendChunk flush) when needsChunked $ send chunkedTransferTerminator mbs <- finish maybe (return ()) (sendFragment conn th) mbs return (Just s, Nothing) -- fixme: can we tell the actual sent bytes? ---------------------------------------------------------------- sendRsp conn _ _ _ _ (RspRaw withApp src tickle) = do withApp recv send return (Nothing, Nothing) where recv = do bs <- src unless (S.null bs) tickle return bs send bs = connSendAll conn bs >> tickle ---------------------------------------------------------------- -- Sophisticated WAI applications. -- We respect s0. s0 MUST be a proper value. sendRsp conn ii ver s0 hs0 (RspFile path (Just part) _ isHead hook) = sendRspFile2XX conn ii ver s0 hs path beg len isHead hook where beg = filePartOffset part len = filePartByteCount part hs = addContentHeadersForFilePart hs0 part ---------------------------------------------------------------- -- Simple WAI applications. -- Status is ignored sendRsp conn ii ver _ hs0 (RspFile path Nothing idxhdr isHead hook) = do efinfo <- E.try $ getFileInfo ii path case efinfo of Left (_ex :: E.IOException) -> #ifdef WARP_DEBUG print _ex >> #endif sendRspFile404 conn ii ver hs0 Right finfo -> case conditionalRequest finfo hs0 idxhdr of WithoutBody s -> sendRsp conn ii ver s hs0 RspNoBody WithBody s hs beg len -> sendRspFile2XX conn ii ver s hs path beg len isHead hook ---------------------------------------------------------------- sendRspFile2XX :: Connection -> InternalInfo -> H.HttpVersion -> H.Status -> H.ResponseHeaders -> FilePath -> Integer -> Integer -> Bool -> IO () -> IO (Maybe H.Status, Maybe Integer) sendRspFile2XX conn ii ver s hs path beg len isHead hook | isHead = sendRsp conn ii ver s hs RspNoBody | otherwise = do lheader <- composeHeader ver s hs (mfd, fresher) <- getFd ii path let fid = FileId path mfd hook' = hook >> fresher connSendFile conn fid beg len hook' [lheader] return (Just s, Just len) sendRspFile404 :: Connection -> InternalInfo -> H.HttpVersion -> H.ResponseHeaders -> IO (Maybe H.Status, Maybe Integer) sendRspFile404 conn ii ver hs0 = sendRsp conn ii ver s hs (RspBuilder body True) where s = H.notFound404 hs = replaceHeader H.hContentType "text/plain; charset=utf-8" hs0 body = byteString "File not found" ---------------------------------------------------------------- ---------------------------------------------------------------- -- | Use 'connSendAll' to send this data while respecting timeout rules. sendFragment :: Connection -> T.Handle -> ByteString -> IO () sendFragment Connection { connSendAll = send } th bs = do T.resume th send bs T.pause th -- We pause timeouts before passing control back to user code. This ensures -- that a timeout will only ever be executed when Warp is in control. We -- also make sure to resume the timeout after the completion of user code -- so that we can kill idle connections. ---------------------------------------------------------------- infoFromRequest :: Request -> IndexedHeader -> (Bool -- isPersist ,Bool) -- isChunked infoFromRequest req reqidxhdr = (checkPersist req reqidxhdr, checkChunk req) checkPersist :: Request -> IndexedHeader -> Bool checkPersist req reqidxhdr | ver == H.http11 = checkPersist11 conn | otherwise = checkPersist10 conn where ver = httpVersion req conn = reqidxhdr ! fromEnum ReqConnection checkPersist11 (Just x) | CI.foldCase x == "close" = False checkPersist11 _ = True checkPersist10 (Just x) | CI.foldCase x == "keep-alive" = True checkPersist10 _ = False checkChunk :: Request -> Bool checkChunk req = httpVersion req == H.http11 ---------------------------------------------------------------- -- Used for ResponseBuilder and ResponseSource. -- Don't use this for ResponseFile since this logic does not fit -- for ResponseFile. For instance, isKeepAlive should be True in some cases -- even if the response header does not have Content-Length. -- -- Content-Length is specified by a reverse proxy. -- Note that CGI does not specify Content-Length. infoFromResponse :: IndexedHeader -> (Bool,Bool) -> (Bool,Bool) infoFromResponse rspidxhdr (isPersist,isChunked) = (isKeepAlive, needsChunked) where needsChunked = isChunked && not hasLength isKeepAlive = isPersist && (isChunked || hasLength) hasLength = isJust $ rspidxhdr ! fromEnum ResContentLength ---------------------------------------------------------------- hasBody :: H.Status -> Bool hasBody s = sc /= 204 && sc /= 304 && sc >= 200 where sc = H.statusCode s ---------------------------------------------------------------- addTransferEncoding :: H.ResponseHeaders -> H.ResponseHeaders #if MIN_VERSION_http_types(0,9,0) addTransferEncoding hdrs = (H.hTransferEncoding, "chunked") : hdrs #else addTransferEncoding hdrs = ("transfer-encoding", "chunked") : hdrs #endif addDate :: IO D.GMTDate -> IndexedHeader -> H.ResponseHeaders -> IO H.ResponseHeaders addDate getdate rspidxhdr hdrs = case rspidxhdr ! fromEnum ResDate of Nothing -> do gmtdate <- getdate return $ (H.hDate, gmtdate) : hdrs Just _ -> return hdrs ---------------------------------------------------------------- -- | The version of Warp. warpVersion :: String warpVersion = showVersion Paths_warp.version addServer :: HeaderValue -> IndexedHeader -> H.ResponseHeaders -> H.ResponseHeaders addServer serverName rspidxhdr hdrs = case rspidxhdr ! fromEnum ResServer of Nothing -> (H.hServer, serverName) : hdrs _ -> hdrs ---------------------------------------------------------------- -- | -- -- >>> replaceHeader "Content-Type" "new" [("content-type","old")] -- [("Content-Type","new")] replaceHeader :: H.HeaderName -> HeaderValue -> H.ResponseHeaders -> H.ResponseHeaders replaceHeader k v hdrs = (k,v) : deleteBy ((==) `on` fst) (k,v) hdrs ---------------------------------------------------------------- composeHeaderBuilder :: H.HttpVersion -> H.Status -> H.ResponseHeaders -> Bool -> IO Builder composeHeaderBuilder ver s hs True = byteString <$> composeHeader ver s (addTransferEncoding hs) composeHeaderBuilder ver s hs False = byteString <$> composeHeader ver s hs
utdemir/wai
warp/Network/Wai/Handler/Warp/Response.hs
Haskell
mit
16,931
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="zh-CN"> <title>DOM XSS Active Scan Rule | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/domxss/src/main/javahelp/org/zaproxy/zap/extension/domxss/resources/help_zh_CN/helpset_zh_CN.hs
Haskell
apache-2.0
985
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hi-IN"> <title>Technology detection | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/wappalyzer/src/main/javahelp/org/zaproxy/zap/extension/wappalyzer/resources/help_hi_IN/helpset_hi_IN.hs
Haskell
apache-2.0
981
module Qualified2 where -- import qualified Control.Parallel.Strategies as T import qualified Control.Parallel.Strategies as S -- should fail, as there are two possible qualifiers... fib n | n <= 1 = 1 | otherwise = n1_2 + n2_2 + 1 where n1 = fib (n-1) n2 = fib (n-2) (n1_2, n2_2) = S.runEval (do n1_2 <- S.rpar n1 n2_2 <- S.rpar n2 return (n1_2, n2_2)) n1_2 = "bob"
RefactoringTools/HaRe
old/testing/evalAddEvalMon/Qualified2_TokOut.hs
Haskell
bsd-3-clause
487
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>AJAX Spider | ZAP Extensions</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/spiderAjax/resources/help_ur_PK/helpset_ur_PK.hs
Haskell
apache-2.0
974
-- This one elicited a bug in the simplifier -- that produces a Lint out-of-scope error module T4345 where isNull :: IO Bool isNull = error "urk" wrapMatchAll :: IO (Maybe ()) wrapMatchAll = do nsub <- undefined let loop True = do atEnd <- isNull return Nothing loop False = loop False result <- undefined loop undefined
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/simplCore/should_compile/T4345.hs
Haskell
bsd-3-clause
365
{-# LANGUAGE OverloadedStrings #-} module Cric.PackagesSpec ( test ) where import Test.Hspec import SpecHelpers import Cric import Cric.Packages test :: Spec test = do describe "getPackageManager" $ do it "detects RPM" $ do let sshMock = mockCommand "which rpm" (0, "/bin/rpm") defaultSshMock result <- testCricWith sshMock getPackageManager result `shouldBe` RPM it "detects Yum" $ do let sshMock = mockCommand "which yum" (0, "/bin/yum") defaultSshMock result <- testCricWith sshMock getPackageManager result `shouldBe` Yum it "detects APT" $ do let sshMock = mockCommand "which apt-get" (0, "/bin/apt-get") defaultSshMock result <- testCricWith sshMock getPackageManager result `shouldBe` APT it "returns UnknownPackageManager if it can't find anything" $ do result <- testCric getPackageManager result `shouldBe` UnknownPackageManager describe "installPackage" $ do it "uses the package manager found" $ do let mock = mockCommand "which apt-get" (0, "/bin/apt-get") . mockCommand "apt-get install" (0, "apt-get called") $ defaultSshMock result <- testCricWith mock $ installPackage ("haskell-platform" :: String) result `shouldBe` Right "apt-get called" context "when it can't find a package manager" $ do it "returns a NoPackageManagerFound error" $ do result <- testCric $ installPackage ("haskell-platform" :: String) result `shouldBe` Left NoPackageManagerFound context "when the installation fails" $ do it "returns an error" $ do let mock = mockCommand "which rpm" (0, "/bin/rpm") . mockCommand "rpm -i" (1, "installation failed") $ defaultSshMock result <- testCricWith mock $ installPackage ("haskell-platform" :: String) result `shouldBe` Left (UnknownPkgManagerError $ Failure 1 "installation failed" "") describe "removePackage" $ do it "uses the package manager found" $ do let mock = mockCommand "which apt-get" (0, "/bin/apt-get") . mockCommand "apt-get remove" (0, "apt-get called") $ defaultSshMock result <- testCricWith mock $ removePackage ("haskell-platform" :: String) result `shouldBe` Right "apt-get called" context "when it can't find a package manager" $ do it "returns a NoPackageManagerFound error" $ do result <- testCric $ removePackage ("haskell-platform" :: String) result `shouldBe` Left NoPackageManagerFound context "when the removal fails" $ do it "returns an error" $ do let mock = mockCommand "which rpm" (0, "/bin/rpm") . mockCommand "rpm -e" (1, "removal failed") $ defaultSshMock result <- testCricWith mock $ removePackage ("haskell-platform" :: String) result `shouldBe` Left (UnknownPkgManagerError $ Failure 1 "removal failed" "")
thoferon/cric
tests/Cric/PackagesSpec.hs
Haskell
mit
3,007
module Main where import Control.Monad import Control.AutoUpdate main = do update <- mkAutoUpdate $ do putStrLn "hello, world" forever update
arianvp/ghcjs-auto-update
example/Main.hs
Haskell
mit
155
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SVGPathSegCurvetoQuadraticAbs (setX, getX, setY, getY, setX1, getX1, setY1, getY1, SVGPathSegCurvetoQuadraticAbs(..), gTypeSVGPathSegCurvetoQuadraticAbs) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.x Mozilla SVGPathSegCurvetoQuadraticAbs.x documentation> setX :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> Float -> m () setX self val = liftDOM (self ^. jss "x" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.x Mozilla SVGPathSegCurvetoQuadraticAbs.x documentation> getX :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> m Float getX self = liftDOM (realToFrac <$> ((self ^. js "x") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.y Mozilla SVGPathSegCurvetoQuadraticAbs.y documentation> setY :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> Float -> m () setY self val = liftDOM (self ^. jss "y" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.y Mozilla SVGPathSegCurvetoQuadraticAbs.y documentation> getY :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> m Float getY self = liftDOM (realToFrac <$> ((self ^. js "y") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.x1 Mozilla SVGPathSegCurvetoQuadraticAbs.x1 documentation> setX1 :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> Float -> m () setX1 self val = liftDOM (self ^. jss "x1" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.x1 Mozilla SVGPathSegCurvetoQuadraticAbs.x1 documentation> getX1 :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> m Float getX1 self = liftDOM (realToFrac <$> ((self ^. js "x1") >>= valToNumber)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.y1 Mozilla SVGPathSegCurvetoQuadraticAbs.y1 documentation> setY1 :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> Float -> m () setY1 self val = liftDOM (self ^. jss "y1" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegCurvetoQuadraticAbs.y1 Mozilla SVGPathSegCurvetoQuadraticAbs.y1 documentation> getY1 :: (MonadDOM m) => SVGPathSegCurvetoQuadraticAbs -> m Float getY1 self = liftDOM (realToFrac <$> ((self ^. js "y1") >>= valToNumber))
ghcjs/jsaddle-dom
src/JSDOM/Generated/SVGPathSegCurvetoQuadraticAbs.hs
Haskell
mit
3,385
module ZoomHub.Web.Types.EmbedConstraint ( EmbedConstraint (..), ) where import Data.Bifunctor (first) import qualified Data.Text as T import Servant (FromHttpApiData, parseUrlPiece) import ZoomHub.Web.Types.OpenSeadragonViewerConfig (Constraint) import qualified ZoomHub.Web.Types.OpenSeadragonViewerConfig as Constraint -- Type newtype EmbedConstraint = EmbedConstraint {unEmbedConstraint :: Constraint} deriving (Eq, Show) parse :: String -> Either String EmbedConstraint parse value = case value of "zoom" -> Right $ EmbedConstraint Constraint.Zoom "full" -> Right $ EmbedConstraint Constraint.Full s -> Left $ "Invalid value: " <> s -- Text instance FromHttpApiData EmbedConstraint where parseUrlPiece p = first T.pack $ parse . T.unpack $ p
zoomhub/zoomhub
src/ZoomHub/Web/Types/EmbedConstraint.hs
Haskell
mit
773
{- provides 'setupGUI' the main gui initialization function. (using the module Language.Astview.Menu to build the menu bar) - -} module Language.Astview.Gui.Init(setupGUI) where import Language.Astview.Gui.Types import Language.Astview.Gui.Actions import Language.Astview.Gui.Menu import Language.Astview.Languages(languages) import Control.Monad.Trans (liftIO) import Data.IORef import System.FilePath ((</>)) import Graphics.UI.Gtk hiding (Language) import Graphics.UI.Gtk.SourceView import Paths_astview (getDataFileName) -- |builds initial gui state from builder file builderToGui :: Builder -> IO GUI builderToGui builder = do win <- builderGetObjectStr builder castToWindow "mainWindow" treeview <- builderGetObjectStr builder castToTreeView "treeview" tb <- buildSourceView =<< builderGetObjectStr builder castToScrolledWindow "swSource" return $ GUI win treeview tb -- |creates initial program state and provides an IORef to that buildState :: Builder -> IO (IORef AstState) buildState builder = do g <- builderToGui builder let astSt = AstState st g defaultValue st = defaultValue { knownLanguages = languages} newIORef astSt -- | initiates gui and returns initial program state setupGUI :: IO (IORef AstState) setupGUI = do initGUI builder <- builderNew builderAddFromFile builder =<< getDataFileName ("data" </> "astview.xml") r <- buildState builder initMenu builder r hooks r return r -- | setup the GtkSourceView and add it to the ScrollPane. return the -- underlying textbuffer buildSourceView :: ScrolledWindow -> IO SourceBuffer buildSourceView sw = do sourceBuffer <- sourceBufferNew Nothing sourceBufferSetHighlightSyntax sourceBuffer True sourceView <- sourceViewNewWithBuffer sourceBuffer sourceViewSetShowLineNumbers sourceView True sourceViewSetHighlightCurrentLine sourceView True srcfont <- fontDescriptionFromString $ font defaultValue ++" "++show (fsize defaultValue) widgetModifyFont sourceView (Just srcfont) containerAdd sw sourceView return sourceBuffer -- ** hooks -- | adds actions to widgets defined in type 'Gui'. (see 'hookNonGuiStateWidgets') hooks :: AstAction (ConnectId Window) hooks ref = do textbuffer <- getSourceBuffer ref storeLastActiveTextPosition textbuffer ref tree <- getTreeView ref storeLastActiveTreePosition tree ref win <- getWindow ref closeAstviewOnWindowClosed win ref close win ref type Hook a = a -> AstAction (ConnectId a) -- |stores the last active cursor position in text to the program state storeLastActiveTextPosition :: Hook SourceBuffer storeLastActiveTextPosition buffer ref = buffer `on` bufferChanged $ do actionBufferChanged ref cp <- getCursorPosition ref setCursor cp ref -- |stores the path to the last selected tree cell to the program state storeLastActiveTreePosition :: Hook TreeView storeLastActiveTreePosition tree ref = tree `on` cursorChanged $ do (p,_) <- treeViewGetCursor tree setTreePath p ref -- |softly terminate application on main window closed closeAstviewOnWindowClosed :: Hook Window closeAstviewOnWindowClosed w ref = w `on` deleteEvent $ tryEvent $ liftIO $ actionQuit ref -- |terminate application on main window closed close :: Hook Window close w _ = w `on` objectDestroy $ mainQuit
jokusi/Astview
src/gui/Language/Astview/Gui/Init.hs
Haskell
mit
3,295
{-# LANGUAGE StandaloneDeriving, DeriveFunctor, FlexibleInstances, KindSignatures, ConstraintKinds, MultiParamTypeClasses, NoImplicitPrelude #-} module OctoTactics.Util.ImprovedPrelude ( module Prelude, module OctoTactics.Util.ImprovedPrelude, module OctoTactics.Util.Combinators ) where import Prelude hiding ((<$>)) import Data.Set (Set) import qualified Data.Set as Set import OctoTactics.Util.Combinators import OctoTactics.Util.Class instance {-# OVERLAPPING #-} Ord b => Functor' Set a b where fmap' = Set.map
Solonarv/OctoTactics
OctoTactics/Util/ImprovedPrelude.hs
Haskell
mit
573
module Main where import Control.Monad.Reader (runReaderT) import qualified Data.Set as Set import Web.Twitter.Conduit (newManager, tlsManagerSettings) import Control.Monad.Base (MonadBase, liftBase) import Web.Twitter.PleaseCaption.Config (getTWInfo) import qualified Web.Twitter.PleaseCaption.Client as Client main :: IO () main = do putStrLn "pleasecaption is pruning follow list" mgr <- newManager tlsManagerSettings twinfo <- getTWInfo let client = Client.Client { Client.twInfo = twinfo, Client.manager = mgr } flip runReaderT client $ do uid <- Client.getUserId following <- Set.fromList <$> Client.getFollowees uid followers <- Set.fromList <$> Client.getFollowers uid let toUnfollow = Set.toList $ following `Set.difference` followers liftBase $ putStrLn $ "unfollowing " ++ show (length toUnfollow) ++ " users" mapM_ Client.unfollowUser toUnfollow putStrLn "all done"
stillinbeta/pleasecaption
exe/Main-unfollow.hs
Haskell
mit
917
module Options ( ColourSpace(..), Settings(..), getSettings ) where -- This has been cribbed from: -- http://www.haskell.org/haskellwiki/High-level_option_handling_with_GetOpt -- At the current stage of my Haskell development, this is basically -- black magic to me :P I'll figure it out eventually! import System.Environment (getArgs) import System.Exit import System.Console.GetOpt import System.FilePath (replaceExtension) import Data.Ratio data ColourSpace = Adaptive | Greyscale | Colour data Settings = Settings { inputFile :: FilePath, paletteFile :: Maybe FilePath, dpiScale :: Rational, outputFile :: FilePath, colourSpace :: ColourSpace } settingsHelp :: ExitCode -> IO a settingsHelp status = do putStrLn $ usageInfo "Usage: tapestry [OPTIONS] FILENAME\n" options exitWith status options :: [OptDescr (Settings -> IO Settings)] options = [ Option "p" ["palette"] (ReqArg (\x i -> return i { paletteFile = Just x }) "FILENAME") "Palette description file", Option "a" ["dpi-in"] (ReqArg (\x i -> let scale = dpiScale i in return i { dpiScale = scale * (1 % (read x :: Integer)) }) "DPI") "Input resolution", Option "b" ["dpi-out"] (ReqArg (\x i -> let scale = dpiScale i in return i { dpiScale = scale * ((read x :: Integer) % 1) }) "DPI") "Output resolution", Option "o" ["output"] (ReqArg (\x i -> return i { outputFile = x }) "FILENAME") "Output file", Option [] ["grey"] (NoArg (\i -> return i { colourSpace = Greyscale })) "Force greyscale", Option [] ["colour"] (NoArg (\i -> return i { colourSpace = Colour })) "Force colour", Option "h" ["help"] (NoArg (\_ -> settingsHelp ExitSuccess)) "Show this help...useful, huh?" ] getSettings :: IO Settings getSettings = do args <- getArgs let (actions, inputFiles, _) = getOpt Permute options args if null inputFiles then settingsHelp $ ExitFailure 1 else do let defaults = Settings { inputFile = filename, paletteFile = Nothing, dpiScale = 1, outputFile = replaceExtension filename "html", colourSpace = Adaptive } where filename = head inputFiles foldl (>>=) (return defaults) actions
Xophmeister/tapestry
Options.hs
Haskell
mit
2,544
{-# htermination (fmapMaybe :: (a -> b) -> Maybe a -> Maybe b) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Maybe a = Nothing | Just a ; fmapMaybe :: (c -> b) -> Maybe c -> Maybe b fmapMaybe f Nothing = Nothing; fmapMaybe f (Just x) = Just (f x);
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/fmap_1.hs
Haskell
mit
322
{-# LANGUAGE BangPatterns #-} module Maze (renderGrid, genMaze) where import Control.Monad.State import Linear import System.Random -- | Alias for the maze generator type MazeGen a = State (StdGen, Grid) a -- | The grid is a collection of all non-wall pieces type Grid = [Point] -- | A position inside the grid type type Point = V2 Integer -- | The grid size type Size = V2 Integer -- | Render the grid to a list of lines renderGrid :: String -- ^ What 'String' to use to render a wall -> String -- ^ What 'String' to user to render an empty space/path -> Size -- ^ The grid size -> Grid -- ^ Input grid -> [String] -- ^ Output lines renderGrid wall empty (V2 sx sy) grid = [concat [renderPos (V2 x y) | x <- [-1..sx]] | y <- [-1..sy]] where -- | Get the correct 'String' for this location renderPos v = if v `elem` grid then empty else wall -- | Generat a maze of the given size genMaze :: Size -- ^ The grid size -> StdGen -- ^ Random number generator -> Grid -- ^ Generated grid genMaze size g = snd $ execState (let p = (round <$> (fromIntegral <$> size) / 2) in iter p p) (g,[]) where iter :: Point -> Point -> MazeGen () iter p' p = do (gen, !grid) <- get when (valid grid p) $ do let (ndirs, gen') = shuffle gen dirs put (gen', p:p':grid) forM_ ndirs $ \d -> iter (p+d) (p+d*2) -- | All four walkable directions dirs :: [Point] dirs = [ V2 1 0 , V2 (-1) 0 , V2 0 1 , V2 0 (-1) ] -- | Check if this point is inside the grid and not already used valid :: Grid -> Point -> Bool valid grid p = inside p && p `notElem` grid -- | Chick if this Point lies inside the grid inside :: Point -> Bool inside (V2 x y) = let V2 sx sy = size in and [ x < sx, x >= 0 , y < sy, y >= 0 ] -- | shuffle a list shuffle :: RandomGen g => g -> [a] -> ([a], g) shuffle gen [] = ([], gen) shuffle gen xs = (e:rest, gen'') where (i, gen') = randomR (0, length xs - 1) gen (ys, e:zs) = splitAt i xs (rest,gen'') = shuffle gen' (ys++zs)
TomSmeets/maze
src/Maze.hs
Haskell
mit
2,276
import Utils answer = goodPairs where interval = [3..10000000] asDigits = map numberToDigits interval sumFactorials = foldl (\a -> \b -> a + (factorial b)) 0 sums = map sumFactorials asDigits pairs = zip interval sums goodPairs = filter (\(a,b) -> a==b) pairs
arekfu/project_euler
p0034/p0034.hs
Haskell
mit
338
module Account5 where import System.IO import Control.Concurrent.STM launchMissiles :: IO () launchMissiles = hPutStr stdout "Zzzing!" main = do xv <- atomically (newTVar 2) yv <- atomically (newTVar 1) atomically (do x <- readTVar xv y <- readTVar yv if x > y then launchMissiles else return () )
NickAger/LearningHaskell
ParallelConcurrent/2-BankAccount.hsproj/Account5.hs
Haskell
mit
379
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TupleSections #-} module Main where import Debian.Control.ByteString import Debian.Relation import Data.Graph.Inductive import Data.Tree import Data.Set (fromList, member) import Data.List (find, intercalate, sortOn) import Data.Maybe import Data.Either import System.IO import System.Console.CmdArgs.Implicit import qualified Data.ByteString.Char8 as B #if !MIN_VERSION_base(4,10,0) fromRight :: b -> Either a b -> b fromRight d = either (const d) id #endif type Package = Paragraph type FieldValue = B.ByteString type PackageName = FieldValue data Style = Roots | Forest deriving (Show, Data, Typeable) data Options = Options { statusFile :: String , style :: Style } deriving (Show, Data, Typeable) options :: Options options = Options { statusFile = def &= typ "STATUSFILE" &= argPos 0 &= opt "/var/lib/dpkg/status" , style = enum [Roots &= help "Show dependency roots (default)", Forest &= help "Show dependency forest"] &= groupname "Options" } &= program "DependencyRoots" &= summary "DependencyRoots v0.5" &= details ["STATUSFILE defaults to /var/lib/dpkg/status"] main :: IO () main = do args <- cmdArgs options parseControlFromFile (statusFile args) >>= either (putErr "Parse error") (putDeps (style args) . packageDeps) where putDeps style = case style of Roots -> putRoots graphRoots showAlts Forest -> putRoots graphForest showTree showTree = drawTree showAlts = intercalate "|" . flatten putErr :: Show e => String -> e -> IO () putErr msg e = hPutStrLn stderr $ msg ++ ": " ++ show e putRoots :: (Gr String () -> Forest String) -> (Tree String -> String) -> [[String]] -> IO () putRoots fRoots fShow = mapM_ (putStrLn . fShow) . sortForest . fRoots . makeGraph where sortForest = sortOn rootLabel graphRoots :: Gr a b -> Forest a graphRoots g = map labelAlts alternates where forest = dff (topsort g) g alternates = map (ancestors . rootLabel) forest ancestors n = head $ rdff [n] g labelAlts = fmap (fromJust . lab g) graphForest :: Gr a b -> Forest a graphForest g = map labelTree forest where forest = dff (topsort g) g labelTree = fmap (fromJust . lab g) makeGraph :: [[String]] -> Gr String () makeGraph deps = fst $ mkMapGraph nodes edges where nodes = map head deps edges = concatMap mkEdges deps mkEdges (n : sucs) = map (n,, ()) sucs mkEdges _ = error "Empty deps" packageDeps :: Control -> [[String]] packageDeps c = map mkDeps pkgs where pkgs = filter pkgIsInstalled . unControl $ c names = fromList . map extName $ pkgs mkDeps p = extName p : filter installed (pkgDeps p) installed name = name `member` names extName p = if a /= baseArch && a /= "all" then n ++ ':' : a else n where n = pkgName p a = pkgArch p baseArch = maybe "" pkgArch $ find (\p -> pkgName p == "base-files") pkgs pkgName :: Package -> String pkgName = maybe "Unnamed" B.unpack . fieldValue "Package" pkgArch :: Package -> String pkgArch = maybe "" B.unpack . fieldValue "Architecture" pkgIsInstalled :: Package -> Bool pkgIsInstalled = maybe False isInstalled . fieldValue "Status" where isInstalled v = parseStatus v !! 2 == B.pack "installed" parseStatus = B.split ' ' . stripWS #if !MIN_VERSION_debian(3,64,0) unBinPkgName = id #elif !MIN_VERSION_debian(3,69,0) unBinPkgName_ = unPkgName . unBinPkgName #define unBinPkgName unBinPkgName_ #endif pkgDeps :: Package -> [String] pkgDeps p = names "Depends" ++ names "Recommends" where field = B.unpack . fromMaybe B.empty . flip fieldValue p rels = fromRight [] . parseRelations . field names = map (relName . head) . rels relName (Rel name _ _) = unBinPkgName name
neilmayhew/RepoExplorer
DependencyRoots.hs
Haskell
mit
3,900
{- Copyright (c) 2008 Russell O'Connor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} -- |Standard illuminants defined by the International Commission on -- Illumination (CIE). module Data.Colour.CIE.Illuminant where import Data.Colour.CIE.Chromaticity -- |Incandescent \/ Tungsten a :: (Fractional a) => Chromaticity a a = mkChromaticity 0.44757 0.40745 -- |{obsolete} Direct sunlight at noon b :: (Fractional a) => Chromaticity a b = mkChromaticity 0.34842 0.35161 -- |{obsolete} Average \/ North sky Daylight c :: (Fractional a) => Chromaticity a c = mkChromaticity 0.31006 0.31616 -- |Horizon Light. ICC profile PCS d50 :: (Fractional a) => Chromaticity a d50 = mkChromaticity 0.34567 0.35850 -- |Mid-morning \/ Mid-afternoon Daylight d55 :: (Fractional a) => Chromaticity a d55 = mkChromaticity 0.33242 0.34743 -- |Noon Daylight: Television, sRGB color space d65 :: (Fractional a) => Chromaticity a d65 = mkChromaticity 0.31271 0.32902 -- |North sky Daylight d75 :: (Fractional a) => Chromaticity a d75 = mkChromaticity 0.29902 0.31485 -- |Equal energy e :: (Fractional a) => Chromaticity a e = mkChromaticity (1/3) (1/3) -- |Daylight Fluorescent f1 :: (Fractional a) => Chromaticity a f1 = mkChromaticity 0.31310 0.33727 -- |Cool White Fluorescent f2 :: (Fractional a) => Chromaticity a f2 = mkChromaticity 0.37208 0.37529 -- |White Fluorescent f3 :: (Fractional a) => Chromaticity a f3 = mkChromaticity 0.40910 0.39430 -- |Warm White Fluorescent f4 :: (Fractional a) => Chromaticity a f4 = mkChromaticity 0.44018 0.40329 -- |Daylight Fluorescent f5 :: (Fractional a) => Chromaticity a f5 = mkChromaticity 0.31379 0.34531 -- |Lite White Fluorescent f6 :: (Fractional a) => Chromaticity a f6 = mkChromaticity 0.37790 0.38835 -- |D65 simulator, Daylight simulator f7 :: (Fractional a) => Chromaticity a f7 = mkChromaticity 0.31292 0.32933 -- |D50 simulator, Sylvania F40 Design 50 f8 :: (Fractional a) => Chromaticity a f8 = mkChromaticity 0.34588 0.35875 -- |Cool White Deluxe Fluorescent f9 :: (Fractional a) => Chromaticity a f9 = mkChromaticity 0.37417 0.37281 -- |Philips TL85, Ultralume 50 f10 :: (Fractional a) => Chromaticity a f10 = mkChromaticity 0.34609 0.35986 -- |Philips TL84, Ultralume 40 f11 :: (Fractional a) => Chromaticity a f11 = mkChromaticity 0.38052 0.37713 -- |Philips TL83, Ultralume 30 f12 :: (Fractional a) => Chromaticity a f12 = mkChromaticity 0.43695 0.40441
haasn/colour
Data/Colour/CIE/Illuminant.hs
Haskell
mit
3,431
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveGeneric #-} {-# OPTIONS_GHC -fdefer-type-errors #-} module Handler.GameJson where import Import import Control.Lens (makeLenses, (^.), (^?), (.~), (&)) import qualified Data.Aeson.Lens as AL (key, _Bool, _Integer) import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier) import qualified Data.List as L (foldl) import Data.Time.LocalTime (zonedTimeToUTC) import Jabara.Persist.Util (toKey, toRecord) import Jabara.Util (omittedFirstCharLower) import Minibas.Util (buildGameData) import ModelDef (Quarter(..), mapQuartersM) getGameIndexR :: Handler [GameData] getGameIndexR = runDB $ do games::[Entity Game] <- selectList [] [Asc GameDate] leagues::[Entity League] <- selectList [LeagueId <-. map (_gameLeague.toRecord) games] [] scores::[Entity Score] <- selectList [ScoreGame <-. map toKey games] [] teams::[Entity Team] <- selectList [TeamId <-. (map (_gameTeamA.toRecord) games)++(map (_gameTeamB.toRecord) games)] [] mapM (buildGameData leagues teams scores) games data Put = Put { _putLeagueName :: Text , _putGameName :: Text , _putGamePlace :: Text , _putTeamAName :: Text , _putTeamBName :: Text } deriving (Show, Eq, Read, Generic) makeLenses ''Put $(deriveJSON defaultOptions { fieldLabelModifier = omittedFirstCharLower "_put" } ''Put) putGameIndexR :: Handler () putGameIndexR = do put::Put <- requireJsonBody gameId <- runDB $ do leagueId <- insertIfNotExists (UniqueLeague $ put^.putLeagueName) (League $ put^.putLeagueName) teamAId <- insertIfNotExists (UniqueTeam $ put^.putTeamAName) (Team $ put^.putTeamAName) teamBId <- insertIfNotExists (UniqueTeam $ put^.putTeamBName) (Team $ put^.putTeamBName) now <- liftIO $ getCurrentTime game <- pure $ Game { _gameLeague = leagueId , _gameName = put^.putGameName , _gamePlace = put^.putGamePlace , _gameTeamA = teamAId , _gameTeamB = teamBId , _gameDate = now } gameId <- insert game _ <- mapQuartersM (\q -> insert $ emptyScore gameId q) pure gameId sendResponseCreated $ GameUiR gameId emptyScore :: GameId -> Quarter -> Score emptyScore gameId quarter = Score { _scoreGame = gameId , _scoreQuarter = quarter , _scoreTeamAPoint = 0 , _scoreTeamBPoint = 0 , _scoreLock = False } insertIfNotExists :: (MonadIO m, PersistUnique (PersistEntityBackend val), PersistEntity val) => Unique val -> val -> ReaderT (PersistEntityBackend val) m (Key val) insertIfNotExists unique creator = do mEntity <- getBy unique case mEntity of Nothing -> insert creator Just e -> pure $ toKey e getGameR :: GameId -> Handler GameData getGameR gameId = runDB $ do game <- get404 gameId leagues <- selectList [LeagueId ==. game^.gameLeague] [] teams <- selectList [TeamId <-. [game^.gameTeamA, game^.gameTeamB]] [] scores <- selectList [ScoreGame ==. gameId] [] buildGameData leagues teams scores (Entity gameId game) postGameR :: GameId -> Handler () postGameR gameId = do req::GameData <- requireJsonBody runDB $ do replace gameId $ toGame req mapM_ (\score -> replace (score^.scoreDataId) (toScore score)) $ req^.gameDataScoreList where toGame :: GameData -> Game toGame g = Game { _gameLeague = toKey $ g^.gameDataLeague , _gameName = g^.gameDataName , _gamePlace = g^.gameDataPlace , _gameTeamA = toKey $ g^.gameDataTeamA , _gameTeamB = toKey $ g^.gameDataTeamB , _gameDate = zonedTimeToUTC $ g^.gameDataDate } toScore :: ScoreData -> Score toScore s = Score { _scoreGame = gameId , _scoreQuarter = s^.scoreDataQuarter , _scoreTeamAPoint = s^.scoreDataTeamAPoint , _scoreTeamBPoint = s^.scoreDataTeamBPoint , _scoreLock = s^.scoreDataLock } deleteGameR :: GameId -> Handler () deleteGameR gameId = runDB $ do deleteWhere [ScoreGame ==. gameId] delete gameId type QuarterIndex = Int patchGameScoreFirstR :: GameId -> Handler (Entity Score) patchGameScoreFirstR gameId = patchGameScore gameId First patchGameScoreSecondR :: GameId -> Handler (Entity Score) patchGameScoreSecondR gameId = patchGameScore gameId Second patchGameScoreThirdR :: GameId -> Handler (Entity Score) patchGameScoreThirdR gameId = patchGameScore gameId Third patchGameScoreFourthR :: GameId -> Handler (Entity Score) patchGameScoreFourthR gameId = patchGameScore gameId Fourth patchGameScoreExtraR :: GameId -> Handler (Entity Score) patchGameScoreExtraR gameId = patchGameScore gameId Extra patchGameScore :: GameId -> Quarter -> Handler (Entity Score) patchGameScore gameId quarter = do req::Value <- requireJsonBody eScore@(Entity key score) <- runDB $ getBy404 $ UniqueScore gameId quarter _ <- case req of Object _ -> pure req _ -> sendResponseStatus badRequest400 eScore let ps::[(Score -> Score)] = [ (\sc -> case req ^? AL.key "lock" . AL._Bool of Nothing -> sc Just b -> sc&scoreLock .~ b ) , (\sc -> case req ^? AL.key "teamAPoint" . AL._Integer of Nothing -> sc Just p -> sc&scoreTeamAPoint .~ (fromInteger p) ) , (\sc -> case req ^? AL.key "teamBPoint" . AL._Integer of Nothing -> sc Just p -> sc&scoreTeamBPoint .~ (fromInteger p) ) ] score' = L.foldl (\sc f -> f sc) score ps _ <- runDB $ replace key score' pure $ Entity key score'
jabaraster/minibas-web
Handler/GameJson.hs
Haskell
mit
6,539
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html module Stratosphere.Resources.KMSKey where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.Tag -- | Full data type definition for KMSKey. See 'kmsKey' for a more convenient -- constructor. data KMSKey = KMSKey { _kMSKeyDescription :: Maybe (Val Text) , _kMSKeyEnableKeyRotation :: Maybe (Val Bool) , _kMSKeyEnabled :: Maybe (Val Bool) , _kMSKeyKeyPolicy :: Object , _kMSKeyKeyUsage :: Maybe (Val Text) , _kMSKeyPendingWindowInDays :: Maybe (Val Integer) , _kMSKeyTags :: Maybe [Tag] } deriving (Show, Eq) instance ToResourceProperties KMSKey where toResourceProperties KMSKey{..} = ResourceProperties { resourcePropertiesType = "AWS::KMS::Key" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("Description",) . toJSON) _kMSKeyDescription , fmap (("EnableKeyRotation",) . toJSON) _kMSKeyEnableKeyRotation , fmap (("Enabled",) . toJSON) _kMSKeyEnabled , (Just . ("KeyPolicy",) . toJSON) _kMSKeyKeyPolicy , fmap (("KeyUsage",) . toJSON) _kMSKeyKeyUsage , fmap (("PendingWindowInDays",) . toJSON) _kMSKeyPendingWindowInDays , fmap (("Tags",) . toJSON) _kMSKeyTags ] } -- | Constructor for 'KMSKey' containing required fields as arguments. kmsKey :: Object -- ^ 'kmskKeyPolicy' -> KMSKey kmsKey keyPolicyarg = KMSKey { _kMSKeyDescription = Nothing , _kMSKeyEnableKeyRotation = Nothing , _kMSKeyEnabled = Nothing , _kMSKeyKeyPolicy = keyPolicyarg , _kMSKeyKeyUsage = Nothing , _kMSKeyPendingWindowInDays = Nothing , _kMSKeyTags = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-description kmskDescription :: Lens' KMSKey (Maybe (Val Text)) kmskDescription = lens _kMSKeyDescription (\s a -> s { _kMSKeyDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-enablekeyrotation kmskEnableKeyRotation :: Lens' KMSKey (Maybe (Val Bool)) kmskEnableKeyRotation = lens _kMSKeyEnableKeyRotation (\s a -> s { _kMSKeyEnableKeyRotation = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-enabled kmskEnabled :: Lens' KMSKey (Maybe (Val Bool)) kmskEnabled = lens _kMSKeyEnabled (\s a -> s { _kMSKeyEnabled = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-keypolicy kmskKeyPolicy :: Lens' KMSKey Object kmskKeyPolicy = lens _kMSKeyKeyPolicy (\s a -> s { _kMSKeyKeyPolicy = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-keyusage kmskKeyUsage :: Lens' KMSKey (Maybe (Val Text)) kmskKeyUsage = lens _kMSKeyKeyUsage (\s a -> s { _kMSKeyKeyUsage = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-pendingwindowindays kmskPendingWindowInDays :: Lens' KMSKey (Maybe (Val Integer)) kmskPendingWindowInDays = lens _kMSKeyPendingWindowInDays (\s a -> s { _kMSKeyPendingWindowInDays = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-tags kmskTags :: Lens' KMSKey (Maybe [Tag]) kmskTags = lens _kMSKeyTags (\s a -> s { _kMSKeyTags = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/KMSKey.hs
Haskell
mit
3,564
-- | Popular transformation functions for the 'String' observation type. module Control.Monad.Ox.String ( prefix , suffix , substr , shape , pack ) where import qualified Data.Char as C import qualified Data.List as L -- | Prefix of the given size or 'Nothing' if the size exceeds the -- length of the string. prefix :: Int -> String -> Maybe String prefix k xs | k > 0 && k <= n = Just $ take k xs | k <= 0 && n + k > 0 = Just $ take (n + k) xs | otherwise = Nothing where n = length xs -- | Suffix of the given size or 'Nothing' if the size exceeds the -- length of the string. suffix :: Int -> String -> Maybe String suffix k xs | k > 0 && k <= n = Just . reverse . take k . reverse $ xs | k <= 0 && n + k > 0 = Just . reverse . take (n + k) . reverse $ xs | otherwise = Nothing where n = length xs -- | All substrings of the given size. substr :: Int -> String -> [String] substr k xs | k > 0 && k <= n = relevant $ map (take k) (L.tails xs) | otherwise = [] where n = length xs relevant = reverse . dropWhile ((<k).length) . reverse -- | Shape of the string. All lower-case characters are mapped to 'l', -- upper-case characters to 'u', digits to 'd' and rest of characters -- to 'x'. shape :: String -> String shape = map translate where translate char | C.isLower char = 'l' | C.isUpper char = 'u' | C.isDigit char = 'd' | otherwise = 'x' -- | Pack the string, that is remove all adjacent repetitions, -- for example /aabcccdde -> abcde/. pack :: String -> String pack = map head . L.group
kawu/monad-ox
Control/Monad/Ox/String.hs
Haskell
bsd-2-clause
1,676
module Unit ( tests ) where import Test.Tasty import qualified Unit.CommitQueue tests :: TestTree tests = testGroup "Unit tests" [ Unit.CommitQueue.tests ]
sgraf812/feed-gipeda
tests/Unit.hs
Haskell
bsd-3-clause
178
{-# LANGUAGE MultiParamTypeClasses, UndecidableInstances, FlexibleInstances #-} module Database.MetaStorage.Types (MetaStorageT (..), mkMetaStorageDefault) where import Prelude hiding (FilePath) import Filesystem.Path.CurrentOS import Crypto.Hash import Filesystem import Control.Monad.IO.Class import Database.MetaStorage.Classes newtype MetaStorageT = MetaStorage FilePath deriving (Show, Eq) instance (MonadIO m, HashAlgorithm h) => MetaStorage MetaStorageT m h where ms_basedir (MetaStorage fp) = fp mkMetaStorage fp = liftIO $ do createDirectory True fp return (MetaStorage fp, []) mkMetaStorageDefault :: (MonadIO m) => FilePath -> m (MetaStorageT, [Digest SHA1]) mkMetaStorageDefault = mkMetaStorage
alios/metastorage
Database/MetaStorage/Types.hs
Haskell
bsd-3-clause
788
{-# LANGUAGE FlexibleContexts #-} module Charter(singleWeightChangeChart) where import GHC.TypeLits import Graphics.Rendering.Chart.Easy import Graphics.Rendering.Chart.Gtk import Minimizer import Control.Lens import Data.Proxy import Brain import Simulator import Convenience import SizedL import Control.Monad.Random rangedReplace :: _ => [a] -> Sized _ a -> Proxy _ -> [Sized _ a] rangedReplace rep xs index = rep &> replaceAt index xs neuralChart :: forall (m :: Nat) (t :: Nat) b (n1 :: Nat). (KnownNat m, Simulator b) => Proxy (m + 1) -> Int -> NeuralSim b ((m + n1) + 1) t Double -> [(Double, Double)] neuralChart weightIndex numIters (NeuralSim _ startWeights _ nSet) = undefined singleWeightChangeChart :: _ => NeuralSim a _ d Double -> IO () singleWeightChangeChart neuralSim = toWindow 500 500 $ do layout_title .= "Amplitude Modulation" setColors [opaque blue, opaque red, opaque green, opaque purple] -- plot (line "10" ([neuralChart (Proxy @1) 10 neuralSim])) -- plot (line "20" ([neuralChart (Proxy @1) 20 neuralSim])) plot (line "30" ([neuralChart (Proxy @1) 100 neuralSim])) -- plot (line "50" ([neuralChart (Proxy @2) 100 neuralSim]))
bmabsout/neural-swarm
src/Charter.hs
Haskell
bsd-3-clause
1,273
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Servant.ContentType.Processable where import Data.ByteString.Lazy (ByteString) import Data.Proxy import Data.Typeable (Typeable) import Network.HTTP.Media (MediaType) import Servant.API (Accept (..), MimeRender (..)) data to :<- from deriving Typeable class Processable method from where type Processed method :: * process :: Proxy method -> from -> (Processed method) instance Accept to => Accept (to :<- from) where contentType _ = contentType (Proxy :: Proxy to) instance {-# OVERLAPPABLE #-} ( MimeRender to (Processed from) , Processable from a ) => MimeRender (to :<- from) a where mimeRender _ = mimeRender' Proxy . process' Proxy where mimeRender' :: Proxy to -> Processed from -> ByteString mimeRender' = mimeRender process' :: Proxy from -> a -> Processed from process' = process
notcome/liu-ms-adult
src/Servant/ContentType/Processable.hs
Haskell
bsd-3-clause
1,111
module Options.Language where import Types languageOptions :: [Flag] languageOptions = [ flag { flagName = "-fconstraint-solver-iterations=⟨n⟩" , flagDescription = "*default: 4.* Set the iteration limit for the type-constraint "++ "solver. Typically one iteration suffices; so please "++ "yell if you find you need to set it higher than the default. "++ "Zero means infinity." , flagType = DynamicFlag } , flag { flagName = "-freduction-depth=⟨n⟩" , flagDescription = "*default: 200.* Set the :ref:`limit for type simplification "++ "<undecidable-instances>`. Zero means infinity." , flagType = DynamicFlag } , flag { flagName = "-fcontext-stack=⟨n⟩" , flagDescription = "Deprecated. Use ``-freduction-depth=⟨n⟩`` instead." , flagType = DynamicFlag } , flag { flagName = "-fglasgow-exts" , flagDescription = "Deprecated. Enable most language extensions; "++ "see :ref:`options-language` for exactly which ones." , flagType = DynamicFlag , flagReverse = "-fno-glasgow-exts" } , flag { flagName = "-firrefutable-tuples" , flagDescription = "Make tuple pattern matching irrefutable" , flagType = DynamicFlag , flagReverse = "-fno-irrefutable-tuples" } , flag { flagName = "-fpackage-trust" , flagDescription = "Enable :ref:`Safe Haskell <safe-haskell>` trusted package "++ "requirement for trustworthy modules." , flagType = DynamicFlag } , flag { flagName = "-ftype-function-depth=⟨n⟩" , flagDescription = "Deprecated. Use ``-freduction-depth=⟨n⟩`` instead." , flagType = DynamicFlag } , flag { flagName = "-XAllowAmbiguousTypes" , flagDescription = "Allow the user to write :ref:`ambiguous types <ambiguity>`, and "++ "the type inference engine to infer them." , flagType = DynamicFlag , flagReverse = "-XNoAllowAmbiguousTypes" , flagSince = "7.8.1" } , flag { flagName = "-XArrows" , flagDescription = "Enable :ref:`arrow notation <arrow-notation>` extension" , flagType = DynamicFlag , flagReverse = "-XNoArrows" , flagSince = "6.8.1" } , flag { flagName = "-XApplicativeDo" , flagDescription = "Enable :ref:`Applicative do-notation desugaring <applicative-do>`" , flagType = DynamicFlag , flagReverse = "-XNoApplicativeDo" , flagSince = "8.0.1" } , flag { flagName = "-XAutoDeriveTypeable" , flagDescription = "As of GHC 7.10, this option is not needed, and should not be "++ "used. Previously this would automatically :ref:`derive Typeable "++ "instances for every datatype and type class declaration "++ "<deriving-typeable>`. Implies ``-XDeriveDataTypeable``." , flagType = DynamicFlag , flagReverse = "-XNoAutoDeriveTypeable" , flagSince = "7.8.1" } , flag { flagName = "-XBangPatterns" , flagDescription = "Enable :ref:`bang patterns <bang-patterns>`." , flagType = DynamicFlag , flagReverse = "-XNoBangPatterns" , flagSince = "6.8.1" } , flag { flagName = "-XBinaryLiterals" , flagDescription = "Enable support for :ref:`binary literals <binary-literals>`." , flagType = DynamicFlag , flagReverse = "-XNoBinaryLiterals" , flagSince = "7.10.1" } , flag { flagName = "-XCApiFFI" , flagDescription = "Enable :ref:`the CAPI calling convention <ffi-capi>`." , flagType = DynamicFlag , flagReverse = "-XNoCAPIFFI" , flagSince = "7.10.1" } , flag { flagName = "-XConstrainedClassMethods" , flagDescription = "Enable :ref:`constrained class methods <class-method-types>`." , flagType = DynamicFlag , flagReverse = "-XNoConstrainedClassMethods" , flagSince = "6.8.1" } , flag { flagName = "-XConstraintKinds" , flagDescription = "Enable a :ref:`kind of constraints <constraint-kind>`." , flagType = DynamicFlag , flagReverse = "-XNoConstraintKinds" , flagSince = "7.4.1" } , flag { flagName = "-XCPP" , flagDescription = "Enable the :ref:`C preprocessor <c-pre-processor>`." , flagType = DynamicFlag , flagReverse = "-XNoCPP" , flagSince = "6.8.1" } , flag { flagName = "-XDataKinds" , flagDescription = "Enable :ref:`datatype promotion <promotion>`." , flagType = DynamicFlag , flagReverse = "-XNoDataKinds" , flagSince = "7.4.1" } , flag { flagName = "-XDefaultSignatures" , flagDescription = "Enable :ref:`default signatures <class-default-signatures>`." , flagType = DynamicFlag , flagReverse = "-XNoDefaultSignatures" , flagSince = "7.2.1" } , flag { flagName = "-XDeriveAnyClass" , flagDescription = "Enable :ref:`deriving for any class <derive-any-class>`." , flagType = DynamicFlag , flagReverse = "-XNoDeriveAnyClass" , flagSince = "7.10.1" } , flag { flagName = "-XDeriveDataTypeable" , flagDescription = "Enable ``deriving`` for the :ref:`Data class "++ "<deriving-typeable>`. Implied by ``-XAutoDeriveTypeable``." , flagType = DynamicFlag , flagReverse = "-XNoDeriveDataTypeable" , flagSince = "6.8.1" } , flag { flagName = "-XDeriveFunctor" , flagDescription = "Enable :ref:`deriving for the Functor class <deriving-extra>`. "++ "Implied by ``-XDeriveTraversable``." , flagType = DynamicFlag , flagReverse = "-XNoDeriveFunctor" , flagSince = "7.10.1" } , flag { flagName = "-XDeriveFoldable" , flagDescription = "Enable :ref:`deriving for the Foldable class <deriving-extra>`. "++ "Implied by ``-XDeriveTraversable``." , flagType = DynamicFlag , flagReverse = "-XNoDeriveFoldable" , flagSince = "7.10.1" } , flag { flagName = "-XDeriveGeneric" , flagDescription = "Enable :ref:`deriving for the Generic class <deriving-typeable>`." , flagType = DynamicFlag , flagReverse = "-XNoDeriveGeneric" , flagSince = "7.2.1" } , flag { flagName = "-XDeriveGeneric" , flagDescription = "Enable :ref:`deriving for the Generic class <deriving-typeable>`." , flagType = DynamicFlag , flagReverse = "-XNoDeriveGeneric" , flagSince = "7.2.1" } , flag { flagName = "-XDeriveLift" , flagDescription = "Enable :ref:`deriving for the Lift class <deriving-lift>`" , flagType = DynamicFlag , flagReverse = "-XNoDeriveLift" , flagSince = "7.2.1" } , flag { flagName = "-XDeriveTraversable" , flagDescription = "Enable :ref:`deriving for the Traversable class <deriving-extra>`. "++ "Implies ``-XDeriveFunctor`` and ``-XDeriveFoldable``." , flagType = DynamicFlag , flagReverse = "-XNoDeriveTraversable" , flagSince = "7.10.1" } , flag { flagName = "-XDisambiguateRecordFields" , flagDescription = "Enable :ref:`record field disambiguation <disambiguate-fields>`. "++ "Implied by ``-XRecordWildCards``." , flagType = DynamicFlag , flagReverse = "-XNoDisambiguateRecordFields" , flagSince = "6.8.1" } , flag { flagName = "-XEmptyCase" , flagDescription = "Allow :ref:`empty case alternatives <empty-case>`." , flagType = DynamicFlag , flagReverse = "-XNoEmptyCase" , flagSince = "7.8.1" } , flag { flagName = "-XEmptyDataDecls" , flagDescription = "Enable empty data declarations." , flagType = DynamicFlag , flagReverse = "-XNoEmptyDataDecls" , flagSince = "6.8.1" } , flag { flagName = "-XExistentialQuantification" , flagDescription = "Enable :ref:`existential quantification <existential-quantification>`." , flagType = DynamicFlag , flagReverse = "-XNoExistentialQuantification" , flagSince = "6.8.1" } , flag { flagName = "-XExplicitForAll" , flagDescription = "Enable :ref:`explicit universal quantification <explicit-foralls>`."++ " Implied by ``-XScopedTypeVariables``, ``-XLiberalTypeSynonyms``,"++ " ``-XRankNTypes`` and ``-XExistentialQuantification``." , flagType = DynamicFlag , flagReverse = "-XNoExplicitForAll" , flagSince = "6.12.1" } , flag { flagName = "-XExplicitNamespaces" , flagDescription = "Enable using the keyword ``type`` to specify the namespace of "++ "entries in imports and exports (:ref:`explicit-namespaces`). "++ "Implied by ``-XTypeOperators`` and ``-XTypeFamilies``." , flagType = DynamicFlag , flagReverse = "-XNoExplicitNamespaces" , flagSince = "7.6.1" } , flag { flagName = "-XExtendedDefaultRules" , flagDescription = "Use GHCi's :ref:`extended default rules <extended-default-rules>` "++ "in a normal module." , flagType = DynamicFlag , flagReverse = "-XNoExtendedDefaultRules" , flagSince = "6.8.1" } , flag { flagName = "-XFlexibleContexts" , flagDescription = "Enable :ref:`flexible contexts <flexible-contexts>`. Implied by "++ "``-XImplicitParams``." , flagType = DynamicFlag , flagReverse = "-XNoFlexibleContexts" , flagSince = "6.8.1" } , flag { flagName = "-XFlexibleInstances" , flagDescription = "Enable :ref:`flexible instances <instance-rules>`. "++ "Implies ``-XTypeSynonymInstances``. "++ "Implied by ``-XImplicitParams``." , flagType = DynamicFlag , flagReverse = "-XNoFlexibleInstances" , flagSince = "6.8.1" } , flag { flagName = "-XForeignFunctionInterface" , flagDescription = "Enable :ref:`foreign function interface <ffi>`." , flagType = DynamicFlag , flagReverse = "-XNoForeignFunctionInterface" , flagSince = "6.8.1" } , flag { flagName = "-XFunctionalDependencies" , flagDescription = "Enable :ref:`functional dependencies <functional-dependencies>`. "++ "Implies ``-XMultiParamTypeClasses``." , flagType = DynamicFlag , flagReverse = "-XNoFunctionalDependencies" , flagSince = "6.8.1" } , flag { flagName = "-XGADTs" , flagDescription = "Enable :ref:`generalised algebraic data types <gadt>`. "++ "Implies ``-XGADTSyntax`` and ``-XMonoLocalBinds``." , flagType = DynamicFlag , flagReverse = "-XNoGADTs" , flagSince = "6.8.1" } , flag { flagName = "-XGADTSyntax" , flagDescription = "Enable :ref:`generalised algebraic data type syntax <gadt-style>`." , flagType = DynamicFlag , flagReverse = "-XNoGADTSyntax" , flagSince = "7.2.1" } , flag { flagName = "-XGeneralizedNewtypeDeriving" , flagDescription = "Enable :ref:`newtype deriving <newtype-deriving>`." , flagType = DynamicFlag , flagReverse = "-XNoGeneralizedNewtypeDeriving" , flagSince = "6.8.1" } , flag { flagName = "-XGenerics" , flagDescription = "Deprecated, does nothing. No longer enables "++ ":ref:`generic classes <generic-classes>`. See also GHC's support "++ "for :ref:`generic programming <generic-programming>`." , flagType = DynamicFlag , flagReverse = "-XNoGenerics" , flagSince = "6.8.1" } , flag { flagName = "-XImplicitParams" , flagDescription = "Enable :ref:`Implicit Parameters <implicit-parameters>`. "++ "Implies ``-XFlexibleContexts`` and ``-XFlexibleInstances``." , flagType = DynamicFlag , flagReverse = "-XNoImplicitParams" , flagSince = "6.8.1" } , flag { flagName = "-XNoImplicitPrelude" , flagDescription = "Don't implicitly ``import Prelude``. "++ "Implied by ``-XRebindableSyntax``." , flagType = DynamicFlag , flagReverse = "-XImplicitPrelude" , flagSince = "6.8.1" } , flag { flagName = "-XImpredicativeTypes" , flagDescription = "Enable :ref:`impredicative types <impredicative-polymorphism>`. "++ "Implies ``-XRankNTypes``." , flagType = DynamicFlag , flagReverse = "-XNoImpredicativeTypes" , flagSince = "6.10.1" } , flag { flagName = "-XIncoherentInstances" , flagDescription = "Enable :ref:`incoherent instances <instance-overlap>`. "++ "Implies ``-XOverlappingInstances``." , flagType = DynamicFlag , flagReverse = "-XNoIncoherentInstances" , flagSince = "6.8.1" } , flag { flagName = "-XTypeFamilyDependencies" , flagDescription = "Enable :ref:`injective type families <injective-ty-fams>`. "++ "Implies ``-XTypeFamilies``." , flagType = DynamicFlag , flagReverse = "-XNoTypeFamilyDependencies" , flagSince = "8.0.1" } , flag { flagName = "-XInstanceSigs" , flagDescription = "Enable :ref:`instance signatures <instance-sigs>`." , flagType = DynamicFlag , flagReverse = "-XNoInstanceSigs" , flagSince = "7.10.1" } , flag { flagName = "-XInterruptibleFFI" , flagDescription = "Enable interruptible FFI." , flagType = DynamicFlag , flagReverse = "-XNoInterruptibleFFI" , flagSince = "7.2.1" } , flag { flagName = "-XKindSignatures" , flagDescription = "Enable :ref:`kind signatures <kinding>`. "++ "Implied by ``-XTypeFamilies`` and ``-XPolyKinds``." , flagType = DynamicFlag , flagReverse = "-XNoKindSignatures" , flagSince = "6.8.1" } , flag { flagName = "-XLambdaCase" , flagDescription = "Enable :ref:`lambda-case expressions <lambda-case>`." , flagType = DynamicFlag , flagReverse = "-XNoLambdaCase" , flagSince = "7.6.1" } , flag { flagName = "-XLiberalTypeSynonyms" , flagDescription = "Enable :ref:`liberalised type synonyms <type-synonyms>`." , flagType = DynamicFlag , flagReverse = "-XNoLiberalTypeSynonyms" , flagSince = "6.8.1" } , flag { flagName = "-XMagicHash" , flagDescription = "Allow ``#`` as a :ref:`postfix modifier on identifiers <magic-hash>`." , flagType = DynamicFlag , flagReverse = "-XNoMagicHash" , flagSince = "6.8.1" } , flag { flagName = "-XMonadComprehensions" , flagDescription = "Enable :ref:`monad comprehensions <monad-comprehensions>`." , flagType = DynamicFlag , flagReverse = "-XNoMonadComprehensions" , flagSince = "7.2.1" } , flag { flagName = "-XMonoLocalBinds" , flagDescription = "Enable :ref:`do not generalise local bindings <mono-local-binds>`. "++ "Implied by ``-XTypeFamilies`` and ``-XGADTs``." , flagType = DynamicFlag , flagReverse = "-XNoMonoLocalBinds" , flagSince = "6.12.1" } , flag { flagName = "-XNoMonomorphismRestriction" , flagDescription = "Disable the :ref:`monomorphism restriction <monomorphism>`." , flagType = DynamicFlag , flagReverse = "-XMonomorphismRestriction" , flagSince = "6.8.1" } , flag { flagName = "-XMultiParamTypeClasses" , flagDescription = "Enable :ref:`multi parameter type classes "++ "<multi-param-type-classes>`. Implied by "++ "``-XFunctionalDependencies``." , flagType = DynamicFlag , flagReverse = "-XNoMultiParamTypeClasses" , flagSince = "6.8.1" } , flag { flagName = "-XMultiWayIf" , flagDescription = "Enable :ref:`multi-way if-expressions <multi-way-if>`." , flagType = DynamicFlag , flagReverse = "-XNoMultiWayIf" , flagSince = "7.6.1" } , flag { flagName = "-XNamedFieldPuns" , flagDescription = "Enable :ref:`record puns <record-puns>`." , flagType = DynamicFlag , flagReverse = "-XNoNamedFieldPuns" , flagSince = "6.10.1" } , flag { flagName = "-XNamedWildCards" , flagDescription = "Enable :ref:`named wildcards <named-wildcards>`." , flagType = DynamicFlag , flagReverse = "-XNoNamedWildCards" , flagSince = "7.10.1" } , flag { flagName = "-XNegativeLiterals" , flagDescription = "Enable support for :ref:`negative literals <negative-literals>`." , flagType = DynamicFlag , flagReverse = "-XNoNegativeLiterals" , flagSince = "7.8.1" } , flag { flagName = "-XNoNPlusKPatterns" , flagDescription = "Disable support for ``n+k`` patterns." , flagType = DynamicFlag , flagReverse = "-XNPlusKPatterns" , flagSince = "6.12.1" } , flag { flagName = "-XNullaryTypeClasses" , flagDescription = "Deprecated, does nothing. :ref:`nullary (no parameter) type "++ "classes <nullary-type-classes>` are now enabled using "++ "``-XMultiParamTypeClasses``." , flagType = DynamicFlag , flagReverse = "-XNoNullaryTypeClasses" , flagSince = "7.8.1" } , flag { flagName = "-XNumDecimals" , flagDescription = "Enable support for 'fractional' integer literals." , flagType = DynamicFlag , flagReverse = "-XNoNumDecimals" , flagSince = "7.8.1" } , flag { flagName = "-XOverlappingInstances" , flagDescription = "Enable :ref:`overlapping instances <instance-overlap>`." , flagType = DynamicFlag , flagReverse = "-XNoOverlappingInstances" , flagSince = "6.8.1" } , flag { flagName = "-XOverloadedLists" , flagDescription = "Enable :ref:`overloaded lists <overloaded-lists>`." , flagType = DynamicFlag , flagReverse = "-XNoOverloadedLists" , flagSince = "7.8.1" } , flag { flagName = "-XOverloadedStrings" , flagDescription = "Enable :ref:`overloaded string literals <overloaded-strings>`." , flagType = DynamicFlag , flagReverse = "-XNoOverloadedStrings" , flagSince = "6.8.1" } , flag { flagName = "-XPackageImports" , flagDescription = "Enable :ref:`package-qualified imports <package-imports>`." , flagType = DynamicFlag , flagReverse = "-XNoPackageImports" , flagSince = "6.10.1" } , flag { flagName = "-XParallelArrays" , flagDescription = "Enable parallel arrays. Implies ``-XParallelListComp``." , flagType = DynamicFlag , flagReverse = "-XNoParallelArrays" , flagSince = "7.4.1" } , flag { flagName = "-XParallelListComp" , flagDescription = "Enable :ref:`parallel list comprehensions "++ "<parallel-list-comprehensions>`. "++ "Implied by ``-XParallelArrays``." , flagType = DynamicFlag , flagReverse = "-XNoParallelListComp" , flagSince = "6.8.1" } , flag { flagName = "-XPartialTypeSignatures" , flagDescription = "Enable :ref:`partial type signatures <partial-type-signatures>`." , flagType = DynamicFlag , flagReverse = "-XNoPartialTypeSignatures" , flagSince = "7.10.1" } , flag { flagName = "-XPatternGuards" , flagDescription = "Enable :ref:`pattern guards <pattern-guards>`." , flagType = DynamicFlag , flagReverse = "-XNoPatternGuards" , flagSince = "6.8.1" } , flag { flagName = "-XPatternSynonyms" , flagDescription = "Enable :ref:`pattern synonyms <pattern-synonyms>`." , flagType = DynamicFlag , flagReverse = "-XNoPatternSynonyms" , flagSince = "7.10.1" } , flag { flagName = "-XPolyKinds" , flagDescription = "Enable :ref:`kind polymorphism <kind-polymorphism>`. "++ "Implies ``-XKindSignatures``." , flagType = DynamicFlag , flagReverse = "-XNoPolyKinds" , flagSince = "7.4.1" } , flag { flagName = "-XPolymorphicComponents" , flagDescription = "Enable :ref:`polymorphic components for data constructors "++ "<universal-quantification>`. Synonym for ``-XRankNTypes``." , flagType = DynamicFlag , flagReverse = "-XNoPolymorphicComponents" , flagSince = "6.8.1" } , flag { flagName = "-XPostfixOperators" , flagDescription = "Enable :ref:`postfix operators <postfix-operators>`." , flagType = DynamicFlag , flagReverse = "-XNoPostfixOperators" , flagSince = "7.10.1" } , flag { flagName = "-XQuasiQuotes" , flagDescription = "Enable :ref:`quasiquotation <th-quasiquotation>`." , flagType = DynamicFlag , flagReverse = "-XNoQuasiQuotes" , flagSince = "6.10.1" } , flag { flagName = "-XRank2Types" , flagDescription = "Enable :ref:`rank-2 types <universal-quantification>`. "++ "Synonym for ``-XRankNTypes``." , flagType = DynamicFlag , flagReverse = "-XNoRank2Types" , flagSince = "6.8.1" } , flag { flagName = "-XRankNTypes" , flagDescription = "Enable :ref:`rank-N types <universal-quantification>`. "++ "Implied by ``-XImpredicativeTypes``." , flagType = DynamicFlag , flagReverse = "-XNoRankNTypes" , flagSince = "6.8.1" } , flag { flagName = "-XRebindableSyntax" , flagDescription = "Employ :ref:`rebindable syntax <rebindable-syntax>`. "++ "Implies ``-XNoImplicitPrelude``." , flagType = DynamicFlag , flagReverse = "-XNoRebindableSyntax" , flagSince = "7.0.1" } , flag { flagName = "-XRecordWildCards" , flagDescription = "Enable :ref:`record wildcards <record-wildcards>`. "++ "Implies ``-XDisambiguateRecordFields``." , flagType = DynamicFlag , flagReverse = "-XNoRecordWildCards" , flagSince = "6.8.1" } , flag { flagName = "-XRecursiveDo" , flagDescription = "Enable :ref:`recursive do (mdo) notation <recursive-do-notation>`." , flagType = DynamicFlag , flagReverse = "-XNoRecursiveDo" , flagSince = "6.8.1" } , flag { flagName = "-XRelaxedPolyRec" , flagDescription = "*(deprecated)* Relaxed checking for :ref:`mutually-recursive "++ "polymorphic functions <typing-binds>`." , flagType = DynamicFlag , flagReverse = "-XNoRelaxedPolyRec" , flagSince = "6.8.1" } , flag { flagName = "-XRoleAnnotations" , flagDescription = "Enable :ref:`role annotations <role-annotations>`." , flagType = DynamicFlag , flagReverse = "-XNoRoleAnnotations" , flagSince = "7.10.1" } , flag { flagName = "-XSafe" , flagDescription = "Enable the :ref:`Safe Haskell <safe-haskell>` Safe mode." , flagType = DynamicFlag , flagSince = "7.2.1" } , flag { flagName = "-XScopedTypeVariables" , flagDescription = "Enable :ref:`lexically-scoped type variables "++ "<scoped-type-variables>`." , flagType = DynamicFlag , flagReverse = "-XNoScopedTypeVariables" , flagSince = "6.8.1" } , flag { flagName = "-XStandaloneDeriving" , flagDescription = "Enable :ref:`standalone deriving <stand-alone-deriving>`." , flagType = DynamicFlag , flagReverse = "-XNoStandaloneDeriving" , flagSince = "6.8.1" } , flag { flagName = "-XStrictData" , flagDescription = "Enable :ref:`default strict datatype fields <strict-data>`." , flagType = DynamicFlag , flagReverse = "-XNoStrictData" } , flag { flagName = "-XTemplateHaskell" , flagDescription = "Enable :ref:`Template Haskell <template-haskell>`." , flagType = DynamicFlag , flagReverse = "-XNoTemplateHaskell" , flagSince = "6.8.1" } , flag { flagName = "-XTemplateHaskellQuotes" , flagDescription = "Enable quotation subset of "++ ":ref:`Template Haskell <template-haskell>`." , flagType = DynamicFlag , flagReverse = "-XNoTemplateHaskellQuotes" , flagSince = "8.0.1" } , flag { flagName = "-XNoTraditionalRecordSyntax" , flagDescription = "Disable support for traditional record syntax "++ "(as supported by Haskell 98) ``C {f = x}``" , flagType = DynamicFlag , flagReverse = "-XTraditionalRecordSyntax" , flagSince = "7.4.1" } , flag { flagName = "-XTransformListComp" , flagDescription = "Enable :ref:`generalised list comprehensions "++ "<generalised-list-comprehensions>`." , flagType = DynamicFlag , flagReverse = "-XNoTransformListComp" , flagSince = "6.10.1" } , flag { flagName = "-XTrustworthy" , flagDescription = "Enable the :ref:`Safe Haskell <safe-haskell>` Trustworthy mode." , flagType = DynamicFlag , flagSince = "7.2.1" } , flag { flagName = "-XTupleSections" , flagDescription = "Enable :ref:`tuple sections <tuple-sections>`." , flagType = DynamicFlag , flagReverse = "-XNoTupleSections" , flagSince = "7.10.1" } , flag { flagName = "-XTypeFamilies" , flagDescription = "Enable :ref:`type families <type-families>`. "++ "Implies ``-XExplicitNamespaces``, ``-XKindSignatures``, "++ "and ``-XMonoLocalBinds``." , flagType = DynamicFlag , flagReverse = "-XNoTypeFamilies" , flagSince = "6.8.1" } , flag { flagName = "-XTypeOperators" , flagDescription = "Enable :ref:`type operators <type-operators>`. "++ "Implies ``-XExplicitNamespaces``." , flagType = DynamicFlag , flagReverse = "-XNoTypeOperators" , flagSince = "6.8.1" } , flag { flagName = "-XTypeSynonymInstances" , flagDescription = "Enable :ref:`type synonyms in instance heads "++ "<flexible-instance-head>`. Implied by ``-XFlexibleInstances``." , flagType = DynamicFlag , flagReverse = "-XNoTypeSynonymInstances" , flagSince = "6.8.1" } , flag { flagName = "-XUnboxedTuples" , flagDescription = "Enable :ref:`unboxed tuples <unboxed-tuples>`." , flagType = DynamicFlag , flagReverse = "-XNoUnboxedTuples" , flagSince = "6.8.1" } , flag { flagName = "-XUndecidableInstances" , flagDescription = "Enable :ref:`undecidable instances <undecidable-instances>`." , flagType = DynamicFlag , flagReverse = "-XNoUndecidableInstances" , flagSince = "6.8.1" } , flag { flagName = "-XUnicodeSyntax" , flagDescription = "Enable :ref:`unicode syntax <unicode-syntax>`." , flagType = DynamicFlag , flagReverse = "-XNoUnicodeSyntax" , flagSince = "6.8.1" } , flag { flagName = "-XUnliftedFFITypes" , flagDescription = "Enable unlifted FFI types." , flagType = DynamicFlag , flagReverse = "-XNoUnliftedFFITypes" , flagSince = "6.8.1" } , flag { flagName = "-XUnsafe" , flagDescription = "Enable :ref:`Safe Haskell <safe-haskell>` Unsafe mode." , flagType = DynamicFlag , flagSince = "7.4.1" } , flag { flagName = "-XViewPatterns" , flagDescription = "Enable :ref:`view patterns <view-patterns>`." , flagType = DynamicFlag , flagReverse = "-XNoViewPatterns" , flagSince = "6.10.1" } ]
gridaphobe/ghc
utils/mkUserGuidePart/Options/Language.hs
Haskell
bsd-3-clause
29,509
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DataKinds #-} module Main where import SubHask import SubHask.Algebra.Array import SubHask.Algebra.Group import SubHask.Algebra.Container import SubHask.Algebra.Logic import SubHask.Algebra.Metric import SubHask.Algebra.Parallel import SubHask.Algebra.Vector import SubHask.Compatibility.ByteString import SubHask.Compatibility.Containers import SubHask.TemplateHaskell.Deriving import SubHask.TemplateHaskell.Test import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.Framework.Runners.Console import Test.Framework.Runners.Options -------------------------------------------------------------------------------- main = defaultMainWithOpts [ testGroup "simple" [ testGroup "numeric" [ $( mkSpecializedClassTests [t| Int |] [''Enum,''Ring, ''Bounded, ''Metric] ) , $( mkSpecializedClassTests [t| Integer |] [''Enum,''Ring, ''Lattice, ''Metric] ) , $( mkSpecializedClassTests [t| Rational |] [''Ord,''Ring, ''Lattice, ''Metric] ) , $( mkSpecializedClassTests [t| Float |] [''Bounded] ) , $( mkSpecializedClassTests [t| Double |] [''Bounded] ) , testGroup "transformers" [ $( mkSpecializedClassTests [t| NonNegative Int |] [''Enum,''Rig, ''Bounded, ''Metric] ) , $( mkSpecializedClassTests [t| Z 57 |] [''Ring] ) , $( mkSpecializedClassTests [t| NonNegative (Z 57) |] [''Rig] ) ] ] , testGroup "vector" [ $( mkSpecializedClassTests [t| SVector 0 Int |] [ ''Module ] ) , $( mkSpecializedClassTests [t| SVector 1 Int |] [ ''Module ] ) , $( mkSpecializedClassTests [t| SVector 2 Int |] [ ''Module ] ) , $( mkSpecializedClassTests [t| SVector 19 Int |] [ ''Module ] ) , $( mkSpecializedClassTests [t| SVector 1001 Int |] [ ''Module ] ) , $( mkSpecializedClassTests [t| SVector "dyn" Int |] [ ''Module ] ) , $( mkSpecializedClassTests [t| UVector "dyn" Int |] [ ''Module ] ) ] , testGroup "non-numeric" [ $( mkSpecializedClassTests [t| Bool |] [''Enum,''Boolean] ) , $( mkSpecializedClassTests [t| Char |] [''Enum,''Bounded] ) , $( mkSpecializedClassTests [t| Goedel |] [''Heyting] ) , $( mkSpecializedClassTests [t| H3 |] [''Heyting] ) , $( mkSpecializedClassTests [t| K3 |] [''Bounded] ) , testGroup "transformers" [ $( mkSpecializedClassTests [t| Boolean2Ring Bool |] [''Ring] ) ] ] ] , testGroup "objects" [ $( mkSpecializedClassTests [t| Labeled' Int Int |] [ ''Action,''Ord,''Metric ] ) ] , testGroup "arrays" [ $( mkSpecializedClassTests [t| BArray Char |] [ ''Foldable,''MinBound,''IxContainer ] ) , $( mkSpecializedClassTests [t| UArray Char |] [ ''Foldable,''MinBound,''IxContainer ] ) , $( mkSpecializedClassTests [t| UArray (UVector "dyn" Float) |] [ ''Foldable,''IxContainer ] ) , $( mkSpecializedClassTests [t| UArray (Labeled' (UVector "dyn" Float) Int) |] [ ''Foldable,''IxContainer ] ) ] , testGroup "containers" [ $( mkSpecializedClassTests [t| [] Char |] [ ''Foldable,''MinBound,''Partitionable ] ) , $( mkSpecializedClassTests [t| Set Char |] [ ''Foldable,''MinBound ] ) , $( mkSpecializedClassTests [t| Seq Char |] [ ''Foldable,''MinBound,''Partitionable ] ) , $( mkSpecializedClassTests [t| Map Int Int |] [ ''MinBound, ''IxConstructible ] ) , $( mkSpecializedClassTests [t| Map' Int Int |] [ ''MinBound, ''IxContainer ] ) , $( mkSpecializedClassTests [t| IntMap Int |] [ ''MinBound, ''IxContainer ] ) , $( mkSpecializedClassTests [t| IntMap' Int |] [ ''MinBound, ''IxContainer ] ) , $( mkSpecializedClassTests [t| ByteString Char |] [ ''Foldable,''MinBound,''Partitionable ] ) , testGroup "transformers" [ $( mkSpecializedClassTests [t| Lexical [Char] |] [''Ord,''MinBound] ) , $( mkSpecializedClassTests [t| ComponentWise [Char] |] [''Lattice,''MinBound] ) , $( mkSpecializedClassTests [t| Hamming [Char] |] [''Metric] ) , $( mkSpecializedClassTests [t| Levenshtein [Char] |] [''Metric] ) ] , testGroup "metric" -- [ $( mkSpecializedClassTests [t| Ball Int |] [''Eq,''Container] ) -- , $( mkSpecializedClassTests [t| Ball (Hamming [Char]) |] [''Eq,''Container] ) [ $( mkSpecializedClassTests [t| Box Int |] [''Eq,''Container] ) , $( mkSpecializedClassTests [t| Box (ComponentWise [Char]) |] [''Eq,''Container] ) ] ] ] $ RunnerOptions { ropt_threads = Nothing , ropt_test_options = Nothing , ropt_test_patterns = Nothing , ropt_xml_output = Nothing , ropt_xml_nested = Nothing , ropt_color_mode = Just ColorAlways , ropt_hide_successes = Just True , ropt_list_only = Just True } -------------------------------------------------------------------------------- -- orphan instances needed for compilation instance (Show a, Show b) => Show (a -> b) where show _ = "function"
cdepillabout/subhask
test/TestSuite.hs
Haskell
bsd-3-clause
5,624
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module HipChat.Types.API where import Data.Text (Text) import Servant.API import HipChat.Types.Auth import HipChat.Types.Common import HipChat.Types.Extensions import HipChat.Types.RoomAddonUIUpdateRequest import HipChat.Types.Rooms import HipChat.Types.User type HipChatAPI = TokenAuth( SendMessage :<|> SendNotification :<|> CreateRoom :<|> GetRoomStatistics :<|> ViewUser :<|> CreateWebhook :<|> GetAllMembers :<|> RoomAddonUIUpdate :<|> GenerateToken) type GenerateToken = "v2" :> "oauth" :> "token" :> ReqBody '[FormUrlEncoded] TokenRequest :> BasicAuth "oauth" Int :> Post '[JSON] TokenResponse type ViewUser = "v2" :> "user" :> Capture "id_or_email" Text :> Get '[JSON] User -------------------------------------------------------------------------------- -- -- Rooms type CreateRoom = "v2" :> "room" :> ReqBody '[JSON] CreateRoomRequest :> Post '[JSON] CreateRoomResponse type CreateWebhook = "v2" :> "room" :> Capture "room_id_or_name" IdOrName :> "extension" :> "webhook" :> Capture "key" Text :> ReqBody '[JSON] Webhook :> Put '[JSON] CreateWebhookResponse type SendMessage = "v2" :> "room" :> Capture "room" Text :> "message" :> ReqBody '[JSON] Message :> Post '[JSON] SendMessageResponse type SendNotification = "v2" :> "room" :> Capture "room" Text :> "notification" :> ReqBody '[JSON] SendNotificationRequest :> PostNoContent '[JSON] NoContent type GetRoomStatistics = "v2" :> "room" :> Capture "room" Text :> "statistics" :> Get '[JSON] RoomStatistics type GetAllMembers = "v2" :> "room" :> Capture "room_id_or_name" IdOrName :> "member" :> QueryParam "start-index" Int :> QueryParam "max-results" Int :> Get '[JSON] GetAllMembersResponse type GetAllRooms = "v2" :> "room" :> QueryParam "start-index" Int :> QueryParam "max-results" Int :> QueryParam "include-private" Bool :> QueryParam "include-archived" Bool :> Get '[JSON] GetAllRoomsResponse -------------------------------------------------------------------------------- -- Addons type RoomAddonUIUpdate = "v2" :> "addon" :> "ui" :> "room" :> Capture "room_id" Int :> ReqBody '[JSON] RoomAddonUIUpdateRequest :> PostNoContent '[JSON] NoContent
oswynb/hipchat-hs
lib/HipChat/Types/API.hs
Haskell
bsd-3-clause
2,422
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} module DataFlow.Graphviz.Renderer ( renderGraphviz ) where import Data.Char import Data.List.Utils import Text.Printf import DataFlow.PrettyRenderer import DataFlow.Graphviz convertNewline :: String -> String convertNewline = replace "\n" "<br/>" class Renderable t where render :: t -> Renderer () instance Renderable Attr where render (Attr i1 i2) = writeln $ printf "%s = %s;" i1 (convertNewline i2) instance Renderable AttrList where render = mapM_ render instance Renderable Port where render (Port (Just id') c) = write $ printf "%s:%s" (show id') (map toLower $ show c) render (Port Nothing c) = write $ map toLower $ show c instance Renderable NodeID where render (NodeID id' (Just port)) = do write id' write ":" render port render (NodeID id' Nothing) = write id' instance Renderable Subgraph where render (Subgraph id' []) = writeln $ printf "subgraph %s {}" id' render (Subgraph id' stmts) = do writeln $ printf "subgraph %s {" id' withIndent $ render stmts writeln "}" instance Renderable EdgeOperator where render Arrow = write " -> " render Line = write " -- " instance Renderable EdgeOperand where render (IDOperand nodeId) = render nodeId render (SubgraphOperand sg) = render sg instance Renderable EdgeExpr where render (EdgeExpr o1 operator o2) = do render o1 render operator render o2 instance Renderable AttrStmtType where render = write . map toLower . show inBrackets :: Renderer () -> Renderer () inBrackets r = do writeln " [" withIndent r writeln "]" instance Renderable Stmt where render (NodeStmt id' []) = do write id' writeln "" render (NodeStmt id' attrs) = do write id' inBrackets $ render attrs render (EdgeStmt expr []) = do render expr writeln ";" render (EdgeStmt expr attrs) = do render expr inBrackets $ render attrs render (AttrStmt t []) = do render t writeln " []" render (AttrStmt t attrs) = do render t inBrackets $ render attrs render (EqualsStmt i1 i2) = do write i1 write " = " write i2 writeln ";" render (SubgraphStmt sg) = render sg instance Renderable StmtList where render = mapM_ render instance Renderable Graph where render (Digraph id' stmts) = do writeln $ printf "digraph %s {" id' withIndent $ render stmts writeln "}" renderGraphviz :: Graph -> String renderGraphviz = renderWithIndent . render
sonyxperiadev/dataflow
src/DataFlow/Graphviz/Renderer.hs
Haskell
bsd-3-clause
2,530
module Day5 where import Data.List (group, isInfixOf, tails) threeVowels :: String -> Bool threeVowels = (>= 3) . length . filter (`elem` "aeiouAEIOU") doubleLetter :: String -> Bool doubleLetter = any ((>1) . length) . group noBadStrings :: String -> Bool noBadStrings input = all (not . flip isInfixOf input) badstrings where badstrings = ["ab", "cd", "pq", "xy"] hasPalindromeTriplet :: String -> Bool hasPalindromeTriplet = any isPalindrome . triplets where isPalindrome = (==) <*> reverse triplets input = take (length input - 3 + 1) $ map (take 3) $ tails input repeatedPair :: String -> Bool repeatedPair = any repeatedPrefixPair . takeWhile ((>=4) . length) . tails where repeatedPrefixPair input = take 2 input `isInfixOf` drop 2 input applyRules :: [String -> Bool] -> String -> Bool applyRules rules string = and $ sequence rules string isNice :: String -> Bool isNice = applyRules [threeVowels, doubleLetter, noBadStrings] isNicer :: String -> Bool isNicer = applyRules [hasPalindromeTriplet, repeatedPair] solution :: String -> IO () solution input = do print $ length $ filter isNice (lines input) print $ length $ filter isNicer (lines input)
yarbroughw/advent
src/Day5.hs
Haskell
bsd-3-clause
1,186
module Main where import Network.C10kServer import Network.Salvia.Handler.ColorLog import Network.Salvia.Handler.ExtendedFileSystem import Network.Salvia.Handlers import Network.Salvia.Impl.C10k import System.IO main :: IO () main = start "127.0.0.1" "root@localhost" C10kConfig { initHook = return () , exitHook = \s -> putStrLn ("C10kServer error:" ++ s) , parentStartedHook = return () , startedHook = return () , sleepTimer = 10 , preforkProcessNumber = 200 , threadNumberPerProcess = 200 , portName = "8080" , pidFile = "pid" , user = "sebas" , group = "wheel" } (hDefaultEnv (hExtendedFileSystem "." >> hColorLog stdout)) ()
sebastiaanvisser/salvia-demo
src/ServeDemo.hs
Haskell
bsd-3-clause
813
{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Network.SSH.LoadKeys import Network.SSH.Messages import Network.SSH.Server import Control.Concurrent import Control.Exception import Control.Monad import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Graphics.Vty as Vty import Network ( PortID(..), withSocketsDo, listenOn , accept, Socket ) import System.Directory (getHomeDirectory) import System.Environment import System.FilePath import System.IO ( hClose ) import System.IO.Error ( isIllegalOperation ) import System.Posix.IO ( fdToHandle, closeFd ) import Text.Read (readMaybe) import qualified SetGame import Openpty import UnixTerminalFlags #if MIN_VERSION_base(4,8,0) import System.Exit ( die ) #else import System.Exit ( exitFailure ) die :: String -> IO a die err = hPutStrLn stderr err >> exitFailure #endif main :: IO () main = withSocketsDo $ do args <- getArgs progName <- getProgName let usage = die $ "usage: "++progName++" LISTEN_PORT" port <- case args of [portString] -> do let mPort = readMaybe portString maybe usage return mPort _ -> usage sock <- listenOn (PortNumber $ fromInteger port) sAuth <- loadPrivateKeys "server_keys" home <- getHomeDirectory user <- getEnv "USER" let pubKeys = [home </> ".ssh" </> "authorized_keys"] let creds = [(S8.pack user,pubKeys)] let debugLevel = 1 sshServer (mkServer debugLevel sAuth creds sock) mkServer :: Int -> [ServerCredential] -> [ClientCredential] -> Socket -> Server mkServer debugLevel auths creds sock = Server { sAccept = do (handle',_,_) <- accept sock let h = handle2HandleLike handle' let sh = mkSessionHandlers creds return (sh, h) , sAuthenticationAlgs = auths , sVersion = "SSH_HaLVM_2.0" , sDebugLevel = debugLevel } convertWindowSize :: SshWindowSize -> Winsize convertWindowSize winsize = Winsize { wsRow = fromIntegral $ sshWsRows winsize , wsCol = fromIntegral $ sshWsCols winsize , wsXPixel = fromIntegral $ sshWsX winsize , wsYPixel = fromIntegral $ sshWsY winsize } type ClientCredential = (S.ByteString, [FilePath]) mkSessionHandlers :: [ClientCredential] -> SessionHandlers mkSessionHandlers creds = SessionHandlers { .. } where cDirectTcp _host _port _events _writeback = return False cRequestExec "echo" events writeback = do void (forkIO (echoServer events writeback)) return True cRequestExec _command _events _writeback = return False -- Same as 'exec echo' above, which you access in OpenSSH by running -- @ssh <host> echo@. To access this "echo" subsystem in OpenSSH, -- use @ssh <host> -s echo@. cRequestSubsystem "echo" readEvent writeback = do void (forkIO (echoServer readEvent writeback)) return True cRequestSubsystem _ _ _ = return False cOpenShell term winsize termflags readEvent writeBytes = do (masterFd, slaveFd) <- openpty Nothing (Just (convertWindowSize winsize)) (Just (foldl (\t (key,val) -> setTerminalFlag key val t) defaultTermios termflags)) masterH <- fdToHandle masterFd void $ forkIO $ forever (do out <- S.hGetSome masterH 1024 writeBytes (Just out) ) `finally` writeBytes Nothing `catch` \e -> unless (isIllegalOperation e) (throwIO e) void $ forkIO $ let loop = do event <- readEvent case event of SessionEof -> loop SessionClose -> closeFd slaveFd SessionWinsize winsize' -> do changePtyWinsize masterFd (convertWindowSize winsize') loop SessionData bs -> do S.hPut masterH bs loop SessionRequestResponse{} -> loop in loop let config = Vty.Config { Vty.vmin = Just 1 , Vty.vtime = Just 0 , Vty.mouseMode = Nothing , Vty.bracketedPasteMode = Nothing , Vty.debugLog = Nothing , Vty.inputMap = [] , Vty.inputFd = Just slaveFd , Vty.outputFd = Just slaveFd , Vty.termName = Just (S8.unpack term) } void $ forkIO $ do SetGame.gameMain config hClose masterH return True cAuthHandler = defaultAuthHandler (defaultCheckPw (const $ Just "god")) (defaultLookupPubKeys (\user -> return $ maybe [] id $ lookup user creds)) echoServer :: IO SessionEvent -> (Maybe S.ByteString -> IO ()) -> IO () echoServer readEvent write = loop where loop = do event <- readEvent case event of SessionData xs -> write (Just xs) >> loop SessionEof -> loop SessionClose -> write Nothing SessionWinsize{} -> loop SessionRequestResponse{} -> loop
glguy/ssh-hans
server/Main.hs
Haskell
bsd-3-clause
5,609
------------------------------------------------------------------------------- -- | -- Module : Generator.Printer -- Copyright : (c) 2016 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module Generator.Printer ( module Generator.Printer.Classic , module Generator.Printer.Modern , module Generator.Printer.Version ) where import Generator.Printer.Classic import Generator.Printer.Modern import Generator.Printer.Version
oldmanmike/hs-minecraft-protocol
generate/src/Generator/Printer.hs
Haskell
bsd-3-clause
637
module Evaluator.FreeVars ( renamingFreeVars, inFreeVars, pureHeapFreeVars, pureHeapOpenFreeVars, stackFreeVars, stackFrameFreeVars, stateFreeVars ) where import Evaluator.Syntax import Core.FreeVars import Core.Renaming import Renaming import Utilities import qualified Data.Map as M import qualified Data.Set as S renamingFreeVars :: Renaming -> FreeVars -> FreeVars renamingFreeVars rn fvs = S.map (rename rn) fvs inFreeVars :: (a -> FreeVars) -> In a -> FreeVars inFreeVars thing_fvs (rn, thing) = renamingFreeVars rn (thing_fvs thing) pureHeapFreeVars :: PureHeap -> (BoundVars, FreeVars) -> FreeVars pureHeapFreeVars h (bvs, fvs) = fvs' S.\\ bvs' where (bvs', fvs') = pureHeapOpenFreeVars h (bvs, fvs) pureHeapOpenFreeVars :: PureHeap -> (BoundVars, FreeVars) -> (BoundVars, FreeVars) pureHeapOpenFreeVars = flip $ M.foldWithKey (\x' in_e (bvs, fvs) -> (S.insert x' bvs, fvs `S.union` inFreeVars taggedTermFreeVars in_e)) stackFreeVars :: Stack -> FreeVars -> (BoundVars, FreeVars) stackFreeVars k fvs = (S.unions *** (S.union fvs . S.unions)) . unzip . map (stackFrameFreeVars . tagee) $ k stackFrameFreeVars :: StackFrame -> (BoundVars, FreeVars) stackFrameFreeVars kf = case kf of Apply x' -> (S.empty, S.singleton x') Scrutinise in_alts -> (S.empty, inFreeVars taggedAltsFreeVars in_alts) PrimApply _ in_vs in_es -> (S.empty, S.unions (map (inFreeVars taggedValueFreeVars) in_vs) `S.union` S.unions (map (inFreeVars taggedTermFreeVars) in_es)) Update x' -> (S.singleton x', S.empty) stateFreeVars :: State -> FreeVars stateFreeVars (Heap h _, k, in_e) = pureHeapFreeVars h (stackFreeVars k (inFreeVars taggedTermFreeVars in_e))
batterseapower/supercompilation-by-evaluation
Evaluator/FreeVars.hs
Haskell
bsd-3-clause
1,724
module Process.PeerManager ( start ) where {- import Control.Applicative import Control.Concurrent import Control.Concurrent.STM import Control.DeepSeq import Control.Monad.State import Control.Monad.Reader import Data.Array import qualified Data.Map as M import qualified Network.Socket as Sock import System.Log.Logger import Channels import Process import Process.Peer as Peer import Process.ChokeMgr hiding (start) import Process.FS hiding (start) import Process.PieceMgr hiding (start) import Process.Status hiding (start) import Protocol.Wire import Torrent hiding (infoHash) -} numPeers :: Int numPeers = 40 data PConf = PConf { cRateTVar :: RateTVar , cPeerManagerChan :: PeerManagerChannel , cChokeManagerChan :: ChokeMgrChannel , cPeerEventChannel :: PeerEventChannel } data PState = PState , sPeerId :: PeerId , sPeerQueue :: [(InfoHash, Peer)] , sActivePeers :: M.Map ThreadId PeerChannel , sChanManageMap :: M.Map InfoHash TorrentLocal } instance Logging PConf where logName _ = "Process.PeerManager" start :: PeerId -> RateTVar -> PeerManagerChannel -> IO ThreadId start peerId rateTV peerChan = do mgrC <- newTChanIO let conf = PConf rateTV peerChan chokeChan state = PState peerId [] M.empty M.empty spawnProcess conf state (catchProcess loop (return ())) where loop = do peerEventChan <- asks cPeerEventChan peerManagerChan <- asks cPeerManagerChan event <- liftIO . atomically $ (readTChan peerEventChan >>= return . Left) `orElse` (readTChan peerManagerChan >>= return . Right) case event of Left msg -> peerEvent msg Right msg -> incomingPeers msg fillPeers loop fillPeers :: Process PConf PState () fillPeers = do count <- M.size `fmap` gets sActivePeers when (count < numPeers) $ do let addCount = numPeers - count debugP $ "Подключаем новых " ++ show addCount ++ " пиров" queue <- gets sPeerQueue let (peers, rest) = splitAt addCount queue mapM_ addPeer peers modify (\state -> state { sPeerQueue = rest }) addPeer :: (InfoHash, Peer) -> Process PConf PState ThreadId addPeer (infoHash, Peer addr) = do peerId <- gets sPeerId -- pool <- asks cPeerPool mgrC <- asks mgrCh cm <- gets cChanManageMap rateTV <- asks cRateTV liftIO $ connect (addr, peerId, infoHash) pool mgrC rateTV cm incomingPeers :: PeerManagerMessage -> Process PConf PState () incomingPeers msg = case msg of PeersFromTracker infoHash peers -> do debugP "Добавление новых пиров в очередь" modify (\s -> s { sPeerQueue = (map (infohash,) peers) ++ sPeerQueue s }) NewIncoming conn@(sock, _) -> do size <- M.size `fmap` gets peers if size < numPeers then do debugP "Подключаем новые пиры" _ <- addIncoming conn return () else do debugP "Слишком много активных пиров, закрываем" liftIO $ Sock.sClose sock NewTorrent infoHash torrent -> do modify (\s -> s { sChanManageMap = M.insert infoHash torrent (sChanManageMap s) }) StopTorrent _ih -> do errorP "Остановка торрента не реализована" peerEvent :: PeerMessage -> Process PConf PState () peerEvent msg = case msg of Connect infoHash tid chan -> newPeer ih tid chan Disconnect tid -> removePeer tid where newPeer infoHash tid chan = do debugP $ "Подключаем пир " ++ show tid chockChan <- asks chokeMgrCh liftIO . atomically $ writeTChan chockChan (AddPeer infoHash tid chan) peers <- M.insert tid chan <$> gets sActivePeers modify (\s -> s { sActivePeers = peers }) removePeer threadId = do debugP $ "Отключаем пир " ++ show threadId chockChan <- asks cChokeManagerChan liftIO . atomically $ writeTChan chockChan (RemovePeer threadId) peers <- M.delete threadId <$> gets sActivePeers modify (\s -> s { sActivePeers = peers }) addIncoming :: (Sock.Socket, Sock.SockAddr) -> Process CF ST ThreadId addIncoming conn = do ppid <- gets peerId pool <- asks peerPool mgrC <- asks mgrCh v <- asks chokeRTV cm <- gets cmMap liftIO $ acceptor conn pool ppid mgrC v cm type ConnectRecord = (SockAddr, PeerId, InfoHash) connect :: ConnectRecord -> PeerChannel -> RateTVar -> ChanManageMap -> IO ThreadId connect (addr, peerId, infoHash) peeChan rateTV cmap = forkIO connector where connector = do sock <- socket AF_INET Stream defaultProtocol debugP $ "Соединяюсь с " ++ show addr connect sock addr debugP "Соединение установленно, рукопожатие" r <- initiateHandshake sock peerId infoHash case r of Left err -> do debugP $ "Не удалось соединится с " ++ show addr ++ ". Ошибка:" ++ err) return () Right (caps, himPeerId, himInfoHash) -> do debugP "Входим в работчий режис с " ++ show addr let tc = case M.lookup himInfoHash cmap of Just x -> x Nothing -> error "Impossible" children <- Peer.start sock caps mgrC rtv (tcPcMgrCh tc) (tcFSCh tc) (tcStatTV tc) (tcPM tc) (succ . snd . bounds $ tcPM tc) ihsh return () acceptor :: (Sock.Socket, Sock.SockAddr) -> SupervisorChannel -> PeerId -> MgrChannel -> RateTVar -> ChanManageMap -> IO ThreadId acceptor (s,sa) pool pid mgrC rtv cmmap = forkIO (connector >> return ()) where ihTst k = M.member k cmmap connector = {-# SCC "acceptor" #-} do debugLog "Handling incoming connection" r <- receiveHandshake s pid ihTst debugLog "RecvHandshake run" case r of Left err -> do debugLog ("Incoming Peer handshake failure with " ++ show sa ++ ", error: " ++ err) return() Right (caps, _rpid, ih) -> do debugLog "entering peerP loop code" let tc = case M.lookup ih cmmap of Nothing -> error "Impossible, I hope" Just x -> x children <- Peer.start s caps mgrC rtv (tcPcMgrCh tc) (tcFSCh tc) (tcStatTV tc) (tcPM tc) (succ . snd . bounds $ tcPM tc) ih atomically $ writeTChan pool $ SpawnNew (Supervisor $ allForOne "PeerSup" children) return () debugLog = debugM "Process.PeerMgr.acceptor"
artems/htorr
src/Process/PeerManager.hs
Haskell
bsd-3-clause
7,426
{-# LANGUAGE StandaloneDeriving #-} module Web.Rest.HTTP ( runRestT,Hostname,Port,RestError(..) ) where import Web.Rest.Internal ( RestT,RestF(Rest),Method(..), Request(..),Response(..)) import Network.HTTP ( simpleHTTP,mkHeader,lookupHeader, HeaderName(HdrAccept,HdrContentType,HdrContentLength)) import qualified Network.HTTP as HTTP ( Request(Request),RequestMethod(..), Response(rspCode,rspHeaders,rspBody)) import Network.URI ( URI(URI),URIAuth(URIAuth)) import Network.Stream (ConnError) import Control.Error ( EitherT,runEitherT,scriptIO, hoistEither,fmapLT) import Control.Monad.Trans.Free (FreeT,FreeF(Pure,Free),runFreeT) import Control.Monad.Trans (lift) import Control.Monad.IO.Class (MonadIO) import Data.Text (Text,unpack,pack) import qualified Data.ByteString as ByteString (length) -- | The host url. For example "example.com". type Hostname = Text -- | The host port. For example 7474. type Port = Int -- | Possible errors when running a 'RestT' with the HTTP backend. data RestError = SimpleHTTPError String | ConnError ConnError deriving instance Show RestError -- | Run the given rest calls against the given hostname and port. Return a 'Left' on -- error. runRestT :: (MonadIO m) => Hostname -> Port -> RestT m a -> m (Either RestError a) runRestT hostname port = runEitherT . interpretRestT hostname port -- | Run the given rest calls against the given hostname and port and fail in the -- 'EitherT' monad. interpretRestT :: (MonadIO m) => Hostname -> Port -> RestT m a -> EitherT RestError m a interpretRestT hostname port restt = do next <- lift (runFreeT restt) case next of Pure result -> return result Free (Rest request continue) -> do let httprequest = HTTP.Request httpuri httpmethod httpheaders httpbody httpuri = URI "http:" (Just uriauth) (unpack (location request)) "" "" uriauth = URIAuth "" (unpack hostname) (":" ++ (show port)) httpmethod = (methodToMethod (method request)) httpheaders = [ mkHeader HdrAccept (unpack (accept request)), mkHeader HdrContentType (unpack (requestType request)), mkHeader HdrContentLength (show (ByteString.length (httpbody)))] httpbody = (requestBody request) resultresponse <- scriptIO (simpleHTTP httprequest) `onFailure` SimpleHTTPError httpresponse <- hoistEither resultresponse `onFailure` ConnError let mayberesponsetype = lookupHeader HdrContentType (HTTP.rspHeaders httpresponse) response = Response (HTTP.rspCode httpresponse) (fmap pack mayberesponsetype) (HTTP.rspBody httpresponse) interpretRestT hostname port (continue response) -- | Convert the package local definition of the http verb to the one used by io-streams. methodToMethod :: Method -> HTTP.RequestMethod methodToMethod GET = HTTP.GET methodToMethod POST = HTTP.POST methodToMethod PUT = HTTP.PUT methodToMethod DELETE = HTTP.DELETE -- | Annotate an error. onFailure :: Monad m => EitherT a m r -> (a -> b) -> EitherT b m r onFailure = flip fmapLT
phischu/haskell-rest
src/Web/Rest/HTTP.hs
Haskell
bsd-3-clause
3,350
{-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE CPP #-} module Dixi.API where import Control.Lens hiding ((.=)) import Data.Aeson import Data.Aeson.Types import Data.Foldable import Data.Text (Text) import Data.Patch (Hunks, HunkStatus (..)) import Data.Proxy import Data.Vector (Vector) import Servant.API import Servant.HTML.Blaze import Text.Blaze.Html.Renderer.Text import Text.Hamlet (Html) #ifdef OLDBASE import Control.Applicative #endif import Dixi.Config import Dixi.Common import Dixi.Page import Dixi.PatchUtils type a :| b = a :<|> b infixr 8 :| infixr 8 |: (|:) :: a -> b -> a :| b (|:) = (:<|>) data PrettyPage = PP Renders Key Version (Page Html) data RawPage = RP Renders Key Version (Page Text) data DiffPage = DP Renders Key Version Version (Page (Hunks Char)) data History = H Renders Key [Page PatchSummary] data NewBody = NB Text (Maybe Text) data RevReq = DR Version Version (Maybe Text) type HistoryAPI = Get '[HTML, JSON] History :| Capture "version" Version :> VersionAPI :| "diff" :> QueryParam "from" Version :> QueryParam "to" Version :> Get '[HTML, JSON] DiffPage :| "revert" :> ReqBody '[FormUrlEncoded, JSON] RevReq :> Post '[HTML, JSON] PrettyPage type VersionAPI = PageViewAPI :| ReqBody '[FormUrlEncoded, JSON] NewBody :> Post '[HTML, JSON] PrettyPage type PageAPI = PageViewAPI :| "history" :> HistoryAPI type PageViewAPI = Get '[HTML, JSON] PrettyPage :| "raw" :> Get '[HTML, JSON] RawPage type Dixi = Capture "page" Key :> PageAPI :| PageAPI instance FromJSON RevReq where parseJSON (Object o) = DR <$> o .: "from" <*> o .: "to" <*> o .:? "comment" parseJSON wat = typeMismatch "Revert" wat instance ToJSON RevReq where toJSON (DR v1 v2 Nothing) = object ["from" .= v1, "to" .= v2] toJSON (DR v1 v2 (Just c)) = object ["from" .= v1, "to" .= v2, "comment" .= c] instance FromJSON NewBody where parseJSON (Object o) = NB <$> o .: "content" <*> o .:? "comment" parseJSON wat = typeMismatch "NewBody" wat instance ToJSON NewBody where toJSON (NB cn Nothing) = object ["content" .= cn ] toJSON (NB cn (Just c)) = object ["content" .= cn, "comment" .= c ] instance ToJSON DiffPage where toJSON (DP (Renders {..}) k v1 v2 p) = object [ "title" .= k , "versions" .= object [ "from" .= v1 , "to" .= v2 ] , "diff" .= map (uncurry hunkToJSON) (p ^. body) ] where hunkToJSON :: Vector Char -> HunkStatus -> Value hunkToJSON v s = object [ "text" .= toList v , "status" .= case s of Inserted -> '+' Deleted -> '-' Replaced -> '~' Unchanged -> ' ' ] instance ToJSON RawPage where toJSON (RP (Renders {..}) k v p) = let tim = renderTime $ p ^. time com = p ^. comment . traverse in object [ "title" .= k , "version" .= v , "time" .= tim , "comment" .= com , "content" .= (p ^. body) ] instance ToJSON PrettyPage where toJSON (PP (Renders {..}) k v p) = let tim = renderTime $ p ^. time com = p ^. comment . traverse in object [ "title" .= k , "version" .= v , "time" .= tim , "comment" .= com , "content" .= renderHtml (p ^. body) ] instance ToJSON History where toJSON (H (Renders {..}) k cs) = object [ "title" .= k , "history" .= zipWith versionToJSON [1 :: Version ..] cs] where versionToJSON v p = let tim = renderTime $ p ^. time com = p ^. comment . traverse (a,b,c) = p ^. body in object [ "version" .= v , "time" .= tim , "comment" .= com , "changes" .= object [ "insertions" .= a , "deletions" .= b, "modifications" .= c] ] dixi :: Proxy Dixi dixi = Proxy
liamoc/dixi
Dixi/API.hs
Haskell
bsd-3-clause
4,474
module Genotype.Processor.KeepColumnNumbers ( process ) where import Control.Applicative (many) import Data.Attoparsec.Text (Parser) import Genotype.Processor (Processor) import qualified Data.Attoparsec.Text as P import qualified Data.Text as T import qualified Data.Text.IO as T import Genotype.Types getColumnList :: T.Text -> IO [Int] getColumnList filename = do cols <- T.readFile $ T.unpack filename either fail return $ P.parseOnly parseColumnList cols parseColumnList :: Parser [Int] parseColumnList = many $ do d <- P.decimal P.skipSpace return d keepColumns :: [Int] -> [a] -> [a] keepColumns = go 0 where go _ _ [] = [] go _ [] remaining = remaining go index (c:cs) (r:rs) | index == c = r : go (succ index) cs rs go index cs (_:rs) = go (succ index) cs rs process :: T.Text -> Processor process filename genos = do cols <- getColumnList filename return . flip map genos $ \g -> g { geno_datums = keepColumns cols $ geno_datums g }
Jonplussed/genotype-parser
src/Genotype/Processor/KeepColumnNumbers.hs
Haskell
bsd-3-clause
998
------------------------------------------------------------------------------ -- | -- Maintainer : Ralf Laemmel, Joost Visser -- Stability : experimental -- Portability : portable -- -- This module is part of 'StrategyLib', a library of functional strategy -- combinators, including combinators for generic traversal. This module -- overloads basic combinators to enable uniform treatment of TU and TP -- strategies. The overloading scheme is motivated in the -- "... Polymorphic Symphony" paper. The names in the present module -- deviate from the paper in that they are postfixed by an "...S" -- in order to rule out name clashes and to avoid labour-intensive -- resolution. The class constraints in this module seem to be outrageous -- but this has to do with a type inferencing bug for class hierarchies -- in hugs. This bug is removed in the October 2002 release. ------------------------------------------------------------------------------ module OverloadingTheme where import Control.Monad import Data.Monoid import StrategyPrelude ------------------------------------------------------------------------------ -- * Unconstrained -- | Overload completely unconstrained strategy combinators class Monad m => Strategy s m where voidS :: s m -> TU () m -- | Sequential composition seqS :: TP m -> s m -> s m -- | Sequential composition with value passing passS :: TU a m -> (a -> s m) -> s m instance Monad m => Strategy TP m where voidS = voidTP seqS = seqTP passS = passTP instance Monad m => Strategy (TU a) m where voidS = voidTU seqS = seqTU passS = passTU -- | Overload apply and adhoc combinators class (Strategy s m, Monad m, Term t) => StrategyApply s m t x | s t -> x where -- | Strategy application applyS :: s m -> t -> m x -- | Dynamic type case adhocS :: s m -> (t -> m x) -> s m instance (Monad m, Term t) => StrategyApply TP m t t where applyS = applyTP adhocS = adhocTP instance (Monad m, Term t) => StrategyApply (TU a) m t a where applyS = applyTU adhocS = adhocTU ------------------------------------------------------------------------------ -- * Involving Monoid, MonadPlus, -- | Overload basic combinators which might involve a monoid class (Monad m, Strategy s m) => StrategyMonoid s m where -- | Identity (success) skipS :: s m -- | Push down to all children allS :: s m -> s m -- | Combine sequentially combS :: s m -> s m -> s m instance (Monad m, Strategy TP m) => StrategyMonoid TP m where skipS = idTP allS = allTP combS = seqTP instance (Monad m, Monoid u, Strategy (TU u) m) => StrategyMonoid (TU u) m where skipS = constTU mempty allS = allTU' combS = op2TU mappend -- | Overload basic combinators which involve MonadPlus class (Strategy s m, Monad m, MonadPlus m) => StrategyPlus s m where -- | Failure failS :: s m -- | Choice choiceS :: s m -> s m -> s m -- | Push down to a single child oneS :: s m -> s m instance (Monad m, MonadPlus m, Strategy TP m) => StrategyPlus TP m where failS = failTP choiceS = choiceTP oneS = oneTP instance (Monad m, MonadPlus m, Strategy (TU u) m) => StrategyPlus (TU u) m where failS = failTU choiceS = choiceTU oneS = oneTU -- | Overloaded lifting with failure monoS :: (StrategyApply s m t x, StrategyPlus s m) => (t -> m x) -> s m monoS f = adhocS failS f ------------------------------------------------------------------------------ -- * Effect substitution (see "EffectTheme"). -- | Overload msubst combinator (Experimental) class StrategyMSubst s where -- | Substitute one monad for another msubstS :: (Monad m, Monad m') => (forall t . m t -> m' t) -> s m -> s m' instance StrategyMSubst TP where msubstS f = msubstTP f instance StrategyMSubst (TU a) where msubstS f = msubstTU f ------------------------------------------------------------------------------
forste/haReFork
StrategyLib-4.0-beta/library/OverloadingTheme.hs
Haskell
bsd-3-clause
4,178
module CommandLine ( optDescrs, cmdLineArgsMap, cmdFlavour, lookupFreeze1, cmdIntegerSimple, cmdProgressInfo, cmdConfigure, cmdCompleteSetting, cmdDocsArgs, lookupBuildRoot, TestArgs(..), TestSpeed(..), defaultTestArgs ) where import Data.Either import qualified Data.HashMap.Strict as Map import Data.List.Extra import Development.Shake hiding (Normal) import Flavour (DocTargets, DocTarget(..)) import Hadrian.Utilities hiding (buildRoot) import Settings.Parser import System.Console.GetOpt import System.Environment import qualified System.Directory as Directory import qualified Data.Set as Set data TestSpeed = TestSlow | TestNormal | TestFast deriving (Show, Eq) -- | All arguments that can be passed to Hadrian via the command line. data CommandLineArgs = CommandLineArgs { configure :: Bool , flavour :: Maybe String , freeze1 :: Bool , integerSimple :: Bool , progressInfo :: ProgressInfo , buildRoot :: BuildRoot , testArgs :: TestArgs , docTargets :: DocTargets , completeStg :: Maybe String } deriving (Eq, Show) -- | Default values for 'CommandLineArgs'. defaultCommandLineArgs :: CommandLineArgs defaultCommandLineArgs = CommandLineArgs { configure = False , flavour = Nothing , freeze1 = False , integerSimple = False , progressInfo = Brief , buildRoot = BuildRoot "_build" , testArgs = defaultTestArgs , docTargets = Set.fromList [minBound..maxBound] , completeStg = Nothing } -- | These arguments are used by the `test` target. data TestArgs = TestArgs { testKeepFiles :: Bool , testCompiler :: String , testConfigFile :: String , testConfigs :: [String] , testJUnit :: Maybe FilePath , testOnly :: [String] , testOnlyPerf :: Bool , testSkipPerf :: Bool , testRootDirs :: [FilePath] , testSpeed :: TestSpeed , testSummary :: Maybe FilePath , testVerbosity :: Maybe String , testWays :: [String] , testAccept :: Bool} deriving (Eq, Show) -- | Default value for `TestArgs`. defaultTestArgs :: TestArgs defaultTestArgs = TestArgs { testKeepFiles = False , testCompiler = "stage2" , testConfigFile = "testsuite/config/ghc" , testConfigs = [] , testJUnit = Nothing , testOnly = [] , testOnlyPerf = False , testSkipPerf = False , testRootDirs = [] , testSpeed = TestNormal , testSummary = Nothing , testVerbosity = Nothing , testWays = [] , testAccept = False } readConfigure :: Either String (CommandLineArgs -> CommandLineArgs) readConfigure = Right $ \flags -> flags { configure = True } readFlavour :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readFlavour ms = Right $ \flags -> flags { flavour = lower <$> ms } readBuildRoot :: Maybe FilePath -> Either String (CommandLineArgs -> CommandLineArgs) readBuildRoot ms = maybe (Left "Cannot parse build-root") (Right . set) (go =<< ms) where go :: String -> Maybe BuildRoot go = Just . BuildRoot set :: BuildRoot -> CommandLineArgs -> CommandLineArgs set flag flags = flags { buildRoot = flag } readFreeze1 :: Either String (CommandLineArgs -> CommandLineArgs) readFreeze1 = Right $ \flags -> flags { freeze1 = True } readIntegerSimple :: Either String (CommandLineArgs -> CommandLineArgs) readIntegerSimple = Right $ \flags -> flags { integerSimple = True } readProgressInfo :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readProgressInfo ms = maybe (Left "Cannot parse progress-info") (Right . set) (go =<< lower <$> ms) where go :: String -> Maybe ProgressInfo go "none" = Just None go "brief" = Just Brief go "normal" = Just Normal go "unicorn" = Just Unicorn go _ = Nothing set :: ProgressInfo -> CommandLineArgs -> CommandLineArgs set flag flags = flags { progressInfo = flag } readTestKeepFiles :: Either String (CommandLineArgs -> CommandLineArgs) readTestKeepFiles = Right $ \flags -> flags { testArgs = (testArgs flags) { testKeepFiles = True } } readTestAccept :: Either String (CommandLineArgs -> CommandLineArgs) readTestAccept = Right $ \flags -> flags { testArgs = (testArgs flags) { testAccept = True } } readTestCompiler :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestCompiler compiler = maybe (Left "Cannot parse compiler") (Right . set) compiler where set compiler = \flags -> flags { testArgs = (testArgs flags) { testCompiler = compiler } } readTestConfig :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestConfig config = case config of Nothing -> Right id Just conf -> Right $ \flags -> let configs = conf : testConfigs (testArgs flags) in flags { testArgs = (testArgs flags) { testConfigs = configs } } readTestConfigFile :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestConfigFile filepath = maybe (Left "Cannot parse test-config-file") (Right . set) filepath where set filepath flags = flags { testArgs = (testArgs flags) { testConfigFile = filepath } } readTestJUnit :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestJUnit filepath = Right $ \flags -> flags { testArgs = (testArgs flags) { testJUnit = filepath } } readTestOnly :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestOnly tests = Right $ \flags -> flags { testArgs = (testArgs flags) { testOnly = tests'' flags } } where tests' = maybe [] words tests tests'' flags = testOnly (testArgs flags) ++ tests' readTestOnlyPerf :: Either String (CommandLineArgs -> CommandLineArgs) readTestOnlyPerf = Right $ \flags -> flags { testArgs = (testArgs flags) { testOnlyPerf = True } } readTestSkipPerf :: Either String (CommandLineArgs -> CommandLineArgs) readTestSkipPerf = Right $ \flags -> flags { testArgs = (testArgs flags) { testSkipPerf = True } } readTestRootDirs :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestRootDirs rootdirs = Right $ \flags -> flags { testArgs = (testArgs flags) { testRootDirs = rootdirs'' flags } } where rootdirs' = maybe [] (splitOn ":") rootdirs rootdirs'' flags = testRootDirs (testArgs flags) ++ rootdirs' readTestSpeed :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestSpeed ms = maybe (Left "Cannot parse test-speed") (Right . set) (go =<< lower <$> ms) where go :: String -> Maybe TestSpeed go "fast" = Just TestFast go "slow" = Just TestSlow go "normal" = Just TestNormal go _ = Nothing set :: TestSpeed -> CommandLineArgs -> CommandLineArgs set flag flags = flags { testArgs = (testArgs flags) {testSpeed = flag} } readTestSummary :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestSummary filepath = Right $ \flags -> flags { testArgs = (testArgs flags) { testJUnit = filepath } } readTestVerbose :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestVerbose verbose = Right $ \flags -> flags { testArgs = (testArgs flags) { testVerbosity = verbose } } readTestWay :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readTestWay way = case way of Nothing -> Right id Just way -> Right $ \flags -> let newWays = way : testWays (testArgs flags) in flags { testArgs = (testArgs flags) {testWays = newWays} } readCompleteStg :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readCompleteStg ms = Right $ \flags -> flags { completeStg = ms } readDocsArg :: Maybe String -> Either String (CommandLineArgs -> CommandLineArgs) readDocsArg ms = maybe (Left "Cannot parse docs argument") (Right . set) (go =<< ms) where go :: String -> Maybe (DocTargets -> DocTargets) go "none" = Just (const Set.empty) go "no-haddocks" = Just (Set.delete Haddocks) go "no-sphinx-html" = Just (Set.delete SphinxHTML) go "no-sphinx-pdfs" = Just (Set.delete SphinxPDFs) go "no-sphinx-man" = Just (Set.delete SphinxMan) go "no-sphinx-info" = Just (Set.delete SphinxInfo) go "no-sphinx" = Just (Set.delete SphinxHTML . Set.delete SphinxPDFs . Set.delete SphinxMan . Set.delete SphinxInfo) go _ = Nothing set :: (DocTargets -> DocTargets) -> CommandLineArgs -> CommandLineArgs set tweakTargets flags = flags { docTargets = tweakTargets (docTargets flags) } -- | Standard 'OptDescr' descriptions of Hadrian's command line arguments. optDescrs :: [OptDescr (Either String (CommandLineArgs -> CommandLineArgs))] optDescrs = [ Option ['c'] ["configure"] (NoArg readConfigure) "Run the boot and configure scripts (if you do not want to run them manually)." , Option ['o'] ["build-root"] (OptArg readBuildRoot "BUILD_ROOT") "Where to store build artifacts. (Default _build)." , Option [] ["flavour"] (OptArg readFlavour "FLAVOUR") "Build flavour (Default, Devel1, Devel2, Perf, Prof, Quick or Quickest)." , Option [] ["freeze1"] (NoArg readFreeze1) "Freeze Stage1 GHC." , Option [] ["integer-simple"] (NoArg readIntegerSimple) "Build GHC with integer-simple library." , Option [] ["progress-info"] (OptArg readProgressInfo "STYLE") "Progress info style (None, Brief, Normal or Unicorn)." , Option [] ["docs"] (OptArg readDocsArg "TARGET") "Strip down docs targets (none, no-haddocks, no-sphinx[-{html, pdfs, man}]." , Option ['k'] ["keep-test-files"] (NoArg readTestKeepFiles) "Keep all the files generated when running the testsuite." , Option [] ["test-compiler"] (OptArg readTestCompiler "TEST_COMPILER") "Use given compiler [Default=stage2]." , Option [] ["test-config-file"] (OptArg readTestConfigFile "CONFIG_FILE") "configuration file for testsuite. Default=testsuite/config/ghc" , Option [] ["config"] (OptArg readTestConfig "EXTRA_TEST_CONFIG") "Configurations to run test, in key=value format." , Option [] ["summary-junit"] (OptArg readTestJUnit "TEST_SUMMARY_JUNIT") "Output testsuite summary in JUnit format." , Option [] ["only"] (OptArg readTestOnly "TESTS") "Test cases to run." , Option [] ["only-perf"] (NoArg readTestOnlyPerf) "Only run performance tests." , Option [] ["skip-perf"] (NoArg readTestSkipPerf) "Skip performance tests." , Option [] ["test-root-dirs"] (OptArg readTestRootDirs "DIR1:[DIR2:...:DIRn]") "Test root directories to look at (all by default)." , Option [] ["test-speed"] (OptArg readTestSpeed "SPEED") "fast, slow or normal. Normal by default" , Option [] ["summary"] (OptArg readTestSummary "TEST_SUMMARY") "Where to output the test summary file." , Option [] ["test-verbose"] (OptArg readTestVerbose "TEST_VERBOSE") "A verbosity value between 0 and 5. 0 is silent, 4 and higher activates extra output." , Option [] ["test-way"] (OptArg readTestWay "TEST_WAY") "only run these ways" , Option ['a'] ["test-accept"] (NoArg readTestAccept) "Accept new output of tests" , Option [] ["complete-setting"] (OptArg readCompleteStg "SETTING") "Setting key to autocomplete, for the 'autocomplete' target." ] -- | A type-indexed map containing Hadrian command line arguments to be passed -- to Shake via 'shakeExtra'. cmdLineArgsMap :: IO (Map.HashMap TypeRep Dynamic) cmdLineArgsMap = do xs <- getArgs let -- We split the arguments between the ones that look like -- "k = v" or "k += v", in cliSettings, and the rest in -- optArgs. (optsArgs, cliSettings) = partitionKVs xs -- We only use the arguments that don't look like setting -- updates for parsing Hadrian and Shake flags/options. (opts, _, _) = getOpt Permute optDescrs optsArgs args = foldl (flip id) defaultCommandLineArgs (rights opts) BuildRoot root = buildRoot args settingsFile = root -/- "hadrian.settings" -- We try to look at <root>/hadrian.settings, and if it exists -- we read as many settings as we can from it, combining -- them with the ones we got on the command line, in allSettings. -- We then insert all those settings in the dynamic map, so that -- the 'Settings.flavour' action can look them up and apply -- all the relevant updates to the flavour that Hadrian is set -- to run with. settingsFileExists <- Directory.doesFileExist settingsFile fileSettings <- if settingsFileExists then parseJustKVs . lines <$> readFile settingsFile else return [] let allSettings = cliSettings ++ fileSettings return $ insertExtra (progressInfo args) -- Accessed by Hadrian.Utilities $ insertExtra (buildRoot args) -- Accessed by Hadrian.Utilities $ insertExtra (testArgs args) -- Accessed by Settings.Builders.RunTest $ insertExtra allSettings -- Accessed by Settings $ insertExtra args Map.empty cmdLineArgs :: Action CommandLineArgs cmdLineArgs = userSetting defaultCommandLineArgs cmdConfigure :: Action Bool cmdConfigure = configure <$> cmdLineArgs cmdFlavour :: Action (Maybe String) cmdFlavour = flavour <$> cmdLineArgs cmdCompleteSetting :: Action (Maybe String) cmdCompleteSetting = completeStg <$> cmdLineArgs lookupBuildRoot :: Map.HashMap TypeRep Dynamic -> BuildRoot lookupBuildRoot = buildRoot . lookupExtra defaultCommandLineArgs lookupFreeze1 :: Map.HashMap TypeRep Dynamic -> Bool lookupFreeze1 = freeze1 . lookupExtra defaultCommandLineArgs cmdIntegerSimple :: Action Bool cmdIntegerSimple = integerSimple <$> cmdLineArgs cmdProgressInfo :: Action ProgressInfo cmdProgressInfo = progressInfo <$> cmdLineArgs cmdDocsArgs :: Action DocTargets cmdDocsArgs = docTargets <$> cmdLineArgs
sdiehl/ghc
hadrian/src/CommandLine.hs
Haskell
bsd-3-clause
14,186
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Hchain.BlockChain (BlockChain, Hash, Block (..), content, BContent (..), isValidChain, addBlock, mkInitialChain, addValidBlock, mineBlock) where import qualified Data.ByteString.Lazy.Char8 as C8 import Control.Lens import Data.Digest.Pure.SHA (sha256, showDigest) import Data.String.Utils (startswith) import Data.Maybe (fromJust) import Data.Binary import Data.Typeable import GHC.Generics type Hash = String type BNum = Int type BNonce = Int data Block a = Block { _num :: BNum, _nonce :: BNonce, _content :: a, _prevH :: Hash, _bHash :: Hash } deriving (Show, Generic, Typeable, Eq) $(makeLenses ''Block) type BlockChain a = [a] class BContent a where serial :: a -> String mApply :: a -> [a] -> (a -> b) -> Maybe b instance (Typeable a, Binary a) => Binary (Block a) mkInitialChain :: BContent a => a -> BlockChain (Block a) mkInitialChain c = [mine (mkInitialBlock c)] mkInitialBlock :: BContent a => a -> Block a mkInitialBlock c = Block 1 1 c emptyHash emptyHash where emptyHash = "0000000000000000000000000000000000000000000000000000000000000000" isValidChain :: BContent a => BlockChain (Block a) -> Bool isValidChain = all $ checkSignature . view bHash mineBlock :: BContent a => a -> BlockChain (Block a) -> Maybe (BlockChain (Block a)) mineBlock = addBlock mine addValidBlock :: BContent a => Block a -> BlockChain (Block a) -> Maybe (BlockChain (Block a)) addValidBlock block chain | checkSignature (block ^. bHash) && not (null (addBlock id (block ^. content) chain)) = Just $ block : chain | otherwise = Nothing addBlock :: BContent a => (Block a -> Block a) -> a -> BlockChain (Block a) -> Maybe (BlockChain (Block a)) addBlock op c chain@(x:_xs) | null contentBlock = Nothing | otherwise = Just $ op (fromJust contentBlock) : chain where contentBlock = mApply c (reverse contents) cont cont = mkBlock (x ^. num + 1) (x ^. bHash) contents = map _content chain mkBlock :: BContent a => BNum -> Hash -> a -> Block a mkBlock n prevh c = Block n 1 c prevh "" hash :: BContent a => Block a -> Hash hash block = showDigest $ sha256 (C8.pack (serialize block)) serialize :: BContent a => Block a -> String serialize block = show (block ^. num) ++ show (block ^. nonce) ++ serial (block ^. content) ++ block ^. prevH checkSignature :: Hash -> Bool checkSignature = startswith "0000" mine :: BContent a => Block a -> Block a mine block | checkSignature computedHash = block & bHash .~ computedHash | otherwise = mine (block & nonce +~ 1) where computedHash = hash block
jesuspc/hchain
src/hchain/BlockChain.hs
Haskell
bsd-3-clause
2,682
{-# LANGUAGE ImplicitParams #-} ---------------------------------------------------------------------------- -- | -- Module : DART.Run -- Copyright : (c) Carlos López-Camey, University of Freiburg -- License : BSD-3 -- -- Maintainer : c.lopez@kmels.net -- Stability : stable -- -- -- Runs the interpreter and the dart tester ----------------------------------------------------------------------------- module DART.Run where -------------------------------------------------------------------------------- -- DART import DART.DARTSettings import DART.FileIO import DART.FunctionFeeder import DART.MkRandomValue import DART.CmdLine import qualified DART.ModuleTester as T -------------------------------------------------------------------------------- -- Data structures import qualified Data.HashTable.IO as H import Data.Maybe -------------------------------------------------------------------------------- -- Core import Language.Core.Core import Language.Core.Interp import qualified Language.Core.Interpreter as I import Language.Core.Interpreter.Acknowledge(acknowledgeModule) import qualified Language.Core.Interpreter.Libraries as Libs import Language.Core.Interpreter.Structures import Language.Core.Interpreter.Util(showValue) import Language.Core.Util(showType) import Language.Core.Vdefg -------------------------------------------------------------------------------- -- Prelude import System.Directory(getCurrentDirectory) import System.Environment -------------------------------------------------------------------------------- -- import Text.Encoding.Z -------------------------------------------------------------------------------- -- system import Data.Time.Clock(getCurrentTime) -- | Creates an initial state given the arguments given -- in the command line and parsed by CmdArgs initDART :: DARTSettings -> IO DARTState initDART settings' = do h <- io H.new -- create a fresh new heap current_dir <- getCurrentDirectory let prependCurrentDir = (++) (current_dir ++ "/") let user_includes = include settings' let absolute_includes = map prependCurrentDir $ prelude_files ++ user_includes now <- io getCurrentTime return $ DState { benchmarks = [] , pbranches_record = [] , libraries_env = [] , heap = h , heap_count = 0 , number_of_reductions = 0 , number_of_reductions_part = 0 , tab_indentation = 1 , settings = settings' { include = (absolute_includes) } , start_time = now , test_name = Nothing , samplerStatus = UnitializedSampler , samplerDataSize = 0 } -- | Returns a list of *relative* paths pointing to default included libraries e.g. base -- Use case: if we always want the function split to be in scope for programs that we are testing, then we should load Data.List in the base package -- The file paths are path to .hcr files, since these modules sometimes need different arguments to be compiled with -fext-core prelude_files :: [FilePath] prelude_files = [ "/lib/base/GHC/Base.hcr" , "/lib/base/GHC/Base.hcr" , "/lib/base/Data/Tuple.hcr" , "/lib/base/GHC/Show.hcr" , "/lib/base/GHC/Enum.hcr" , "/lib/base/Data/Maybe.hcr" , "/lib/base/GHC/List.hcr" , "/lib/base/Data/List.hcr" ] -- | Assumming no library has been loaded, this function looks for the settings (often coming from the command line and loads: -- * the includes, -- * the base library -- * the builtin functions (coming from the Interpreter/Libraries module family) -- for the interpreter to work. loadLibraries :: IM () loadLibraries = do debugMStep ("Loading includes ") settings <- gets settings -- get the list of includes and acknowledge definitions in heap let includes = include settings lib_envs <- mapM loadFilePath includes -- :: [Env] -- builtin funs, e.g. GHC.Num.+ ghc_builtin_funs <- I.loadLibrary Libs.ghc_base modify $ \st -> st { libraries_env = ghc_builtin_funs ++ concat lib_envs } -- | After an initial state is created, evaluates according to the settings runDART :: IM () runDART = do settgs <- gets settings -- Evaluate specified module let pathToModule = file settgs let ?be_verbose = verbose settgs debugMStep $ "Reading module " ++ pathToModule ++ " .." m@(Module mdlname tdefs vdefgs) <- io . readModule $ file settgs module_env <- acknowledgeModule m loadLibraries let eval_funname = evaluate_function settgs test_funname = test_function settgs -- What should we eval? a function or the whole module? unless (not $ null test_funname) $ evaluate m module_env eval_funname -- What should we test? a function or the whole module? unless (not $ null eval_funname) $ test m module_env test_funname where test :: Module -> Env -> String -> IM () -- | No function specified test m env [] = do tested_funs <- T.testModule m env -- let prettyPrint :: TestedFun -> IM String -- prettyPrint (id,test_result) = T.showTestedFun test_result >>= return . (++) (id ++ ": \n") io . putStrLn $ "**************************************************" io . putStrLn $ "Module test results " io . putStrLn $ "**************************************************" mapM T.showTestedFun tested_funs >>= io . mapM_ putStrLn h <- gets heap whenFlag show_heap $ io . printHeap $ h -- | test specified function test m env fun_name = -- let prettyPrint :: Maybe (Id,T.TestResult) -> IM String -- prettyPrint Nothing = return $ "No test result " -- prettyPrint (Just (id,test_result)) = T.showTest test_result >>= return . (++) (id ++ ": \n") do fun_test_str <- T.testHaskellExpression m fun_name env >>= T.showFunTest io . putStrLn $ "**************************************************" io . putStrLn $ "Test results of " ++ fun_name io . putStrLn $ "**************************************************" io . putStrLn $ fun_test_str (gets heap >>= \h -> whenFlag show_heap $ io . printHeap $ h) evaluate :: Module -> Env -> String -> IM () -- | no function specified evaluate m env [] = do vals <- I.evalModule m env -- interpret values -- funt ion to pretty print let prettyPrint :: (Id,Value) -> IM String prettyPrint (id,val) = do pp <- showValue val setts <- gets settings case (benchmark setts) of False -> return $ id ++ " => " ++ pp True -> do bs <- gets benchmarks let time = fromJust $ lookup id bs return $ id ++ " => " ++ pp ++ " .. done in " ++ show time io . putStrLn $ "**************************************************" io . putStrLn $ "Module definitions evaluation: " io . putStrLn $ "**************************************************" mapM prettyPrint vals >>= io . mapM_ putStrLn h <- gets heap st <- gets settings when (show_heap st) $ io . printHeap $ h -- | eval fun_name evaluate m env fun_name = do debugM $ "evaluate fun_name; env.size == " ++ (show . length $ env) result <- I.evalHaskellExpression m fun_name env -- do we print the heap? h <- gets heap st <- gets settings when (show_heap $ st) $ io . printHeap $ h -- output computed result io . putStrLn $ "**************************************************" io . putStrLn $ "Evaluation of " ++ fun_name io . putStrLn $ "**************************************************" showValue result >>= io . putStrLn
kmels/dart-haskell
src/DART/Run.hs
Haskell
bsd-3-clause
7,988
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} module Lib ( getKey , startAPI , verboseLog ) where import ClassyPrelude import Types.API.Base import Types.General import Types.Options getKey :: APICaller APIKey getKey = asks apiKey isVerbose :: APICaller Bool isVerbose = do verbosity <- asks apiVerbosity return $ verbosity == Verbose verboseLog :: Text -> APICaller () verboseLog = whenM isVerbose . putStrLn startAPI = flip runReaderT
JoeMShanahan/blizzard-haskell-api
src/Lib.hs
Haskell
bsd-3-clause
478
{-# LANGUAGE CPP, NondecreasingIndentation, ScopedTypeVariables #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2005-2012 -- -- The GHC API -- -- ----------------------------------------------------------------------------- module GHC ( -- * Initialisation defaultErrorHandler, defaultCleanupHandler, prettyPrintGhcErrors, -- * GHC Monad Ghc, GhcT, GhcMonad(..), HscEnv, runGhc, runGhcT, initGhcMonad, gcatch, gbracket, gfinally, printException, handleSourceError, needsTemplateHaskell, -- * Flags and settings DynFlags(..), GeneralFlag(..), Severity(..), HscTarget(..), gopt, GhcMode(..), GhcLink(..), defaultObjectTarget, parseDynamicFlags, getSessionDynFlags, setSessionDynFlags, getProgramDynFlags, setProgramDynFlags, getInteractiveDynFlags, setInteractiveDynFlags, parseStaticFlags, -- * Targets Target(..), TargetId(..), Phase, setTargets, getTargets, addTarget, removeTarget, guessTarget, -- * Loading\/compiling the program depanal, load, LoadHowMuch(..), InteractiveImport(..), SuccessFlag(..), succeeded, failed, defaultWarnErrLogger, WarnErrLogger, workingDirectoryChanged, parseModule, typecheckModule, desugarModule, loadModule, ParsedModule(..), TypecheckedModule(..), DesugaredModule(..), TypecheckedSource, ParsedSource, RenamedSource, -- ditto TypecheckedMod, ParsedMod, moduleInfo, renamedSource, typecheckedSource, parsedSource, coreModule, -- ** Compiling to Core CoreModule(..), compileToCoreModule, compileToCoreSimplified, -- * Inspecting the module structure of the program ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..), getModSummary, getModuleGraph, isLoaded, topSortModuleGraph, -- * Inspecting modules ModuleInfo, getModuleInfo, modInfoTyThings, modInfoTopLevelScope, modInfoExports, modInfoInstances, modInfoIsExportedName, modInfoLookupName, modInfoIface, modInfoSafe, lookupGlobalName, findGlobalAnns, mkPrintUnqualifiedForModule, ModIface(..), SafeHaskellMode(..), -- * Querying the environment packageDbModules, -- * Printing PrintUnqualified, alwaysQualify, -- * Interactive evaluation getBindings, getInsts, getPrintUnqual, findModule, lookupModule, #ifdef GHCI isModuleTrusted, moduleTrustReqs, setContext, getContext, getNamesInScope, getRdrNamesInScope, getGRE, moduleIsInterpreted, getInfo, exprType, typeKind, parseName, RunResult(..), runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation, runTcInteractive, -- Desired by some clients (Trac #8878) parseImportDecl, SingleStep(..), resume, Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan, resumeHistory, resumeHistoryIx), History(historyBreakInfo, historyEnclosingDecls), GHC.getHistorySpan, getHistoryModule, getResumeContext, abandon, abandonAll, InteractiveEval.back, InteractiveEval.forward, showModule, isModuleInterpreted, InteractiveEval.compileExpr, HValue, dynCompileExpr, GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType, modInfoModBreaks, ModBreaks(..), BreakIndex, BreakInfo(breakInfo_number, breakInfo_module), BreakArray, setBreakOn, setBreakOff, getBreak, #endif lookupName, #ifdef GHCI -- ** EXPERIMENTAL setGHCiMonad, #endif -- * Abstract syntax elements -- ** Packages PackageId, -- ** Modules Module, mkModule, pprModule, moduleName, modulePackageId, ModuleName, mkModuleName, moduleNameString, -- ** Names Name, isExternalName, nameModule, pprParenSymName, nameSrcSpan, NamedThing(..), RdrName(Qual,Unqual), -- ** Identifiers Id, idType, isImplicitId, isDeadBinder, isExportedId, isLocalId, isGlobalId, isRecordSelector, isPrimOpId, isFCallId, isClassOpId_maybe, isDataConWorkId, idDataCon, isBottomingId, isDictonaryId, recordSelectorFieldLabel, -- ** Type constructors TyCon, tyConTyVars, tyConDataCons, tyConArity, isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon, isFamilyTyCon, isOpenFamilyTyCon, tyConClass_maybe, synTyConRhs_maybe, synTyConDefn_maybe, synTyConResKind, -- ** Type variables TyVar, alphaTyVars, -- ** Data constructors DataCon, dataConSig, dataConType, dataConTyCon, dataConFieldLabels, dataConIsInfix, isVanillaDataCon, dataConUserType, dataConStrictMarks, StrictnessMark(..), isMarkedStrict, -- ** Classes Class, classMethods, classSCTheta, classTvsFds, classATs, pprFundeps, -- ** Instances ClsInst, instanceDFunId, pprInstance, pprInstanceHdr, pprFamInst, FamInst, -- ** Types and Kinds Type, splitForAllTys, funResultTy, pprParendType, pprTypeApp, Kind, PredType, ThetaType, pprForAll, pprThetaArrowTy, -- ** Entities TyThing(..), -- ** Syntax module HsSyn, -- ToDo: remove extraneous bits -- ** Fixities FixityDirection(..), defaultFixity, maxPrecedence, negateFixity, compareFixity, -- ** Source locations SrcLoc(..), RealSrcLoc, mkSrcLoc, noSrcLoc, srcLocFile, srcLocLine, srcLocCol, SrcSpan(..), RealSrcSpan, mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan, srcSpanStart, srcSpanEnd, srcSpanFile, srcSpanStartLine, srcSpanEndLine, srcSpanStartCol, srcSpanEndCol, -- ** Located GenLocated(..), Located, -- *** Constructing Located noLoc, mkGeneralLocated, -- *** Deconstructing Located getLoc, unLoc, -- *** Combining and comparing Located values eqLocated, cmpLocated, combineLocs, addCLoc, leftmost_smallest, leftmost_largest, rightmost, spans, isSubspanOf, -- * Exceptions GhcException(..), showGhcException, -- * Token stream manipulations Token, getTokenStream, getRichTokenStream, showRichTokenStream, addSourceToTokens, -- * Pure interface to the parser parser, -- * Miscellaneous --sessionHscEnv, cyclicModuleErr, ) where {- ToDo: * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt. * what StaticFlags should we expose, if any? -} #include "HsVersions.h" #ifdef GHCI import ByteCodeInstr import BreakArray import InteractiveEval import TcRnDriver ( runTcInteractive ) #endif import HscMain import GhcMake import DriverPipeline ( compileOne' ) import GhcMonad import TcRnMonad ( finalSafeMode ) import TcRnTypes import Packages import NameSet import RdrName import qualified HsSyn -- hack as we want to reexport the whole module import HsSyn import Type hiding( typeKind ) import Kind ( synTyConResKind ) import TcType hiding( typeKind ) import Id import TysPrim ( alphaTyVars ) import TyCon import Class import DataCon import Name hiding ( varName ) import Avail import InstEnv import FamInstEnv import SrcLoc import CoreSyn import TidyPgm import DriverPhases ( Phase(..), isHaskellSrcFilename ) import Finder import HscTypes import DynFlags import StaticFlags import SysTools import Annotations import Module import UniqFM import Panic import Platform import Bag ( unitBag ) import ErrUtils import MonadUtils import Util import StringBuffer import Outputable import BasicTypes import Maybes ( expectJust ) import FastString import qualified Parser import Lexer import System.Directory ( doesFileExist ) import Data.Maybe import Data.List ( find ) import Data.Time import Data.Typeable ( Typeable ) import Data.Word ( Word8 ) import Control.Monad import System.Exit ( exitWith, ExitCode(..) ) import Exception import Data.IORef import System.FilePath import System.IO import Prelude hiding (init) -- %************************************************************************ -- %* * -- Initialisation: exception handlers -- %* * -- %************************************************************************ -- | Install some default exception handlers and run the inner computation. -- Unless you want to handle exceptions yourself, you should wrap this around -- the top level of your program. The default handlers output the error -- message(s) to stderr and exit cleanly. defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => FatalMessager -> FlushOut -> m a -> m a defaultErrorHandler fm (FlushOut flushOut) inner = -- top-level exception handler: any unrecognised exception is a compiler bug. ghandle (\exception -> liftIO $ do flushOut case fromException exception of -- an IO exception probably isn't our fault, so don't panic Just (ioe :: IOException) -> fatalErrorMsg'' fm (show ioe) _ -> case fromException exception of Just UserInterrupt -> -- Important to let this one propagate out so our -- calling process knows we were interrupted by ^C liftIO $ throwIO UserInterrupt Just StackOverflow -> fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it" _ -> case fromException exception of Just (ex :: ExitCode) -> liftIO $ throwIO ex _ -> fatalErrorMsg'' fm (show (Panic (show exception))) exitWith (ExitFailure 1) ) $ -- error messages propagated as exceptions handleGhcException (\ge -> liftIO $ do flushOut case ge of PhaseFailed _ code -> exitWith code Signal _ -> exitWith (ExitFailure 1) _ -> do fatalErrorMsg'' fm (show ge) exitWith (ExitFailure 1) ) $ inner -- | Install a default cleanup handler to remove temporary files deposited by -- a GHC run. This is separate from 'defaultErrorHandler', because you might -- want to override the error handling, but still get the ordinary cleanup -- behaviour. defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a defaultCleanupHandler dflags inner = -- make sure we clean up after ourselves inner `gfinally` (liftIO $ do cleanTempFiles dflags cleanTempDirs dflags ) -- exceptions will be blocked while we clean the temporary files, -- so there shouldn't be any difficulty if we receive further -- signals. -- %************************************************************************ -- %* * -- The Ghc Monad -- %* * -- %************************************************************************ -- | Run function for the 'Ghc' monad. -- -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call -- to this function will create a new session which should not be shared among -- several threads. -- -- Any errors not handled inside the 'Ghc' action are propagated as IO -- exceptions. runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'. -> Ghc a -- ^ The action to perform. -> IO a runGhc mb_top_dir ghc = do ref <- newIORef (panic "empty session") let session = Session ref flip unGhc session $ do initGhcMonad mb_top_dir ghc -- XXX: unregister interrupt handlers here? -- | Run function for 'GhcT' monad transformer. -- -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call -- to this function will create a new session which should not be shared among -- several threads. runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) => Maybe FilePath -- ^ See argument to 'initGhcMonad'. -> GhcT m a -- ^ The action to perform. -> m a runGhcT mb_top_dir ghct = do ref <- liftIO $ newIORef (panic "empty session") let session = Session ref flip unGhcT session $ do initGhcMonad mb_top_dir ghct -- | Initialise a GHC session. -- -- If you implement a custom 'GhcMonad' you must call this function in the -- monad run function. It will initialise the session variable and clear all -- warnings. -- -- The first argument should point to the directory where GHC's library files -- reside. More precisely, this should be the output of @ghc --print-libdir@ -- of the version of GHC the module using this API is compiled with. For -- portability, you should use the @ghc-paths@ package, available at -- <http://hackage.haskell.org/package/ghc-paths>. initGhcMonad :: GhcMonad m => Maybe FilePath -> m () initGhcMonad mb_top_dir = do { env <- liftIO $ do { installSignalHandlers -- catch ^C ; initStaticOpts ; mySettings <- initSysTools mb_top_dir ; dflags <- initDynFlags (defaultDynFlags mySettings) ; checkBrokenTablesNextToCode dflags ; setUnsafeGlobalDynFlags dflags -- c.f. DynFlags.parseDynamicFlagsFull, which -- creates DynFlags and sets the UnsafeGlobalDynFlags ; newHscEnv dflags } ; setSession env } -- | The binutils linker on ARM emits unnecessary R_ARM_COPY relocations which -- breaks tables-next-to-code in dynamically linked modules. This -- check should be more selective but there is currently no released -- version where this bug is fixed. -- See https://sourceware.org/bugzilla/show_bug.cgi?id=16177 and -- https://ghc.haskell.org/trac/ghc/ticket/4210#comment:29 checkBrokenTablesNextToCode :: MonadIO m => DynFlags -> m () checkBrokenTablesNextToCode dflags = do { broken <- checkBrokenTablesNextToCode' dflags ; when broken $ do { _ <- liftIO $ throwIO $ mkApiErr dflags invalidLdErr ; fail "unsupported linker" } } where invalidLdErr = text "Tables-next-to-code not supported on ARM" <+> text "when using binutils ld (please see:" <+> text "https://sourceware.org/bugzilla/show_bug.cgi?id=16177)" checkBrokenTablesNextToCode' :: MonadIO m => DynFlags -> m Bool checkBrokenTablesNextToCode' dflags | not (isARM arch) = return False | WayDyn `notElem` ways dflags = return False | not (tablesNextToCode dflags) = return False | otherwise = do linkerInfo <- liftIO $ getLinkerInfo dflags case linkerInfo of GnuLD _ -> return True _ -> return False where platform = targetPlatform dflags arch = platformArch platform -- %************************************************************************ -- %* * -- Flags & settings -- %* * -- %************************************************************************ -- $DynFlags -- -- The GHC session maintains two sets of 'DynFlags': -- -- * The "interactive" @DynFlags@, which are used for everything -- related to interactive evaluation, including 'runStmt', -- 'runDecls', 'exprType', 'lookupName' and so on (everything -- under \"Interactive evaluation\" in this module). -- -- * The "program" @DynFlags@, which are used when loading -- whole modules with 'load' -- -- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the -- interactive @DynFlags@. -- -- 'setProgramDynFlags', 'getProgramDynFlags' work with the -- program @DynFlags@. -- -- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags' -- retrieves the program @DynFlags@ (for backwards compatibility). -- | Updates both the interactive and program DynFlags in a Session. -- This also reads the package database (unless it has already been -- read), and prepares the compilers knowledge about packages. It can -- be called again to load new packages: just add new package flags to -- (packageFlags dflags). -- -- Returns a list of new packages that may need to be linked in using -- the dynamic linker (see 'linkPackages') as a result of new package -- flags. If you are not doing linking or doing static linking, you -- can ignore the list of packages returned. -- setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageId] setSessionDynFlags dflags = do (dflags', preload) <- liftIO $ initPackages dflags modifySession $ \h -> h{ hsc_dflags = dflags' , hsc_IC = (hsc_IC h){ ic_dflags = dflags' } } invalidateModSummaryCache return preload -- | Sets the program 'DynFlags'. setProgramDynFlags :: GhcMonad m => DynFlags -> m [PackageId] setProgramDynFlags dflags = do (dflags', preload) <- liftIO $ initPackages dflags modifySession $ \h -> h{ hsc_dflags = dflags' } invalidateModSummaryCache return preload -- When changing the DynFlags, we want the changes to apply to future -- loads, but without completely discarding the program. But the -- DynFlags are cached in each ModSummary in the hsc_mod_graph, so -- after a change to DynFlags, the changes would apply to new modules -- but not existing modules; this seems undesirable. -- -- Furthermore, the GHC API client might expect that changing -- log_action would affect future compilation messages, but for those -- modules we have cached ModSummaries for, we'll continue to use the -- old log_action. This is definitely wrong (#7478). -- -- Hence, we invalidate the ModSummary cache after changing the -- DynFlags. We do this by tweaking the date on each ModSummary, so -- that the next downsweep will think that all the files have changed -- and preprocess them again. This won't necessarily cause everything -- to be recompiled, because by the time we check whether we need to -- recopmile a module, we'll have re-summarised the module and have a -- correct ModSummary. -- invalidateModSummaryCache :: GhcMonad m => m () invalidateModSummaryCache = modifySession $ \h -> h { hsc_mod_graph = map inval (hsc_mod_graph h) } where inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) } -- | Returns the program 'DynFlags'. getProgramDynFlags :: GhcMonad m => m DynFlags getProgramDynFlags = getSessionDynFlags -- | Set the 'DynFlags' used to evaluate interactive expressions. -- Note: this cannot be used for changes to packages. Use -- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the -- 'pkgState' into the interactive @DynFlags@. setInteractiveDynFlags :: GhcMonad m => DynFlags -> m () setInteractiveDynFlags dflags = do modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags }} -- | Get the 'DynFlags' used to evaluate interactive expressions. getInteractiveDynFlags :: GhcMonad m => m DynFlags getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h)) parseDynamicFlags :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) parseDynamicFlags = parseDynamicFlagsCmdLine -- %************************************************************************ -- %* * -- Setting, getting, and modifying the targets -- %* * -- %************************************************************************ -- ToDo: think about relative vs. absolute file paths. And what -- happens when the current directory changes. -- | Sets the targets for this session. Each target may be a module name -- or a filename. The targets correspond to the set of root modules for -- the program\/library. Unloading the current program is achieved by -- setting the current set of targets to be empty, followed by 'load'. setTargets :: GhcMonad m => [Target] -> m () setTargets targets = modifySession (\h -> h{ hsc_targets = targets }) -- | Returns the current set of targets getTargets :: GhcMonad m => m [Target] getTargets = withSession (return . hsc_targets) -- | Add another target. addTarget :: GhcMonad m => Target -> m () addTarget target = modifySession (\h -> h{ hsc_targets = target : hsc_targets h }) -- | Remove a target removeTarget :: GhcMonad m => TargetId -> m () removeTarget target_id = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) }) where filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ] -- | Attempts to guess what Target a string refers to. This function -- implements the @--make@/GHCi command-line syntax for filenames: -- -- - if the string looks like a Haskell source filename, then interpret it -- as such -- -- - if adding a .hs or .lhs suffix yields the name of an existing file, -- then use that -- -- - otherwise interpret the string as a module name -- guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target guessTarget str (Just phase) = return (Target (TargetFile str (Just phase)) True Nothing) guessTarget str Nothing | isHaskellSrcFilename file = return (target (TargetFile file Nothing)) | otherwise = do exists <- liftIO $ doesFileExist hs_file if exists then return (target (TargetFile hs_file Nothing)) else do exists <- liftIO $ doesFileExist lhs_file if exists then return (target (TargetFile lhs_file Nothing)) else do if looksLikeModuleName file then return (target (TargetModule (mkModuleName file))) else do dflags <- getDynFlags liftIO $ throwGhcExceptionIO (ProgramError (showSDoc dflags $ text "target" <+> quotes (text file) <+> text "is not a module name or a source file")) where (file,obj_allowed) | '*':rest <- str = (rest, False) | otherwise = (str, True) hs_file = file <.> "hs" lhs_file = file <.> "lhs" target tid = Target tid obj_allowed Nothing -- | Inform GHC that the working directory has changed. GHC will flush -- its cache of module locations, since it may no longer be valid. -- -- Note: Before changing the working directory make sure all threads running -- in the same session have stopped. If you change the working directory, -- you should also unload the current program (set targets to empty, -- followed by load). workingDirectoryChanged :: GhcMonad m => m () workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches) -- %************************************************************************ -- %* * -- Running phases one at a time -- %* * -- %************************************************************************ class ParsedMod m where modSummary :: m -> ModSummary parsedSource :: m -> ParsedSource class ParsedMod m => TypecheckedMod m where renamedSource :: m -> Maybe RenamedSource typecheckedSource :: m -> TypecheckedSource moduleInfo :: m -> ModuleInfo tm_internals :: m -> (TcGblEnv, ModDetails) -- ToDo: improvements that could be made here: -- if the module succeeded renaming but not typechecking, -- we can still get back the GlobalRdrEnv and exports, so -- perhaps the ModuleInfo should be split up into separate -- fields. class TypecheckedMod m => DesugaredMod m where coreModule :: m -> ModGuts -- | The result of successful parsing. data ParsedModule = ParsedModule { pm_mod_summary :: ModSummary , pm_parsed_source :: ParsedSource , pm_extra_src_files :: [FilePath] } instance ParsedMod ParsedModule where modSummary m = pm_mod_summary m parsedSource m = pm_parsed_source m -- | The result of successful typechecking. It also contains the parser -- result. data TypecheckedModule = TypecheckedModule { tm_parsed_module :: ParsedModule , tm_renamed_source :: Maybe RenamedSource , tm_typechecked_source :: TypecheckedSource , tm_checked_module_info :: ModuleInfo , tm_internals_ :: (TcGblEnv, ModDetails) } instance ParsedMod TypecheckedModule where modSummary m = modSummary (tm_parsed_module m) parsedSource m = parsedSource (tm_parsed_module m) instance TypecheckedMod TypecheckedModule where renamedSource m = tm_renamed_source m typecheckedSource m = tm_typechecked_source m moduleInfo m = tm_checked_module_info m tm_internals m = tm_internals_ m -- | The result of successful desugaring (i.e., translation to core). Also -- contains all the information of a typechecked module. data DesugaredModule = DesugaredModule { dm_typechecked_module :: TypecheckedModule , dm_core_module :: ModGuts } instance ParsedMod DesugaredModule where modSummary m = modSummary (dm_typechecked_module m) parsedSource m = parsedSource (dm_typechecked_module m) instance TypecheckedMod DesugaredModule where renamedSource m = renamedSource (dm_typechecked_module m) typecheckedSource m = typecheckedSource (dm_typechecked_module m) moduleInfo m = moduleInfo (dm_typechecked_module m) tm_internals m = tm_internals_ (dm_typechecked_module m) instance DesugaredMod DesugaredModule where coreModule m = dm_core_module m type ParsedSource = Located (HsModule RdrName) type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString) type TypecheckedSource = LHsBinds Id -- NOTE: -- - things that aren't in the output of the typechecker right now: -- - the export list -- - the imports -- - type signatures -- - type/data/newtype declarations -- - class declarations -- - instances -- - extra things in the typechecker's output: -- - default methods are turned into top-level decls. -- - dictionary bindings -- | Return the 'ModSummary' of a module with the given name. -- -- The module must be part of the module graph (see 'hsc_mod_graph' and -- 'ModuleGraph'). If this is not the case, this function will throw a -- 'GhcApiError'. -- -- This function ignores boot modules and requires that there is only one -- non-boot module with the given name. getModSummary :: GhcMonad m => ModuleName -> m ModSummary getModSummary mod = do mg <- liftM hsc_mod_graph getSession case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of [] -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph") [ms] -> return ms multiple -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple) -- | Parse a module. -- -- Throws a 'SourceError' on parse error. parseModule :: GhcMonad m => ModSummary -> m ParsedModule parseModule ms = do hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } hpm <- liftIO $ hscParse hsc_env_tmp ms return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm)) -- | Typecheck and rename a parsed module. -- -- Throws a 'SourceError' if either fails. typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule typecheckModule pmod = do let ms = modSummary pmod hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } (tc_gbl_env, rn_info) <- liftIO $ hscTypecheckRename hsc_env_tmp ms $ HsParsedModule { hpm_module = parsedSource pmod, hpm_src_files = pm_extra_src_files pmod } details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env return $ TypecheckedModule { tm_internals_ = (tc_gbl_env, details), tm_parsed_module = pmod, tm_renamed_source = rn_info, tm_typechecked_source = tcg_binds tc_gbl_env, tm_checked_module_info = ModuleInfo { minf_type_env = md_types details, minf_exports = availsToNameSet $ md_exports details, minf_rdr_env = Just (tcg_rdr_env tc_gbl_env), minf_instances = md_insts details, minf_iface = Nothing, minf_safe = safe #ifdef GHCI ,minf_modBreaks = emptyModBreaks #endif }} -- | Desugar a typechecked module. desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule desugarModule tcm = do let ms = modSummary tcm let (tcg, _) = tm_internals tcm hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg return $ DesugaredModule { dm_typechecked_module = tcm, dm_core_module = guts } -- | Load a module. Input doesn't need to be desugared. -- -- A module must be loaded before dependent modules can be typechecked. This -- always includes generating a 'ModIface' and, depending on the -- 'DynFlags.hscTarget', may also include code generation. -- -- This function will always cause recompilation and will always overwrite -- previous compilation results (potentially files on disk). -- loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod loadModule tcm = do let ms = modSummary tcm let mod = ms_mod_name ms let loc = ms_location ms let (tcg, _details) = tm_internals tcm mb_linkable <- case ms_obj_date ms of Just t | t > ms_hs_date ms -> do l <- liftIO $ findObjectLinkable (ms_mod ms) (ml_obj_file loc) t return (Just l) _otherwise -> return Nothing let source_modified | isNothing mb_linkable = SourceModified | otherwise = SourceUnmodified -- we can't determine stability here -- compile doesn't change the session hsc_env <- getSession mod_info <- liftIO $ compileOne' (Just tcg) Nothing hsc_env ms 1 1 Nothing mb_linkable source_modified modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info } return tcm -- %************************************************************************ -- %* * -- Dealing with Core -- %* * -- %************************************************************************ -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for -- the 'GHC.compileToCoreModule' interface. data CoreModule = CoreModule { -- | Module name cm_module :: !Module, -- | Type environment for types declared in this module cm_types :: !TypeEnv, -- | Declarations cm_binds :: CoreProgram, -- | Safe Haskell mode cm_safe :: SafeHaskellMode } instance Outputable CoreModule where ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb, cm_safe = sf}) = text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te $$ vcat (map ppr cb) -- | This is the way to get access to the Core bindings corresponding -- to a module. 'compileToCore' parses, typechecks, and -- desugars the module, then returns the resulting Core module (consisting of -- the module name, type declarations, and function declarations) if -- successful. compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule compileToCoreModule = compileCore False -- | Like compileToCoreModule, but invokes the simplifier, so -- as to return simplified and tidied Core. compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule compileToCoreSimplified = compileCore True compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule compileCore simplify fn = do -- First, set the target to the desired filename target <- guessTarget fn Nothing addTarget target _ <- load LoadAllTargets -- Then find dependencies modGraph <- depanal [] True case find ((== fn) . msHsFilePath) modGraph of Just modSummary -> do -- Now we have the module name; -- parse, typecheck and desugar the module mod_guts <- coreModule `fmap` -- TODO: space leaky: call hsc* directly? (desugarModule =<< typecheckModule =<< parseModule modSummary) liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $ if simplify then do -- If simplify is true: simplify (hscSimplify), then tidy -- (tidyProgram). hsc_env <- getSession simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts return $ Left tidy_guts else return $ Right mod_guts Nothing -> panic "compileToCoreModule: target FilePath not found in\ module dependency graph" where -- two versions, based on whether we simplify (thus run tidyProgram, -- which returns a (CgGuts, ModDetails) pair, or not (in which case -- we just have a ModGuts. gutsToCoreModule :: SafeHaskellMode -> Either (CgGuts, ModDetails) ModGuts -> CoreModule gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule { cm_module = cg_module cg, cm_types = md_types md, cm_binds = cg_binds cg, cm_safe = safe_mode } gutsToCoreModule safe_mode (Right mg) = CoreModule { cm_module = mg_module mg, cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg)) (mg_tcs mg) (mg_fam_insts mg), cm_binds = mg_binds mg, cm_safe = safe_mode } -- %************************************************************************ -- %* * -- Inspecting the session -- %* * -- %************************************************************************ -- | Get the module dependency graph. getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary getModuleGraph = liftM hsc_mod_graph getSession -- | Determines whether a set of modules requires Template Haskell. -- -- Note that if the session's 'DynFlags' enabled Template Haskell when -- 'depanal' was called, then each module in the returned module graph will -- have Template Haskell enabled whether it is actually needed or not. needsTemplateHaskell :: ModuleGraph -> Bool needsTemplateHaskell ms = any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms -- | Return @True@ <==> module is loaded. isLoaded :: GhcMonad m => ModuleName -> m Bool isLoaded m = withSession $ \hsc_env -> return $! isJust (lookupUFM (hsc_HPT hsc_env) m) -- | Return the bindings for the current interactive session. getBindings :: GhcMonad m => m [TyThing] getBindings = withSession $ \hsc_env -> return $ icInScopeTTs $ hsc_IC hsc_env -- | Return the instances for the current interactive session. getInsts :: GhcMonad m => m ([ClsInst], [FamInst]) getInsts = withSession $ \hsc_env -> return $ ic_instances (hsc_IC hsc_env) getPrintUnqual :: GhcMonad m => m PrintUnqualified getPrintUnqual = withSession $ \hsc_env -> return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env)) -- | Container for information about a 'Module'. data ModuleInfo = ModuleInfo { minf_type_env :: TypeEnv, minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails? minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod minf_instances :: [ClsInst], minf_iface :: Maybe ModIface, minf_safe :: SafeHaskellMode #ifdef GHCI ,minf_modBreaks :: ModBreaks #endif } -- We don't want HomeModInfo here, because a ModuleInfo applies -- to package modules too. -- | Request information about a loaded 'Module' getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X getModuleInfo mdl = withSession $ \hsc_env -> do let mg = hsc_mod_graph hsc_env if mdl `elem` map ms_mod mg then liftIO $ getHomeModuleInfo hsc_env mdl else do {- if isHomeModule (hsc_dflags hsc_env) mdl then return Nothing else -} liftIO $ getPackageModuleInfo hsc_env mdl -- ToDo: we don't understand what the following comment means. -- (SDM, 19/7/2011) -- getPackageModuleInfo will attempt to find the interface, so -- we don't want to call it for a home module, just in case there -- was a problem loading the module and the interface doesn't -- exist... hence the isHomeModule test here. (ToDo: reinstate) getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo) #ifdef GHCI getPackageModuleInfo hsc_env mdl = do eps <- hscEPS hsc_env iface <- hscGetModuleInterface hsc_env mdl let avails = mi_exports iface names = availsToNameSet avails pte = eps_PTE eps tys = [ ty | name <- concatMap availNames avails, Just ty <- [lookupTypeEnv pte name] ] -- return (Just (ModuleInfo { minf_type_env = mkTypeEnv tys, minf_exports = names, minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails, minf_instances = error "getModuleInfo: instances for package module unimplemented", minf_iface = Just iface, minf_safe = getSafeMode $ mi_trust iface, minf_modBreaks = emptyModBreaks })) #else -- bogusly different for non-GHCI (ToDo) getPackageModuleInfo _hsc_env _mdl = do return Nothing #endif getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo) getHomeModuleInfo hsc_env mdl = case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of Nothing -> return Nothing Just hmi -> do let details = hm_details hmi iface = hm_iface hmi return (Just (ModuleInfo { minf_type_env = md_types details, minf_exports = availsToNameSet (md_exports details), minf_rdr_env = mi_globals $! hm_iface hmi, minf_instances = md_insts details, minf_iface = Just iface, minf_safe = getSafeMode $ mi_trust iface #ifdef GHCI ,minf_modBreaks = getModBreaks hmi #endif })) -- | The list of top-level entities defined in a module modInfoTyThings :: ModuleInfo -> [TyThing] modInfoTyThings minf = typeEnvElts (minf_type_env minf) modInfoTopLevelScope :: ModuleInfo -> Maybe [Name] modInfoTopLevelScope minf = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf) modInfoExports :: ModuleInfo -> [Name] modInfoExports minf = nameSetToList $! minf_exports minf -- | Returns the instances defined by the specified module. -- Warning: currently unimplemented for package modules. modInfoInstances :: ModuleInfo -> [ClsInst] modInfoInstances = minf_instances modInfoIsExportedName :: ModuleInfo -> Name -> Bool modInfoIsExportedName minf name = elemNameSet name (minf_exports minf) mkPrintUnqualifiedForModule :: GhcMonad m => ModuleInfo -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf)) modInfoLookupName :: GhcMonad m => ModuleInfo -> Name -> m (Maybe TyThing) -- XXX: returns a Maybe X modInfoLookupName minf name = withSession $ \hsc_env -> do case lookupTypeEnv (minf_type_env minf) name of Just tyThing -> return (Just tyThing) Nothing -> do eps <- liftIO $ readIORef (hsc_EPS hsc_env) return $! lookupType (hsc_dflags hsc_env) (hsc_HPT hsc_env) (eps_PTE eps) name modInfoIface :: ModuleInfo -> Maybe ModIface modInfoIface = minf_iface -- | Retrieve module safe haskell mode modInfoSafe :: ModuleInfo -> SafeHaskellMode modInfoSafe = minf_safe #ifdef GHCI modInfoModBreaks :: ModuleInfo -> ModBreaks modInfoModBreaks = minf_modBreaks #endif isDictonaryId :: Id -> Bool isDictonaryId id = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau } -- | Looks up a global name: that is, any top-level name in any -- visible module. Unlike 'lookupName', lookupGlobalName does not use -- the interactive context, and therefore does not require a preceding -- 'setContext'. lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing) lookupGlobalName name = withSession $ \hsc_env -> do liftIO $ lookupTypeHscEnv hsc_env name findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a] findGlobalAnns deserialize target = withSession $ \hsc_env -> do ann_env <- liftIO $ prepareAnnotations hsc_env Nothing return (findAnns deserialize ann_env target) #ifdef GHCI -- | get the GlobalRdrEnv for a session getGRE :: GhcMonad m => m GlobalRdrEnv getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env) #endif -- ----------------------------------------------------------------------------- -- | Return all /external/ modules available in the package database. -- Modules from the current session (i.e., from the 'HomePackageTable') are -- not included. packageDbModules :: GhcMonad m => Bool -- ^ Only consider exposed packages. -> m [Module] packageDbModules only_exposed = do dflags <- getSessionDynFlags let pkgs = eltsUFM (pkgIdMap (pkgState dflags)) return $ [ mkModule pid modname | p <- pkgs , not only_exposed || exposed p , let pid = packageConfigId p , modname <- exposedModules p ] -- ----------------------------------------------------------------------------- -- Misc exported utils dataConType :: DataCon -> Type dataConType dc = idType (dataConWrapId dc) -- | print a 'NamedThing', adding parentheses if the name is an operator. pprParenSymName :: NamedThing a => a -> SDoc pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a)) -- ---------------------------------------------------------------------------- #if 0 -- ToDo: -- - Data and Typeable instances for HsSyn. -- ToDo: check for small transformations that happen to the syntax in -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral) -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way -- to get from TyCons, Ids etc. to TH syntax (reify). -- :browse will use either lm_toplev or inspect lm_interface, depending -- on whether the module is interpreted or not. #endif -- Extract the filename, stringbuffer content and dynflags associed to a module -- -- XXX: Explain pre-conditions getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags) getModuleSourceAndFlags mod = do m <- getModSummary (moduleName mod) case ml_hs_file $ ms_location m of Nothing -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod) Just sourceFile -> do source <- liftIO $ hGetStringBuffer sourceFile return (sourceFile, source, ms_hspp_opts m) -- | Return module source as token stream, including comments. -- -- The module must be in the module graph and its source must be available. -- Throws a 'HscTypes.SourceError' on parse error. getTokenStream :: GhcMonad m => Module -> m [Located Token] getTokenStream mod = do (sourceFile, source, flags) <- getModuleSourceAndFlags mod let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1 case lexTokenStream source startLoc flags of POk _ ts -> return ts PFailed span err -> do dflags <- getDynFlags liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err) -- | Give even more information on the source than 'getTokenStream' -- This function allows reconstructing the source completely with -- 'showRichTokenStream'. getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)] getRichTokenStream mod = do (sourceFile, source, flags) <- getModuleSourceAndFlags mod let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1 case lexTokenStream source startLoc flags of POk _ ts -> return $ addSourceToTokens startLoc source ts PFailed span err -> do dflags <- getDynFlags liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err) -- | Given a source location and a StringBuffer corresponding to this -- location, return a rich token stream with the source associated to the -- tokens. addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token] -> [(Located Token, String)] addSourceToTokens _ _ [] = [] addSourceToTokens loc buf (t@(L span _) : ts) = case span of UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts where (newLoc, newBuf, str) = go "" loc buf start = realSrcSpanStart s end = realSrcSpanEnd s go acc loc buf | loc < start = go acc nLoc nBuf | start <= loc && loc < end = go (ch:acc) nLoc nBuf | otherwise = (loc, buf, reverse acc) where (ch, nBuf) = nextChar buf nLoc = advanceSrcLoc loc ch -- | Take a rich token stream such as produced from 'getRichTokenStream' and -- return source code almost identical to the original code (except for -- insignificant whitespace.) showRichTokenStream :: [(Located Token, String)] -> String showRichTokenStream ts = go startLoc ts "" where sourceFile = getFile $ map (getLoc . fst) ts getFile [] = panic "showRichTokenStream: No source file found" getFile (UnhelpfulSpan _ : xs) = getFile xs getFile (RealSrcSpan s : _) = srcSpanFile s startLoc = mkRealSrcLoc sourceFile 1 1 go _ [] = id go loc ((L span _, str):ts) = case span of UnhelpfulSpan _ -> go loc ts RealSrcSpan s | locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++) . (str ++) . go tokEnd ts | otherwise -> ((replicate (tokLine - locLine) '\n') ++) . ((replicate (tokCol - 1) ' ') ++) . (str ++) . go tokEnd ts where (locLine, locCol) = (srcLocLine loc, srcLocCol loc) (tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s) tokEnd = realSrcSpanEnd s -- ----------------------------------------------------------------------------- -- Interactive evaluation -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the -- filesystem and package database to find the corresponding 'Module', -- using the algorithm that is used for an @import@ declaration. findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module findModule mod_name maybe_pkg = withSession $ \hsc_env -> do let dflags = hsc_dflags hsc_env this_pkg = thisPackage dflags -- case maybe_pkg of Just pkg | fsToPackageId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do res <- findImportedModule hsc_env mod_name maybe_pkg case res of Found _ m -> return m err -> throwOneError $ noModError dflags noSrcSpan mod_name err _otherwise -> do home <- lookupLoadedHomeModule mod_name case home of Just m -> return m Nothing -> liftIO $ do res <- findImportedModule hsc_env mod_name maybe_pkg case res of Found loc m | modulePackageId m /= this_pkg -> return m | otherwise -> modNotLoadedError dflags m loc err -> throwOneError $ noModError dflags noSrcSpan mod_name err modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $ text "module is not loaded:" <+> quotes (ppr (moduleName m)) <+> parens (text (expectJust "modNotLoadedError" (ml_hs_file loc))) -- | Like 'findModule', but differs slightly when the module refers to -- a source file, and the file has not been loaded via 'load'. In -- this case, 'findModule' will throw an error (module not loaded), -- but 'lookupModule' will check to see whether the module can also be -- found in a package, and if so, that package 'Module' will be -- returned. If not, the usual module-not-found error will be thrown. -- lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg) lookupModule mod_name Nothing = withSession $ \hsc_env -> do home <- lookupLoadedHomeModule mod_name case home of Just m -> return m Nothing -> liftIO $ do res <- findExposedPackageModule hsc_env mod_name Nothing case res of Found _ m -> return m err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module) lookupLoadedHomeModule mod_name = withSession $ \hsc_env -> case lookupUFM (hsc_HPT hsc_env) mod_name of Just mod_info -> return (Just (mi_module (hm_iface mod_info))) _not_a_home_module -> return Nothing #ifdef GHCI -- | Check that a module is safe to import (according to Safe Haskell). -- -- We return True to indicate the import is safe and False otherwise -- although in the False case an error may be thrown first. isModuleTrusted :: GhcMonad m => Module -> m Bool isModuleTrusted m = withSession $ \hsc_env -> liftIO $ hscCheckSafe hsc_env m noSrcSpan -- | Return if a module is trusted and the pkgs it depends on to be trusted. moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [PackageId]) moduleTrustReqs m = withSession $ \hsc_env -> liftIO $ hscGetSafe hsc_env m noSrcSpan -- | EXPERIMENTAL: DO NOT USE. -- -- Set the monad GHCi lifts user statements into. -- -- Checks that a type (in string form) is an instance of the -- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is, -- throws an error otherwise. {-# WARNING setGHCiMonad "This is experimental! Don't use." #-} setGHCiMonad :: GhcMonad m => String -> m () setGHCiMonad name = withSession $ \hsc_env -> do ty <- liftIO $ hscIsGHCiMonad hsc_env name modifySession $ \s -> let ic = (hsc_IC s) { ic_monad = ty } in s { hsc_IC = ic } getHistorySpan :: GhcMonad m => History -> m SrcSpan getHistorySpan h = withSession $ \hsc_env -> return $ InteractiveEval.getHistorySpan hsc_env h obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term obtainTermFromVal bound force ty a = withSession $ \hsc_env -> liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term obtainTermFromId bound force id = withSession $ \hsc_env -> liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id #endif -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any -- entity known to GHC, including 'Name's defined using 'runStmt'. lookupName :: GhcMonad m => Name -> m (Maybe TyThing) lookupName name = withSession $ \hsc_env -> liftIO $ hscTcRcLookupName hsc_env name -- ----------------------------------------------------------------------------- -- Pure API -- | A pure interface to the module parser. -- parser :: String -- ^ Haskell module source text (full Unicode is supported) -> DynFlags -- ^ the flags -> FilePath -- ^ the filename (for source locations) -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName)) parser str dflags filename = let loc = mkRealSrcLoc (mkFastString filename) 1 1 buf = stringToStringBuffer str in case unP Parser.parseModule (mkPState dflags buf loc) of PFailed span err -> Left (unitBag (mkPlainErrMsg dflags span err)) POk pst rdr_module -> let (warns,_) = getMessages pst in Right (warns, rdr_module)
ryantm/ghc
compiler/main/GHC.hs
Haskell
bsd-3-clause
54,766
{-# LANGUAGE GADTs, RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts, FlexibleInstances #-} -- | 'ProgramAlt' example: simple applicative parsers module Parser where import Control.Applicative import Control.Alternative.Operational import Control.Operational.Instruction import Control.Monad import Control.Monad.Trans.State import Data.Functor.Compose import Data.Traversable import Data.Maybe (listToMaybe) import Data.List (find, stripPrefix) --------------------------------------------------------------- --------------------------------------------------------------- -- -- Parser combinators -- data ParserI a where Symbol :: Char -> ParserI Char char :: Operational ParserI f => Char -> f Char char = singleton . Symbol string :: (Operational ParserI f, Applicative f) => String -> f String string = traverse char oneOf :: (Operational ParserI f, Alternative f) => String -> f Char oneOf = foldr (<|>) empty . map char -- | Interpret a parser program syntactically by pattern matching on -- its view. runParser :: ProgramAlt ParserI a -> String -> Maybe a runParser = fmap listToMaybe . eval . viewAlt where eval :: ProgramViewAlt ParserI a -> String -> [a] eval (Pure a) [] = pure a eval (Pure a) _ = empty eval (Symbol c :<**> k) [] = empty eval (Symbol c :<**> k) (x:xs) | c == x = pure c <**> eval k xs | otherwise = empty eval (Many ps) str = fmap asum (sequenceA (map eval ps)) str asum :: Alternative f => [f a] -> f a asum = foldr (<|>) empty -- | This version is maybe more conventional than 'runParser'. runConventional :: ProgramAlt ParserI a -> String -> Maybe a runConventional = (succeed .) . eval . viewAlt where eval :: ProgramViewAlt ParserI a -> String -> [(a, String)] eval (Pure a) str = [(a, str)] eval (Symbol c :<**> k) "" = [] eval (Symbol c :<**> k) (x:xs) | c == x = [(k' c, str') | (k', str') <- eval k xs] | otherwise = [] eval (Many ps) str = asum $ map (flip eval str) ps -- | Example parser: match parentheses and count depth. parens :: ProgramAlt ParserI Int parens = pure 0 <|> fmap (+1) (char '(' *> parens <* char ')') -- | Interpret a parser program denotationally, by evaluating each -- 'ParserI' instruction to an 'Alternative' action. runParser' :: ProgramAlt ParserI a -> String -> Maybe a runParser' = (succeed .) . runStateT . interpretAlt evalParserI succeed :: [(a, String)] -> Maybe a succeed = fmap fst . find step where step (a, "") = True step (_, _) = False evalParserI :: ParserI a -> StateT String [] a evalParserI (Symbol c) = do str <- get case str of x:xs | c == x -> put xs >> return c otherwise -> mzero -- | Static analysis example: enumerate the strings accepted by a parser. -- Not all parsers can be enumerate; for example, this one doesn't: -- -- > -- diverges: -- > let a = char 'a' *> a -- > in enumerate a -- -- The problem in this example is that there is no string such that -- the parser accepts it in finitely many steps. enumerate :: ProgramAlt ParserI a -> [String] enumerate = go [showString ""] . viewAlt where go :: [ShowS] -> ProgramViewAlt ParserI a -> [String] go strs (Pure a) = map ($"") strs go strs (Symbol c :<**> k) = go (map (.(showChar c)) strs) k go strs (Many ps) = interleave $ map (go strs) ps interleave :: [[a]] -> [a] interleave = foldr interleave2 [] where interleave2 :: [a] -> [a] -> [a] interleave2 [] ys = ys interleave2 (x:xs) ys = x : interleave2 ys xs -- | Static analysis example: optimize a parser by merging shared -- prefixes. This works by reducing a parser to this normal form: -- -- > 1. Pure a -- > 2. Symbol c :<**> nf -- nf is in normal form -- > 3. Many [nf, ...] -- nf is Pure _ or Symbol c :<**> nf' -- -- In addition, we order the branches by Symbol order to ensure -- merging. optimize :: ProgramAlt ParserI a -> ProgramAlt ParserI a optimize = compileAlt . merge . viewAlt merge :: ProgramViewAlt ParserI a -> ProgramViewAlt ParserI a merge p@(Pure _) = p merge (Symbol a :<**> k) = Symbol a :<**> merge k merge (Many ps) = Many (mergeMany ps) mergeMany :: [ProgramViewAlt ParserI a] -> [ProgramViewAlt ParserI a] mergeMany = foldr step [] . map merge where step (Pure a) ps = Pure a : ps step (Symbol a :<**> l) ((Symbol b :<**> r) : ps) = case a `compare` b of EQ -> (Symbol a :<**> Many (mergeMany [l, r])) : ps LT -> (Symbol a :<**> l) : (Symbol b :<**> r) : ps GT -> (Symbol b :<**> r) : (Symbol a :<**> l) : ps step (Symbol a :<**> l) ps = (Symbol a :<**> l) : ps step (Many ps) ps' = mergeMany (mergeMany ps ++ ps') tokens :: [String] -> ProgramAlt ParserI String tokens = asum . map string example = ["abactor", "abacus", "abaft", "abaisance", "abaissed", "abalone"] describe :: forall a. ProgramAlt ParserI a -> Description describe = eval . viewAlt where eval :: forall x. ProgramViewAlt ParserI x -> Description eval (Pure _) = Ok eval (Symbol c :<**> k) = c :> (eval k) eval (Many ps) = OneOf (map eval ps) data Description = Ok | Char :> Description | OneOf [Description] deriving Show data StringI a where String :: String -> StringI String evalStringI :: StringI a -> StateT String [] a evalStringI (String "") = return "" evalStringI (String str) = do str' <- get case str `stripPrefix` str' of Nothing -> mzero Just suffix -> put suffix >> return str runStringP :: ProgramAlt (Coproduct ParserI StringI) a -> String -> [(a, String)] runStringP = runStateT . interpretAlt (coproduct evalParserI evalStringI)
sacundim/free-operational
examples/Parser.hs
Haskell
bsd-3-clause
5,927
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE StandaloneDeriving #-} module Snap.Internal.Types where ------------------------------------------------------------------------------ import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Char.Utf8 import Control.Applicative import Control.Exception (SomeException, throwIO, ErrorCall(..)) import Control.Monad import Control.Monad.CatchIO import qualified Control.Monad.Error.Class as EC import Control.Monad.State import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.CaseInsensitive (CI) import Data.Int import Data.IORef import Data.Maybe import Data.Monoid import Data.Time import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Data.Typeable #if MIN_VERSION_base(4,6,0) import Prelude hiding (take) #else import Prelude hiding (catch, take) #endif import System.PosixCompat.Files hiding (setFileSize) import System.Posix.Types (FileOffset) ------------------------------------------------------------------------------ import Snap.Internal.Exceptions import Snap.Internal.Http.Types import Snap.Internal.Iteratee.Debug import Snap.Iteratee hiding (map) import qualified Snap.Types.Headers as H import Snap.Util.Readable ------------------------------------------------------------------------------ -------------------- -- The Snap Monad -- -------------------- {-| 'Snap' is the 'Monad' that user web handlers run in. 'Snap' gives you: 1. stateful access to fetch or modify an HTTP 'Request' 2. stateful access to fetch or modify an HTTP 'Response' 3. failure \/ 'Alternative' \/ 'MonadPlus' semantics: a 'Snap' handler can choose not to handle a given request, using 'empty' or its synonym 'pass', and you can try alternative handlers with the '<|>' operator: > a :: Snap String > a = pass > > b :: Snap String > b = return "foo" > > c :: Snap String > c = a <|> b -- try running a, if it fails then try b 4. convenience functions ('writeBS', 'writeLBS', 'writeText', 'writeLazyText', 'addToOutput') for queueing output to be written to the 'Response': > a :: (forall a . Enumerator a) -> Snap () > a someEnumerator = do > writeBS "I'm a strict bytestring" > writeLBS "I'm a lazy bytestring" > writeText "I'm strict text" > addToOutput someEnumerator 5. early termination: if you call 'finishWith': > a :: Snap () > a = do > modifyResponse $ setResponseStatus 500 "Internal Server Error" > writeBS "500 error" > r <- getResponse > finishWith r then any subsequent processing will be skipped and supplied 'Response' value will be returned from 'runSnap' as-is. 6. access to the 'IO' monad through a 'MonadIO' instance: > a :: Snap () > a = liftIO fireTheMissiles 7. the ability to set or extend a timeout which will kill the handler thread after @N@ seconds of inactivity (the default is 20 seconds): > a :: Snap () > a = setTimeout 30 8. throw and catch exceptions using a 'MonadCatchIO' instance: > foo :: Snap () > foo = bar `catch` \(e::SomeException) -> baz > where > bar = throw FooException 9. log a message to the error log: > foo :: Snap () > foo = logError "grumble." You may notice that most of the type signatures in this module contain a @(MonadSnap m) => ...@ typeclass constraint. 'MonadSnap' is a typeclass which, in essence, says \"you can get back to the 'Snap' monad from here\". Using 'MonadSnap' you can extend the 'Snap' monad with additional functionality and still have access to most of the 'Snap' functions without writing 'lift' everywhere. Instances are already provided for most of the common monad transformers ('ReaderT', 'WriterT', 'StateT', etc.). -} ------------------------------------------------------------------------------ -- | 'MonadSnap' is a type class, analogous to 'MonadIO' for 'IO', that makes -- it easy to wrap 'Snap' inside monad transformers. class (Monad m, MonadIO m, MonadCatchIO m, MonadPlus m, Functor m, Applicative m, Alternative m) => MonadSnap m where liftSnap :: Snap a -> m a ------------------------------------------------------------------------------ data SnapResult a = SnapValue a | PassOnProcessing String | EarlyTermination Response ------------------------------------------------------------------------------ newtype Snap a = Snap { unSnap :: StateT SnapState (Iteratee ByteString IO) (SnapResult a) } ------------------------------------------------------------------------------ data SnapState = SnapState { _snapRequest :: Request , _snapResponse :: Response , _snapLogError :: ByteString -> IO () , _snapModifyTimeout :: (Int -> Int) -> IO () } ------------------------------------------------------------------------------ instance Monad Snap where (>>=) = snapBind return = snapReturn fail = snapFail ------------------------------------------------------------------------------ snapBind :: Snap a -> (a -> Snap b) -> Snap b snapBind (Snap m) f = Snap $ do res <- m case res of SnapValue a -> unSnap $! f a PassOnProcessing r -> return $! PassOnProcessing r EarlyTermination r -> return $! EarlyTermination r {-# INLINE snapBind #-} snapReturn :: a -> Snap a snapReturn = Snap . return . SnapValue {-# INLINE snapReturn #-} snapFail :: String -> Snap a snapFail !m = Snap $! return $! PassOnProcessing m {-# INLINE snapFail #-} ------------------------------------------------------------------------------ instance MonadIO Snap where liftIO m = Snap $! liftM SnapValue $! liftIO m ------------------------------------------------------------------------------ instance MonadCatchIO Snap where catch (Snap m) handler = Snap $! m `catch` h where h e = do rethrowIfUncatchable $ fromException e maybe (throw e) (\e' -> let (Snap z) = handler e' in z) (fromException e) block (Snap m) = Snap $ block m unblock (Snap m) = Snap $ unblock m ------------------------------------------------------------------------------ rethrowIfUncatchable :: (MonadCatchIO m) => Maybe UncatchableException -> m () rethrowIfUncatchable Nothing = return () rethrowIfUncatchable (Just e) = throw e ------------------------------------------------------------------------------ instance MonadPlus Snap where mzero = Snap $! return $! PassOnProcessing "" a `mplus` b = Snap $! do r <- unSnap a -- redundant just in case ordering by frequency helps here. case r of SnapValue _ -> return r PassOnProcessing _ -> unSnap b _ -> return r ------------------------------------------------------------------------------ instance (EC.MonadError String) Snap where throwError = fail catchError act hndl = Snap $ do r <- unSnap act -- redundant just in case ordering by frequency helps here. case r of SnapValue _ -> return r PassOnProcessing m -> unSnap $ hndl m _ -> return r ------------------------------------------------------------------------------ instance Functor Snap where fmap = liftM ------------------------------------------------------------------------------ instance Applicative Snap where pure = return (<*>) = ap ------------------------------------------------------------------------------ instance Alternative Snap where empty = mzero (<|>) = mplus ------------------------------------------------------------------------------ instance MonadSnap Snap where liftSnap = id ------------------------------------------------------------------------------ -- | The Typeable instance is here so Snap can be dynamically executed with -- Hint. snapTyCon :: TyCon #if MIN_VERSION_base(4,4,0) snapTyCon = mkTyCon3 "snap-core" "Snap.Core" "Snap" #else snapTyCon = mkTyCon "Snap.Core.Snap" #endif {-# NOINLINE snapTyCon #-} #if __GLASGOW_HASKELL__ < 708 instance Typeable1 Snap where typeOf1 _ = mkTyConApp snapTyCon [] #else deriving instance Typeable Snap #endif ------------------------------------------------------------------------------ liftIter :: MonadSnap m => Iteratee ByteString IO a -> m a liftIter i = liftSnap $ Snap (lift i >>= return . SnapValue) ------------------------------------------------------------------------------ -- | Sends the request body through an iteratee (data consumer) and -- returns the result. -- -- If the iteratee you pass in here throws an exception, Snap will attempt to -- clear the rest of the unread request body before rethrowing the exception. -- If your iteratee used 'terminateConnection', however, Snap will give up and -- immediately close the socket. runRequestBody :: MonadSnap m => Iteratee ByteString IO a -> m a runRequestBody iter = do bumpTimeout <- liftM ($ max 5) getTimeoutModifier req <- getRequest senum <- liftIO $ readIORef $ rqBody req let (SomeEnumerator enum) = senum -- make sure the iteratee consumes all of the output let iter' = handle bumpTimeout req (iter >>= \a -> skipToEnd bumpTimeout >> return a) -- run the iteratee step <- liftIO $ runIteratee iter' result <- liftIter $ enum step -- stuff a new dummy enumerator into the request, so you can only try to -- read the request body from the socket once resetEnum req return result where resetEnum req = liftIO $ writeIORef (rqBody req) $ SomeEnumerator $ joinI . take 0 skipToEnd bump = killIfTooSlow bump 500 5 skipToEof `catchError` \e -> throwError $ ConnectionTerminatedException e handle bump req = (`catches` [ Handler $ \(e :: ConnectionTerminatedException) -> do let en = SomeEnumerator $ const $ throwError e liftIO $ writeIORef (rqBody req) en throwError e , Handler $ \(e :: SomeException) -> do resetEnum req skipToEnd bump throwError e ]) ------------------------------------------------------------------------------ -- | Returns the request body as a lazy bytestring. -- -- This function is deprecated as of 0.6; it places no limits on the size of -- the request being read, and as such, if used, can result in a -- denial-of-service attack on your server. Please use 'readRequestBody' -- instead. getRequestBody :: MonadSnap m => m L.ByteString getRequestBody = liftM L.fromChunks $ runRequestBody consume {-# INLINE getRequestBody #-} {-# DEPRECATED getRequestBody "As of 0.6, please use 'readRequestBody' instead" #-} ------------------------------------------------------------------------------ -- | Returns the request body as a lazy bytestring. /New in 0.6./ readRequestBody :: MonadSnap m => Int64 -- ^ size of the largest request body we're willing -- to accept. If a request body longer than this is -- received, a 'TooManyBytesReadException' is -- thrown. See 'takeNoMoreThan'. -> m L.ByteString readRequestBody sz = liftM L.fromChunks $ runRequestBody $ joinI $ takeNoMoreThan sz $$ consume ------------------------------------------------------------------------------ -- | Normally Snap is careful to ensure that the request body is fully -- consumed after your web handler runs, but before the 'Response' enumerator -- is streamed out the socket. If you want to transform the request body into -- some output in O(1) space, you should use this function. -- -- Note that upon calling this function, response processing finishes early as -- if you called 'finishWith'. Make sure you set any content types, headers, -- cookies, etc. before you call this function. -- transformRequestBody :: (forall a . Enumerator Builder IO a) -- ^ the output 'Iteratee' is passed to this -- 'Enumerator', and then the resulting 'Iteratee' is -- fed the request body stream. Your 'Enumerator' is -- responsible for transforming the input. -> Snap () transformRequestBody trans = do req <- getRequest let ioref = rqBody req senum <- liftIO $ readIORef ioref let (SomeEnumerator enum') = senum let enum = mapEnum toByteString fromByteString enum' liftIO $ writeIORef ioref (SomeEnumerator enumEOF) origRsp <- getResponse let rsp = setResponseBody (\writeEnd -> do let i = iterateeDebugWrapperWith showBuilder "transformRequestBody" $ trans writeEnd st <- liftIO $ runIteratee i enum st) $ origRsp { rspTransformingRqBody = True } finishWith rsp ------------------------------------------------------------------------------ -- | Short-circuits a 'Snap' monad action early, storing the given -- 'Response' value in its state. finishWith :: MonadSnap m => Response -> m a finishWith = liftSnap . Snap . return . EarlyTermination {-# INLINE finishWith #-} ------------------------------------------------------------------------------ -- | Capture the flow of control in case a handler calls 'finishWith'. -- -- /WARNING/: in the event of a call to 'transformRequestBody' it is possible -- to violate HTTP protocol safety when using this function. If you call -- 'catchFinishWith' it is suggested that you do not modify the body of the -- 'Response' which was passed to the 'finishWith' call. catchFinishWith :: Snap a -> Snap (Either Response a) catchFinishWith (Snap m) = Snap $ do r <- m case r of SnapValue a -> return $! SnapValue $! Right a PassOnProcessing e -> return $! PassOnProcessing e EarlyTermination resp -> return $! SnapValue $! Left resp {-# INLINE catchFinishWith #-} ------------------------------------------------------------------------------ -- | Fails out of a 'Snap' monad action. This is used to indicate -- that you choose not to handle the given request within the given -- handler. pass :: MonadSnap m => m a pass = empty ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action only if the request's HTTP method matches -- the given method. method :: MonadSnap m => Method -> m a -> m a method m action = do req <- getRequest unless (rqMethod req == m) pass action {-# INLINE method #-} ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action only if the request's HTTP method matches -- one of the given methods. methods :: MonadSnap m => [Method] -> m a -> m a methods ms action = do req <- getRequest unless (rqMethod req `elem` ms) pass action {-# INLINE methods #-} ------------------------------------------------------------------------------ -- Appends n bytes of the path info to the context path with a -- trailing slash. updateContextPath :: Int -> Request -> Request updateContextPath n req | n > 0 = req { rqContextPath = ctx , rqPathInfo = pinfo } | otherwise = req where ctx' = S.take n (rqPathInfo req) ctx = S.concat [rqContextPath req, ctx', "/"] pinfo = S.drop (n+1) (rqPathInfo req) ------------------------------------------------------------------------------ -- Runs a 'Snap' monad action only if the 'rqPathInfo' matches the given -- predicate. pathWith :: MonadSnap m => (ByteString -> ByteString -> Bool) -> ByteString -> m a -> m a pathWith c p action = do req <- getRequest unless (c p (rqPathInfo req)) pass localRequest (updateContextPath $ S.length p) action ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action only when the 'rqPathInfo' of the request -- starts with the given path. For example, -- -- > dir "foo" handler -- -- Will fail if 'rqPathInfo' is not \"@\/foo@\" or \"@\/foo\/...@\", and will -- add @\"foo\/\"@ to the handler's local 'rqContextPath'. dir :: MonadSnap m => ByteString -- ^ path component to match -> m a -- ^ handler to run -> m a dir = pathWith f where f dr pinfo = dr == x where (x,_) = S.break (=='/') pinfo {-# INLINE dir #-} ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action only for requests where 'rqPathInfo' is -- exactly equal to the given string. If the path matches, locally sets -- 'rqContextPath' to the old value of 'rqPathInfo', sets 'rqPathInfo'=\"\", -- and runs the given handler. path :: MonadSnap m => ByteString -- ^ path to match against -> m a -- ^ handler to run -> m a path = pathWith (==) {-# INLINE path #-} ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action only when the first path component is -- successfully parsed as the argument to the supplied handler function. pathArg :: (Readable a, MonadSnap m) => (a -> m b) -> m b pathArg f = do req <- getRequest let (p,_) = S.break (=='/') (rqPathInfo req) a <- fromBS p localRequest (updateContextPath $ S.length p) (f a) ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action only when 'rqPathInfo' is empty. ifTop :: MonadSnap m => m a -> m a ifTop = path "" {-# INLINE ifTop #-} ------------------------------------------------------------------------------ -- | Local Snap version of 'get'. sget :: Snap SnapState sget = Snap $ liftM SnapValue get {-# INLINE sget #-} ------------------------------------------------------------------------------ -- | Local Snap monad version of 'modify'. smodify :: (SnapState -> SnapState) -> Snap () smodify f = Snap $ modify f >> return (SnapValue ()) {-# INLINE smodify #-} ------------------------------------------------------------------------------ -- | Grabs the 'Request' object out of the 'Snap' monad. getRequest :: MonadSnap m => m Request getRequest = liftSnap $ liftM _snapRequest sget {-# INLINE getRequest #-} ------------------------------------------------------------------------------ -- | Grabs something out of the 'Request' object, using the given projection -- function. See 'gets'. getsRequest :: MonadSnap m => (Request -> a) -> m a getsRequest f = liftSnap $ liftM (f . _snapRequest) sget {-# INLINE getsRequest #-} ------------------------------------------------------------------------------ -- | Grabs the 'Response' object out of the 'Snap' monad. getResponse :: MonadSnap m => m Response getResponse = liftSnap $ liftM _snapResponse sget {-# INLINE getResponse #-} ------------------------------------------------------------------------------ -- | Grabs something out of the 'Response' object, using the given projection -- function. See 'gets'. getsResponse :: MonadSnap m => (Response -> a) -> m a getsResponse f = liftSnap $ liftM (f . _snapResponse) sget {-# INLINE getsResponse #-} ------------------------------------------------------------------------------ -- | Puts a new 'Response' object into the 'Snap' monad. putResponse :: MonadSnap m => Response -> m () putResponse r = liftSnap $ smodify $ \ss -> ss { _snapResponse = r } {-# INLINE putResponse #-} ------------------------------------------------------------------------------ -- | Puts a new 'Request' object into the 'Snap' monad. putRequest :: MonadSnap m => Request -> m () putRequest r = liftSnap $ smodify $ \ss -> ss { _snapRequest = r } {-# INLINE putRequest #-} ------------------------------------------------------------------------------ -- | Modifies the 'Request' object stored in a 'Snap' monad. modifyRequest :: MonadSnap m => (Request -> Request) -> m () modifyRequest f = liftSnap $ smodify $ \ss -> ss { _snapRequest = f $ _snapRequest ss } {-# INLINE modifyRequest #-} ------------------------------------------------------------------------------ -- | Modifes the 'Response' object stored in a 'Snap' monad. modifyResponse :: MonadSnap m => (Response -> Response) -> m () modifyResponse f = liftSnap $ smodify $ \ss -> ss { _snapResponse = f $ _snapResponse ss } {-# INLINE modifyResponse #-} ------------------------------------------------------------------------------ -- | Performs a redirect by setting the @Location@ header to the given target -- URL/path and the status code to 302 in the 'Response' object stored in a -- 'Snap' monad. Note that the target URL is not validated in any way. -- Consider using 'redirect\'' instead, which allows you to choose the correct -- status code. redirect :: MonadSnap m => ByteString -> m a redirect target = redirect' target 302 {-# INLINE redirect #-} ------------------------------------------------------------------------------ -- | Performs a redirect by setting the @Location@ header to the given target -- URL/path and the status code (should be one of 301, 302, 303 or 307) in the -- 'Response' object stored in a 'Snap' monad. Note that the target URL is not -- validated in any way. redirect' :: MonadSnap m => ByteString -> Int -> m a redirect' target status = do r <- getResponse finishWith $ setResponseCode status $ setContentLength 0 $ modifyResponseBody (const $ enumBuilder mempty) $ setHeader "Location" target r {-# INLINE redirect' #-} ------------------------------------------------------------------------------ -- | Log an error message in the 'Snap' monad logError :: MonadSnap m => ByteString -> m () logError s = liftSnap $ Snap $ gets _snapLogError >>= (\l -> liftIO $ l s) >> return (SnapValue ()) {-# INLINE logError #-} ------------------------------------------------------------------------------ -- | Adds the output from the given enumerator to the 'Response' -- stored in the 'Snap' monad state. addToOutput :: MonadSnap m => (forall a . Enumerator Builder IO a) -- ^ output to add -> m () addToOutput enum = modifyResponse $ modifyResponseBody (>==> enum) ------------------------------------------------------------------------------ -- | Adds the given 'Builder' to the body of the 'Response' stored in the -- | 'Snap' monad state. writeBuilder :: MonadSnap m => Builder -> m () writeBuilder b = addToOutput $ enumBuilder b {-# INLINE writeBuilder #-} ------------------------------------------------------------------------------ -- | Adds the given strict 'ByteString' to the body of the 'Response' stored -- in the 'Snap' monad state. -- -- Warning: This function is intentionally non-strict. If any pure -- exceptions are raised by the expression creating the 'ByteString', -- the exception won't actually be raised within the Snap handler. writeBS :: MonadSnap m => ByteString -> m () writeBS s = writeBuilder $ fromByteString s ------------------------------------------------------------------------------ -- | Adds the given lazy 'L.ByteString' to the body of the 'Response' stored -- in the 'Snap' monad state. -- -- Warning: This function is intentionally non-strict. If any pure -- exceptions are raised by the expression creating the 'ByteString', -- the exception won't actually be raised within the Snap handler. writeLBS :: MonadSnap m => L.ByteString -> m () writeLBS s = writeBuilder $ fromLazyByteString s ------------------------------------------------------------------------------ -- | Adds the given strict 'T.Text' to the body of the 'Response' stored in -- the 'Snap' monad state. -- -- Warning: This function is intentionally non-strict. If any pure -- exceptions are raised by the expression creating the 'ByteString', -- the exception won't actually be raised within the Snap handler. writeText :: MonadSnap m => T.Text -> m () writeText s = writeBuilder $ fromText s ------------------------------------------------------------------------------ -- | Adds the given lazy 'LT.Text' to the body of the 'Response' stored in the -- 'Snap' monad state. -- -- Warning: This function is intentionally non-strict. If any pure -- exceptions are raised by the expression creating the 'ByteString', -- the exception won't actually be raised within the Snap handler. writeLazyText :: MonadSnap m => LT.Text -> m () writeLazyText s = writeBuilder $ fromLazyText s ------------------------------------------------------------------------------ -- | Sets the output to be the contents of the specified file. -- -- Calling 'sendFile' will overwrite any output queued to be sent in the -- 'Response'. If the response body is not modified after the call to -- 'sendFile', Snap will use the efficient @sendfile()@ system call on -- platforms that support it. -- -- If the response body is modified (using 'modifyResponseBody'), the file -- will be read using @mmap()@. sendFile :: (MonadSnap m) => FilePath -> m () sendFile f = modifyResponse $ \r -> r { rspBody = SendFile f Nothing } ------------------------------------------------------------------------------ -- | Sets the output to be the contents of the specified file, within the -- given (start,end) range. -- -- Calling 'sendFilePartial' will overwrite any output queued to be sent in -- the 'Response'. If the response body is not modified after the call to -- 'sendFilePartial', Snap will use the efficient @sendfile()@ system call on -- platforms that support it. -- -- If the response body is modified (using 'modifyResponseBody'), the file -- will be read using @mmap()@. sendFilePartial :: (MonadSnap m) => FilePath -> (Int64,Int64) -> m () sendFilePartial f rng = modifyResponse $ \r -> r { rspBody = SendFile f (Just rng) } ------------------------------------------------------------------------------ -- | Runs a 'Snap' action with a locally-modified 'Request' state -- object. The 'Request' object in the Snap monad state after the call -- to localRequest will be unchanged. localRequest :: MonadSnap m => (Request -> Request) -> m a -> m a localRequest f m = do req <- getRequest runAct req <|> (putRequest req >> pass) where runAct req = do modifyRequest f result <- m putRequest req return result {-# INLINE localRequest #-} ------------------------------------------------------------------------------ -- | Fetches the 'Request' from state and hands it to the given action. withRequest :: MonadSnap m => (Request -> m a) -> m a withRequest = (getRequest >>=) {-# INLINE withRequest #-} ------------------------------------------------------------------------------ -- | Fetches the 'Response' from state and hands it to the given action. withResponse :: MonadSnap m => (Response -> m a) -> m a withResponse = (getResponse >>=) {-# INLINE withResponse #-} ------------------------------------------------------------------------------ -- | Modifies the 'Request' in the state to set the 'rqRemoteAddr' -- field to the value in the X-Forwarded-For header. If the header is -- not present, this action has no effect. -- -- This action should be used only when working behind a reverse http -- proxy that sets the X-Forwarded-For header. This is the only way to -- ensure the value in the X-Forwarded-For header can be trusted. -- -- This is provided as a filter so actions that require the remote -- address can get it in a uniform manner. It has specifically limited -- functionality to ensure that its transformation can be trusted, -- when used correctly. ipHeaderFilter :: MonadSnap m => m () ipHeaderFilter = ipHeaderFilter' "x-forwarded-for" ------------------------------------------------------------------------------ -- | Modifies the 'Request' in the state to set the 'rqRemoteAddr' -- field to the value from the header specified. If the header -- specified is not present, this action has no effect. -- -- This action should be used only when working behind a reverse http -- proxy that sets the header being looked at. This is the only way to -- ensure the value in the header can be trusted. -- -- This is provided as a filter so actions that require the remote -- address can get it in a uniform manner. It has specifically limited -- functionality to ensure that its transformation can be trusted, -- when used correctly. ipHeaderFilter' :: MonadSnap m => CI ByteString -> m () ipHeaderFilter' header = do headerContents <- getHeader header <$> getRequest let whitespace = [ ' ', '\t', '\r', '\n' ] ipChrs = [ '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ] trim f s = f (`elem` s) clean = trim S.takeWhile ipChrs . trim S.dropWhile whitespace setIP ip = modifyRequest $ \rq -> rq { rqRemoteAddr = clean ip } maybe (return ()) setIP headerContents ------------------------------------------------------------------------------ -- | This function brackets a Snap action in resource acquisition and -- release. This is provided because MonadCatchIO's 'bracket' function -- doesn't work properly in the case of a short-circuit return from -- the action being bracketed. -- -- In order to prevent confusion regarding the effects of the -- aquisition and release actions on the Snap state, this function -- doesn't accept Snap actions for the acquire or release actions. -- -- This function will run the release action in all cases where the -- acquire action succeeded. This includes the following behaviors -- from the bracketed Snap action. -- -- 1. Normal completion -- -- 2. Short-circuit completion, either from calling 'fail' or 'finishWith' -- -- 3. An exception being thrown. bracketSnap :: IO a -> (a -> IO b) -> (a -> Snap c) -> Snap c bracketSnap before after thing = block . Snap $ do a <- liftIO before let after' = liftIO $ after a (Snap thing') = thing a r <- unblock thing' `onException` after' _ <- after' return r ------------------------------------------------------------------------------ -- | This exception is thrown if the handler you supply to 'runSnap' fails. data NoHandlerException = NoHandlerException String deriving (Eq, Typeable) ------------------------------------------------------------------------------ instance Show NoHandlerException where show (NoHandlerException e) = "No handler for request: failure was " ++ e ------------------------------------------------------------------------------ instance Exception NoHandlerException ------------------------------------------------------------------------------ -- | Terminate the HTTP session with the given exception. terminateConnection :: (Exception e, MonadCatchIO m) => e -> m a terminateConnection = throw . ConnectionTerminatedException . toException ------------------------------------------------------------------------------ -- | Terminate the HTTP session and hand control to some external handler, -- escaping all further HTTP traffic. -- -- The external handler takes two arguments: a function to modify the thread's -- timeout, and a write end to the socket. escapeHttp :: MonadCatchIO m => EscapeHttpHandler -> m () escapeHttp = throw . EscapeHttpException ------------------------------------------------------------------------------ -- | Runs a 'Snap' monad action in the 'Iteratee IO' monad. runSnap :: Snap a -> (ByteString -> IO ()) -> ((Int -> Int) -> IO ()) -> Request -> Iteratee ByteString IO (Request,Response) runSnap (Snap m) logerr timeoutAction req = do (r, ss') <- runStateT m ss let resp = case r of SnapValue _ -> _snapResponse ss' PassOnProcessing _ -> fourohfour EarlyTermination x -> x let req' = _snapRequest ss' resp' <- liftIO $ fixupResponse req' resp return (req', resp') where -------------------------------------------------------------------------- fourohfour = do clearContentLength $ setResponseStatus 404 "Not Found" $ setResponseBody enum404 $ emptyResponse -------------------------------------------------------------------------- enum404 = enumBuilder $ mconcat $ map fromByteString html -------------------------------------------------------------------------- html = [ S.concat [ "<!DOCTYPE html>\n" , "<html>\n" , "<head>\n" , "<title>Not found</title>\n" , "</head>\n" , "<body>\n" , "<code>No handler accepted \"" ] , rqURI req , "\"</code>\n</body></html>" ] -------------------------------------------------------------------------- dresp = emptyResponse { rspHttpVersion = rqVersion req } -------------------------------------------------------------------------- ss = SnapState req dresp logerr timeoutAction {-# INLINE runSnap #-} -------------------------------------------------------------------------- -- | Post-process a finalized HTTP response: -- -- * fixup content-length header -- * properly handle 204/304 responses -- * if request was HEAD, remove response body -- -- Note that we do NOT deal with transfer-encoding: chunked or "connection: -- close" here. fixupResponse :: Request -> Response -> IO Response fixupResponse req rsp = {-# SCC "fixupResponse" #-} do let code = rspStatus rsp let rsp' = if code == 204 || code == 304 then handle304 rsp else rsp rsp'' <- do z <- case rspBody rsp' of (Enum _) -> return rsp' (SendFile f Nothing) -> setFileSize f rsp' (SendFile _ (Just (s,e))) -> return $! setContentLength (e-s) rsp' return $! case rspContentLength z of Nothing -> deleteHeader "Content-Length" z (Just sz) -> setHeader "Content-Length" (toByteString $ fromShow sz) z -- HEAD requests cannot have bodies per RFC 2616 sec. 9.4 if rqMethod req == HEAD then return $! deleteHeader "Transfer-Encoding" $ rsp'' { rspBody = Enum $ enumBuilder mempty } else return $! rsp'' where -------------------------------------------------------------------------- setFileSize :: FilePath -> Response -> IO Response setFileSize fp r = {-# SCC "setFileSize" #-} do fs <- liftM fromIntegral $ getFileSize fp return $! r { rspContentLength = Just fs } ------------------------------------------------------------------------------ getFileSize :: FilePath -> IO FileOffset getFileSize fp = liftM fileSize $ getFileStatus fp -------------------------------------------------------------------------- handle304 :: Response -> Response handle304 r = setResponseBody (enumBuilder mempty) $ updateHeaders (H.delete "Transfer-Encoding") $ clearContentLength r {-# INLINE fixupResponse #-} ------------------------------------------------------------------------------ evalSnap :: Snap a -> (ByteString -> IO ()) -> ((Int -> Int) -> IO ()) -> Request -> Iteratee ByteString IO a evalSnap (Snap m) logerr timeoutAction req = do (r, _) <- runStateT m ss case r of SnapValue x -> return x PassOnProcessing e -> liftIO $ throwIO $ NoHandlerException e EarlyTermination _ -> liftIO $ throwIO $ ErrorCall "no value" where dresp = emptyResponse { rspHttpVersion = rqVersion req } ss = SnapState req dresp logerr timeoutAction {-# INLINE evalSnap #-} ------------------------------------------------------------------------------ getParamFrom :: MonadSnap m => (ByteString -> Request -> Maybe [ByteString]) -> ByteString -> m (Maybe ByteString) getParamFrom f k = do rq <- getRequest return $! liftM (S.intercalate " ") $ f k rq {-# INLINE getParamFrom #-} ------------------------------------------------------------------------------ -- | See 'rqParam'. Looks up a value for the given named parameter in the -- 'Request'. If more than one value was entered for the given parameter name, -- 'getParam' gloms the values together with: -- -- @ 'S.intercalate' \" \"@ -- getParam :: MonadSnap m => ByteString -- ^ parameter name to look up -> m (Maybe ByteString) getParam = getParamFrom rqParam {-# INLINE getParam #-} ------------------------------------------------------------------------------ -- | See 'rqPostParam'. Looks up a value for the given named parameter in the -- POST form parameters mapping in 'Request'. If more than one value was -- entered for the given parameter name, 'getPostParam' gloms the values -- together with: -- -- @ 'S.intercalate' \" \"@ -- getPostParam :: MonadSnap m => ByteString -- ^ parameter name to look up -> m (Maybe ByteString) getPostParam = getParamFrom rqPostParam {-# INLINE getPostParam #-} ------------------------------------------------------------------------------ -- | See 'rqQueryParam'. Looks up a value for the given named parameter in the -- query string parameters mapping in 'Request'. If more than one value was -- entered for the given parameter name, 'getQueryParam' gloms the values -- together with: -- -- @ 'S.intercalate' \" \"@ -- getQueryParam :: MonadSnap m => ByteString -- ^ parameter name to look up -> m (Maybe ByteString) getQueryParam = getParamFrom rqQueryParam {-# INLINE getQueryParam #-} ------------------------------------------------------------------------------ -- | See 'rqParams'. Convenience function to return 'Params' from the -- 'Request' inside of a 'MonadSnap' instance. getParams :: MonadSnap m => m Params getParams = getRequest >>= return . rqParams ------------------------------------------------------------------------------ -- | See 'rqParams'. Convenience function to return 'Params' from the -- 'Request' inside of a 'MonadSnap' instance. getPostParams :: MonadSnap m => m Params getPostParams = getRequest >>= return . rqPostParams ------------------------------------------------------------------------------ -- | See 'rqParams'. Convenience function to return 'Params' from the -- 'Request' inside of a 'MonadSnap' instance. getQueryParams :: MonadSnap m => m Params getQueryParams = getRequest >>= return . rqQueryParams ------------------------------------------------------------------------------ -- | Gets the HTTP 'Cookie' with the specified name. getCookie :: MonadSnap m => ByteString -> m (Maybe Cookie) getCookie name = withRequest $ return . listToMaybe . filter (\c -> cookieName c == name) . rqCookies ------------------------------------------------------------------------------ -- | Gets the HTTP 'Cookie' with the specified name and decodes it. If the -- decoding fails, the handler calls pass. readCookie :: (MonadSnap m, Readable a) => ByteString -> m a readCookie name = maybe pass (fromBS . cookieValue) =<< getCookie name ------------------------------------------------------------------------------ -- | Expire the given 'Cookie' in client's browser. expireCookie :: (MonadSnap m) => ByteString -- ^ Cookie name -> Maybe ByteString -- ^ Cookie domain -> m () expireCookie nm dm = do let old = UTCTime (ModifiedJulianDay 0) 0 modifyResponse $ addResponseCookie $ Cookie nm "" (Just old) Nothing dm False False ------------------------------------------------------------------------------ -- | Causes the handler thread to be killed @n@ seconds from now. setTimeout :: MonadSnap m => Int -> m () setTimeout = modifyTimeout . const ------------------------------------------------------------------------------ -- | Causes the handler thread to be killed at least @n@ seconds from now. extendTimeout :: MonadSnap m => Int -> m () extendTimeout = modifyTimeout . max ------------------------------------------------------------------------------ -- | Modifies the amount of time remaining before the request times out. modifyTimeout :: MonadSnap m => (Int -> Int) -> m () modifyTimeout f = do m <- getTimeoutModifier liftIO $ m f ------------------------------------------------------------------------------ -- | Returns an 'IO' action which you can use to set the handling thread's -- timeout value. getTimeoutAction :: MonadSnap m => m (Int -> IO ()) getTimeoutAction = do modifier <- liftSnap $ liftM _snapModifyTimeout sget return $! modifier . const {-# DEPRECATED getTimeoutAction "use getTimeoutModifier instead. Since 0.8." #-} ------------------------------------------------------------------------------ -- | Returns an 'IO' action which you can use to modify the timeout value. getTimeoutModifier :: MonadSnap m => m ((Int -> Int) -> IO ()) getTimeoutModifier = liftSnap $ liftM _snapModifyTimeout sget
f-me/snap-core
src/Snap/Internal/Types.hs
Haskell
bsd-3-clause
42,614
module Fibon.Run.BenchmarkRunner ( RunResult(..) , RunFailure(..) , Fibon.Run.BenchmarkRunner.run ) where import Control.Concurrent import Control.Monad import Control.Exception import qualified Data.ByteString as B import Data.Maybe import Data.Time.Clock import qualified Data.Vector.Unboxed as Vector import Fibon.BenchmarkInstance import Fibon.Result import Fibon.Run.BenchmarkBundle import Fibon.Run.Log as Log import qualified Fibon.Run.SysTools as SysTools import Statistics.Sample import System.Directory import System.FilePath import System.IO import System.Process import Text.Printf data RunResult = Success {runSummary :: RunSummary, runDetails :: [RunDetail]} | Failure [RunFailure] deriving (Read, Show) data RunFailure = MissingOutput FilePath | DiffError String | Timeout | ExitError {exitExpected :: ExitCode, exitActual :: ExitCode} deriving (Read, Show) run :: BenchmarkBundle -> IO RunResult run bb = do let bmk = (bundleName bb) pwd = (pathToExeBuildDir bb) cmd = (prettyRunCommand bb) Log.info $ "Running Benchmark " Log.info $ " BMK: " ++ bmk Log.info $ " PWD: " ++ pwd Log.info $ " CMD: " ++ cmd Log.info $ printf "\n@%s|%s|%s" bmk pwd cmd runDirect bb checkResult :: BenchmarkBundle -> ExitCode -> IO (Maybe [RunFailure]) checkResult bb exitCode = do outputs <- mapM (checkOutput bb) (output . benchDetails $ bb) let results = checkExit bb exitCode : outputs errs = filter isJust results case errs of [] -> return $ Nothing es -> return $ Just (catMaybes es) checkExit :: BenchmarkBundle -> ExitCode -> Maybe RunFailure checkExit bb actual = if actual == expected then Nothing else Just ee where expected = expectedExit . benchDetails $ bb ee = ExitError {exitExpected = expected, exitActual = actual} checkOutput :: BenchmarkBundle -> OutputDescription -> IO (Maybe RunFailure) checkOutput bb (o, Exists) = do let f = (destinationToRealFile bb o) e <- doesFileExist f if e then return Nothing else return $ Just $ MissingOutput ("File "++f++" does not exist") checkOutput bb (o, Diff diffFile) = do e1 <- checkOutput bb (o, Exists) e2 <- checkOutput bb (d, Exists) e3 <- runDiff f1 f2 return $ msum [e1, e2, e3] where d = OutputFile diffFile f1 = (destinationToRealFile bb o) f2 = (destinationToRealFile bb d) runDiff :: FilePath -> FilePath -> IO (Maybe RunFailure) runDiff f1 f2 = do Log.info $ "Diffing files: "++f1++" "++f2 (r, o, _) <- readProcessWithExitCode (SysTools.diff) [f1, f2] "" if r == ExitSuccess then Log.info "No diff error" >> return Nothing else Log.info "Diff error" >> (return $ Just $ DiffError o) destinationToRealFile :: BenchmarkBundle -> OutputDestination -> FilePath destinationToRealFile bb (OutputFile f) = (pathToExeRunDir bb) </> f destinationToRealFile bb Stdout = (pathToStdoutFile bb) destinationToRealFile bb Stderr = (pathToStderrFile bb) readExtraStats :: BenchmarkBundle -> IO ExtraStats readExtraStats bb = do let mbStatsFile = extraStats bb statsFile = fromJust mbStatsFile logReadE :: IOException -> IO ExtraStats logReadE e = Log.warn ("Error reading stats file: "++statsFile++"\n "++show e) >> return B.empty case mbStatsFile of Nothing -> return B.empty Just f -> do handle logReadE $ bracket (openFile ((pathToExeRunDir bb) </> f) ReadMode) (hClose) (\h -> B.hGetContents h >>= \s -> B.length s `seq` return s) type RunStepResult = IO (Either [RunFailure] RunDetail) runDirect :: BenchmarkBundle -> IO RunResult runDirect bb = do mbDetails <- go count [] case mbDetails of Left e -> return $ Failure e Right ds -> return $ Success (summarize ds) ds where go 0 ds = return $ Right (reverse ds) go n ds = do res <- runB bb case res of Right d -> go (n-1) (d:ds) Left e -> return $ Left e runB = maybe runBenchmarkWithoutTimeout runBenchmarkWithTimeout limit limit = timeout bb count = (iters bb) summarize :: [RunDetail] -> RunSummary summarize ds = RunSummary { meanTime = mean times , stdDevTime = stdDev times , statsSummary = stats } where times = (Vector.fromList $ map runTime ds) stats = case ds of (x:_) -> runStats x; _ -> B.empty type TimeoutLength = Int runBenchmarkWithTimeout :: TimeoutLength -> BenchmarkBundle -> RunStepResult runBenchmarkWithTimeout us bb = do resMVar <- newEmptyMVar pidMVar <- newEmptyMVar tid1 <- forkIO $ (putMVar resMVar . Just) =<< timeBenchmarkExe bb (Just pidMVar) _ <- forkIO $ threadDelay us >> putMVar resMVar Nothing res <- takeMVar resMVar case res of Nothing -> do Log.info $ "benchmark timed out after "++(show us)++" us" -- try to kill the subprocess pid <- tryTakeMVar pidMVar maybe pass terminateProcess pid -- kill the haskell thread killThread tid1 return $ Left [Timeout] Just (runDetail, exitCode) -> do maybe (Right runDetail) Left `liftM` checkResult bb exitCode runBenchmarkWithoutTimeout :: BenchmarkBundle -> RunStepResult runBenchmarkWithoutTimeout bb = do (runDetail, exitCode) <- timeBenchmarkExe bb Nothing maybe (Right runDetail) Left `liftM` checkResult bb exitCode timeBenchmarkExe :: BenchmarkBundle -- benchmark to run -> Maybe (MVar ProcessHandle) -- in case we need to kill it -> IO (RunDetail, ExitCode) timeBenchmarkExe bb pidMVar = do p <- bundleProcessSpec bb start <- getCurrentTime (_, _, _, pid) <- createProcess p maybe pass (flip putMVar pid) pidMVar exit <- waitForProcess pid end <- getCurrentTime mapM_ closeStdIO [std_in p, std_out p, std_err p] stats <- readExtraStats bb return $ (RunDetail (realToFrac (diffUTCTime end start)) stats, exit) closeStdIO :: StdStream -> IO () closeStdIO (UseHandle h) = hClose h closeStdIO _ = return () pass :: IO () pass = return()
dmpots/fibon
tools/fibon-run/Fibon/Run/BenchmarkRunner.hs
Haskell
bsd-3-clause
6,130
{- Copyright 2012-2013 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Plush.Run.BuiltIns.Syntax ( -- * Standard Utiilty Syntax stdSyntax, perArg, -- * Option Specification flag, flagAlt, toggle, argOpt, ) where import Control.Monad.Exception (catchAll) import Data.List ((\\)) import Data.Monoid import Plush.ArgParser import Plush.Run.Posix import Plush.Run.Posix.Return import Plush.Run.Posix.Utilities import Plush.Run.Types import Plush.Types.CommandSummary -- | Create a 'Utility' that can parse options on execution, as well as -- provide annotations and completions of candidate command lines. -- -- Option parsing proceeds according to the \"Utility Conventions\" in §12. -- This is essentially the common conventions for single letter options, and -- using "--" to end argument processing. -- -- The supplied utility function takes the resulting option state and the -- arguments to produce an 'ExitCode'. -- -- The 'CommandSummary' argument is last because it is supplied by the -- machinery in "Plush.Run.BuiltIns", since that is where a utility's -- implementation is associated with a name, which is used there to find -- the summary info. Hence, typical usage is: -- -- @ -- example = BuiltInUtility $ stdSyntax options initialFlags exec -- where -- exec flags args = ... -- ... -- @ stdSyntax :: (PosixLike m, Returnable r) => [OptionSpec a] -- ^ options -> a -- ^ the initial option state -> (a -> Args -> m r) -- ^ utility function -> CommandSummary -- ^ summary information for error help messages -> Utility m r stdSyntax options opt0 action summary = Utility exec anno where exec cmdLineArgs = case mconcat $ processArgs options cmdLineArgs of OA (Right (optF, args)) -> reportError $ action (optF opt0) args OA (Left errs) -> do errStr errs errStrLn $ ciSynopsis summary errStr $ formatOptions summary failure anno cmdLineArgs = return $ map (argAnnotations summary) $ processArgs options cmdLineArgs -- | When a utility simply applies to each of the arguments in turn, this -- transforms a function of option state and single arg into the function -- of option state and all args needed by 'stdUtility'. perArg :: (PosixLike m) => (a -> String -> m ExitCode) -> a -> [String] -> m ExitCode perArg cmd opts args = mapM (reportError . cmd opts) args >>= return . maximum -- | Catch any errors, report them, and return an error exit code. reportError :: (PosixLike m, Returnable r) => m r -> m r reportError act = act `catchAll` (exitMsg 1 . show) -- | Declare a flag option. The option state is a list of flag characters, -- last flag from the command line, first. If a flag is repeated, it will -- only be included in the state once. flag :: Char -> OptionSpec String flag f = OptionSpec [f] [] (NoArg (\fs -> f : (fs \\ [f]))) -- | Declare a flag option, with possible alternatives. The first flag -- listed will be used as the canonical flag added to the option state. flagAlt :: String -> OptionSpec String flagAlt fa@(f0:_) = OptionSpec fa [] (NoArg (\fs -> f0 : (fs \\ fa))) flagAlt [] = error "Plush.Run.Builtins.Syntax.flagAlt: no flags supplied" -- | Declare a flag that is among an exclusive set of flags. Only one of -- the flags will appear in the final option state. In the initial option -- state supplied to 'stdUtility', either include the default flag as, or -- include none if you want to detect if the user didn't specify a choice. toggle :: Char -- ^ the flag character -> String -- ^ the mutually exclusive set of flags -> OptionSpec String toggle f excl = OptionSpec [f] [] (NoArg (\fs -> f : (fs \\ excl))) -- | Declare a string option. The option state is the value of this option. -- Supply the default as the initial option state to 'stdUtility'. argOpt :: Char -- ^ the flag character -> OptionSpec String argOpt f = OptionSpec [f] [] (ReqArg const)
mzero/plush
src/Plush/Run/BuiltIns/Syntax.hs
Haskell
apache-2.0
4,587
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Path.CheckInstall where import Control.Monad (unless) import Control.Monad.Extra (anyM, (&&^)) import Control.Monad.IO.Class import Control.Monad.Logger import Data.Foldable (forM_) import Data.Text (Text) import qualified Data.Text as T import qualified System.Directory as D import qualified System.FilePath as FP -- | Checks if the installed executable will be available on the user's -- PATH. This doesn't use @envSearchPath menv@ because it includes paths -- only visible when running in the stack environment. warnInstallSearchPathIssues :: (MonadIO m, MonadLogger m) => FilePath -> [Text] -> m () warnInstallSearchPathIssues destDir installed = do searchPath <- liftIO FP.getSearchPath destDirIsInPATH <- liftIO $ anyM (\dir -> D.doesDirectoryExist dir &&^ fmap (FP.equalFilePath destDir) (D.canonicalizePath dir)) searchPath if destDirIsInPATH then forM_ installed $ \exe -> do mexePath <- (liftIO . D.findExecutable . T.unpack) exe case mexePath of Just exePath -> do exeDir <- (liftIO . fmap FP.takeDirectory . D.canonicalizePath) exePath unless (exeDir `FP.equalFilePath` destDir) $ do $logWarn "" $logWarn $ T.concat [ "WARNING: The \"" , exe , "\" executable found on the PATH environment variable is " , T.pack exePath , ", and not the version that was just installed." ] $logWarn $ T.concat [ "This means that \"" , exe , "\" calls on the command line will not use this version." ] Nothing -> do $logWarn "" $logWarn $ T.concat [ "WARNING: Installation path " , T.pack destDir , " is on the PATH but the \"" , exe , "\" executable that was just installed could not be found on the PATH." ] else do $logWarn "" $logWarn $ T.concat [ "WARNING: Installation path " , T.pack destDir , " not found on the PATH environment variable" ]
mrkkrp/stack
src/Path/CheckInstall.hs
Haskell
bsd-3-clause
2,672
-- this file illustrates several uses of `zoom` -- one of them is quadratic in the length of the file -- since it has to decode and encode repeatedly, -- and is thus no good on long files. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns#-} {-# LANGUAGE RankNTypes #-} import Blaze.ByteString.Builder (Builder, fromByteString, toByteString) import Control.Exception (Exception) import Control.Monad.Trans.Class (lift) import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TEE import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TLE import Pipes import Pipes.Parse import qualified Pipes.Prelude as PP import qualified Pipes.ByteString as Bytes import qualified Pipes.Text as Txt import Pipes.Text.Encoding (utf8) import Control.Lens -- we use 'zoom' with MonadState, not just StateT import Control.Monad import qualified System.IO as IO import Control.Monad.Trans.Maybe import Control.Monad.State.Class main :: IO () main = do S.writeFile fp $ contents 10000 -- 10000 cannot be handled fileParser0 and 1 -- parse_file fileParser0 -- pathological -- parse_file fileParser1 -- programs parse_file fileParser2 -- good program where parse_file parser = IO.withBinaryFile fp IO.ReadMode $ \h -> do p' <- runEffect $ parseWith parser ( Bytes.fromHandle h ) >-> PP.print runEffect $ p' >-> PP.print parseWith parser = loop where loop p = do (m,p') <- lift (runStateT (runMaybeT parser) p) case m of Nothing -> return p' Just file -> do yield file loop p' fp = "encoded.fileformat" contents n = (toByteString . mconcat . replicate n . encodeFiles) input <> S.pack (replicate 10 250) fileParser0, fileParser1, fileParser2 :: Monad m => MaybeT (StateT (Producer ByteString m x) m) File fileParser0 = do (name, len) <- zoom utf8 parseText contents <- zoom (Bytes.splitAt len) (lift drawAll) return (File name (S.concat contents)) where -- this parser aggregates all Text parsing into one preliminary parser -- which is then applied with `zoom utf8` -- we cannot tell in advance how long, e.g. the file name will be parseText :: Monad m => MaybeT (StateT (Producer Text m x) m) (Text, Int) parseText = do nameLength <- parseNumber names <- zoom (Txt.splitAt nameLength) $ (lift drawAll) contentLength <- parseNumber return $! (T.concat names, contentLength) -- here we disaggregate the little Text parsers but still apply them with `zoom utf8` -- this makes no difference fileParser1 = do nameLength <- zoom utf8 parseNumber names <- zoom (utf8 . Txt.splitAt nameLength) (lift drawAll) contentLength <- zoom utf8 parseNumber contents <- zoom (Bytes.splitAt contentLength) (lift drawAll) return (File (T.concat names) (S.concat contents)) -- This is the good program; by reflecting on the fact that file names -- should not be a 1000 bytes long, and binary files longer than e.g. 10 ^ 10 -- we can restrict the length of the byte stream to which we apply `zoom utf8` fileParser2 = do nameLength <- zoom (Bytes.splitAt 3 . utf8) parseNumber names <- zoom (Bytes.splitAt nameLength . utf8) (lift drawAll) len <- zoom (Bytes.splitAt 10 . utf8) parseNumber contents <- zoom (Bytes.splitAt len) (lift drawAll) return (File (T.concat names) (S.concat contents)) parseNumber :: Monad m => MaybeT (StateT (Producer Text m x) m) Int parseNumber = loop 0 where loop !n = do c <- MaybeT Txt.drawChar case c of ':' -> return n _ -> do guard ('0' <= c && c <= '9') loop $! n * 10 + (fromEnum c - fromEnum '0') -- --- Michael S's `File` type and its binary encoding, etc. data File = File { fileName :: !Text , fileContents :: !ByteString } deriving Show encodeFile :: File -> Builder encodeFile (File name contents) = tellLength (S.length bytesname) <> fromByteString bytesname <> tellLength (S.length contents) <> fromByteString contents where tellLength i = fromByteString $ TEE.encodeUtf8 (T.pack (shows i ":")) bytesname = TEE.encodeUtf8 name encodeFiles :: [File] -> Builder encodeFiles = mconcat . map encodeFile input :: [File] input = [ File "utf8.txt" $ TEE.encodeUtf8 "This file is in UTF-8" , File "utf16.txt" $ TEE.encodeUtf16LE "This file is in UTF-16" , File "binary.dat" "we'll pretend to be binary" ]
bitemyapp/text-pipes
examples/zoom.hs
Haskell
bsd-3-clause
5,180
module RunCommand (runCommandStrWait) where import System.Process import System.Exit import System.IO import Control.Concurrent import Control.Concurrent.Chan import Data.Either type Pipe = Chan (Either Char ()) pipeGetContents :: Pipe -> IO String pipeGetContents p = do s <- getChanContents p return $ map fromLeft $ takeWhile isLeft s pipeWrite :: Pipe -> String -> IO () pipeWrite p s = writeList2Chan p (map Left s) -- close the pipe for writing pipeClose :: Pipe -> IO () pipeClose p = writeChan p (Right ()) -- -- * Either utilities -- isLeft :: Either a b -> Bool isLeft = either (const True) (const False) fromLeft :: Either a b -> a fromLeft = either id (error "fromLeft: Right") -- -- * Various versions of runCommand -- runCommandChan :: String -- ^ command -> IO (Pipe,Pipe,Pipe,ProcessHandle) -- ^ stdin, stdout, stderr, process runCommandChan c = do inC <- newChan outC <- newChan errC <- newChan (pin,pout,perr,p) <- runInteractiveCommand c forkIO (pipeGetContents inC >>= hPutStr pin >> hClose pin) forkIO (hGetContents pout >>= pipeWrite outC >> pipeClose outC) forkIO (hGetContents perr >>= pipeWrite errC >> pipeClose errC) return (inC,outC,errC,p) runCommandStr :: String -- ^ command -> String -- ^ stdin data -> IO (String,String,ProcessHandle) -- ^ stdout, stderr, process runCommandStr c inStr = do (inC,outC,errC,p) <- runCommandChan c forkIO (pipeWrite inC inStr >> pipeClose inC) out <- pipeGetContents outC err <- pipeGetContents errC return (out,err,p) runCommandStrWait :: String -- ^ command -> String -- ^ stdin data -> IO (String,String,ExitCode) -- ^ stdout, stderr, process exit status runCommandStrWait c inStr = do (out,err,p) <- runCommandStr c inStr s <- waitForProcess p return (out,err,s)
bvdelft/parac2
simpletestsuite/RunCommand.hs
Haskell
bsd-3-clause
1,866
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section{SetLevels} *************************** Overview *************************** 1. We attach binding levels to Core bindings, in preparation for floating outwards (@FloatOut@). 2. We also let-ify many expressions (notably case scrutinees), so they will have a fighting chance of being floated sensible. 3. Note [Need for cloning during float-out] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We clone the binders of any floatable let-binding, so that when it is floated out it will be unique. Example (let x=2 in x) + (let x=3 in x) we must clone before floating so we get let x1=2 in let x2=3 in x1+x2 NOTE: this can't be done using the uniqAway idea, because the variable must be unique in the whole program, not just its current scope, because two variables in different scopes may float out to the same top level place NOTE: Very tiresomely, we must apply this substitution to the rules stored inside a variable too. We do *not* clone top-level bindings, because some of them must not change, but we *do* clone bindings that are heading for the top level 4. Note [Binder-swap during float-out] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the expression case x of wild { p -> ...wild... } we substitute x for wild in the RHS of the case alternatives: case x of wild { p -> ...x... } This means that a sub-expression involving x is not "trapped" inside the RHS. And it's not inconvenient because we already have a substitution. Note that this is EXACTLY BACKWARDS from the what the simplifier does. The simplifier tries to get rid of occurrences of x, in favour of wild, in the hope that there will only be one remaining occurrence of x, namely the scrutinee of the case, and we can inline it. -} {-# LANGUAGE CPP, MultiWayIf #-} module SetLevels ( setLevels, Level(..), LevelType(..), tOP_LEVEL, isJoinCeilLvl, asJoinCeilLvl, LevelledBind, LevelledExpr, LevelledBndr, FloatSpec(..), floatSpecLevel, incMinorLvl, ltMajLvl, ltLvl, isTopLvl ) where #include "HsVersions.h" import GhcPrelude import CoreSyn import CoreMonad ( FloatOutSwitches(..) ) import CoreUtils ( exprType, exprIsHNF , exprOkForSpeculation , exprIsTopLevelBindable , isExprLevPoly , collectMakeStaticArgs ) import CoreArity ( exprBotStrictness_maybe ) import CoreFVs -- all of it import CoreSubst import MkCore ( sortQuantVars ) import Id import IdInfo import Var import VarSet import UniqSet ( nonDetFoldUniqSet ) import VarEnv import Literal ( litIsTrivial ) import Demand ( StrictSig, Demand, isStrictDmd, splitStrictSig, increaseStrictSigArity ) import Name ( getOccName, mkSystemVarName ) import OccName ( occNameString ) import Type ( Type, mkLamTypes, splitTyConApp_maybe, tyCoVarsOfType ) import BasicTypes ( Arity, RecFlag(..), isRec ) import DataCon ( dataConOrigResTy ) import TysWiredIn import UniqSupply import Util import Outputable import FastString import UniqDFM import FV import Data.Maybe import MonadUtils ( mapAccumLM ) {- ************************************************************************ * * \subsection{Level numbers} * * ************************************************************************ -} type LevelledExpr = TaggedExpr FloatSpec type LevelledBind = TaggedBind FloatSpec type LevelledBndr = TaggedBndr FloatSpec data Level = Level Int -- Level number of enclosing lambdas Int -- Number of big-lambda and/or case expressions and/or -- context boundaries between -- here and the nearest enclosing lambda LevelType -- Binder or join ceiling? data LevelType = BndrLvl | JoinCeilLvl deriving (Eq) data FloatSpec = FloatMe Level -- Float to just inside the binding -- tagged with this level | StayPut Level -- Stay where it is; binding is -- tagged with this level floatSpecLevel :: FloatSpec -> Level floatSpecLevel (FloatMe l) = l floatSpecLevel (StayPut l) = l {- The {\em level number} on a (type-)lambda-bound variable is the nesting depth of the (type-)lambda which binds it. The outermost lambda has level 1, so (Level 0 0) means that the variable is bound outside any lambda. On an expression, it's the maximum level number of its free (type-)variables. On a let(rec)-bound variable, it's the level of its RHS. On a case-bound variable, it's the number of enclosing lambdas. Top-level variables: level~0. Those bound on the RHS of a top-level definition but ``before'' a lambda; e.g., the \tr{x} in (levels shown as ``subscripts'')... \begin{verbatim} a_0 = let b_? = ... in x_1 = ... b ... in ... \end{verbatim} The main function @lvlExpr@ carries a ``context level'' (@le_ctxt_lvl@). That's meant to be the level number of the enclosing binder in the final (floated) program. If the level number of a sub-expression is less than that of the context, then it might be worth let-binding the sub-expression so that it will indeed float. If you can float to level @Level 0 0@ worth doing so because then your allocation becomes static instead of dynamic. We always start with context @Level 0 0@. Note [FloatOut inside INLINE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @InlineCtxt@ very similar to @Level 0 0@, but is used for one purpose: to say "don't float anything out of here". That's exactly what we want for the body of an INLINE, where we don't want to float anything out at all. See notes with lvlMFE below. But, check this out: -- At one time I tried the effect of not float anything out of an InlineMe, -- but it sometimes works badly. For example, consider PrelArr.done. It -- has the form __inline (\d. e) -- where e doesn't mention d. If we float this to -- __inline (let x = e in \d. x) -- things are bad. The inliner doesn't even inline it because it doesn't look -- like a head-normal form. So it seems a lesser evil to let things float. -- In SetLevels we do set the context to (Level 0 0) when we get to an InlineMe -- which discourages floating out. So the conclusion is: don't do any floating at all inside an InlineMe. (In the above example, don't float the {x=e} out of the \d.) One particular case is that of workers: we don't want to float the call to the worker outside the wrapper, otherwise the worker might get inlined into the floated expression, and an importing module won't see the worker at all. Note [Join ceiling] ~~~~~~~~~~~~~~~~~~~ Join points can't float very far; too far, and they can't remain join points So, suppose we have: f x = (joinrec j y = ... x ... in jump j x) + 1 One may be tempted to float j out to the top of f's RHS, but then the jump would not be a tail call. Thus we keep track of a level called the *join ceiling* past which join points are not allowed to float. The troublesome thing is that, unlike most levels to which something might float, there is not necessarily an identifier to which the join ceiling is attached. Fortunately, if something is to be floated to a join ceiling, it must be dropped at the *nearest* join ceiling. Thus each level is marked as to whether it is a join ceiling, so that FloatOut can tell which binders are being floated to the nearest join ceiling and which to a particular binder (or set of binders). -} instance Outputable FloatSpec where ppr (FloatMe l) = char 'F' <> ppr l ppr (StayPut l) = ppr l tOP_LEVEL :: Level tOP_LEVEL = Level 0 0 BndrLvl incMajorLvl :: Level -> Level incMajorLvl (Level major _ _) = Level (major + 1) 0 BndrLvl incMinorLvl :: Level -> Level incMinorLvl (Level major minor _) = Level major (minor+1) BndrLvl asJoinCeilLvl :: Level -> Level asJoinCeilLvl (Level major minor _) = Level major minor JoinCeilLvl maxLvl :: Level -> Level -> Level maxLvl l1@(Level maj1 min1 _) l2@(Level maj2 min2 _) | (maj1 > maj2) || (maj1 == maj2 && min1 > min2) = l1 | otherwise = l2 ltLvl :: Level -> Level -> Bool ltLvl (Level maj1 min1 _) (Level maj2 min2 _) = (maj1 < maj2) || (maj1 == maj2 && min1 < min2) ltMajLvl :: Level -> Level -> Bool -- Tells if one level belongs to a difft *lambda* level to another ltMajLvl (Level maj1 _ _) (Level maj2 _ _) = maj1 < maj2 isTopLvl :: Level -> Bool isTopLvl (Level 0 0 _) = True isTopLvl _ = False isJoinCeilLvl :: Level -> Bool isJoinCeilLvl (Level _ _ t) = t == JoinCeilLvl instance Outputable Level where ppr (Level maj min typ) = hcat [ char '<', int maj, char ',', int min, char '>' , ppWhen (typ == JoinCeilLvl) (char 'C') ] instance Eq Level where (Level maj1 min1 _) == (Level maj2 min2 _) = maj1 == maj2 && min1 == min2 {- ************************************************************************ * * \subsection{Main level-setting code} * * ************************************************************************ -} setLevels :: FloatOutSwitches -> CoreProgram -> UniqSupply -> [LevelledBind] setLevels float_lams binds us = initLvl us (do_them init_env binds) where init_env = initialEnv float_lams do_them :: LevelEnv -> [CoreBind] -> LvlM [LevelledBind] do_them _ [] = return [] do_them env (b:bs) = do { (lvld_bind, env') <- lvlTopBind env b ; lvld_binds <- do_them env' bs ; return (lvld_bind : lvld_binds) } lvlTopBind :: LevelEnv -> Bind Id -> LvlM (LevelledBind, LevelEnv) lvlTopBind env (NonRec bndr rhs) = do { rhs' <- lvl_top env NonRecursive bndr rhs ; let (env', [bndr']) = substAndLvlBndrs NonRecursive env tOP_LEVEL [bndr] ; return (NonRec bndr' rhs', env') } lvlTopBind env (Rec pairs) = do { let (env', bndrs') = substAndLvlBndrs Recursive env tOP_LEVEL (map fst pairs) ; rhss' <- mapM (\(b,r) -> lvl_top env' Recursive b r) pairs ; return (Rec (bndrs' `zip` rhss'), env') } lvl_top :: LevelEnv -> RecFlag -> Id -> CoreExpr -> LvlM LevelledExpr lvl_top env is_rec bndr rhs = lvlRhs env is_rec (isBottomingId bndr) Nothing -- Not a join point (freeVars rhs) {- ************************************************************************ * * \subsection{Setting expression levels} * * ************************************************************************ Note [Floating over-saturated applications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we see (f x y), and (f x) is a redex (ie f's arity is 1), we call (f x) an "over-saturated application" Should we float out an over-sat app, if can escape a value lambda? It is sometimes very beneficial (-7% runtime -4% alloc over nofib -O2). But we don't want to do it for class selectors, because the work saved is minimal, and the extra local thunks allocated cost money. Arguably we could float even class-op applications if they were going to top level -- but then they must be applied to a constant dictionary and will almost certainly be optimised away anyway. -} lvlExpr :: LevelEnv -- Context -> CoreExprWithFVs -- Input expression -> LvlM LevelledExpr -- Result expression {- The @le_ctxt_lvl@ is, roughly, the level of the innermost enclosing binder. Here's an example v = \x -> ...\y -> let r = case (..x..) of ..x.. in .. When looking at the rhs of @r@, @le_ctxt_lvl@ will be 1 because that's the level of @r@, even though it's inside a level-2 @\y@. It's important that @le_ctxt_lvl@ is 1 and not 2 in @r@'s rhs, because we don't want @lvlExpr@ to turn the scrutinee of the @case@ into an MFE --- because it isn't a *maximal* free expression. If there were another lambda in @r@'s rhs, it would get level-2 as well. -} lvlExpr env (_, AnnType ty) = return (Type (CoreSubst.substTy (le_subst env) ty)) lvlExpr env (_, AnnCoercion co) = return (Coercion (substCo (le_subst env) co)) lvlExpr env (_, AnnVar v) = return (lookupVar env v) lvlExpr _ (_, AnnLit lit) = return (Lit lit) lvlExpr env (_, AnnCast expr (_, co)) = do expr' <- lvlNonTailExpr env expr return (Cast expr' (substCo (le_subst env) co)) lvlExpr env (_, AnnTick tickish expr) = do expr' <- lvlNonTailExpr env expr let tickish' = substTickish (le_subst env) tickish return (Tick tickish' expr') lvlExpr env expr@(_, AnnApp _ _) = lvlApp env expr (collectAnnArgs expr) -- We don't split adjacent lambdas. That is, given -- \x y -> (x+1,y) -- we don't float to give -- \x -> let v = x+1 in \y -> (v,y) -- Why not? Because partial applications are fairly rare, and splitting -- lambdas makes them more expensive. lvlExpr env expr@(_, AnnLam {}) = do { new_body <- lvlNonTailMFE new_env True body ; return (mkLams new_bndrs new_body) } where (bndrs, body) = collectAnnBndrs expr (env1, bndrs1) = substBndrsSL NonRecursive env bndrs (new_env, new_bndrs) = lvlLamBndrs env1 (le_ctxt_lvl env) bndrs1 -- At one time we called a special verion of collectBinders, -- which ignored coercions, because we don't want to split -- a lambda like this (\x -> coerce t (\s -> ...)) -- This used to happen quite a bit in state-transformer programs, -- but not nearly so much now non-recursive newtypes are transparent. -- [See SetLevels rev 1.50 for a version with this approach.] lvlExpr env (_, AnnLet bind body) = do { (bind', new_env) <- lvlBind env bind ; body' <- lvlExpr new_env body -- No point in going via lvlMFE here. If the binding is alive -- (mentioned in body), and the whole let-expression doesn't -- float, then neither will the body ; return (Let bind' body') } lvlExpr env (_, AnnCase scrut case_bndr ty alts) = do { scrut' <- lvlNonTailMFE env True scrut ; lvlCase env (freeVarsOf scrut) scrut' case_bndr ty alts } lvlNonTailExpr :: LevelEnv -- Context -> CoreExprWithFVs -- Input expression -> LvlM LevelledExpr -- Result expression lvlNonTailExpr env expr = lvlExpr (placeJoinCeiling env) expr ------------------------------------------- lvlApp :: LevelEnv -> CoreExprWithFVs -> (CoreExprWithFVs, [CoreExprWithFVs]) -- Input application -> LvlM LevelledExpr -- Result expression lvlApp env orig_expr ((_,AnnVar fn), args) | floatOverSat env -- See Note [Floating over-saturated applications] , arity > 0 , arity < n_val_args , Nothing <- isClassOpId_maybe fn = do { rargs' <- mapM (lvlNonTailMFE env False) rargs ; lapp' <- lvlNonTailMFE env False lapp ; return (foldl App lapp' rargs') } | otherwise = do { (_, args') <- mapAccumLM lvl_arg stricts args -- Take account of argument strictness; see -- Note [Floating to the top] ; return (foldl App (lookupVar env fn) args') } where n_val_args = count (isValArg . deAnnotate) args arity = idArity fn stricts :: [Demand] -- True for strict /value/ arguments stricts = case splitStrictSig (idStrictness fn) of (arg_ds, _) | arg_ds `lengthExceeds` n_val_args -> [] | otherwise -> arg_ds -- Separate out the PAP that we are floating from the extra -- arguments, by traversing the spine until we have collected -- (n_val_args - arity) value arguments. (lapp, rargs) = left (n_val_args - arity) orig_expr [] left 0 e rargs = (e, rargs) left n (_, AnnApp f a) rargs | isValArg (deAnnotate a) = left (n-1) f (a:rargs) | otherwise = left n f (a:rargs) left _ _ _ = panic "SetLevels.lvlExpr.left" is_val_arg :: CoreExprWithFVs -> Bool is_val_arg (_, AnnType {}) = False is_val_arg _ = True lvl_arg :: [Demand] -> CoreExprWithFVs -> LvlM ([Demand], LevelledExpr) lvl_arg strs arg | (str1 : strs') <- strs , is_val_arg arg = do { arg' <- lvlMFE env (isStrictDmd str1) arg ; return (strs', arg') } | otherwise = do { arg' <- lvlMFE env False arg ; return (strs, arg') } lvlApp env _ (fun, args) = -- No PAPs that we can float: just carry on with the -- arguments and the function. do { args' <- mapM (lvlNonTailMFE env False) args ; fun' <- lvlNonTailExpr env fun ; return (foldl App fun' args') } ------------------------------------------- lvlCase :: LevelEnv -- Level of in-scope names/tyvars -> DVarSet -- Free vars of input scrutinee -> LevelledExpr -- Processed scrutinee -> Id -> Type -- Case binder and result type -> [CoreAltWithFVs] -- Input alternatives -> LvlM LevelledExpr -- Result expression lvlCase env scrut_fvs scrut' case_bndr ty alts | [(con@(DataAlt {}), bs, body)] <- alts , exprOkForSpeculation (deTagExpr scrut') -- See Note [Check the output scrutinee for okForSpec] , not (isTopLvl dest_lvl) -- Can't have top-level cases , not (floatTopLvlOnly env) -- Can float anywhere = -- See Note [Floating cases] -- Always float the case if possible -- Unlike lets we don't insist that it escapes a value lambda do { (env1, (case_bndr' : bs')) <- cloneCaseBndrs env dest_lvl (case_bndr : bs) ; let rhs_env = extendCaseBndrEnv env1 case_bndr scrut' ; body' <- lvlMFE rhs_env True body ; let alt' = (con, map (stayPut dest_lvl) bs', body') ; return (Case scrut' (TB case_bndr' (FloatMe dest_lvl)) ty' [alt']) } | otherwise -- Stays put = do { let (alts_env1, [case_bndr']) = substAndLvlBndrs NonRecursive env incd_lvl [case_bndr] alts_env = extendCaseBndrEnv alts_env1 case_bndr scrut' ; alts' <- mapM (lvl_alt alts_env) alts ; return (Case scrut' case_bndr' ty' alts') } where ty' = substTy (le_subst env) ty incd_lvl = incMinorLvl (le_ctxt_lvl env) dest_lvl = maxFvLevel (const True) env scrut_fvs -- Don't abstract over type variables, hence const True lvl_alt alts_env (con, bs, rhs) = do { rhs' <- lvlMFE new_env True rhs ; return (con, bs', rhs') } where (new_env, bs') = substAndLvlBndrs NonRecursive alts_env incd_lvl bs {- Note [Floating cases] ~~~~~~~~~~~~~~~~~~~~~ Consider this: data T a = MkT !a f :: T Int -> blah f x vs = case x of { MkT y -> let f vs = ...(case y of I# w -> e)...f.. in f vs Here we can float the (case y ...) out, because y is sure to be evaluated, to give f x vs = case x of { MkT y -> caes y of I# w -> let f vs = ...(e)...f.. in f vs That saves unboxing it every time round the loop. It's important in some DPH stuff where we really want to avoid that repeated unboxing in the inner loop. Things to note * We can't float a case to top level * It's worth doing this float even if we don't float the case outside a value lambda. Example case x of { MkT y -> (case y of I# w2 -> ..., case y of I# w2 -> ...) If we floated the cases out we could eliminate one of them. * We only do this with a single-alternative case Note [Check the output scrutinee for okForSpec] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: case x of y { A -> ....(case y of alts).... } Because of the binder-swap, the inner case will get substituted to (case x of ..). So when testing whether the scrutinee is okForSpeculation we must be careful to test the *result* scrutinee ('x' in this case), not the *input* one 'y'. The latter *is* ok for speculation here, but the former is not -- and indeed we can't float the inner case out, at least not unless x is also evaluated at its binding site. See Trac #5453. That's why we apply exprOkForSpeculation to scrut' and not to scrut. -} lvlNonTailMFE :: LevelEnv -- Level of in-scope names/tyvars -> Bool -- True <=> strict context [body of case -- or let] -> CoreExprWithFVs -- input expression -> LvlM LevelledExpr -- Result expression lvlNonTailMFE env strict_ctxt ann_expr = lvlMFE (placeJoinCeiling env) strict_ctxt ann_expr lvlMFE :: LevelEnv -- Level of in-scope names/tyvars -> Bool -- True <=> strict context [body of case or let] -> CoreExprWithFVs -- input expression -> LvlM LevelledExpr -- Result expression -- lvlMFE is just like lvlExpr, except that it might let-bind -- the expression, so that it can itself be floated. lvlMFE env _ (_, AnnType ty) = return (Type (CoreSubst.substTy (le_subst env) ty)) -- No point in floating out an expression wrapped in a coercion or note -- If we do we'll transform lvl = e |> co -- to lvl' = e; lvl = lvl' |> co -- and then inline lvl. Better just to float out the payload. lvlMFE env strict_ctxt (_, AnnTick t e) = do { e' <- lvlMFE env strict_ctxt e ; let t' = substTickish (le_subst env) t ; return (Tick t' e') } lvlMFE env strict_ctxt (_, AnnCast e (_, co)) = do { e' <- lvlMFE env strict_ctxt e ; return (Cast e' (substCo (le_subst env) co)) } lvlMFE env strict_ctxt e@(_, AnnCase {}) | strict_ctxt -- Don't share cases in a strict context = lvlExpr env e -- See Note [Case MFEs] lvlMFE env strict_ctxt ann_expr | floatTopLvlOnly env && not (isTopLvl dest_lvl) -- Only floating to the top level is allowed. || anyDVarSet isJoinId fvs -- If there is a free join, don't float -- See Note [Free join points] || isExprLevPoly expr -- We can't let-bind levity polymorphic expressions -- See Note [Levity polymorphism invariants] in CoreSyn || notWorthFloating expr abs_vars || not float_me = -- Don't float it out lvlExpr env ann_expr | float_is_new_lam || exprIsTopLevelBindable expr expr_ty -- No wrapping needed if the type is lifted, or is a literal string -- or if we are wrapping it in one or more value lambdas = do { expr1 <- lvlFloatRhs abs_vars dest_lvl rhs_env NonRecursive (isJust mb_bot_str) join_arity_maybe ann_expr -- Treat the expr just like a right-hand side ; var <- newLvlVar expr1 join_arity_maybe is_mk_static ; let var2 = annotateBotStr var float_n_lams mb_bot_str ; return (Let (NonRec (TB var2 (FloatMe dest_lvl)) expr1) (mkVarApps (Var var2) abs_vars)) } -- OK, so the float has an unlifted type (not top-level bindable) -- and no new value lambdas (float_is_new_lam is False) -- Try for the boxing strategy -- See Note [Floating MFEs of unlifted type] | escapes_value_lam , not expr_ok_for_spec -- Boxing/unboxing isn't worth it for cheap expressions -- See Note [Test cheapness with exprOkForSpeculation] , Just (tc, _) <- splitTyConApp_maybe expr_ty , Just dc <- boxingDataCon_maybe tc , let dc_res_ty = dataConOrigResTy dc -- No free type variables [bx_bndr, ubx_bndr] = mkTemplateLocals [dc_res_ty, expr_ty] = do { expr1 <- lvlExpr rhs_env ann_expr ; let l1r = incMinorLvlFrom rhs_env float_rhs = mkLams abs_vars_w_lvls $ Case expr1 (stayPut l1r ubx_bndr) dc_res_ty [(DEFAULT, [], mkConApp dc [Var ubx_bndr])] ; var <- newLvlVar float_rhs Nothing is_mk_static ; let l1u = incMinorLvlFrom env use_expr = Case (mkVarApps (Var var) abs_vars) (stayPut l1u bx_bndr) expr_ty [(DataAlt dc, [stayPut l1u ubx_bndr], Var ubx_bndr)] ; return (Let (NonRec (TB var (FloatMe dest_lvl)) float_rhs) use_expr) } | otherwise -- e.g. do not float unboxed tuples = lvlExpr env ann_expr where expr = deAnnotate ann_expr expr_ty = exprType expr fvs = freeVarsOf ann_expr fvs_ty = tyCoVarsOfType expr_ty is_bot = isBottomThunk mb_bot_str is_function = isFunction ann_expr mb_bot_str = exprBotStrictness_maybe expr -- See Note [Bottoming floats] -- esp Bottoming floats (2) expr_ok_for_spec = exprOkForSpeculation expr dest_lvl = destLevel env fvs fvs_ty is_function is_bot False abs_vars = abstractVars dest_lvl env fvs -- float_is_new_lam: the floated thing will be a new value lambda -- replacing, say (g (x+4)) by (lvl x). No work is saved, nor is -- allocation saved. The benefit is to get it to the top level -- and hence out of the body of this function altogether, making -- it smaller and more inlinable float_is_new_lam = float_n_lams > 0 float_n_lams = count isId abs_vars (rhs_env, abs_vars_w_lvls) = lvlLamBndrs env dest_lvl abs_vars join_arity_maybe = Nothing is_mk_static = isJust (collectMakeStaticArgs expr) -- Yuk: See Note [Grand plan for static forms] in main/StaticPtrTable -- A decision to float entails let-binding this thing, and we only do -- that if we'll escape a value lambda, or will go to the top level. float_me = saves_work || saves_alloc || is_mk_static -- We can save work if we can move a redex outside a value lambda -- But if float_is_new_lam is True, then the redex is wrapped in a -- a new lambda, so no work is saved saves_work = escapes_value_lam && not float_is_new_lam escapes_value_lam = dest_lvl `ltMajLvl` (le_ctxt_lvl env) -- See Note [Escaping a value lambda] -- See Note [Floating to the top] saves_alloc = isTopLvl dest_lvl && floatConsts env && (not strict_ctxt || is_bot || exprIsHNF expr) isBottomThunk :: Maybe (Arity, s) -> Bool -- See Note [Bottoming floats] (2) isBottomThunk (Just (0, _)) = True -- Zero arity isBottomThunk _ = False {- Note [Floating to the top] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We are keen to float something to the top level, even if it does not escape a value lambda (and hence save work), for two reasons: * Doing so makes the function smaller, by floating out bottoming expressions, or integer or string literals. That in turn makes it easier to inline, with less duplication. * (Minor) Doing so may turn a dynamic allocation (done by machine instructions) into a static one. Minor because we are assuming we are not escaping a value lambda. But do not so if: - the context is a strict, and - the expression is not a HNF, and - the expression is not bottoming Exammples: * Bottoming f x = case x of 0 -> error <big thing> _ -> x+1 Here we want to float (error <big thing>) to top level, abstracting over 'x', so as to make f's RHS smaller. * HNF f = case y of True -> p:q False -> blah We may as well float the (p:q) so it becomes a static data structure. * Case scrutinee f = case g True of .... Don't float (g True) to top level; then we have the admin of a top-level thunk to worry about, with zero gain. * Case alternative h = case y of True -> g True False -> False Don't float (g True) to the top level * Arguments t = f (g True) If f is lazy, we /do/ float (g True) because then we can allocate the thunk statically rather than dynamically. But if f is strict we don't (see the use of idStrictness in lvlApp). It's not clear if this test is worth the bother: it's only about CAFs! It's controlled by a flag (floatConsts), because doing this too early loses opportunities for RULES which (needless to say) are important in some nofib programs (gcd is an example). [SPJ note: I think this is obselete; the flag seems always on.] Note [Floating join point bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mostly we only float a join point if it can /stay/ a join point. But there is one exception: if it can go to the top level (Trac #13286). Consider f x = joinrec j y n = <...j y' n'...> in jump j x 0 Here we may just as well produce j y n = <....j y' n'...> f x = j x 0 and now there is a chance that 'f' will be inlined at its call sites. It shouldn't make a lot of difference, but thes tests perf/should_run/MethSharing simplCore/should_compile/spec-inline and one nofib program, all improve if you do float to top, because of the resulting inlining of f. So ok, let's do it. Note [Free join points] ~~~~~~~~~~~~~~~~~~~~~~~ We never float a MFE that has a free join-point variable. You mght think this can never occur. After all, consider join j x = ... in ....(jump j x).... How might we ever want to float that (jump j x)? * If it would escape a value lambda, thus join j x = ... in (\y. ...(jump j x)... ) then 'j' isn't a valid join point in the first place. But consider join j x = .... in joinrec j2 y = ...(jump j x)...(a+b).... Since j2 is recursive, it /is/ worth floating (a+b) out of the joinrec. But it is emphatically /not/ good to float the (jump j x) out: (a) 'j' will stop being a join point (b) In any case, jumping to 'j' must be an exit of the j2 loop, so no work would be saved by floating it out of the \y. Even if we floated 'j' to top level, (b) would still hold. Bottom line: never float a MFE that has a free JoinId. Note [Floating MFEs of unlifted type] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have case f x of (r::Int#) -> blah we'd like to float (f x). But it's not trivial because it has type Int#, and we don't want to evaluate it too early. But we can instead float a boxed version y = case f x of r -> I# r and replace the original (f x) with case (case y of I# r -> r) of r -> blah Being able to float unboxed expressions is sometimes important; see Trac #12603. I'm not sure how /often/ it is important, but it's not hard to achieve. We only do it for a fixed collection of types for which we have a convenient boxing constructor (see boxingDataCon_maybe). In particular we /don't/ do it for unboxed tuples; it's better to float the components of the tuple individually. I did experiment with a form of boxing that works for any type, namely wrapping in a function. In our example let y = case f x of r -> \v. f x in case y void of r -> blah It works fine, but it's 50% slower (based on some crude benchmarking). I suppose we could do it for types not covered by boxingDataCon_maybe, but it's more code and I'll wait to see if anyone wants it. Note [Test cheapness with exprOkForSpeculation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't want to float very cheap expressions by boxing and unboxing. But we use exprOkForSpeculation for the test, not exprIsCheap. Why? Because it's important /not/ to transform f (a /# 3) to f (case bx of I# a -> a /# 3) and float bx = I# (a /# 3), because the application of f no longer obeys the let/app invariant. But (a /# 3) is ok-for-spec due to a special hack that says division operators can't fail when the denominator is definitely non-zero. And yet that same expression says False to exprIsCheap. Simplest way to guarantee the let/app invariant is to use the same function! If an expression is okay for speculation, we could also float it out *without* boxing and unboxing, since evaluating it early is okay. However, it turned out to usually be better not to float such expressions, since they tend to be extremely cheap things like (x +# 1#). Even the cost of spilling the let-bound variable to the stack across a call may exceed the cost of recomputing such an expression. (And we can't float unlifted bindings to top-level.) We could try to do something smarter here, and float out expensive yet okay-for-speculation things, such as division by non-zero constants. But I suspect it's a narrow target. Note [Bottoming floats] ~~~~~~~~~~~~~~~~~~~~~~~ If we see f = \x. g (error "urk") we'd like to float the call to error, to get lvl = error "urk" f = \x. g lvl But, as ever, we need to be careful: (1) We want to float a bottoming expression even if it has free variables: f = \x. g (let v = h x in error ("urk" ++ v)) Then we'd like to abstract over 'x' can float the whole arg of g: lvl = \x. let v = h x in error ("urk" ++ v) f = \x. g (lvl x) To achieve this we pass is_bot to destLevel (2) We do not do this for lambdas that return bottom. Instead we treat the /body/ of such a function specially, via point (1). For example: f = \x. ....(\y z. if x then error y else error z).... ===> lvl = \x z y. if b then error y else error z f = \x. ...(\y z. lvl x z y)... (There is no guarantee that we'll choose the perfect argument order.) (3) If we have a /binding/ that returns bottom, we want to float it to top level, even if it has free vars (point (1)), and even it has lambdas. Example: ... let { v = \y. error (show x ++ show y) } in ... We want to abstract over x and float the whole thing to top: lvl = \xy. errror (show x ++ show y) ...let {v = lvl x} in ... Then of course we don't want to separately float the body (error ...) as /another/ MFE, so we tell lvlFloatRhs not to do that, via the is_bot argument. See Maessen's paper 1999 "Bottom extraction: factoring error handling out of functional programs" (unpublished I think). When we do this, we set the strictness and arity of the new bottoming Id, *immediately*, for three reasons: * To prevent the abstracted thing being immediately inlined back in again via preInlineUnconditionally. The latter has a test for bottoming Ids to stop inlining them, so we'd better make sure it *is* a bottoming Id! * So that it's properly exposed as such in the interface file, even if this is all happening after strictness analysis. * In case we do CSE with the same expression that *is* marked bottom lvl = error "urk" x{str=bot) = error "urk" Here we don't want to replace 'x' with 'lvl', else we may get Lint errors, e.g. via a case with empty alternatives: (case x of {}) Lint complains unless the scrutinee of such a case is clearly bottom. This was reported in Trac #11290. But since the whole bottoming-float thing is based on the cheap-and-cheerful exprIsBottom, I'm not sure that it'll nail all such cases. Note [Bottoming floats: eta expansion] c.f Note [Bottoming floats] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tiresomely, though, the simplifier has an invariant that the manifest arity of the RHS should be the same as the arity; but we can't call etaExpand during SetLevels because it works over a decorated form of CoreExpr. So we do the eta expansion later, in FloatOut. Note [Case MFEs] ~~~~~~~~~~~~~~~~ We don't float a case expression as an MFE from a strict context. Why not? Because in doing so we share a tiny bit of computation (the switch) but in exchange we build a thunk, which is bad. This case reduces allocation by 7% in spectral/puzzle (a rather strange benchmark) and 1.2% in real/fem. Doesn't change any other allocation at all. We will make a separate decision for the scrutinee and alternatives. However this can have a knock-on effect for fusion: consider \v -> foldr k z (case x of I# y -> build ..y..) Perhaps we can float the entire (case x of ...) out of the \v. Then fusion will not happen, but we will get more sharing. But if we don't float the case (as advocated here) we won't float the (build ...y..) either, so fusion will happen. It can be a big effect, esp in some artificial benchmarks (e.g. integer, queens), but there is no perfect answer. -} annotateBotStr :: Id -> Arity -> Maybe (Arity, StrictSig) -> Id -- See Note [Bottoming floats] for why we want to add -- bottoming information right now -- -- n_extra are the number of extra value arguments added during floating annotateBotStr id n_extra mb_str = case mb_str of Nothing -> id Just (arity, sig) -> id `setIdArity` (arity + n_extra) `setIdStrictness` (increaseStrictSigArity n_extra sig) notWorthFloating :: CoreExpr -> [Var] -> Bool -- Returns True if the expression would be replaced by -- something bigger than it is now. For example: -- abs_vars = tvars only: return True if e is trivial, -- but False for anything bigger -- abs_vars = [x] (an Id): return True for trivial, or an application (f x) -- but False for (f x x) -- -- One big goal is that floating should be idempotent. Eg if -- we replace e with (lvl79 x y) and then run FloatOut again, don't want -- to replace (lvl79 x y) with (lvl83 x y)! notWorthFloating e abs_vars = go e (count isId abs_vars) where go (Var {}) n = n >= 0 go (Lit lit) n = ASSERT( n==0 ) litIsTrivial lit -- Note [Floating literals] go (Tick t e) n = not (tickishIsCode t) && go e n go (Cast e _) n = go e n go (App e arg) n | Type {} <- arg = go e n | Coercion {} <- arg = go e n | n==0 = False | is_triv arg = go e (n-1) | otherwise = False go _ _ = False is_triv (Lit {}) = True -- Treat all literals as trivial is_triv (Var {}) = True -- (ie not worth floating) is_triv (Cast e _) = is_triv e is_triv (App e (Type {})) = is_triv e is_triv (App e (Coercion {})) = is_triv e is_triv (Tick t e) = not (tickishIsCode t) && is_triv e is_triv _ = False {- Note [Floating literals] ~~~~~~~~~~~~~~~~~~~~~~~~ It's important to float Integer literals, so that they get shared, rather than being allocated every time round the loop. Hence the litIsTrivial. Ditto literal strings (MachStr), which we'd like to float to top level, which is now possible. Note [Escaping a value lambda] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to float even cheap expressions out of value lambdas, because that saves allocation. Consider f = \x. .. (\y.e) ... Then we'd like to avoid allocating the (\y.e) every time we call f, (assuming e does not mention x). An example where this really makes a difference is simplrun009. Another reason it's good is because it makes SpecContr fire on functions. Consider f = \x. ....(f (\y.e)).... After floating we get lvl = \y.e f = \x. ....(f lvl)... and that is much easier for SpecConstr to generate a robust specialisation for. However, if we are wrapping the thing in extra value lambdas (in abs_vars), then nothing is saved. E.g. f = \xyz. ...(e1[y],e2).... If we float lvl = \y. (e1[y],e2) f = \xyz. ...(lvl y)... we have saved nothing: one pair will still be allocated for each call of 'f'. Hence the (not float_is_lam) in float_me. ************************************************************************ * * \subsection{Bindings} * * ************************************************************************ The binding stuff works for top level too. -} lvlBind :: LevelEnv -> CoreBindWithFVs -> LvlM (LevelledBind, LevelEnv) lvlBind env (AnnNonRec bndr rhs) | isTyVar bndr -- Don't do anything for TyVar binders -- (simplifier gets rid of them pronto) || isCoVar bndr -- Difficult to fix up CoVar occurrences (see extendPolyLvlEnv) -- so we will ignore this case for now || not (profitableFloat env dest_lvl) || (isTopLvl dest_lvl && not (exprIsTopLevelBindable deann_rhs bndr_ty)) -- We can't float an unlifted binding to top level (except -- literal strings), so we don't float it at all. It's a -- bit brutal, but unlifted bindings aren't expensive either = -- No float do { rhs' <- lvlRhs env NonRecursive is_bot mb_join_arity rhs ; let bind_lvl = incMinorLvl (le_ctxt_lvl env) (env', [bndr']) = substAndLvlBndrs NonRecursive env bind_lvl [bndr] ; return (NonRec bndr' rhs', env') } -- Otherwise we are going to float | null abs_vars = do { -- No type abstraction; clone existing binder rhs' <- lvlFloatRhs [] dest_lvl env NonRecursive is_bot mb_join_arity rhs ; (env', [bndr']) <- cloneLetVars NonRecursive env dest_lvl [bndr] ; let bndr2 = annotateBotStr bndr' 0 mb_bot_str ; return (NonRec (TB bndr2 (FloatMe dest_lvl)) rhs', env') } | otherwise = do { -- Yes, type abstraction; create a new binder, extend substitution, etc rhs' <- lvlFloatRhs abs_vars dest_lvl env NonRecursive is_bot mb_join_arity rhs ; (env', [bndr']) <- newPolyBndrs dest_lvl env abs_vars [bndr] ; let bndr2 = annotateBotStr bndr' n_extra mb_bot_str ; return (NonRec (TB bndr2 (FloatMe dest_lvl)) rhs', env') } where bndr_ty = idType bndr ty_fvs = tyCoVarsOfType bndr_ty rhs_fvs = freeVarsOf rhs bind_fvs = rhs_fvs `unionDVarSet` dIdFreeVars bndr abs_vars = abstractVars dest_lvl env bind_fvs dest_lvl = destLevel env bind_fvs ty_fvs (isFunction rhs) is_bot is_join deann_rhs = deAnnotate rhs mb_bot_str = exprBotStrictness_maybe deann_rhs is_bot = isJust mb_bot_str -- NB: not isBottomThunk! See Note [Bottoming floats] point (3) n_extra = count isId abs_vars mb_join_arity = isJoinId_maybe bndr is_join = isJust mb_join_arity lvlBind env (AnnRec pairs) | floatTopLvlOnly env && not (isTopLvl dest_lvl) -- Only floating to the top level is allowed. || not (profitableFloat env dest_lvl) = do { let bind_lvl = incMinorLvl (le_ctxt_lvl env) (env', bndrs') = substAndLvlBndrs Recursive env bind_lvl bndrs lvl_rhs (b,r) = lvlRhs env' Recursive is_bot (isJoinId_maybe b) r ; rhss' <- mapM lvl_rhs pairs ; return (Rec (bndrs' `zip` rhss'), env') } | null abs_vars = do { (new_env, new_bndrs) <- cloneLetVars Recursive env dest_lvl bndrs ; new_rhss <- mapM (do_rhs new_env) pairs ; return ( Rec ([TB b (FloatMe dest_lvl) | b <- new_bndrs] `zip` new_rhss) , new_env) } -- ToDo: when enabling the floatLambda stuff, -- I think we want to stop doing this | [(bndr,rhs)] <- pairs , count isId abs_vars > 1 = do -- Special case for self recursion where there are -- several variables carried around: build a local loop: -- poly_f = \abs_vars. \lam_vars . letrec f = \lam_vars. rhs in f lam_vars -- This just makes the closures a bit smaller. If we don't do -- this, allocation rises significantly on some programs -- -- We could elaborate it for the case where there are several -- mutually functions, but it's quite a bit more complicated -- -- This all seems a bit ad hoc -- sigh let (rhs_env, abs_vars_w_lvls) = lvlLamBndrs env dest_lvl abs_vars rhs_lvl = le_ctxt_lvl rhs_env (rhs_env', [new_bndr]) <- cloneLetVars Recursive rhs_env rhs_lvl [bndr] let (lam_bndrs, rhs_body) = collectAnnBndrs rhs (body_env1, lam_bndrs1) = substBndrsSL NonRecursive rhs_env' lam_bndrs (body_env2, lam_bndrs2) = lvlLamBndrs body_env1 rhs_lvl lam_bndrs1 new_rhs_body <- lvlRhs body_env2 Recursive is_bot (get_join bndr) rhs_body (poly_env, [poly_bndr]) <- newPolyBndrs dest_lvl env abs_vars [bndr] return (Rec [(TB poly_bndr (FloatMe dest_lvl) , mkLams abs_vars_w_lvls $ mkLams lam_bndrs2 $ Let (Rec [( TB new_bndr (StayPut rhs_lvl) , mkLams lam_bndrs2 new_rhs_body)]) (mkVarApps (Var new_bndr) lam_bndrs1))] , poly_env) | otherwise -- Non-null abs_vars = do { (new_env, new_bndrs) <- newPolyBndrs dest_lvl env abs_vars bndrs ; new_rhss <- mapM (do_rhs new_env) pairs ; return ( Rec ([TB b (FloatMe dest_lvl) | b <- new_bndrs] `zip` new_rhss) , new_env) } where (bndrs,rhss) = unzip pairs is_join = isJoinId (head bndrs) -- bndrs is always non-empty and if one is a join they all are -- Both are checked by Lint is_fun = all isFunction rhss is_bot = False -- It's odd to have an unconditionally divergent -- function in a Rec, and we don't much care what -- happens to it. False is simple! do_rhs env (bndr,rhs) = lvlFloatRhs abs_vars dest_lvl env Recursive is_bot (get_join bndr) rhs get_join bndr | need_zap = Nothing | otherwise = isJoinId_maybe bndr need_zap = dest_lvl `ltLvl` joinCeilingLevel env -- Finding the free vars of the binding group is annoying bind_fvs = ((unionDVarSets [ freeVarsOf rhs | (_, rhs) <- pairs]) `unionDVarSet` (fvDVarSet $ unionsFV [ idFVs bndr | (bndr, (_,_)) <- pairs])) `delDVarSetList` bndrs ty_fvs = foldr (unionVarSet . tyCoVarsOfType . idType) emptyVarSet bndrs dest_lvl = destLevel env bind_fvs ty_fvs is_fun is_bot is_join abs_vars = abstractVars dest_lvl env bind_fvs profitableFloat :: LevelEnv -> Level -> Bool profitableFloat env dest_lvl = (dest_lvl `ltMajLvl` le_ctxt_lvl env) -- Escapes a value lambda || isTopLvl dest_lvl -- Going all the way to top level ---------------------------------------------------- -- Three help functions for the type-abstraction case lvlRhs :: LevelEnv -> RecFlag -> Bool -- Is this a bottoming function -> Maybe JoinArity -> CoreExprWithFVs -> LvlM LevelledExpr lvlRhs env rec_flag is_bot mb_join_arity expr = lvlFloatRhs [] (le_ctxt_lvl env) env rec_flag is_bot mb_join_arity expr lvlFloatRhs :: [OutVar] -> Level -> LevelEnv -> RecFlag -> Bool -- Binding is for a bottoming function -> Maybe JoinArity -> CoreExprWithFVs -> LvlM (Expr LevelledBndr) -- Ignores the le_ctxt_lvl in env; treats dest_lvl as the baseline lvlFloatRhs abs_vars dest_lvl env rec is_bot mb_join_arity rhs = do { body' <- if not is_bot -- See Note [Floating from a RHS] && any isId bndrs then lvlMFE body_env True body else lvlExpr body_env body ; return (mkLams bndrs' body') } where (bndrs, body) | Just join_arity <- mb_join_arity = collectNAnnBndrs join_arity rhs | otherwise = collectAnnBndrs rhs (env1, bndrs1) = substBndrsSL NonRecursive env bndrs all_bndrs = abs_vars ++ bndrs1 (body_env, bndrs') | Just _ <- mb_join_arity = lvlJoinBndrs env1 dest_lvl rec all_bndrs | otherwise = case lvlLamBndrs env1 dest_lvl all_bndrs of (env2, bndrs') -> (placeJoinCeiling env2, bndrs') -- The important thing here is that we call lvlLamBndrs on -- all these binders at once (abs_vars and bndrs), so they -- all get the same major level. Otherwise we create stupid -- let-bindings inside, joyfully thinking they can float; but -- in the end they don't because we never float bindings in -- between lambdas {- Note [Floating from a RHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When float the RHS of a let-binding, we don't always want to apply lvlMFE to the body of a lambda, as we usually do, because the entire binding body is already going to the right place (dest_lvl). A particular example is the top level. Consider concat = /\ a -> foldr ..a.. (++) [] We don't want to float the body of the lambda to get lvl = /\ a -> foldr ..a.. (++) [] concat = /\ a -> lvl a That would be stupid. Previously this was avoided in a much nastier way, by testing strict_ctxt in float_me in lvlMFE. But that wasn't even right because it would fail to float out the error sub-expression in f = \x. case x of True -> error ("blah" ++ show x) False -> ... But we must be careful: * If we had f = \x -> factorial 20 we /would/ want to float that (factorial 20) out! Functions are treated differently: see the use of isFunction in the calls to destLevel. If there are only type lambdas, then destLevel will say "go to top, and abstract over the free tyvars" and we don't want that here. * But if we had f = \x -> error (...x....) we would NOT want to float the bottoming expression out to give lvl = \x -> error (...x...) f = \x -> lvl x Conclusion: use lvlMFE if there are * any value lambdas in the original function, and * this is not a bottoming function (the is_bot argument) Use lvlExpr otherwise. A little subtle, and I got it wrong at least twice (e.g. Trac #13369). -} {- ************************************************************************ * * \subsection{Deciding floatability} * * ************************************************************************ -} substAndLvlBndrs :: RecFlag -> LevelEnv -> Level -> [InVar] -> (LevelEnv, [LevelledBndr]) substAndLvlBndrs is_rec env lvl bndrs = lvlBndrs subst_env lvl subst_bndrs where (subst_env, subst_bndrs) = substBndrsSL is_rec env bndrs substBndrsSL :: RecFlag -> LevelEnv -> [InVar] -> (LevelEnv, [OutVar]) -- So named only to avoid the name clash with CoreSubst.substBndrs substBndrsSL is_rec env@(LE { le_subst = subst, le_env = id_env }) bndrs = ( env { le_subst = subst' , le_env = foldl add_id id_env (bndrs `zip` bndrs') } , bndrs') where (subst', bndrs') = case is_rec of NonRecursive -> substBndrs subst bndrs Recursive -> substRecBndrs subst bndrs lvlLamBndrs :: LevelEnv -> Level -> [OutVar] -> (LevelEnv, [LevelledBndr]) -- Compute the levels for the binders of a lambda group lvlLamBndrs env lvl bndrs = lvlBndrs env new_lvl bndrs where new_lvl | any is_major bndrs = incMajorLvl lvl | otherwise = incMinorLvl lvl is_major bndr = isId bndr && not (isProbablyOneShotLambda bndr) -- The "probably" part says "don't float things out of a -- probable one-shot lambda" -- See Note [Computing one-shot info] in Demand.hs lvlJoinBndrs :: LevelEnv -> Level -> RecFlag -> [OutVar] -> (LevelEnv, [LevelledBndr]) lvlJoinBndrs env lvl rec bndrs = lvlBndrs env new_lvl bndrs where new_lvl | isRec rec = incMajorLvl lvl | otherwise = incMinorLvl lvl -- Non-recursive join points are one-shot; recursive ones are not lvlBndrs :: LevelEnv -> Level -> [CoreBndr] -> (LevelEnv, [LevelledBndr]) -- The binders returned are exactly the same as the ones passed, -- apart from applying the substitution, but they are now paired -- with a (StayPut level) -- -- The returned envt has le_ctxt_lvl updated to the new_lvl -- -- All the new binders get the same level, because -- any floating binding is either going to float past -- all or none. We never separate binders. lvlBndrs env@(LE { le_lvl_env = lvl_env }) new_lvl bndrs = ( env { le_ctxt_lvl = new_lvl , le_join_ceil = new_lvl , le_lvl_env = addLvls new_lvl lvl_env bndrs } , map (stayPut new_lvl) bndrs) stayPut :: Level -> OutVar -> LevelledBndr stayPut new_lvl bndr = TB bndr (StayPut new_lvl) -- Destination level is the max Id level of the expression -- (We'll abstract the type variables, if any.) destLevel :: LevelEnv -> DVarSet -- Free vars of the term -> TyCoVarSet -- Free in the /type/ of the term -- (a subset of the previous argument) -> Bool -- True <=> is function -> Bool -- True <=> is bottom -> Bool -- True <=> is a join point -> Level -- INVARIANT: if is_join=True then result >= join_ceiling destLevel env fvs fvs_ty is_function is_bot is_join | isTopLvl max_fv_id_level -- Float even joins if they get to top level -- See Note [Floating join point bindings] = tOP_LEVEL | is_join -- Never float a join point past the join ceiling -- See Note [Join points] in FloatOut = if max_fv_id_level `ltLvl` join_ceiling then join_ceiling else max_fv_id_level | is_bot -- Send bottoming bindings to the top = as_far_as_poss -- regardless; see Note [Bottoming floats] -- Esp Bottoming floats (1) | Just n_args <- floatLams env , n_args > 0 -- n=0 case handled uniformly by the 'otherwise' case , is_function , countFreeIds fvs <= n_args = as_far_as_poss -- Send functions to top level; see -- the comments with isFunction | otherwise = max_fv_id_level where join_ceiling = joinCeilingLevel env max_fv_id_level = maxFvLevel isId env fvs -- Max over Ids only; the -- tyvars will be abstracted as_far_as_poss = maxFvLevel' isId env fvs_ty -- See Note [Floating and kind casts] {- Note [Floating and kind casts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this case x of K (co :: * ~# k) -> let v :: Int |> co v = e in blah Then, even if we are abstracting over Ids, or if e is bottom, we can't float v outside the 'co' binding. Reason: if we did we'd get v' :: forall k. (Int ~# Age) => Int |> co and now 'co' isn't in scope in that type. The underlying reason is that 'co' is a value-level thing and we can't abstract over that in a type (else we'd get a dependent type). So if v's /type/ mentions 'co' we can't float it out beyond the binding site of 'co'. That's why we have this as_far_as_poss stuff. Usually as_far_as_poss is just tOP_LEVEL; but occasionally a coercion variable (which is an Id) mentioned in type prevents this. Example Trac #14270 comment:15. -} isFunction :: CoreExprWithFVs -> Bool -- The idea here is that we want to float *functions* to -- the top level. This saves no work, but -- (a) it can make the host function body a lot smaller, -- and hence inlinable. -- (b) it can also save allocation when the function is recursive: -- h = \x -> letrec f = \y -> ...f...y...x... -- in f x -- becomes -- f = \x y -> ...(f x)...y...x... -- h = \x -> f x x -- No allocation for f now. -- We may only want to do this if there are sufficiently few free -- variables. We certainly only want to do it for values, and not for -- constructors. So the simple thing is just to look for lambdas isFunction (_, AnnLam b e) | isId b = True | otherwise = isFunction e -- isFunction (_, AnnTick _ e) = isFunction e -- dubious isFunction _ = False countFreeIds :: DVarSet -> Int countFreeIds = nonDetFoldUDFM add 0 -- It's OK to use nonDetFoldUDFM here because we're just counting things. where add :: Var -> Int -> Int add v n | isId v = n+1 | otherwise = n {- ************************************************************************ * * \subsection{Free-To-Level Monad} * * ************************************************************************ -} data LevelEnv = LE { le_switches :: FloatOutSwitches , le_ctxt_lvl :: Level -- The current level , le_lvl_env :: VarEnv Level -- Domain is *post-cloned* TyVars and Ids , le_join_ceil:: Level -- Highest level to which joins float -- Invariant: always >= le_ctxt_lvl -- See Note [le_subst and le_env] , le_subst :: Subst -- Domain is pre-cloned TyVars and Ids -- The Id -> CoreExpr in the Subst is ignored -- (since we want to substitute a LevelledExpr for -- an Id via le_env) but we do use the Co/TyVar substs , le_env :: IdEnv ([OutVar], LevelledExpr) -- Domain is pre-cloned Ids } {- Note [le_subst and le_env] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We clone let- and case-bound variables so that they are still distinct when floated out; hence the le_subst/le_env. (see point 3 of the module overview comment). We also use these envs when making a variable polymorphic because we want to float it out past a big lambda. The le_subst and le_env always implement the same mapping, in_x :-> out_x a b where out_x is an OutVar, and a,b are its arguments (when we perform abstraction at the same time as floating). le_subst maps to CoreExpr le_env maps to LevelledExpr Since the range is always a variable or application, there is never any difference between the two, but sadly the types differ. The le_subst is used when substituting in a variable's IdInfo; the le_env when we find a Var. In addition the le_env records a [OutVar] of variables free in the OutExpr/LevelledExpr, just so we don't have to call freeVars repeatedly. This list is always non-empty, and the first element is out_x The domain of the both envs is *pre-cloned* Ids, though The domain of the le_lvl_env is the *post-cloned* Ids -} initialEnv :: FloatOutSwitches -> LevelEnv initialEnv float_lams = LE { le_switches = float_lams , le_ctxt_lvl = tOP_LEVEL , le_join_ceil = panic "initialEnv" , le_lvl_env = emptyVarEnv , le_subst = emptySubst , le_env = emptyVarEnv } addLvl :: Level -> VarEnv Level -> OutVar -> VarEnv Level addLvl dest_lvl env v' = extendVarEnv env v' dest_lvl addLvls :: Level -> VarEnv Level -> [OutVar] -> VarEnv Level addLvls dest_lvl env vs = foldl (addLvl dest_lvl) env vs floatLams :: LevelEnv -> Maybe Int floatLams le = floatOutLambdas (le_switches le) floatConsts :: LevelEnv -> Bool floatConsts le = floatOutConstants (le_switches le) floatOverSat :: LevelEnv -> Bool floatOverSat le = floatOutOverSatApps (le_switches le) floatTopLvlOnly :: LevelEnv -> Bool floatTopLvlOnly le = floatToTopLevelOnly (le_switches le) incMinorLvlFrom :: LevelEnv -> Level incMinorLvlFrom env = incMinorLvl (le_ctxt_lvl env) -- extendCaseBndrEnv adds the mapping case-bndr->scrut-var if it can -- See Note [Binder-swap during float-out] extendCaseBndrEnv :: LevelEnv -> Id -- Pre-cloned case binder -> Expr LevelledBndr -- Post-cloned scrutinee -> LevelEnv extendCaseBndrEnv le@(LE { le_subst = subst, le_env = id_env }) case_bndr (Var scrut_var) = le { le_subst = extendSubstWithVar subst case_bndr scrut_var , le_env = add_id id_env (case_bndr, scrut_var) } extendCaseBndrEnv env _ _ = env -- See Note [Join ceiling] placeJoinCeiling :: LevelEnv -> LevelEnv placeJoinCeiling le@(LE { le_ctxt_lvl = lvl }) = le { le_ctxt_lvl = lvl', le_join_ceil = lvl' } where lvl' = asJoinCeilLvl (incMinorLvl lvl) maxFvLevel :: (Var -> Bool) -> LevelEnv -> DVarSet -> Level maxFvLevel max_me env var_set = foldDVarSet (maxIn max_me env) tOP_LEVEL var_set maxFvLevel' :: (Var -> Bool) -> LevelEnv -> TyCoVarSet -> Level -- Same but for TyCoVarSet maxFvLevel' max_me env var_set = nonDetFoldUniqSet (maxIn max_me env) tOP_LEVEL var_set maxIn :: (Var -> Bool) -> LevelEnv -> InVar -> Level -> Level maxIn max_me (LE { le_lvl_env = lvl_env, le_env = id_env }) in_var lvl = case lookupVarEnv id_env in_var of Just (abs_vars, _) -> foldr max_out lvl abs_vars Nothing -> max_out in_var lvl where max_out out_var lvl | max_me out_var = case lookupVarEnv lvl_env out_var of Just lvl' -> maxLvl lvl' lvl Nothing -> lvl | otherwise = lvl -- Ignore some vars depending on max_me lookupVar :: LevelEnv -> Id -> LevelledExpr lookupVar le v = case lookupVarEnv (le_env le) v of Just (_, expr) -> expr _ -> Var v -- Level to which join points are allowed to float (boundary of current tail -- context). See Note [Join ceiling] joinCeilingLevel :: LevelEnv -> Level joinCeilingLevel = le_join_ceil abstractVars :: Level -> LevelEnv -> DVarSet -> [OutVar] -- Find the variables in fvs, free vars of the target expression, -- whose level is greater than the destination level -- These are the ones we are going to abstract out -- -- Note that to get reproducible builds, the variables need to be -- abstracted in deterministic order, not dependent on the values of -- Uniques. This is achieved by using DVarSets, deterministic free -- variable computation and deterministic sort. -- See Note [Unique Determinism] in Unique for explanation of why -- Uniques are not deterministic. abstractVars dest_lvl (LE { le_subst = subst, le_lvl_env = lvl_env }) in_fvs = -- NB: sortQuantVars might not put duplicates next to each other map zap $ sortQuantVars $ uniq [out_var | out_fv <- dVarSetElems (substDVarSet subst in_fvs) , out_var <- dVarSetElems (close out_fv) , abstract_me out_var ] -- NB: it's important to call abstract_me only on the OutIds the -- come from substDVarSet (not on fv, which is an InId) where uniq :: [Var] -> [Var] -- Remove duplicates, preserving order uniq = dVarSetElems . mkDVarSet abstract_me v = case lookupVarEnv lvl_env v of Just lvl -> dest_lvl `ltLvl` lvl Nothing -> False -- We are going to lambda-abstract, so nuke any IdInfo, -- and add the tyvars of the Id (if necessary) zap v | isId v = WARN( isStableUnfolding (idUnfolding v) || not (isEmptyRuleInfo (idSpecialisation v)), text "absVarsOf: discarding info on" <+> ppr v ) setIdInfo v vanillaIdInfo | otherwise = v close :: Var -> DVarSet -- Close over variables free in the type -- Result includes the input variable itself close v = foldDVarSet (unionDVarSet . close) (unitDVarSet v) (fvDVarSet $ varTypeTyCoFVs v) type LvlM result = UniqSM result initLvl :: UniqSupply -> UniqSM a -> a initLvl = initUs_ newPolyBndrs :: Level -> LevelEnv -> [OutVar] -> [InId] -> LvlM (LevelEnv, [OutId]) -- The envt is extended to bind the new bndrs to dest_lvl, but -- the le_ctxt_lvl is unaffected newPolyBndrs dest_lvl env@(LE { le_lvl_env = lvl_env, le_subst = subst, le_env = id_env }) abs_vars bndrs = ASSERT( all (not . isCoVar) bndrs ) -- What would we add to the CoSubst in this case. No easy answer. do { uniqs <- getUniquesM ; let new_bndrs = zipWith mk_poly_bndr bndrs uniqs bndr_prs = bndrs `zip` new_bndrs env' = env { le_lvl_env = addLvls dest_lvl lvl_env new_bndrs , le_subst = foldl add_subst subst bndr_prs , le_env = foldl add_id id_env bndr_prs } ; return (env', new_bndrs) } where add_subst env (v, v') = extendIdSubst env v (mkVarApps (Var v') abs_vars) add_id env (v, v') = extendVarEnv env v ((v':abs_vars), mkVarApps (Var v') abs_vars) mk_poly_bndr bndr uniq = transferPolyIdInfo bndr abs_vars $ -- Note [transferPolyIdInfo] in Id.hs transfer_join_info bndr $ mkSysLocalOrCoVar (mkFastString str) uniq poly_ty where str = "poly_" ++ occNameString (getOccName bndr) poly_ty = mkLamTypes abs_vars (CoreSubst.substTy subst (idType bndr)) -- If we are floating a join point to top level, it stops being -- a join point. Otherwise it continues to be a join point, -- but we may need to adjust its arity dest_is_top = isTopLvl dest_lvl transfer_join_info bndr new_bndr | Just join_arity <- isJoinId_maybe bndr , not dest_is_top = new_bndr `asJoinId` join_arity + length abs_vars | otherwise = new_bndr newLvlVar :: LevelledExpr -- The RHS of the new binding -> Maybe JoinArity -- Its join arity, if it is a join point -> Bool -- True <=> the RHS looks like (makeStatic ...) -> LvlM Id newLvlVar lvld_rhs join_arity_maybe is_mk_static = do { uniq <- getUniqueM ; return (add_join_info (mk_id uniq rhs_ty)) } where add_join_info var = var `asJoinId_maybe` join_arity_maybe de_tagged_rhs = deTagExpr lvld_rhs rhs_ty = exprType de_tagged_rhs mk_id uniq rhs_ty -- See Note [Grand plan for static forms] in StaticPtrTable. | is_mk_static = mkExportedVanillaId (mkSystemVarName uniq (mkFastString "static_ptr")) rhs_ty | otherwise = mkLocalIdOrCoVar (mkSystemVarName uniq (mkFastString "lvl")) rhs_ty cloneCaseBndrs :: LevelEnv -> Level -> [Var] -> LvlM (LevelEnv, [Var]) cloneCaseBndrs env@(LE { le_subst = subst, le_lvl_env = lvl_env, le_env = id_env }) new_lvl vs = do { us <- getUniqueSupplyM ; let (subst', vs') = cloneBndrs subst us vs env' = env { le_ctxt_lvl = new_lvl , le_join_ceil = new_lvl , le_lvl_env = addLvls new_lvl lvl_env vs' , le_subst = subst' , le_env = foldl add_id id_env (vs `zip` vs') } ; return (env', vs') } cloneLetVars :: RecFlag -> LevelEnv -> Level -> [InVar] -> LvlM (LevelEnv, [OutVar]) -- See Note [Need for cloning during float-out] -- Works for Ids bound by let(rec) -- The dest_lvl is attributed to the binders in the new env, -- but cloneVars doesn't affect the le_ctxt_lvl of the incoming env cloneLetVars is_rec env@(LE { le_subst = subst, le_lvl_env = lvl_env, le_env = id_env }) dest_lvl vs = do { us <- getUniqueSupplyM ; let vs1 = map zap vs -- See Note [Zapping the demand info] (subst', vs2) = case is_rec of NonRecursive -> cloneBndrs subst us vs1 Recursive -> cloneRecIdBndrs subst us vs1 prs = vs `zip` vs2 env' = env { le_lvl_env = addLvls dest_lvl lvl_env vs2 , le_subst = subst' , le_env = foldl add_id id_env prs } ; return (env', vs2) } where zap :: Var -> Var zap v | isId v = zap_join (zapIdDemandInfo v) | otherwise = v zap_join | isTopLvl dest_lvl = zapJoinId | otherwise = \v -> v add_id :: IdEnv ([Var], LevelledExpr) -> (Var, Var) -> IdEnv ([Var], LevelledExpr) add_id id_env (v, v1) | isTyVar v = delVarEnv id_env v | otherwise = extendVarEnv id_env v ([v1], ASSERT(not (isCoVar v1)) Var v1) {- Note [Zapping the demand info] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VERY IMPORTANT: we must zap the demand info if the thing is going to float out, because it may be less demanded than at its original binding site. Eg f :: Int -> Int f x = let v = 3*4 in v+x Here v is strict; but if we float v to top level, it isn't any more. Similarly, if we're floating a join point, it won't be one anymore, so we zap join point information as well. -}
shlevy/ghc
compiler/simplCore/SetLevels.hs
Haskell
bsd-3-clause
70,015
{-# LANGUAGE OverloadedStrings #-} module NativeWhitelist (read) where import Prelude hiding (read) import Data.Aeson as Json import qualified Data.ByteString.Lazy as LBS import qualified System.Directory as Dir import System.IO import qualified Elm.Package.Name as Name nativeWhitelist :: FilePath nativeWhitelist = "native-whitelist.json" read :: IO [Name.Name] read = do exists <- Dir.doesFileExist nativeWhitelist case exists of False -> return [] True -> withBinaryFile nativeWhitelist ReadMode $ \handle -> do json <- LBS.hGetContents handle case Json.decode json of Nothing -> return [] Just names -> return names
Dedoig/package.elm-lang.org
backend/NativeWhitelist.hs
Haskell
bsd-3-clause
750
-- Unlike the rest of xmonad, this file is copyright under the terms of the -- GPL. -- -- Generates man/xmonad.1 from man/xmonad.1.in by filling the list of -- keybindings with values scraped from Config.hs -- -- Uses cabal to grab the xmonad version from xmonad.cabal -- -- Uses pandoc to convert the "xmonad.1.markdown" to "xmonad.1" -- -- Format for the docstrings in Config.hs takes the following form: -- -- -- mod-x %! Frob the whatsit -- -- "Frob the whatsit" will be used as the description for keybinding "mod-x" -- -- If the keybinding name is omitted, it will try to guess from the rest of the -- line. For example: -- -- [ ((modMask .|. shiftMask, xK_Return), spawn "xterm") -- %! Launch an xterm -- -- Here, mod-shift-return will be used as the keybinding name. import Control.Monad import Control.Applicative import Text.Regex.Posix import Data.Char import Data.List import Distribution.PackageDescription.Parse import Distribution.Verbosity import Distribution.Package import Distribution.PackageDescription import Text.PrettyPrint.HughesPJ import Distribution.Text import Text.Pandoc -- works with 1.12.4 releaseDate = "31 December 2012" trim :: String -> String trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace guessKeys line = concat $ intersperse "-" (modifiers ++ [map toLower key]) where modifiers = map (!!1) (line =~ "(mod|shift|control)Mask") (_, _, _, [key]) = line =~ "xK_([_[:alnum:]]+)" :: (String, String, String, [String]) binding :: [String] -> (String, String) binding [ _, bindingLine, "", desc ] = (guessKeys bindingLine, desc) binding [ _, _, keyCombo, desc ] = (keyCombo, desc) allBindings :: String -> [(String, String)] allBindings xs = map (binding . map trim) (xs =~ "(.*)--(.*)%!(.*)") -- FIXME: What escaping should we be doing on these strings? markdownDefn :: (String, String) -> String markdownDefn (key, desc) = key ++ "\n: " ++ desc replace :: Eq a => a -> a -> [a] -> [a] replace x y = map (\a -> if a == x then y else a) -- rawSystem "pandoc" ["--read=markdown","--write=man","man/xmonad.1.markdown"] main = do releaseName <- (show . disp . package . packageDescription) `liftM`readPackageDescription normal "xmonad.cabal" keybindings <- (intercalate "\n\n" . map markdownDefn . allBindings) `liftM` readFile "./src/XMonad/Config.hs" let manHeader = unwords [".TH xmonad 1","\""++releaseDate++"\"",releaseName,"\"xmonad manual\""] parsed <- readMarkdown def . unlines . replace "___KEYBINDINGS___" keybindings . lines <$> readFile "./man/xmonad.1.markdown" Right template <- getDefaultTemplate Nothing "man" writeFile "./man/xmonad.1" . (manHeader ++) . writeMan def{ writerStandalone = True, writerTemplate = template } $ parsed putStrLn "Documentation created: man/xmonad.1" Right template <- getDefaultTemplate Nothing "html" writeFile "./man/xmonad.1.html" . writeHtmlString def { writerVariables = [("include-before" ,"<h1>"++releaseName++"</h1>"++ "<p>Section: xmonad manual (1)<br/>"++ "Updated: "++releaseDate++"</p>"++ "<hr/>")] , writerStandalone = True , writerTemplate = template , writerTableOfContents = True } $ parsed putStrLn "Documentation created: man/xmonad.1.html"
atupal/xmonad-mirror
xmonad/util/GenerateManpage.hs
Haskell
mit
3,525
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ar-SA"> <title>Reveal | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>بحث</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/reveal/src/main/javahelp/org/zaproxy/zap/extension/reveal/resources/help_ar_SA/helpset_ar_SA.hs
Haskell
apache-2.0
967
module PatternIn3 where sumSquares y = let x = 1 in (case x of 0 -> 0 x -> x ^ pow) + (sq y) where sq 0 = 0 sq x = x ^ pow sumSquares_1 y = let x = 1 in case x of 0 -> return 0 x -> return 1 where sq 0 = 0 sq x = x ^ pow pow = 2
kmate/HaRe
old/testing/simplifyExpr/PatternIn3AST.hs
Haskell
bsd-3-clause
367
{-# LANGUAGE TemplateHaskell #-} module T16195 where import T16195A main2 :: IO () main2 = return () main :: IO () main = $$foo main3 :: IO () main3 = putStrLn ($$showC $$unitC)
sdiehl/ghc
testsuite/tests/th/T16195.hs
Haskell
bsd-3-clause
184
module A3 where data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: Ord a => [a] -> BTree a buildtree [] = Empty buildtree ((x : xs)) = insert x (buildtree xs) insert :: Ord a => a -> (BTree a) -> BTree a insert val (t@(T val Empty Empty)) = T val Empty result where result = t insert val (T tval left right) | val > tval = T tval left (insert val right) | otherwise = T tval (insert val left) right newPat_1 = Empty main :: BTree Int main = buildtree [3, 1, 2]
kmate/HaRe
old/testing/unfoldAsPatterns/A3AST.hs
Haskell
bsd-3-clause
515
{- We expect to get a suggestion to add 'type' keyword and enable TypeOperators extension. -} {-# LANGUAGE TypeOperators #-} module T11432 ((-.->)(..)) where newtype (f -.-> g) a = Fn { apFn :: f a -> g a }
ezyang/ghc
testsuite/tests/module/T11432.hs
Haskell
bsd-3-clause
209
-- Basic Tic Tac Toe game against the AI, for testing import Core import Algo import AI runCycle :: Board -> Board runCycle board = if checkGameOver board then board else makeMove board PO runMove :: Board -> IO (Bool, Player, Board) runMove board = do if checkGameOver board then do return (True, case determineWin board of (Just p) -> p _ -> N, board) else do putStrLn "Board:" print board putStrLn "Enter move coordinates in format (x, y):" coordStr <- getLine let coords = read coordStr if placeIsFull $ getByPosition board coords then do putStrLn "Selected position is already occupied. Please try again.\n" runMove board else do let board' = setByPosition board coords X runMove $ runCycle board' main :: IO () main = do putStrLn "Tic Tac Toe game: You are player X.\n" let board = emptyBoard (_, player, board') <- runMove board putStrLn $ case player of PO -> "Sorry, you lose" PX -> "Congratulations, you win" _ -> "It's a tie" putStrLn "Final board:\n" print board'
quantum-dan/tictactoe-ai
Play.hs
Haskell
mit
1,254
module Main ( main ) where import RunDataAssocWekaApriorySimple import DataAssociation import System.Environment import System.Exit import System.IO import Data.Maybe import Control.Monad main :: IO () main = getArgs >>= parse maybeRead = fmap fst . listToMaybe . reads maybeReadInUnit :: String -> Maybe Float maybeReadInUnit s = (maybeRead s :: Maybe Float) >>= f where f x | x <= 1 && x >= 0 = Just x | otherwise = Nothing parse ["-h"] = usage >> exitSuccess parse [fname, msup, mconf] = do let minsup = maybe minsupError MinSupport $ maybeReadInUnit msup let minconf = maybe minconfError MinConfidence $ maybeReadInUnit mconf run fname minsup minconf parse _ = unknownCmd >> usage >> exitFailure unknownCmd = putStrLn "Wrong arguments!" usage = do putStrLn "Usage: mine-rules [-h] file MinSupport MinConfidence" putStrLn " where file is an *.arff nominal data file" putStrLn " MinSupport and MinConfidence must be Float values in [0, 1]" minsupError = boundError "MinSupport" minconfError = boundError "MinConfidence" boundError nme = error $ nme ++ " must be a Float in [0, 1]"
fehu/min-dat--a-priori
core/src/Main.hs
Haskell
mit
1,197
module LogicProver.Prover (isValid) where import qualified Data.Map as M import LogicProver.Lang -- The type of the proof tree used for determining the validity of a proposition data ProofTree = Leaf Bool Prop -- used, prop | Branch1 Bool Prop ProofTree -- used, prop, left | Branch2 Bool Prop ProofTree ProofTree -- used, prop, left, right deriving (Show, Eq) getProp :: ProofTree -> Prop getProp (Leaf _ p) = p getProp (Branch1 _ p _) = p getProp (Branch2 _ p _ _) = p getUsed :: ProofTree -> Bool getUsed (Leaf u _) = u getUsed (Branch1 u _ _) = u getUsed (Branch2 u _ _ _) = u -- Return true if the proposition is valid: there is some combination of truth -- values for all of the atomic variables that allow the proposition to be true. isValid :: Prop -> Bool isValid = allClosed . collapseBranches . openBranches . solveProp -- Return true if all variables are consitent isConsistent :: [(String, Bool)] -> Bool isConsistent = all (\(k,v) -> v) -- Takes a list of True for an open branch and False for a closed branch allClosed :: [Bool]-> Bool allClosed = all (\x -> not x) -- Collapse a branch of the proof tree (a list of vars to consistency) into a -- single consistency value. collapseBranches :: [[(String, Bool)]] -> [Bool] collapseBranches l = map isConsistent l -- Create a list where each element in a branch of the proof tree. Each subelement -- is a variable appearing in the branch and its consistency within the branch. openBranches :: ProofTree -> [[(String, Bool)]] openBranches t = map isOpenBranch $ getAtoms t -- Create an association list of variable name to consitency isOpenBranch :: M.Map String [Prop] -> [(String, Bool)] isOpenBranch m = map gather $ M.toList $ m where gather :: (String, [Prop]) -> (String, Bool) gather (k, l) = (k, all (\x -> x == head l) l) -- Create a dictionary of variable names to atomic presence in the prooftree getAtoms :: ProofTree -> [ M.Map String [Prop] ] getAtoms t = getAtoms' t M.empty where getAtoms' t m = if isAtom t -- If the current node is an atom, then add it to the dictionary then let var = getVar $ getProp t in case M.lookup var m of -- If it does not exist in the dictionary, add it Nothing -> case t of Leaf _ p -> (M.insert var [p] m) : [] Branch1 _ p l -> getAtoms' l $ M.insert var [p] m Branch2 _ p l r -> (getAtoms' l $ M.insert var [p] m) ++ (getAtoms' r $ M.insert var [p] m) -- Otherwise, append it to the current entry for the variable Just past -> case t of Leaf _ p -> (M.insert var (p:past) m) : [] Branch1 _ p l -> getAtoms' l $ M.insert var (p:past) m Branch2 _ p l r -> (getAtoms' l $ M.insert var (p:past) m) ++ (getAtoms' r $ M.insert var (p:past) m) -- If the current node is not atomic, skip the entry and continue else case t of Leaf _ p -> [m] Branch1 _ p l -> getAtoms' l m Branch2 _ p l r -> (getAtoms' l m) ++ (getAtoms' r m) -- Apply a function to each leaf of a proof tree morphLeaves :: (Prop -> ProofTree -> ProofTree) -> Prop -> ProofTree -> ProofTree morphLeaves f p t = case t of Leaf _ _ -> f p t Branch1 u p' l -> Branch1 u p' (morphLeaves f p l) Branch2 u p' l r -> Branch2 u p' (morphLeaves f p l) (morphLeaves f p r) -- 1) Take a proof tree -- 2) Traverse the tree looking for the highest node that has not had a rule applied to it -- 3) Construct the proof tree resulting from applying the found rule to the given tree -- 4) Return the tree step :: ProofTree -> ProofTree step t = case getUsed t of -- This branch has been used, so step its children if applicable True -> case t of Leaf _ _ -> t Branch1 _ p l -> Branch1 True p (step l) Branch2 _ p l r -> Branch2 True p (step l) (step r) -- Otherwise -- If atomic, there are no rules to apply, so mark it as hit -- If not, apply the rule associated with its proposition False -> case isAtom t of True -> setUsed t False -> case t of Leaf u p -> setUsed $ morphLeaves propToTree p t Branch1 u p l -> setUsed $ morphLeaves propToTree p t Branch2 u p l r -> setUsed $ morphLeaves propToTree p t -- Turn a proposition into a prooftree and apply all rules to it solveProp :: Prop -> ProofTree solveProp = solveTree . initTree -- Given a proof tree, proceed to iteratively apply all rules to it until there -- are no more rules to apply solveTree :: ProofTree -> ProofTree solveTree t = case treeSolved t of True -> t False -> solveTree $ step t -- Returns true if the tree has been fully applied, false otherwise treeSolved :: ProofTree -> Bool treeSolved t = case t of Leaf u _ -> u Branch1 u _ l -> u && treeSolved l Branch2 u _ l r -> u && treeSolved l && treeSolved r -- Given a proposition and a prooftree, apply the rule of the proposition on a -- new proof tree that has as its root the given proposition propToTree :: Prop -> ProofTree -> ProofTree -- (not (not P)) propToTree p'@(PNegate (PNegate _)) (Leaf u p) = Branch1 u p $ Leaf False (collapseNegations p') -- P and Q propToTree (PAnd p1 p2) (Leaf u p) = Branch1 u p $ Branch1 False p1 $ Leaf False p2 -- ~(P and Q) propToTree (PNegate (PAnd p1 p2)) l = propToTree (POr (PNegate p1) (PNegate p2)) l -- (P or Q) propToTree (POr p1 p2) (Leaf u p) = Branch2 u p (Leaf False p1) (Leaf False p2) -- ~(P or Q) propToTree (PNegate (POr p1 p2)) l = propToTree (PAnd (PNegate p1) (PNegate p2)) l -- P implies Q propToTree (PCond p1 p2) l = propToTree (POr (PNegate p1) p2) l -- ~(P implies Q) propToTree (PNegate (PCond p1 p2)) l = propToTree (PAnd p1 (PNegate p2)) l -- Collapse all stacked negations collapseNegations :: Prop -> Prop collapseNegations (PNegate (PNegate p)) = collapseNegations p collapseNegations p = p -- Return true is there is no rule to apply on the given node isAtom :: ProofTree -> Bool isAtom t = case getProp t of PVar _ -> True PNegate (PVar _) -> True _ -> False -- Given a propsition, create a proof tree by negating the proposition. This is -- to facilitate a proof by contradication of the validity of the proposition. initTree :: Prop -> ProofTree initTree p = Leaf False (PNegate p) -- Set the `used` flag on a prooftree node setUsed :: ProofTree -> ProofTree setUsed (Leaf _ p) = Leaf True p setUsed (Branch1 _ p b) = Branch1 True p b setUsed (Branch2 _ p b1 b2) = Branch2 True p b1 b2
igorii/LogicProver
LogicProver/Prover.hs
Haskell
mit
6,837
-- Speed Control -- http://www.codewars.com/kata/56484848ba95170a8000004d/ module Codewars.G964.Gps1 where gps :: Int -> [Double] -> Int gps _ [] = 0 gps _ [x] = 0 gps s xs = floor . maximum $ zipWith (\a b -> (b-a)*60*60 / fromIntegral s) xs (tail xs)
gafiatulin/codewars
src/7 kyu/Gps1.hs
Haskell
mit
260
{-# LANGUAGE CPP #-} module Stackage.Config where import Control.Monad (when) import Control.Monad.Trans.Writer (execWriter, tell) import qualified Data.Map as Map import Data.Set (fromList, singleton) import Distribution.Text (simpleParse) import Stackage.Types -- | Packages which are shipped with GHC but are not included in the -- Haskell Platform list of core packages. defaultExtraCore :: GhcMajorVersion -> Set PackageName defaultExtraCore _ = fromList $ map PackageName $ words "binary Win32" -- | Test suites which are expected to fail for some reason. The test suite -- will still be run and logs kept, but a failure will not indicate an -- error in our package combination. defaultExpectedFailures :: GhcMajorVersion -> Set PackageName defaultExpectedFailures ghcVer = execWriter $ do -- Requires an old version of WAI and Warp for tests add "HTTP" -- text and setenv have recursive dependencies in their tests, which -- cabal can't (yet) handle add "text" add "setenv" -- The version of GLUT included with the HP does not generate -- documentation correctly. add "GLUT" -- https://github.com/bos/statistics/issues/42 add "statistics" -- https://github.com/kazu-yamamoto/simple-sendfile/pull/10 add "simple-sendfile" -- http://hackage.haskell.org/trac/hackage/ticket/954 add "diagrams" -- https://github.com/fpco/stackage/issues/24 add "unix-time" -- With transformers 0.3, it doesn't provide any modules add "transformers-compat" -- Tests require shell script and are incompatible with sandboxed package -- databases add "HTF" -- https://github.com/simonmar/monad-par/issues/28 add "monad-par" -- Unfortunately network failures seem to happen haphazardly add "network" -- https://github.com/ekmett/hyphenation/issues/1 add "hyphenation" -- Test suite takes too long to run on some systems add "punycode" -- http://hub.darcs.net/stepcut/happstack/issue/1 add "happstack-server" -- Requires a Facebook app. add "fb" -- https://github.com/tibbe/hashable/issues/64 add "hashable" -- https://github.com/vincenthz/language-java/issues/10 add "language-java" add "threads" add "crypto-conduit" add "pandoc" add "language-ecmascript" add "hspec" add "alex" -- https://github.com/basvandijk/concurrent-extra/issues/ add "concurrent-extra" -- https://github.com/rrnewton/haskell-lockfree-queue/issues/7 add "abstract-deque" -- https://github.com/skogsbaer/xmlgen/issues/2 add "xmlgen" -- Something very strange going on with the test suite, I can't figure -- out how to fix it add "bson" -- Requires a locally running PostgreSQL server with appropriate users add "postgresql-simple" -- Missing files add "websockets" -- Some kind of Cabal bug when trying to run tests add "thyme" when (ghcVer < GhcMajorVersion 7 6) $ do -- https://github.com/haskell-suite/haskell-names/issues/39 add "haskell-names" add "shake" -- https://github.com/jgm/pandoc-citeproc/issues/5 add "pandoc-citeproc" -- Problems with doctest and sandboxing add "warp" add "wai-logger" -- https://github.com/fpco/stackage/issues/163 add "hTalos" add "seqloc" -- FIXME the test suite fails fairly regularly in builds, though I haven't -- discovered why yet add "crypto-numbers" where add = tell . singleton . PackageName -- | List of packages for our stable Hackage. All dependencies will be -- included as well. Please indicate who will be maintaining the package -- via comments. defaultStablePackages :: GhcMajorVersion -> Map PackageName (VersionRange, Maintainer) defaultStablePackages ghcVer = unPackageMap $ execWriter $ do mapM_ (add "michael@snoyman.com") $ words =<< [ "yesod yesod-newsfeed yesod-sitemap yesod-static yesod-test yesod-bin" , "markdown filesystem-conduit mime-mail-ses" , "persistent persistent-template persistent-sqlite" , "network-conduit-tls yackage warp-tls keter" , "shakespeare-text process-conduit stm-conduit" , "classy-prelude-yesod yesod-fay yesod-eventsource wai-websockets" , "random-shuffle safe-failure hackage-proxy hebrew-time" ] when (ghcVer >= GhcMajorVersion 7 6) $ add "michael@snoyman.com" "mega-sdist" mapM_ (add "FP Complete <michael@fpcomplete.com>") $ words =<< [ "web-fpco th-expand-syns configurator compdata smtLib unification-fd" , "fixed-list indents language-c pretty-class" , "aws yesod-auth-oauth csv-conduit cassava" , "async shelly thyme" , "hxt hxt-relaxng dimensional" , "cairo diagrams-cairo" , "persistent-mongoDB" , "threepenny-gui base16-bytestring convertible" ] when (ghcVer < GhcMajorVersion 7 6) $ do addRange "FP Complete <michael@fpcomplete.com>" "hxt" "<= 9.3.0.1" addRange "FP Complete <michael@fpcomplete.com>" "shelly" "<= 1.0" when (ghcVer >= GhcMajorVersion 7 6) $ do add "FP Complete <michael@fpcomplete.com>" "repa-devil" addRange "FP Complete <michael@fpcomplete.com>" "kure" "<= 2.4.10" mapM_ (add "Neil Mitchell") $ words "hlint hoogle shake derive" mapM_ (add "Alan Zimmerman") $ words "hjsmin language-javascript" mapM_ (add "Jasper Van der Jeugt") $ words "blaze-html blaze-markup stylish-haskell" mapM_ (add "Antoine Latter") $ words "uuid byteorder" mapM_ (add "Stefan Wehr <wehr@factisresearch.com>") $ words "HTF hscurses xmlgen stm-stats" mapM_ (add "Bart Massey <bart.massey+stackage@gmail.com>") $ words "parseargs" mapM_ (add "Vincent Hanquez") $ words =<< [ "asn1-data bytedump certificate cipher-aes cipher-rc4 connection" , "cprng-aes cpu crypto-pubkey-types crypto-random-api cryptocipher" , "cryptohash hit language-java libgit pem siphash socks tls" , "tls-debug tls-extra vhd" ] addRange "Vincent Hanquez" "language-java" "< 0.2.5" #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) -- Does not compile on Windows mapM_ (add "Vincent Hanquez") $ words "udbus xenstore" #endif mapM_ (add "Alberto G. Corona <agocorona@gmail.com>") $ words "RefSerialize TCache Workflow MFlow" mapM_ (add "Edward Kmett <ekmett@gmail.com>") $ words =<< [ "ad adjunctions bifunctors bound categories charset comonad comonad-transformers" , "comonads-fd comonad-extras compressed concurrent-supply constraints contravariant" , "distributive either eq free groupoids heaps hyphenation" , "integration intervals kan-extensions lca lens linear monadic-arrays machines" , "mtl profunctors profunctor-extras reducers reflection" , "semigroups semigroupoids semigroupoid-extras speculation tagged void" , "graphs monad-products monad-st wl-pprint-extras wl-pprint-terminfo" , "numeric-extras parsers pointed prelude-extras recursion-schemes reducers" , "streams syb-extras vector-instances" ] mapM_ (add "Simon Hengel <sol@typeful.net>") $ words "hspec doctest base-compat" mapM_ (add "Mario Blazevic <blamario@yahoo.com>") $ words "monad-parallel monad-coroutine" -- https://github.com/blamario/monoid-subclasses/issues/3 when (ghcVer >= GhcMajorVersion 7 6) $ do mapM_ (add "Mario Blazevic <blamario@yahoo.com>") $ words "incremental-parser monoid-subclasses" mapM_ (add "Brent Yorgey <byorgey@gmail.com>") $ words =<< [ "monoid-extras dual-tree vector-space-points active force-layout" , "diagrams diagrams-contrib diagrams-core diagrams-lib diagrams-svg" , "diagrams-postscript diagrams-builder diagrams-haddock haxr" , "BlogLiterately BlogLiterately-diagrams" , "MonadRandom" ] mapM_ (add "Patrick Brisbin") $ words "gravatar" mapM_ (add "Felipe Lessa <felipe.lessa@gmail.com>") $ words "esqueleto fb fb-persistent yesod-fb yesod-auth-fb" mapM_ (add "Alexander Altman <alexanderaltman@me.com>") $ words "base-unicode-symbols containers-unicode-symbols" mapM_ (add "Ryan Newton <ryan.newton@alum.mit.edu>") $ words "accelerate" when (ghcVer < GhcMajorVersion 7 6) $ do addRange "Ryan Newton <ryan.newton@alum.mit.edu>" "accelerate" "< 0.14" addRange "Ryan Newton <ryan.newton@alum.mit.edu>" "fclabels" "< 2.0" mapM_ (add "Dan Burton <danburton.email@gmail.com>") $ words =<< [ "basic-prelude composition io-memoize numbers rev-state runmemo" , "tardis" ] mapM_ (add "Daniel Díaz <dhelta.diaz@gmail.com>") $ words "HaTeX" mapM_ (add "Adam Bergmark <adam@bergmark.nl>") $ words "fay fay-base fay-dom fay-jquery fay-text fay-uri snaplet-fay" mapM_ (add "Boris Lykah <lykahb@gmail.com>") $ words "groundhog groundhog-th groundhog-sqlite groundhog-postgresql groundhog-mysql" mapM_ (add "Janne Hellsten <jjhellst@gmail.com>") $ words "sqlite-simple" mapM_ (add "Michal J. Gajda") $ words "iterable Octree FenwickTree hPDB" when (ghcVer >= GhcMajorVersion 7 6) $ do mapM_ (add "Michal J. Gajda") $ words "hPDB-examples" mapM_ (add "Roman Cheplyaka <roma@ro-che.info>") $ words =<< [ "smallcheck tasty tasty-smallcheck tasty-quickcheck tasty-hunit tasty-golden" , "traverse-with-class regex-applicative time-lens" , "haskell-names haskell-packages hse-cpp" ] -- https://github.com/fpco/stackage/issues/160 when (ghcVer >= GhcMajorVersion 7 6) $ do mapM_ (add "Ketil Malde") $ words =<< [ "biocore biofasta biofastq biosff" , "blastxml bioace biophd" , "biopsl samtools" , "seqloc bioalign BlastHTTP" , "RNAFold" , "parsestar hTalos" -- The following have out-of-date dependencies currently -- biostockholm memexml RNAwolf -- , "Biobase BiobaseDotP BiobaseFR3D BiobaseInfernal BiobaseMAF" -- , "BiobaseTrainingData BiobaseTurner BiobaseXNA BiobaseVienna" -- , "BiobaseTypes BiobaseFasta" -- MC-Fold-DP ] -- https://github.com/fpco/stackage/issues/163 addRange "Michael Snoyman" "biophd" "< 0.0.6 || > 0.0.6" -- https://github.com/fpco/stackage/issues/46 addRange "Michael Snoyman" "QuickCheck" "< 2.6" -- https://github.com/fpco/stackage/issues/68 addRange "Michael Snoyman" "criterion" "< 0.8" -- https://github.com/fpco/stackage/issues/72 addRange "Michael Snoyman" "HaXml" "< 1.24" -- Due to binary package dep addRange "Michael Snoyman" "statistics" "< 0.10.4" -- Newest hxt requires network 2.4 or newest addRange "Michael Snoyman" "hxt" "< 9.3.1" addRange "Michael Snoyman" "network" "< 2.4" -- https://github.com/fpco/stackage/issues/153 addRange "Michael Snoyman" "text" "< 1.0" -- https://github.com/fpco/stackage/issues/156 addRange "Michael Snoyman" "hspec" "< 1.8" addRange "Michael Snoyman" "hspec-expectations" "< 0.4" -- https://github.com/fpco/stackage/issues/159 addRange "Michael Snoyman" "pretty-show" "< 1.6.2" -- https://github.com/fpco/stackage/issues/161 addRange "Michael Snoyman" "RSA" "< 1.3" -- https://github.com/fpco/stackage/issues/168 addRange "Michael Snoyman" "crypto-api" "< 0.13" -- https://github.com/fpco/stackage/issues/170 addRange "Michael Snoyman" "aeson" "< 0.7" -- https://github.com/fpco/stackage/issues/171 addRange "Michael Snoyman" "pandoc-citeproc" "< 0.3" -- https://github.com/fpco/stackage/issues/172 addRange "Michael Snoyman" "attoparsec" "< 0.11" addRange "Michael Snoyman" "fay" "< 0.19" addRange "Michael Snoyman" "fay-base" "< 0.19" addRange "Michael Snoyman" "fay-text" "< 0.3.0.1" -- binary package dep issue, figure out more fine-grained workaround addRange "Michael Snoyman" "SHA" "< 1.6.3" addRange "Michael Snoyman" "hashable" "< 1.2" -- Requires binary 0.7 addRange "FP Complete <michael@fpcomplete.com>" "bson" "< 0.2.3" -- Version 0.15.3 requires a newer template-haskell addRange "FP Complete <michael@fpcomplete.com>" "language-ecmascript" "< 0.15.3" -- unknown symbol `utf8_table4' addRange "Michael Snoyman" "regex-pcre-builtin" "< 0.94.4.6.8.31" where add maintainer package = addRange maintainer package "-any" addRange maintainer package range = case simpleParse range of Nothing -> error $ "Invalid range " ++ show range ++ " for " ++ package Just range' -> tell $ PackageMap $ Map.singleton (PackageName package) (range', Maintainer maintainer)
sinelaw/stackage
Stackage/Config.hs
Haskell
mit
13,098
{-# LANGUAGE RecordWildCards #-} -- | Defines the XglImporter. {- Importer notes: - Ignores ambient and spherermap lights. -} module Codec.Soten.Importer.XglImporter ( XglImporter(..) -- Only for testing purpose. , transformLights , transformMaterials , transformToScene ) where import Data.List ( intercalate ) import Data.Maybe ( catMaybes ) import qualified Data.ByteString.Lazy as ByteString ( readFile ) import Data.ByteString.Lazy.Char8 ( unpack ) import qualified Data.Vector as V ( fromList , length , replicate ) import Codec.Compression.Zlib ( decompress ) import Control.Lens ((&), (^.), (.~)) import Linear ( V3(..) , cross , dot , normalize ) import Linear.Matrix ( M44 , (!!*) , identity , mkTransformationMat ) import Codec.Soten.BaseImporter ( BaseImporter(..) , searchFileHeaderForToken ) import Codec.Soten.Data.XglData as X ( Model(..) , LightingTag(..) , Material(..) , Mesh(..) , Face(..) , Transform(..) , Vertex(..) ) import qualified Codec.Soten.Parser.XglParser as Parser ( getModel ) import Codec.Soten.Scene.Light ( Light(..) , LightSource(LightDirectional) , newLight , lightType , lightDirection , lightColorDiffuse , lightColorSpecular ) import Codec.Soten.Scene.Material as S ( Material(..) , MaterialProperty(..) , newMaterial , addProperty ) import Codec.Soten.Scene.Mesh as S ( Mesh(..) , PrimitiveType(..) , Face(..) , newMesh , meshPrimitiveTypes , meshNormals , meshVertices , meshFaces , meshMaterialIndex ) import Codec.Soten.Scene ( Scene(..) , newScene , sceneLights , sceneMaterials ) import Codec.Soten.Util ( CheckType(..) , DeadlyImporterError(..) , throw , hasExtention , squareLength ) -- | Implementation of the XGL/ZGL importer. data XglImporter = XglImporter deriving Show instance BaseImporter XglImporter where canImport _ filePath CheckExtension = return $ hasExtention filePath [".xgl", ".zgl"] canImport _ filePath CheckHeader = searchFileHeaderForToken filePath ["<WORLD>"] readModel _ = internalReadFile -- | Reads file content and parsers it into the 'Scene'. Returns error messages -- as 'String's. internalReadFile :: FilePath -> IO (Either String Scene) internalReadFile filePath = Right <$> transformToScene <$> parseModelFile filePath -- | Parses model file into its internal representation. Decodess zlib files if -- needed. parseModelFile :: FilePath -> IO Model parseModelFile filePath = if hasExtention filePath [".zgl"] then do fileContent <- ByteString.readFile filePath Parser.getModel (unpack $ decompress fileContent) else readFile filePath >>= Parser.getModel -- | Transforms internal model representation into the 'Scene' object. transformToScene :: Model -> Scene transformToScene Model{..} = newScene & sceneMaterials .~ V.fromList (transformMaterials materials) -- & sceneMeshes .~ V.fromList (transformMeshes meshMaterials) -- & sceneRootNode .~ Just node & sceneLights .~ V.fromList (transformLights modelLightingTags) where materials = intercalate [] $ map meshMaterials modelMeshes -- | Transforms direction light into Light object. transformLights :: [LightingTag] -> [Light] transformLights = foldl tagToLight [] where tagToLight :: [Light] -> LightingTag -> [Light] tagToLight acc LightingTagDirectional{..} = light : acc where light = newLight & lightType .~ LightDirectional & lightDirection .~ lightingTagDirectionalDirection & lightColorDiffuse .~ lightingTagDirectionalDiffuse & lightColorSpecular .~ lightingTagDirectionalSpecular tagToLight acc _ = acc -- | Transforms internal material into scene's ones. transformMaterials :: [X.Material] -> [S.Material] transformMaterials = map sceneMat where -- TODO: Material id is missing! sceneMat X.Material{..} = foldl addProperty newMaterial (requiredProperties ++ optionalProperties) where requiredProperties = [ MaterialName "DefaultMaterial" , MaterialColorAmbient materialAmbient , MaterialColorDiffuse materialDiffuse ] optionalProperties = catMaybes [ fmap MaterialColorSpecular materialSpecular , fmap MaterialColorEmissive materialEmiss , fmap MaterialColorShininess materialShine , fmap MaterialColorOpacity materialAlpha ] -- | Calculates matrix of transformation. transformation :: Transform -> M44 Float transformation Transform{..} | squareLength transForward < 1e-4 = identity | squareLength transUp < 1e-4 = identity | up `dot` forward > 1e-4 = identity | otherwise = mkTransformationMat scaledRotMat transForward where forward = normalize transForward up = normalize transUp right = forward `cross` up rotateMatrix = V3 right up forward scaledRotMat = maybe rotateMatrix (rotateMatrix !!* ) transScale -- | Transforms internal mesh structure into global one. transformMeshes :: [X.Mesh] -> [S.Mesh] transformMeshes = map sceneMesh where sceneMesh X.Mesh{..} = newMesh & S.meshNormals .~ normals & meshVertices .~ vertices & S.meshFaces .~ V.fromList (map mkFace meshFaces) & meshMaterialIndex .~ Just 0 -- TODO: Retrive index from mat list. & meshPrimitiveTypes .~ V.replicate (V.length normals `div` 3) PrimitiveTriangle where vertices = V.fromList meshPositions normals = V.fromList meshNormals mkFace :: X.Face -> S.Face mkFace (X.Face _ v1 v2 v3) = S.Face (V.fromList [ vertexPosition v1 , vertexPosition v2 , vertexPosition v3 ])
triplepointfive/soten
src/Codec/Soten/Importer/XglImporter.hs
Haskell
mit
7,173
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} module Betfair.StreamingAPI.Requests.AuthenticationMessage ( AuthenticationMessage(..) , defaultAuthenticationMessage ) where import Data.Aeson.TH (Options (omitNothingFields), defaultOptions, deriveJSON) import Protolude import Text.PrettyPrint.GenericPretty import Betfair.StreamingAPI.API.AddId data AuthenticationMessage = AuthenticationMessage { op :: Text , id :: Int -- Client generated unique id to link request with response (like json rpc) , appKey :: Text , session :: Text } deriving (Eq, Read, Show, Generic, Pretty) $(deriveJSON defaultOptions {omitNothingFields = True} ''AuthenticationMessage) defaultAuthenticationMessage :: AuthenticationMessage defaultAuthenticationMessage = AuthenticationMessage "authentication" 0 undefined undefined instance AddId AuthenticationMessage where addId o i = o {id = i}
joe9/streaming-betfair-api
src/Betfair/StreamingAPI/Requests/AuthenticationMessage.hs
Haskell
mit
1,182
module GHCJS.DOM.WebGLCompressedTextureATC ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/WebGLCompressedTextureATC.hs
Haskell
mit
55
import XMonad -- LAYOUTS import XMonad.Layout.Spacing import XMonad.Layout.Fullscreen import XMonad.Layout.NoBorders import XMonad.Layout.PerWorkspace import XMonad.Layout.SimplestFloat import XMonad.Layout.ResizableTile import XMonad.Layout.Circle import XMonad.Layout.Grid import XMonad.Layout.IM -- WINDOW RULES import XMonad.ManageHook -- KEYBOARD & MOUSE CONFIG import XMonad.Util.EZConfig import XMonad.Actions.FloatKeys import Graphics.X11.ExtraTypes.XF86 -- STATUS BAR import XMonad.Hooks.DynamicLog hiding (xmobar, xmobarPP, xmobarColor, sjanssenPP, byorgeyPP) import XMonad.Hooks.ManageDocks import XMonad.Hooks.ManageHelpers import XMonad.Hooks.SetWMName import XMonad.Hooks.UrgencyHook import XMonad.Util.Dmenu --import XMonad.Hooks.FadeInactive import XMonad.Hooks.EwmhDesktops hiding (fullscreenEventHook) import System.IO (hPutStrLn) --import XMonad.Operations import XMonad.Util.Run (spawnPipe) import XMonad.Actions.CycleWS -- nextWS, prevWS import Data.List -- clickable workspaces import Data.Ratio ((%)) -- clickable workspaces -------------------------------------------------------------------------------------------------------------------- -- DECLARE WORKSPACES RULES -------------------------------------------------------------------------------------------------------------------- myLayout = onWorkspace (myWorkspaces !! 0) (avoidStruts (tiledSpace ||| tiled) ||| fullTile) $ onWorkspace (myWorkspaces !! 1) (avoidStruts (noBorders(tiledSpace ||| fullTile)) ||| fullScreen) $ onWorkspace (myWorkspaces !! 2) (avoidStruts simplestFloat) $ onWorkspace (myWorkspaces !! 6) (avoidStruts pidginLayout) -- --$ onWorkspace (myWorkspaces !! 6) (pidginLayout) $ avoidStruts ( tiledSpace ||| tiled ||| fullTile ) where tiled = spacing 5 $ ResizableTall nmaster delta ratio [] tiledSpace = spacing 60 $ ResizableTall nmaster delta ratio [] fullScreen = noBorders(fullscreenFull Full) fullTile = ResizableTall nmaster delta ratio [] fullTiled = ResizableTall nmaster delta ratio [] borderlessTile = noBorders(fullTile) -- Default number of windows in master pane nmaster = 1 -- Percent of the screen to increment when resizing delta = 5/100 -- Default proportion of the screen taken up by main pane ratio = toRational (2/(1 + sqrt 5 :: Double)) gridLayout = spacing 8 $ Grid pidginRoster = And (ClassName "Pidgin") (Role "buddy_list") pidginLayout = withIM (1%9) pidginRoster gridLayout -------------------------------------------------------------------------------------------------------------------- -- WORKSPACE DEFINITIONS -------------------------------------------------------------------------------------------------------------------- myWorkspaces = clickable $ ["term" ,"web" ,"float" ,"docs" ,"tunes" ,"mail" ,"pidgin"] where clickable l = [ "^ca(1,xdotool key alt+" ++ show (n) ++ ")" ++ ws ++ "^ca()" | (i,ws) <- zip [1..] l, let n = i ] -------------------------------------------------------------------------------------------------------------------- -- APPLICATION SPECIFIC RULES -------------------------------------------------------------------------------------------------------------------- myManageHook = composeAll [ resource =? "dmenu" --> doFloat , resource =? "skype" --> doFloat , resource =? "mplayer" --> doFloat , resource =? "feh" --> doFloat , resource =? "google-chrome"--> doShift (myWorkspaces !! 1) , className =? "Pidgin"--> doShift (myWorkspaces !! 6) , resource =? "lowriter"--> doShift (myWorkspaces !! 3) , resource =? "localc"--> doShift (myWorkspaces !! 3) , resource =? "loimpress"--> doShift (myWorkspaces !! 3) , resource =? "zathura"--> doShift (myWorkspaces !! 3) , resource =? "ario"--> doShift (myWorkspaces !! 4) , resource =? "ncmpcpp"--> doShift (myWorkspaces !! 4) , resource =? "alsamixer"--> doShift (myWorkspaces !! 4) , resource =? "mutt"--> doShift (myWorkspaces !! 5) , resource =? "irssi"--> doShift (myWorkspaces !! 5) , resource =? "centerim"--> doShift (myWorkspaces !! 5) , manageDocks] newManageHook = myManageHook <+> manageHook defaultConfig -------------------------------------------------------------------------------------------------------------------- -- DZEN LOG RULES for workspace names, layout image, current program title -------------------------------------------------------------------------------------------------------------------- myLogHook h = dynamicLogWithPP ( defaultPP { ppCurrent = dzenColor green0 background . pad , ppVisible = dzenColor red0 background . pad , ppHidden = dzenColor red0 background . pad , ppHiddenNoWindows = dzenColor yellow0 background. pad , ppWsSep = "" , ppSep = " " , ppLayout = wrap "^ca(1,xdotool key alt+space)" "^ca()" . dzenColor white1 background . (\x -> case x of "Full" -> "^i(~/.xmonad/dzen2/layout_full.xbm)" "Spacing 5 ResizableTall" -> "^i(~/.xmonad/dzen2/layout_tall.xbm)" "ResizableTall" -> "^i(~/.xmonad/dzen2/layout_tall.xbm)" "SimplestFloat" -> "^i(~/.xmonad/dzen2/mouse_01.xbm)" "Circle" -> "^i(~/.xmonad/dzen2/full.xbm)" _ -> "^i(~/.xmonad/dzen2/grid.xbm)" ) -- , ppTitle = wrap "^ca(1,xdotool key alt+shift+x)^fg(#222222)^i(~/.xmonad/dzen2/corner_left.xbm)^bg(#222222)^fg(#AADB0F)^fn(fkp)x^fn()" "^fg(#222222)^i(~/.xmonad/dzen2/corner_right.xbm)^ca()" . dzenColor white0 "#222222" . shorten 40 . pad , ppOrder = \(ws:l:t:_) -> [ws,l] , ppOutput = hPutStrLn h } ) -------------------------------------------------------------------------------------------------------------------- -- Spawn pipes and menus on boot, set default settings -------------------------------------------------------------------------------------------------------------------- myXmonadBar = "dzen2 -x '0' -y '0' -h '14' -w '1500' -ta 'l' -fg '"++foreground++"' -bg '"++background++"' -fn "++myFont myStatusBar = "conky -qc ~/.xmonad/.conky_dzen | dzen2 -x '1200' -w '666' -h '14' -ta 'r' -bg '"++background++"' -fg '"++foreground++"' -y '0' -fn "++myFont --myConky = "conky -c ~/conkyrc" --myStartMenu = "~/.xmonad/start ~/.xmonad/start_apps" main = do dzenLeftBar <- spawnPipe myXmonadBar dzenRightBar <- spawnPipe myStatusBar xmproc <- spawnPipe "GTK2_RC_FILES=~/.gtkdocky /usr/bin/docky" xmproc <- spawnPipe "tint2 -c ~/.config/tint2/xmonad.tint2rc" -- conky <- spawn myConky -- dzenStartMenu <- spawnPipe myStartMenu xmonad $ ewmh defaultConfig { terminal = myTerminal , borderWidth = 1 , normalBorderColor = yellow0 , focusedBorderColor = green0 , modMask = mod1Mask , layoutHook = myLayout , workspaces = myWorkspaces , manageHook = newManageHook , handleEventHook = fullscreenEventHook <+> docksEventHook , startupHook = setWMName "LG3D" , logHook = myLogHook dzenLeftBar -- >> fadeInactiveLogHook 0xdddddddd } -------------------------------------------------------------------------------------------------------------------- -- Keyboard options -------------------------------------------------------------------------------------------------------------------- `additionalKeys` [((mod1Mask .|. shiftMask , xK_b), spawn "chromium") ,((mod1Mask , xK_b), spawn "dwb") ,((mod1Mask .|. shiftMask , xK_n), spawn "xterm -fn '-*-gohufont-medium-r-normal-*-12-*-*-*-*-*-*-*' -fb '-*-gohufont-medium-r-normal-*-12-*-*-*-*-*-*-*' -fi '-*-gohufont-medium-r-normal-*-12-*-*-*-*-*-*-*'") ,((mod1Mask .|. shiftMask , xK_t), spawn "xterm -e tmux") ,((mod4Mask , xK_z), spawn "zathura") ,((mod4Mask , xK_w), spawn "lowriter") ,((mod4Mask , xK_c), spawn "localc") ,((mod4Mask , xK_m), spawn "xterm -title mutt -name mutt -e muttb") ,((mod4Mask , xK_i), spawn "xterm -title irssi -name irssi -e irssi") ,((mod4Mask , xK_n), spawn "xterm -title ncmpcpp -name ncmpcpp -e ncmpcpp") ,((mod4Mask , xK_a), spawn "xterm -title alsamixer -name alsamixer -e alsamixer") ,((mod4Mask , xK_M), spawn "xterm -title centerim -name centerim -e centerim") ,((mod1Mask , xK_r), spawn "~/scripts/lens") ,((mod1Mask .|. shiftMask , xK_r), spawn "~/scripts/dmenu/spotlight") ,((mod1Mask , xK_q), spawn "killall dzen2; killall conky; cd ~/.xmonad; ghc -threaded xmonad.hs; mv xmonad xmonad-x86_64-linux; xmonad --restart" ) ,((mod1Mask .|. shiftMask , xK_i), spawn "xcalib -invert -alter") ,((mod1Mask .|. shiftMask , xK_x), kill) ,((mod1Mask .|. shiftMask , xK_c), return()) ,((mod1Mask , xK_p), moveTo Prev NonEmptyWS) ,((mod1Mask , xK_n), moveTo Next NonEmptyWS) ,((mod1Mask , xK_c), moveTo Next EmptyWS) ,((mod1Mask .|. shiftMask , xK_l), sendMessage MirrorShrink) ,((mod1Mask .|. shiftMask , xK_h), sendMessage MirrorExpand) ,((mod1Mask , xK_a), withFocused (keysMoveWindow (-20,0))) ,((mod1Mask , xK_d), withFocused (keysMoveWindow (0,-20))) ,((mod1Mask , xK_s), withFocused (keysMoveWindow (0,20))) ,((mod1Mask , xK_f), withFocused (keysMoveWindow (20,0))) ,((mod1Mask .|. shiftMask , xK_a), withFocused (keysResizeWindow (-20,0) (0,0))) ,((mod1Mask .|. shiftMask , xK_d), withFocused (keysResizeWindow (0,-20) (0,0))) ,((mod1Mask .|. shiftMask , xK_s), withFocused (keysResizeWindow (0,20) (0,0))) ,((mod1Mask .|. shiftMask , xK_f), withFocused (keysResizeWindow (20,0) (0,0))) ,((0 , xK_Super_L), spawn "menu ~/.xmonad/apps") ,((mod1Mask , xK_Super_L), spawn "menu ~/.xmonad/configs") ,((mod1Mask , xK_F1), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_music.sh") ,((mod1Mask , xK_F2), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_vol.sh") ,((mod1Mask , xK_F3), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_network.sh") ,((mod1Mask , xK_F4), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_battery.sh") ,((mod1Mask , xK_F5), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_hardware.sh") ,((mod1Mask , xK_F6), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_pacman.sh") ,((mod1Mask , xK_F7), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_date.sh") ,((mod1Mask , xK_F8), spawn "~/.xmonad/sc ~/.xmonad/scripts/dzen_log.sh") ,((0 , xK_Print), spawn "scrot & mplayer /usr/share/sounds/freedesktop/stereo/screen-capture.oga") ,((mod1Mask , xK_Print), spawn "scrot -s & mplayer /usr/share/sounds/freedesktop/stereo/screen-capture.oga") ,((0 , xF86XK_AudioLowerVolume), spawn "amixer set Master 2- & mplayer /usr/share/sounds/freedesktop/stereo/audio-volume-change.oga") ,((0 , xF86XK_AudioRaiseVolume), spawn "amixer set Master 2+ & mplayer /usr/share/sounds/freedesktop/stereo/audio-volume-change.oga") ,((0 , xF86XK_AudioMute), spawn "amixer set Master toggle") -- ,((0 , xF86XK_Display), spawn "xrandr --newmode `cvt 1366 768 | tail -n1 | cut' ' -f2`; xrandr --addmode VGA1 1368x768_60.00; xrandr --output VGA1 --mode 1368x768_60.00") ,((0 , xF86XK_Sleep), spawn "pm-suspend") ,((0 , xF86XK_AudioPlay), spawn "ncmpcpp toggle") ,((0 , xF86XK_AudioNext), spawn "ncmpcpp next") ,((0 , xF86XK_AudioPrev), spawn "ncmpcpp prev") ,((0, 0x1008FF05), spawn "asus-kbd-backlight up" ) -- XF86XK_MonBrightnessUp ,((0, 0x1008FF06), spawn "asus-kbd-backlight down" ) -- XF86XK_MonBrightnessDown , ((0, 0x1008FF12), spawn "~/common/bin/pa-vol.sh mute" ) -- XF86XK_AudioMute , ((0, 0x1008FF11), spawn "~/common/bin/pa-vol.sh minus" ) -- XF86XK_AudioLowerVolume , ((0, 0x1008FF13), spawn "~/common/bin/pa-vol.sh plus" ) -- XF86XK_AudioRaiseVolume , ((0, 0x1008FF2C), spawn "eject" ) -- XF86XK_Eject , ((0, 0x1008ff2a), spawn "sudo pm-suspend" ) -- XF86XK_PowerOff ] `additionalMouseBindings` [((mod1Mask , 6), (\_ -> moveTo Next NonEmptyWS)) ,((mod1Mask , 7), (\_ -> moveTo Prev NonEmptyWS)) ,((mod1Mask , 5), (\_ -> moveTo Prev NonEmptyWS)) ,((mod1Mask , 4), (\_ -> moveTo Next NonEmptyWS)) ] -- Define constants myTerminal = "xterm" myBitmapsDir = "~/.xmonad/dzen2/" --myFont = "-*-tamsyn-medium-*-normal-*-10-*-*-*-*-*-*-*" --myFont = "-*-terminus-medium-*-normal-*-9-*-*-*-*-*-*-*" --myFont = "-*-lime-*-*-*-*-*-*-*-*-*-*-*-*" myFont = "-*-nu-*-*-*-*-*-*-*-*-*-*-*-*" --myFont = "'sans:italic:bold:underline'" --myFont = "xft:droid sans mono:size=9" --myFont = "xft:Droid Sans:size=12" --myFont = "-*-cure-*-*-*-*-*-*-*-*-*-*-*-*" foreground= "#D3D3D3" background= "#111111" black0= "#181818" black1= "#181818" red0= "#D7D7D7" red1= "#D7D7D7" green0= "#AADB0F" green1= "#AADB0F" --green0= "#A80036" --green1= "#A80036" --green0= "#E2791B" --green1= "#E2791B" yellow0= "#666666" yellow1= "#666666" blue0= "#FFFFFF" blue1= "#FFFFFF" --magenta0= "#91BA0D" --magenta1= "#91BA0D" --magenta0= "#740629" --magenta1= "#740629" magenta0= "#BF3C0A" magenta1= "#BF3C0A" cyan0= "#D4D4D4" cyan1= "#D4D4D4" white0= "#D3D3D3" white1= "#D3D3D3"
Bryan792/dotfiles
.xmonad/xmonad.hs
Haskell
mit
13,686
module Rebase.System.IO.Unsafe ( module System.IO.Unsafe ) where import System.IO.Unsafe
nikita-volkov/rebase
library/Rebase/System/IO/Unsafe.hs
Haskell
mit
92