code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
function onPlot(sprite, plot) {
var game = sprite.game;
var scene = game.scene;
game.log("onPlot - by [" + sprite.scene.name + "]" + sprite.name);
var profile = scene.get("player");
if (profile.progress != 0) {
if (game.music("battle").isPlaying()) plot.musicFadeOut("battle", 2000);
else if(game.music("boss").isPlaying()) plot.musicFadeOut("boss", 2000);
}
if (profile.progress > 0) {
game.music("win").play(1);
scene.spr("info1").enable();
game.sys("text").setText(scene.spr("info1"), "YOU WIN");
} else if (profile.progress < 0) {
game.music("lose").play(1);
scene.spr("info1").enable();
game.sys("text").setText(scene.spr("info1"), "YOU LOSE");
}
if (profile.progress != 0) {
plot.wait(6000);
plot.nextScene(game, "menu", 200, 60);
}
plot.disable(sprite);
}
|
joelam789/oge2d
|
examples/stg/Assets/scenes/battle/sprites/gameover.hs
|
mit
| 805
| 41
| 12
| 118
| 416
| 242
| 174
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
-- | Functions to update accounting table.
module AAA.Account ( addAccount
, getPermissions
, permit
, secretMatches ) where
import AAA.Types
import qualified AAA.Crypto as C
import qualified Data.Map as M
import qualified Data.Text as T
import Data.Maybe (fromJust)
type E a b = Either a b
-- | Gets an explicit `Salt`; tuple of `Id Account`, `Secret`; and current registry
-- of `Accounts` and returns `Either (Account, Accounts) Error`.
--
-- ```
-- Example:
-- addAccount (Id "artosis", Secret "pylon", Salt "menzoberranzan") M.empty
-- > Right ( Account { aaaAct_name = Id {getId = "artosis"}
-- , aaaAct_salted = Salted {getSalted = "gR0MteJb6J8+CIA9AhGd4juJr3S2rKhYwws4gA+vKEU="}
-- , aaaAct_permissions = fromList [] }
-- , fromList [ ( Id {getId = "sweater"}
-- , Account { aaaAct_name = Id {getId = "artosis"},
-- *snip* } ) ] )
-- ```
addAccount :: Salt -> (Id Account, Secret) -> Accounts -> E Error (Account, Accounts)
addAccount s a@(x, _) xs
| M.lookup x xs == Nothing = Right $ addAccountDo s a xs
| True = Left $ Error ( EAccountAlreadyRegistered
, T.unwords [ "Account"
, (getId x)
, "is already registered" ] )
-- | Returns `Maybe Permissions` of an account by `Id Account`
getPermissions :: Id Account -> Accounts -> Maybe Permissions
getPermissions x xs
| y == Nothing = Nothing
| True = Just $ aaaAct_permissions $ fromJust y
where
y = M.lookup x xs
-- | Authorizes (permits) a certain account to do some classes of actions.
-- Takes `Id Account`, `Permissions`, and `Accounts` and *adds* given `Permissions`
-- to the current `Permissions` map of this `Account`.
-- Gives back either updated version of `Account` along with updated `Accounts`, or `Error`.
permit :: Id Account -> Permissions -> Accounts -> E Error (Account, Accounts)
permit x ps xs = permitDo x (M.lookup x xs) ps xs
addAccountDo :: Salt -> (Id Account, Secret) -> Accounts -> (Account, Accounts)
addAccountDo z (x, y) xs =
(acc, M.insert x acc xs)
where
acc = Account { aaaAct_name = x
, aaaAct_salted = C.saltBinary (getSecret y) z
, aaaAct_permissions = M.empty }
permitDo :: Id Account -> Maybe Account -> Permissions -> Accounts -> E Error (Account, Accounts)
permitDo x (Just acc0) ps xs =
Right (acc, M.update (const $ Just acc) x xs)
where
acc = acc0 { aaaAct_permissions = M.union ps ps0 }
ps0 = aaaAct_permissions acc0
permitDo _ _ _ _ = Left $ Error ( EAccountNotFound
, "Requested account does not exist" )
-- | Check if Secret matches stored Salted hash.
secretMatches :: Salt -> Secret -> Id Account -> Accounts -> Bool
secretMatches z (Secret s) x xs
| y == Nothing = False
| True = C.saltBinary s z == g y
where
y = M.lookup x xs
g (Just a) = aaaAct_salted a
g Nothing = undefined
|
manpages/AAA
|
src/AAA/Account.hs
|
mit
| 3,248
| 0
| 12
| 1,002
| 722
| 388
| 334
| 45
| 2
|
module HChip.Debug where
import Control.Lens
import Control.Monad
import Control.Monad.Trans
import Text.Printf
import HChip.Machine
dumpState :: Emu ()
dumpState = do
forM_ [0x0..0xF] $ \r -> do
v <- load16 (Reg r)
liftIO $ printf "R%X: %d " r v
liftIO $ putStrLn ""
z <- use zero
when z $ liftIO $ putStr "ZERO "
n <- use negative
when n $ liftIO $ putStr "NEG "
c <- use carry
when c $ liftIO $ putStr "CARRY "
o <- use overflow
when o $ liftIO $ putStr "OVRF "
liftIO $ putStrLn ""
|
chpatrick/hchip
|
HChip/Debug.hs
|
mit
| 503
| 0
| 14
| 112
| 225
| 103
| 122
| 21
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html
module Stratosphere.ResourceProperties.EMRInstanceGroupConfigConfiguration where
import Stratosphere.ResourceImports
-- | Full data type definition for EMRInstanceGroupConfigConfiguration. See
-- 'emrInstanceGroupConfigConfiguration' for a more convenient constructor.
data EMRInstanceGroupConfigConfiguration =
EMRInstanceGroupConfigConfiguration
{ _eMRInstanceGroupConfigConfigurationClassification :: Maybe (Val Text)
, _eMRInstanceGroupConfigConfigurationConfigurationProperties :: Maybe Object
, _eMRInstanceGroupConfigConfigurationConfigurations :: Maybe [EMRInstanceGroupConfigConfiguration]
} deriving (Show, Eq)
instance ToJSON EMRInstanceGroupConfigConfiguration where
toJSON EMRInstanceGroupConfigConfiguration{..} =
object $
catMaybes
[ fmap (("Classification",) . toJSON) _eMRInstanceGroupConfigConfigurationClassification
, fmap (("ConfigurationProperties",) . toJSON) _eMRInstanceGroupConfigConfigurationConfigurationProperties
, fmap (("Configurations",) . toJSON) _eMRInstanceGroupConfigConfigurationConfigurations
]
-- | Constructor for 'EMRInstanceGroupConfigConfiguration' containing required
-- fields as arguments.
emrInstanceGroupConfigConfiguration
:: EMRInstanceGroupConfigConfiguration
emrInstanceGroupConfigConfiguration =
EMRInstanceGroupConfigConfiguration
{ _eMRInstanceGroupConfigConfigurationClassification = Nothing
, _eMRInstanceGroupConfigConfigurationConfigurationProperties = Nothing
, _eMRInstanceGroupConfigConfigurationConfigurations = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html#cfn-emr-cluster-configuration-classification
emrigccClassification :: Lens' EMRInstanceGroupConfigConfiguration (Maybe (Val Text))
emrigccClassification = lens _eMRInstanceGroupConfigConfigurationClassification (\s a -> s { _eMRInstanceGroupConfigConfigurationClassification = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html#cfn-emr-cluster-configuration-configurationproperties
emrigccConfigurationProperties :: Lens' EMRInstanceGroupConfigConfiguration (Maybe Object)
emrigccConfigurationProperties = lens _eMRInstanceGroupConfigConfigurationConfigurationProperties (\s a -> s { _eMRInstanceGroupConfigConfigurationConfigurationProperties = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html#cfn-emr-cluster-configuration-configurations
emrigccConfigurations :: Lens' EMRInstanceGroupConfigConfiguration (Maybe [EMRInstanceGroupConfigConfiguration])
emrigccConfigurations = lens _eMRInstanceGroupConfigConfigurationConfigurations (\s a -> s { _eMRInstanceGroupConfigConfigurationConfigurations = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/EMRInstanceGroupConfigConfiguration.hs
|
mit
| 3,038
| 0
| 12
| 249
| 337
| 194
| 143
| 32
| 1
|
module Main where
import Test.QuickCheck
import Test.QuickCheck.Function
-- Functor QuickCheck property test. Based on functor laws.
functorIdentity :: (Functor f, Eq (f a)) => f a -> Bool
functorIdentity f = fmap id f == f
functorCompose :: (Eq(f c), Functor f) => (a -> b) -> (b -> c) -> f a -> Bool
functorCompose f g x = (fmap g (fmap f x)) == (fmap (g . f) x)
-- QuickCheck will give us Fun (quickCheckSpecialFunctionWeDontNeed, generalFunction)
-- We'll take general haskell funtion and use in our prover.
functorCompose' :: (Eq(f c), Functor f) => f a -> Fun a b -> Fun b c -> Bool
functorCompose' x (Fun _ f) (Fun _ g) = (fmap g (fmap f x)) == (fmap (g . f) x)
-- To check this we run standard quickCheck scenario:
-- quickCheck (functorIdentity :: [Int] -> Bool)
-- To prove composion we need more advanced tool:
-- c = functorCompose (+1) (*2)
-- li x = c (x :: [Int])
-- quickCheck li
-- We can generate function with quickCheck this way.
-- This is the type for QuickCheck to work with:
-- type IntToInt = Fun Int Int
-- This is the type for whole proof.
-- type IntFC = [Int] -> IntToInt -> IntToInt -> Bool
-- quickCheck (functorCompose' :: IntFC)
-- There is a legend that `verboseCheck` cannot print Fun, but it could smth like this:
-- $ Passed:
-- $ [8,-44,-36,39]
-- $ <fun>
-- $ <fun>
-- Which is not so bad in my opinion.
-- Exercise: Instances of Func (IOF)
-- General setup. I will use Ints everywhere in specs.
type IntToInt = Fun Int Int
type ID a = a -> Bool -- For Identity proof.
type FC a = a -> IntToInt -> IntToInt -> Bool -- For composition proof.
-- Could be nice to generate types dynamically with this. Not sure how to do it.
-- proofIdentity :: a -> b
-- proofIdentity x = functorIdentity :: (IntID x)
-- AFAIK there is no currently any technology to apply this.
-- And the same with composition.
-- proofComposition
-- 1.
newtype Identity a = Identity a deriving(Eq, Show)
instance Functor(Identity) where
fmap f (Identity x) = Identity $ f x
instance (Arbitrary a) => Arbitrary(Identity a) where
arbitrary = do
x <- arbitrary
return $ Identity x
type IdentityBase = Identity Int -- Concrete type
runIOF1spec :: IO ()
runIOF1spec = do
quickCheck (functorIdentity :: (ID IdentityBase))
quickCheck (functorCompose' :: (FC IdentityBase))
-- 2.
data Pair a = Pair a a deriving(Eq, Show)
instance Functor(Pair) where
fmap f (Pair a b) = Pair (f a) (f b)
instance (Arbitrary a) => Arbitrary(Pair a) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Pair x y
type PairBase = Pair Int
runIOF2Spec :: IO ()
runIOF2Spec = do
quickCheck (functorIdentity :: (ID PairBase))
quickCheck (functorCompose' :: (FC PairBase))
-- 3.
data Two a b = Two a b
instance Functor(Two a) where
fmap f (Two a b) = Two a $ f b
instance (Arbitrary a, Arbitrary b) => Arbitrary(Two a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Two x y
type TwoBase = Two Int Int
runIOF3Spec :: IO ()
runIOF3Spec = do
quickCheck (functorIdentity :: (ID PairBase))
quickCheck (functorCompose' :: (FC PairBase))
-- 4.
data Three a b c = Three a b c deriving(Eq, Show)
instance Functor(Three a b) where
fmap f (Three a b c) = Three a b $ f c
instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary(Three a b c) where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
return $ Three x y z
type ThreeBase = Three Int Int Int
runIOF4Spec :: IO ()
runIOF4Spec = do
quickCheck (functorIdentity :: (ID ThreeBase))
quickCheck (functorCompose' :: (FC ThreeBase))
-- 5.
data Three' a b = Three' a b b deriving(Eq, Show)
instance Functor(Three' a) where
fmap f (Three' a b c) = Three' a (f b) (f c)
instance (Arbitrary a, Arbitrary b) => Arbitrary(Three' a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
return $ Three' x y z
type ThreeBase' = Three' Int Int
runIOF5Spec :: IO ()
runIOF5Spec = do
quickCheck (functorIdentity :: (ID ThreeBase'))
quickCheck (functorCompose' :: (FC ThreeBase'))
-- 6.
data Four a b c d = Four a b c d deriving(Eq, Show)
instance Functor(Four a b c) where
fmap f (Four a b c d) = Four a b c (f d)
instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary(Four a b c d) where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
w <- arbitrary
return $ Four x y z w
type FourBase = Four Int Int Int Int
runIOF6Spec :: IO ()
runIOF6Spec = do
quickCheck (functorIdentity :: (ID FourBase))
quickCheck (functorCompose' :: (FC FourBase))
-- 7.
data Four' a b = Four' a a a b deriving(Eq, Show)
instance Functor(Four' a) where
fmap f (Four' a b c d) = Four' a b c (f d)
instance (Arbitrary a, Arbitrary b) => Arbitrary(Four' a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
w <- arbitrary
return $ Four' x y z w
type FourBase' = Four' Int Int
runIOF7Spec :: IO ()
runIOF7Spec = do
quickCheck (functorIdentity :: (ID FourBase'))
quickCheck (functorCompose' :: (FC FourBase'))
data Possibly a =
LolNope
| Yep a
deriving (Eq, Show)
instance Functor (Possibly) where
fmap _ LolNope = LolNope
fmap f (Yep a) = Yep (f a)
instance Arbitrary a => Arbitrary (Possibly a) where
arbitrary = do
a <- arbitrary
elements [Yep a, LolNope]
runPossibleSpec :: IO ()
runPossibleSpec = do
-- Just for fun. Let's run 1000 examples instead of 100.
quickCheckWith stdArgs {maxSuccess = 1000} (functorIdentity :: (ID (Possibly Int)))
quickCheck (functorCompose' :: (FC (Possibly Int)))
data Some a b =
First a
| Second b
deriving (Show, Eq)
instance Functor (Some a) where
fmap _ (First a) = First a
fmap f (Second b) = Second (f b)
instance (Arbitrary a, Arbitrary b) => Arbitrary(Some a b) where
arbitrary = do
a <- arbitrary
b <- arbitrary
elements [First a, Second b]
runSomeSpec :: IO ()
runSomeSpec = do
quickCheckWith stdArgs {maxSuccess = 250} (functorIdentity :: (ID (Some Int Int)))
quickCheckWith stdArgs {maxSuccess = 250} (functorCompose' :: (FC (Some Int Int)))
-- -- To apply functor to the first argument we can use Flip
-- {-# LANGUAGE FlexibleInstances #-}
-- data Tuple a b = Tuple a b deriving (Eq, Show)
-- newtype Flip f a b = Flip (f b a) deriving (Eq, Show)
-- -- this works, goofy as it looks.
-- instance Functor (Flip Tuple a) where
-- fmap f (Flip (Tuple a b)) = Flip $ Tuple (f a) b
-- Prelude> fmap (+1) (Flip (Tuple 1 "blah"))
-- Flip (Tuple 2 "blah")
-- Main function. Stub, I'm not using.
main :: IO ()
main = putStrLn "Main stub as usual."
|
raventid/coursera_learning
|
haskell/chapter16/functor/app/Main.hs
|
mit
| 6,652
| 0
| 12
| 1,473
| 2,240
| 1,167
| 1,073
| 141
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE QuasiQuotes #-}
module Graphics.Urho3D.Container.Str(
UrhoString
, UrhoWString
, StringVector
, WStringVector
, stringContext
, loadUrhoString
, loadUrhoText
, loadConstUrhoString
, loadConstUrhoText
, loadConstUrhoWText
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import qualified Data.Text as T
import Graphics.Urho3D.Container.Internal.Str
import Graphics.Urho3D.Container.ForeignVector
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Monad
import Data.Monoid
import Foreign
import Foreign.C.String
C.context (C.cppCtx <> stringCntx)
C.include "<Urho3D/Container/Str.h>"
C.using "namespace Urho3D"
C.verbatim "typedef Vector<String> StringVector;"
C.verbatim "typedef Vector<WString> WStringVector;"
stringContext :: C.Context
stringContext = stringCntx
instance Creatable (Ptr UrhoString) where
type CreationOptions (Ptr UrhoString) = Either String T.Text
newObject (Left s) = liftIO $ withCString s $ \s' -> [C.exp| String* { new String($(const char* s')) } |]
newObject (Right s) = liftIO $ textAsPtrW32 s $ \s' -> [C.exp| String* { new String($(const wchar_t* s')) } |]
deleteObject ptr = liftIO $ [C.exp| void { delete $(String* ptr) } |]
instance Creatable (Ptr UrhoWString) where
type CreationOptions (Ptr UrhoWString) = T.Text
newObject s = liftIO $ textAsPtrW32 s $ \s' -> [C.exp| WString* { new WString(String($(const wchar_t* s'))) } |]
deleteObject ptr = liftIO $ [C.exp| void { delete $(WString* ptr) } |]
instance Creatable (Ptr StringVector) where
type CreationOptions (Ptr StringVector) = ()
newObject _ = liftIO [C.exp| StringVector* { new StringVector() } |]
deleteObject ptr = liftIO $ [C.exp| void {delete $(StringVector* ptr)} |]
instance ReadableVector StringVector where
type ReadVecElem StringVector = String
foreignVectorLength ptr = fromIntegral <$>
liftIO [C.exp| unsigned int {$(StringVector* ptr)->Size()} |]
foreignVectorElement ptr i = liftIO $ do
let i' = fromIntegral i
peekCString =<< [C.exp| const char* { (*$(StringVector* ptr))[$(int i')].CString() } |]
instance WriteableVector StringVector where
type WriteVecElem StringVector = String
foreignVectorAppend ptr s = liftIO $ withCString s $ \s' ->
[C.exp| void { $(StringVector* ptr)->Push(String($(const char* s'))) } |]
instance Creatable (Ptr WStringVector) where
type CreationOptions (Ptr WStringVector) = ()
newObject _ = liftIO [C.exp| WStringVector* { new WStringVector() } |]
deleteObject ptr = liftIO $ [C.exp| void {delete $(WStringVector* ptr)} |]
instance ReadableVector WStringVector where
type ReadVecElem WStringVector = T.Text
foreignVectorLength ptr = fromIntegral <$>
liftIO [C.exp| unsigned int {$(WStringVector* ptr)->Size()} |]
foreignVectorElement ptr i = liftIO $ do
let i' = fromIntegral i
loadConstUrhoWText =<< [C.exp| WString* { &(*$(WStringVector* ptr))[$(int i')] } |]
instance WriteableVector WStringVector where
type WriteVecElem WStringVector = T.Text
foreignVectorAppend ptr s = liftIO $ textAsPtrW32 s $ \s' ->
[C.exp| void { $(WStringVector* ptr)->Push(WString(String($(const wchar_t* s')))) } |]
-- | Loads given Urho3D::String into Haskell Stirng AND deletes the Urho string after creation
loadUrhoString :: (MonadMask m, MonadIO m) => Ptr UrhoString -> m String
loadUrhoString ptr = bracket (return ptr) deleteObject loadConstUrhoString
-- | Loads given Urho3D::String into Haskell Stirng WITHOUT deletion of source Urho string
loadConstUrhoString :: MonadIO m => Ptr UrhoString -> m String
loadConstUrhoString ptr = liftIO $ peekCString =<< [C.exp| const char* { $(String* ptr)->CString() } |]
-- | Loads given Urho3D::String into Haskell Text AND deletes the Urho string after creation
loadUrhoText :: (MonadMask m, MonadIO m) => Ptr UrhoString -> m T.Text
loadUrhoText ptr = bracket
(liftIO [C.exp| WString* { new WString(*$(String* ptr)) } |])
(\wstr -> deleteObject wstr >> deleteObject ptr)
loadConstUrhoWText
-- | Loads given Urho3D::String into Haskell Text WITHOUT deletion of the Urho string after creation
loadConstUrhoText :: (MonadMask m, MonadIO m) => Ptr UrhoString -> m T.Text
loadConstUrhoText ptr = bracket
(liftIO [C.exp| WString* { new WString(*$(String* ptr)) } |])
deleteObject
loadConstUrhoWText
-- | Loads given Urho3D::String into Haskell Text WITHOUT deletion of source Urho string
loadConstUrhoWText :: MonadIO m => Ptr UrhoWString -> m T.Text
loadConstUrhoWText wstr = liftIO $ textFromPtrW32 =<< [C.exp| const wchar_t* { $(WString* wstr)->CString() } |]
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Container/Str.hs
|
mit
| 4,654
| 0
| 12
| 743
| 1,046
| 578
| 468
| -1
| -1
|
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.RpcHeaderProtos.RpcKindProto (RpcKindProto(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data RpcKindProto = RPC_BUILTIN
| RPC_WRITABLE
| RPC_PROTOCOL_BUFFER
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable RpcKindProto
instance Prelude'.Bounded RpcKindProto where
minBound = RPC_BUILTIN
maxBound = RPC_PROTOCOL_BUFFER
instance P'.Default RpcKindProto where
defaultValue = RPC_BUILTIN
toMaybe'Enum :: Prelude'.Int -> P'.Maybe RpcKindProto
toMaybe'Enum 0 = Prelude'.Just RPC_BUILTIN
toMaybe'Enum 1 = Prelude'.Just RPC_WRITABLE
toMaybe'Enum 2 = Prelude'.Just RPC_PROTOCOL_BUFFER
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum RpcKindProto where
fromEnum RPC_BUILTIN = 0
fromEnum RPC_WRITABLE = 1
fromEnum RPC_PROTOCOL_BUFFER = 2
toEnum
= P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Hadoop.Protos.RpcHeaderProtos.RpcKindProto") .
toMaybe'Enum
succ RPC_BUILTIN = RPC_WRITABLE
succ RPC_WRITABLE = RPC_PROTOCOL_BUFFER
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Hadoop.Protos.RpcHeaderProtos.RpcKindProto"
pred RPC_WRITABLE = RPC_BUILTIN
pred RPC_PROTOCOL_BUFFER = RPC_WRITABLE
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Hadoop.Protos.RpcHeaderProtos.RpcKindProto"
instance P'.Wire RpcKindProto where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB RpcKindProto
instance P'.MessageAPI msg' (msg' -> RpcKindProto) RpcKindProto where
getVal m' f' = f' m'
instance P'.ReflectEnum RpcKindProto where
reflectEnum
= [(0, "RPC_BUILTIN", RPC_BUILTIN), (1, "RPC_WRITABLE", RPC_WRITABLE), (2, "RPC_PROTOCOL_BUFFER", RPC_PROTOCOL_BUFFER)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".hadoop.common.RpcKindProto") ["Hadoop", "Protos"] ["RpcHeaderProtos"] "RpcKindProto")
["Hadoop", "Protos", "RpcHeaderProtos", "RpcKindProto.hs"]
[(0, "RPC_BUILTIN"), (1, "RPC_WRITABLE"), (2, "RPC_PROTOCOL_BUFFER")]
instance P'.TextType RpcKindProto where
tellT = P'.tellShow
getT = P'.getRead
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/RpcHeaderProtos/RpcKindProto.hs
|
mit
| 2,780
| 0
| 11
| 424
| 662
| 361
| 301
| 56
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Phb.Db.Internal where
import BasePrelude hiding (delete, insert)
import Prelude ()
import Control.Lens hiding (Action)
import Control.Monad.Cont (MonadIO)
import Control.Monad.Reader (ReaderT)
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (Day, UTCTime (..))
import Database.Persist
import Database.Persist.Postgresql hiding (getJust)
import Database.Persist.TH
import Phb.Db.Enums
share
[mkPersist sqlSettings { mpsGenerateLenses = True }
, mkMigrate "migrateAll"
] [persistLowerCase|
Person
name Text
email Text
department Text
receivesHeartbeat Bool
logsTime Bool
UniquePersonName name
deriving Show
Customer
name Text
UniqueCustomerName name
deriving Show
Action
name Text
due Day
deriving Show
ActionCustomer
action ActionId
customer CustomerId
UniqueActionCustomer action customer
deriving Show
ActionNote
action ActionId
note Text
start UTCTime
finish UTCTime Maybe
deriving Show
ActionStatus
action ActionId
status Text
completed Bool
start UTCTime
finish UTCTime Maybe
deriving Show
ActionPerson
action ActionId
person PersonId
UniqueActionPerson action person
deriving Show
Backlog
name Text
priority Int
deriving Show
BacklogCustomer
backlog BacklogId
customer CustomerId
UniqueBacklogCustomer backlog customer
deriving Show
BacklogStatus
backlog BacklogId
start UTCTime
finish UTCTime Maybe
status BacklogStatusEnum
deriving Show
deriving Eq
BacklogNote
backlog BacklogId
note Text
start UTCTime
finish UTCTime Maybe
deriving Show
deriving Eq
BacklogPerson
backlog BacklogId
person PersonId
UniqueBacklogPerson backlog person
deriving Show
Event
name Text
desc Text
impact Text
start UTCTime
finish UTCTime Maybe
deriving Show
EventCustomer
event EventId
customer CustomerId
UniqueEventCustomer event customer
deriving Show
EventNote
event EventId
note Text
start UTCTime
finish UTCTime Maybe
deriving Show
deriving Eq
EventStatus
event EventId
start UTCTime
finish UTCTime Maybe
status EventStatusEnum
deriving Show
deriving Eq
Heartbeat
start Day
finish Day
upcomingEvents Text
highlights Text
deriving Show
HeartbeatAction
heartbeat HeartbeatId
action ActionId
UniqueHeartbeatAction heartbeat action
deriving Show
HeartbeatBacklog
heartbeat HeartbeatId
backlog BacklogId
UniqueHeartbeatBacklog heartbeat backlog
deriving Show
HeartbeatEvent
heartbeat HeartbeatId
event EventId
UniqueHeartbeatEvent heartbeat event
deriving Show
HeartbeatProject
heartbeat HeartbeatId
project ProjectId
UniqueHeartbeatProject heartbeat project
deriving Show
Project
name Text
priority Int
started Day
finished Day Maybe
deriving Show
ProjectCustomer
project ProjectId
customer CustomerId
UniqueProjectCustomer project customer
deriving Show
ProjectStatus
project ProjectId
start UTCTime
finish UTCTime Maybe
phase Text
colour StatusColourEnum
desc Text Maybe
deriving Show
deriving Eq
ProjectNote
project ProjectId
note Text
start UTCTime
finish UTCTime Maybe
deriving Show
deriving Eq
ProjectPerson
project ProjectId
person PersonId
UniqueProjectPerson project person
deriving Show
ProjectTargetDate
project ProjectId
desc Text
day Day
handwavy Text Maybe
deriving Show
PublicHoliday
day Day
name Text
Success
heartbeat HeartbeatId
what Text
achievements Text
deriving Show
SuccessPerson
success SuccessId
person PersonId
UniqueSuccessPerson success person
deriving Show
Task
person PersonId
name Text
start Day
finish Day Maybe
project ProjectId Maybe
event EventId Maybe
backlog BacklogId Maybe
action ActionId Maybe
category WorkCategoryId Maybe
TimeLog
person PersonId
desc Text
minutes Int
day Day
task TaskId
deriving Show
WorkCategory
name Text
UniqueWorkCategoryName name
deriving Show
PersonLogin
person PersonId
login Text
activatedAt UTCTime Maybe default=now()
suspendedAt UTCTime Maybe default=now()
rememberToken Text Maybe
loginCount Int default=0
failedLoginCount Int default=0
lockedOutUntil UTCTime Maybe default=now()
currentLoginAt UTCTime Maybe default=now()
lastLoginAt UTCTime Maybe default=now()
currentIp Text Maybe
lastIp Text Maybe
createdAt UTCTime default=now()
updatedAt UTCTime default=now()
resetToken Text Maybe
resetRequestedAt UTCTime Maybe
roles String default=''
meta String default=''
|]
type Db m a = (MonadIO m) => SqlPersistT m a
eVal :: Getter (Entity v) v
eVal = to entityVal
eKey :: Getter (Entity v) (Key v)
eKey = to entityKey
getEntity
:: (PersistStore (PersistEntityBackend a), PersistEntity a, MonadIO m, Functor m)
=> Key a
-> ReaderT (PersistEntityBackend a) m (Maybe (Entity a))
getEntity k = fmap (Entity k) <$> get k
getEntityJust
:: (PersistStore (PersistEntityBackend a), PersistEntity a, MonadIO m, Functor m)
=> Key a
-> ReaderT (PersistEntityBackend a) m (Entity a)
getEntityJust k = (Entity k) <$> getJust k
selectLatestNote
:: (PersistQuery (PersistEntityBackend v), PersistEntity v, PersistField k, MonadIO m)
=> EntityField v k
-> EntityField v UTCTime
-> Getting Text v Text
-> k
-> Day
-> ReaderT (PersistEntityBackend v) m [Text]
selectLatestNote nk dk nl k d = do
n <- selectFirst [nk ==. k,dk >=. UTCTime d 0] [Desc dk]
return . unNote . fmap (view nl . entityVal) $ n
unNote :: Maybe Text -> [Text]
unNote = maybe [] T.lines
updateSatellite
:: ( PersistQuery (PersistEntityBackend s)
, PersistEntity s
, PersistField a
, PersistField fk
, MonadIO m
, Applicative m
, Ord a
)
=> fk
-> [a]
-> EntityField s fk
-> EntityField s id
-> EntityField s a
-> Getter s a
-> (fk -> a -> s)
-> ReaderT (PersistEntityBackend s) m ()
updateSatellite fk ri fkCol idCol refCol refLens con = do
ecs <- selectList [fkCol ==. fk] [Asc idCol]
let (toRem,toAdd) = diff (fmap (^. eVal . refLens) ecs) ri
deleteWhere [fkCol ==. fk,refCol <-. toList toRem]
insertMany_ . fmap (con fk) . toList $ toAdd
diff :: Ord a => [a] -> [a] -> (S.Set a, S.Set a)
diff oldList newList = (toRem,toAdd)
where
old = S.fromList oldList
new = S.fromList newList
toRem = S.difference old new
toAdd = S.difference new old
paginate :: Int64 -> Int64 -> (Int64,Int64)
paginate p pw = (pw,(p-1)*pw)
paginateOpts :: (Int64,Int64) -> [SelectOpt record]
paginateOpts (l,o) = [LimitTo $ fromIntegral l,OffsetBy $ fromIntegral o]
|
benkolera/phb
|
hs/Phb/Db/Internal.hs
|
mit
| 7,603
| 0
| 15
| 1,981
| 1,097
| 582
| 515
| 89
| 1
|
module TestImport
( module TestImport
, module X
) where
import Application (makeFoundation, makeLogWare)
#if MIN_VERSION_classy_prelude(1, 0, 0)
import ClassyPrelude as X hiding (Handler)
#else
import ClassyPrelude as X
#endif
import Foundation as X
import Test.Hspec as X
import Yesod.Default.Config2 (useEnv, loadYamlSettings)
import Yesod.Test as X
withApp :: SpecWith (TestApp App) -> Spec
withApp = before $ do
settings <- loadYamlSettings
["config/test-settings.yml", "config/settings.yml"]
[]
useEnv
foundation <- makeFoundation settings
logWare <- liftIO $ makeLogWare foundation
return (foundation, logWare)
|
random-j-farmer/hs-little-helper
|
test/TestImport.hs
|
mit
| 731
| 0
| 10
| 191
| 157
| 92
| 65
| 18
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Golden test management, interactive mode. Runs the tests, and asks
-- the user how to proceed in case of failure or missing golden standard.
module Test.Tasty.Silver.Interactive
(
-- * Command line helpers
defaultMain
, defaultMain1
-- * The ingredient
, interactiveTests
, Interactive (..)
-- * Programmatic API
, runTestsInteractive
, DisabledTests
)
where
import Prelude
import Control.Concurrent.STM.TVar
import Control.Exception
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.STM
import Control.Monad.State
import Data.Char
import Data.Maybe
import Data.Monoid ( Any(..) )
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid ( Monoid(..) )
#endif
import Data.Proxy
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup ( Semigroup(..) )
#endif
import Data.Tagged
import Data.Text ( Text )
import Data.Text.Encoding
import Data.Typeable
import qualified Data.ByteString as BS
import qualified Data.IntMap as IntMap
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Options.Applicative hiding (Failure, Success)
import System.Console.ANSI
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import System.IO.Silently (silence)
import System.IO.Temp
import System.Process
import System.Process.ByteString as PS
import qualified System.Process.Text as ProcessText
import Text.Printf
import Test.Tasty hiding (defaultMain)
import Test.Tasty.Options
import Test.Tasty.Providers
import Test.Tasty.Runners
import Test.Tasty.Silver.Filter
import Test.Tasty.Silver.Interactive.Run
import Test.Tasty.Silver.Internal
type DisabledTests = TestPath -> Bool
-- | Like @defaultMain@ from the main tasty package, but also includes the
-- golden test management capabilities.
defaultMain :: TestTree -> IO ()
defaultMain = defaultMain1 []
defaultMain1 :: [RegexFilter] -> TestTree -> IO ()
defaultMain1 filters =
defaultMainWithIngredients
[ listingTests
, interactiveTests (checkRF False filters)
]
-- | Option for interactive mode.
newtype Interactive = Interactive Bool
deriving (Eq, Ord, Typeable)
instance IsOption Interactive where
defaultValue = Interactive False
parseValue = fmap Interactive . safeRead
optionName = return "interactive"
optionHelp = return "Run tests in interactive mode."
optionCLParser = flagCLParser (Just 'i') (Interactive True)
data ResultType = RTSuccess | RTFail | RTIgnore
deriving (Eq)
data FancyTestException
= Mismatch GoldenResultI
| Disabled
deriving (Show, Typeable)
instance Exception FancyTestException
getResultType :: Result -> ResultType
getResultType (Result { resultOutcome = Success}) = RTSuccess
getResultType (Result { resultOutcome = (Failure (TestThrewException e))}) =
case fromException e of
Just Disabled -> RTIgnore
_ -> RTFail
getResultType (Result { resultOutcome = (Failure _)}) = RTFail
interactiveTests :: DisabledTests
-> Ingredient
interactiveTests dis = TestManager
[ Option (Proxy :: Proxy Interactive)
, Option (Proxy :: Proxy HideSuccesses)
, Option (Proxy :: Proxy AnsiTricks)
, Option (Proxy :: Proxy UseColor)
, Option (Proxy :: Proxy NumThreads)
, Option (Proxy :: Proxy ExcludeFilters)
, Option (Proxy :: Proxy IncludeFilters)
, Option (Proxy :: Proxy AcceptTests)
] $
\opts tree ->
Just $ runTestsInteractive dis opts (filterWithRegex opts tree)
runSingleTest :: IsTest t => DisabledTests -> TestPath -> TestName -> OptionSet -> t -> (Progress -> IO ()) -> IO Result
runSingleTest dis tp _ _ _ _ | dis tp =
return $ (testFailed "")
{ resultOutcome = (Failure $ TestThrewException $ toException Disabled) }
runSingleTest _ _ _ opts t cb = do
case (cast t :: Maybe Golden) of
Nothing -> run opts t cb
Just g -> do
(r, gr) <- runGolden g
-- we may be in a different thread here than the main ui.
-- force evaluation of actual value here, as we have to evaluate it before
-- leaving this test.
gr' <- forceGoldenResult gr
case gr' of
GREqual -> return r
grd -> return $ r { resultOutcome = (Failure $ TestThrewException $ toException $ Mismatch grd) }
-- | A simple console UI.
runTestsInteractive :: DisabledTests -> OptionSet -> TestTree -> IO Bool
runTestsInteractive dis opts tests = do
let tests' = wrapRunTest (runSingleTest dis) tests
launchTestTree opts tests' $ \smap -> do
isTerm <- hSupportsANSI stdout
(\k -> if isTerm
then (do hideCursor; k) `finally` showCursor
else k) $ do
hSetBuffering stdout NoBuffering
let
whenColor = lookupOption opts
HideSuccesses hideSuccesses = lookupOption opts
AnsiTricks ansiTricks = lookupOption opts
let
?colors = useColor whenColor isTerm
let
outp = produceOutput opts tests
stats <- case () of { _
| hideSuccesses && isTerm && ansiTricks ->
consoleOutputHidingSuccesses outp smap
| hideSuccesses && not isTerm ->
streamOutputHidingSuccesses outp smap
| otherwise -> consoleOutput outp smap
}
return $ \time -> do
printStatistics stats time
return $ statFailures stats == 0
-- | Show diff using available external tools.
printDiff :: TestName -> GDiff -> IO ()
printDiff = showDiff_ False
-- | Like 'printDiff', but uses @less@ if available.
showDiff :: TestName -> GDiff -> IO ()
showDiff n d = do
useLess <- useLess
showDiff_ useLess n d
showDiff_ :: Bool -> TestName -> GDiff -> IO ()
showDiff_ _ _ Equal = error "Can't show diff for equal values."
showDiff_ True n (ShowDiffed _ t) = showInLess n t
showDiff_ False _ (ShowDiffed _ t) = TIO.putStrLn t
showDiff_ useLess n (DiffText _ tGold tAct) =
ifM (doesCmdExist "wdiff" `and2M` haveColorDiff) colorDiff $ {-else-}
ifM (doesCmdExist "git") gitDiff {-else-} noDiff
where
-- Display diff using `git diff`.
gitDiff = do
withDiffEnv n tGold tAct $ \ fGold fAct -> do
-- Unless we use `less`, we simply call `git` directly.
if not useLess
then do
(out, err) <- callGitDiff [ fGold, fAct ]
TIO.putStrLn err
TIO.putStrLn out
else callCommand $ unwords
[ "git"
, unwords gitDiffArgs
, "--color=always"
, toSlashesFilename fGold
, toSlashesFilename fAct
, "| less -r > /dev/tty"
-- Option -r: display control characters raw (e.g. sound bell instead of printing ^G).
-- Thus, ANSI escape sequences will be interpreted as that.
-- /dev/tty is "terminal where process started" ("CON" on Windows?)
]
-- Display diff using `wdiff | colordiff`.
colorDiff = do
withDiffEnv n tGold tAct $ \ fGold fAct -> do
let cmd = unwords
[ "wdiff"
, toSlashesFilename fGold
, toSlashesFilename fAct
, "| colordiff"
-- E.g.
, if useLess then "| less -r > /dev/tty" else ""
-- Option -r: display control characters raw (e.g. sound bell instead of printing ^G).
-- Thus, ANSI escape sequences will be interpreted, e.g. as coloring.
-- /dev/tty is "terminal where process started" ("CON" on Windows?)
]
ifM (doesCmdExist "colordiff")
-- If `colordiff` is treated as executable binary, we do not indirect via `sh`,
-- but can let the default shell do the piping for us.
{-then-} (callCommand cmd)
-- Otherwise, let `sh` do the piping for us. (Needed e.g. for Cygwin.)
{-else-} (callProcess "sh" [ "-c", cmd ])
-- Alt:
-- -- We have to pipe ourselves; don't use `less` then.
-- callProcessText "wdiff" [fGold, fAct] T.empty >>=
-- void . callProcessText "colordiff" []
-- -- TODO: invoke "colordiff" through callCommand
-- Newline if we didn't go through less
unless useLess $ putStrLn ""
-- No diff tool: Simply print both golden and actual value.
noDiff = do
putStrLn "`git diff` not available, cannot produce a diff."
putStrLn "Golden value:"
TIO.putStrLn tGold
putStrLn "Actual value:"
TIO.putStrLn tAct
-- | Call external tool @"git" 'gitDiffArgs'@ with given extra arguments, returning its output.
-- If @git diff@ prints to @stderr@ or returns a exitcode indicating failure, throw exception.
callGitDiff
:: [String]
-- ^ File arguments to @git diff@.
-> IO (Text, Text)
-- ^ @stdout@ and @stderr@ produced by the call.
callGitDiff args = do
ret@(exitcode, stdOut, stdErr) <-
ProcessText.readProcessWithExitCode
"git" (gitDiffArgs ++ args) T.empty
let done = return (stdOut, stdErr)
case exitcode of
ExitSuccess -> done
-- With option --no-index, exitcode 1 indicates that files are different.
ExitFailure 1 -> done
-- Other failure codes indicate that something went wrong.
ExitFailure _ -> gitFailed $ show ret
where
gitFailed msg = fail $ "Call to `git diff` failed: " ++ msg
gitDiffArgs :: [String]
gitDiffArgs = [ "diff", "--no-index", "--text" ]
-- #16: filenames get mangled under Windows, backslashes disappearing.
-- We only use this function on names of tempfiles, which do not contain spaces,
-- so it should be enough to hackily replace backslashes by slashes.
-- | Turn backslashes to slashes, which can also be path separators on Windows.
toSlashesFilename :: String -> String
toSlashesFilename = map $ \ c -> case c of
'\\' -> '/'
c -> c
-- | Look for a command on the PATH. If @doesCmdExist cmd@, then
-- @callProcess cmd@ should be possible.
--
-- Note that there are OS-specific differences.
-- E.g. on @cygwin@, only binaries (@.exe@) are deemed to exist,
-- not scripts. The latter also cannot be called directly with
-- @callProcess@, but need indirection via @sh -c@.
-- In particular, @colordiff@, which is a @perl@ script, is not
-- found by @doesCmdExist@ on @cygwin@.
--
-- On @macOS@, there isn't such a distinction, so @colordiff@
-- is both found by @doesCmdExist@ and can be run by @callProcess@.
doesCmdExist :: String -> IO Bool
doesCmdExist cmd = isJust <$> findExecutable cmd
-- | Since @colordiff@ is a script, it may not be found by 'findExecutable'
-- e.g. on Cygwin. So we try also to find it using @which@.
haveColorDiff :: IO Bool
haveColorDiff = orM
[ doesCmdExist "colordiff"
, andM
[ haveSh
, silence $ exitCodeToBool <$> rawSystem "which" [ "colordiff" ]
]
]
exitCodeToBool :: ExitCode -> Bool
exitCodeToBool ExitSuccess = True
exitCodeToBool ExitFailure{} = False
-- Stores the golden/actual text in two files, so we can use it for git diff.
withDiffEnv :: TestName -> T.Text -> T.Text -> (FilePath -> FilePath -> IO ()) -> IO ()
withDiffEnv n tGold tAct cont = do
withSystemTempFile (n <.> "golden") $ \ fGold hGold -> do
withSystemTempFile (n <.> "actual") $ \ fAct hAct -> do
hSetBinaryMode hGold True
hSetBinaryMode hAct True
BS.hPut hGold (encodeUtf8 tGold)
BS.hPut hAct (encodeUtf8 tAct)
hClose hGold
hClose hAct
cont fGold fAct
printValue :: TestName -> GShow -> IO ()
printValue _ (ShowText t) = TIO.putStrLn t
showValue :: TestName -> GShow -> IO ()
showValue n (ShowText t) = showInLess n t
showInLess :: String -> T.Text -> IO ()
showInLess _ t = do
ifNotM useLess
{-then-} (TIO.putStrLn t)
{-else-} $ do
ret <- PS.readCreateProcessWithExitCode (shell "less > /dev/tty") $ encodeUtf8 t
case ret of
ret@(ExitFailure _, _, _) -> error $ show ret
_ -> return ()
-- | Should we use external tool @less@ to display diffs and results?
useLess :: IO Bool
useLess = andM [ hIsTerminalDevice stdin, hSupportsANSI stdout, doesCmdExist "less" ]
-- | Is @sh@ available to take care of piping for us?
haveSh :: IO Bool
haveSh = doesCmdExist "sh"
-- | Ask user whether to accept a new golden value, and run action if yes.
tryAccept
:: String -- ^ @prefix@ printed at the beginning of each line.
-> IO () -- ^ Action to @update@ golden value.
-> IO Bool -- ^ Return decision whether to update the golden value.
tryAccept prefix update = do
-- Andreas, 2021-09-18
-- Accepting by default in batch mode is not the right thing,
-- because CI may then falsely accept broken tests.
--
-- -- If terminal is non-interactive, just assume "yes" always.
-- termIsInteractive <- hIsTerminalDevice stdin
-- if not termIsInteractive then do
-- putStr prefix
-- putStr "Accepting actual value as new golden value."
-- update
-- return True
-- else do
isANSI <- hSupportsANSI stdout
when isANSI showCursor
putStr prefix
putStr "Accept actual value as new golden value? [yn] "
let
done b = do
when isANSI hideCursor
putStr prefix
return b
loop = do
ans <- getLine
case ans of
"y" -> do update; done True
"n" -> done False
_ -> do
putStr prefix
putStrLn "Invalid answer."
loop
loop
--------------------------------------------------
-- TestOutput base definitions
--------------------------------------------------
-- {{{
-- | 'TestOutput' is an intermediary between output formatting and output
-- printing. It lets us have several different printing modes (normal; print
-- failures only; quiet).
data TestOutput
= HandleTest
{- test name, used for golden lookup #-} (TestName)
{- print test name -} (IO ())
{- print test result -} (Result -> IO Statistics)
| PrintHeading (IO ()) TestOutput
| Skip
| Seq TestOutput TestOutput
instance Semigroup TestOutput where
(<>) = Seq
-- The monoid laws should hold observationally w.r.t. the semantics defined
-- in this module
instance Monoid TestOutput where
mempty = Skip
mappend = (<>)
type Level = Int
produceOutput :: (?colors :: Bool) => OptionSet -> TestTree -> TestOutput
produceOutput opts tree =
let
-- Do not retain the reference to the tree more than necessary
!alignment = computeAlignment opts tree
Interactive isInteractive = lookupOption opts
handleSingleTest
:: (IsTest t, ?colors :: Bool)
=> OptionSet -> TestName -> t -> Ap (Reader Level) TestOutput
handleSingleTest _opts name _test = Ap $ do
level <- ask
let
align = replicate (alignment - indentSize * level - length name) ' '
pref = indent level ++ replicate (length name) ' ' ++ " " ++ align
printTestName =
printf "%s%s: %s" (indent level) name align
printResultLine result forceTime = do
-- use an appropriate printing function
let
resTy = getResultType result
printFn = case resTy of
RTSuccess -> ok
RTIgnore -> warn
RTFail -> failure
case resTy of
RTSuccess -> printFn "OK"
RTIgnore -> printFn "DISABLED"
RTFail -> printFn "FAIL"
-- print time only if it's significant
when (resultTime result >= 0.01 || forceTime) $
printFn (printf " (%.2fs)" $ resultTime result)
printFn "\n"
handleTestResult result = do
-- non-interactive mode. Uses different order of printing,
-- as using the interactive layout doesn't go that well
-- with printing the diffs to stdout.
--
printResultLine result True
rDesc <- formatMessage $ resultDescription result
when (not $ null rDesc) $ (case getResultType result of
RTSuccess -> infoOk
RTIgnore -> infoWarn
RTFail -> infoFail) $
printf "%s%s\n" pref (formatDesc (level+1) rDesc)
stat' <- printTestOutput pref name result
return stat'
handleTestResultInteractive result = do
(result', stat') <- case (resultOutcome result) of
Failure (TestThrewException e) ->
case fromException e of
Just (Mismatch (GRDifferent _ _ _ Nothing)) -> do
printResultLine result False
s <- printTestOutput pref name result
return (testFailed "", s)
Just (Mismatch (GRNoGolden a shw (Just upd))) -> do
printf "Golden value missing. Press <enter> to show actual value.\n"
_ <- getLine
let a' = runIdentity a
shw' <- shw a'
showValue name shw'
isUpd <- tryAccept pref $ upd a'
let r =
if isUpd
then ( testPassed "Created golden value."
, mempty { statCreatedGolden = 1 } )
else ( testFailed "Golden value missing."
, mempty { statFailures = 1 } )
printResultLine (fst r) False
return r
Just (Mismatch (GRDifferent _ a diff (Just upd))) -> do
printf "Golden value differs from actual value.\n"
showDiff name diff
isUpd <- tryAccept pref $ upd a
let r =
if isUpd
then ( testPassed "Updated golden value."
, mempty { statUpdatedGolden = 1 } )
else ( testFailed "Golden value does not match actual output."
, mempty { statFailures = 1 } )
printResultLine (fst r) False
return r
Just (Mismatch _) -> error "Impossible case!"
Just Disabled -> do
printResultLine result False
return ( result
, mempty { statDisabled = 1 } )
Nothing -> do
printResultLine result False
return (result, mempty {statFailures = 1})
Success -> do
printResultLine result False
return (result, mempty { statSuccesses = 1 })
Failure _ -> do
printResultLine result False
return (result, mempty { statFailures = 1 })
let result'' = result' { resultTime = resultTime result }
rDesc <- formatMessage $ resultDescription result''
when (not $ null rDesc) $ (case getResultType result'' of
RTSuccess -> infoOk
RTIgnore -> infoWarn
RTFail -> infoFail) $
printf "%s%s\n" pref (formatDesc (level+1) rDesc)
return stat'
let handleTestResult' = (if isInteractive then handleTestResultInteractive else handleTestResult)
return $ HandleTest name printTestName handleTestResult'
handleGroup :: OptionSet -> TestName -> Ap (Reader Level) TestOutput -> Ap (Reader Level) TestOutput
handleGroup _ name grp = Ap $ do
level <- ask
let
printHeading = printf "%s%s\n" (indent level) name
printBody = runReader (getApp grp) (level + 1)
return $ PrintHeading printHeading printBody
in
flip runReader 0 $ getApp $
foldTestTree
trivialFold
{ foldSingle = handleSingleTest
, foldGroup = handleGroup
}
opts tree
printTestOutput :: (?colors :: Bool) => String -> TestName -> Result -> IO Statistics
printTestOutput prefix name result = case resultOutcome result of
Failure (TestThrewException e) ->
case fromException e of
Just (Mismatch (GRNoGolden a shw _)) -> do
infoFail $ printf "%sActual value is:\n" prefix
let a' = runIdentity a
shw' <- shw a'
hsep
printValue name shw'
hsep
return ( mempty { statFailures = 1 } )
Just (Mismatch (GRDifferent _ _ diff _)) -> do
infoFail $ printf "%sDiff between actual and golden value:\n" prefix
hsep
printDiff name diff
hsep
return ( mempty { statFailures = 1 } )
Just (Mismatch _) -> error "Impossible case!"
Just Disabled -> return ( mempty { statDisabled = 1 } )
Nothing -> return ( mempty { statFailures = 1 } )
Failure _ -> return ( mempty { statFailures = 1 } )
Success -> return ( mempty { statSuccesses = 1 } )
hsep :: IO ()
hsep = putStrLn (replicate 40 '=')
foldTestOutput
:: (?colors :: Bool, Monoid b)
=> (IO () -> IO Result
-> (Result -> IO Statistics)
-> b)
-> (IO () -> b -> b)
-> TestOutput -> StatusMap -> b
foldTestOutput foldTest foldHeading outputTree smap =
flip evalState 0 $ getApp $ go outputTree where
go (HandleTest _ printName handleResult) = Ap $ do
ix <- get
put $! ix + 1
let
statusVar =
fromMaybe (error "internal error: index out of bounds") $
IntMap.lookup ix smap
readStatusVar = getResultFromTVar statusVar
return $ foldTest printName readStatusVar handleResult
go (PrintHeading printName printBody) = Ap $
foldHeading printName <$> getApp (go printBody)
go (Seq a b) = mappend (go a) (go b)
go Skip = mempty
-- }}}
--------------------------------------------------
-- TestOutput modes
--------------------------------------------------
-- {{{
consoleOutput :: (?colors :: Bool) => TestOutput -> StatusMap -> IO Statistics
consoleOutput outp smap =
getApp . fst $ foldTestOutput foldTest foldHeading outp smap
where
foldTest printName getResult handleResult =
(Ap $ do
_ <- printName
r <- getResult
handleResult r
, Any True)
foldHeading printHeading (printBody, Any nonempty) =
(Ap $ do
when nonempty $ printHeading
stats <- getApp printBody
return stats
, Any nonempty )
consoleOutputHidingSuccesses :: (?colors :: Bool) => TestOutput -> StatusMap -> IO Statistics
consoleOutputHidingSuccesses outp smap =
snd <$> (getApp $ foldTestOutput foldTest foldHeading outp smap)
where
foldTest printName getResult handleResult =
Ap $ do
_ <- printName
r <- getResult
if resultSuccessful r
then do
clearThisLine
return (Any False, mempty { statSuccesses = 1 })
else do
stats <- handleResult r
return (Any True, stats)
foldHeading printHeading printBody =
Ap $ do
_ <- printHeading
b@(Any failed, _) <- getApp printBody
unless failed clearAboveLine
return b
clearAboveLine = do cursorUpLine 1; clearThisLine
clearThisLine = do clearLine; setCursorColumn 0
streamOutputHidingSuccesses :: (?colors :: Bool) => TestOutput -> StatusMap -> IO Statistics
streamOutputHidingSuccesses outp smap =
snd <$> (flip evalStateT [] . getApp $
foldTestOutput foldTest foldHeading outp smap)
where
foldTest printName getResult handleResult =
Ap $ do
r <- liftIO $ getResult
if resultSuccessful r
then return (Any False, mempty { statSuccesses = 1 })
else do
stack <- get
put []
stats <- liftIO $ do
sequence_ $ reverse stack
_ <- printName
handleResult r
return (Any True, stats)
foldHeading printHeading printBody =
Ap $ do
modify (printHeading :)
b@(Any failed, _) <- getApp printBody
unless failed $
modify $ \stack ->
case stack of
_:rest -> rest
[] -> [] -- shouldn't happen anyway
return b
-- }}}
--------------------------------------------------
-- Statistics
--------------------------------------------------
-- {{{
data Statistics = Statistics
{ statSuccesses :: !Int
, statUpdatedGolden :: !Int
, statCreatedGolden :: !Int
, statFailures :: !Int
, statDisabled :: !Int
}
instance Semigroup Statistics where
Statistics a1 b1 c1 d1 e1 <> Statistics a2 b2 c2 d2 e2 = Statistics (a1 + a2) (b1 + b2) (c1 + c2) (d1 + d2) (e1 + e2)
instance Monoid Statistics where
mempty = Statistics 0 0 0 0 0
mappend = (<>)
printStatistics :: (?colors :: Bool) => Statistics -> Time -> IO ()
printStatistics st time = do
printf "\n"
let total = statFailures st + statUpdatedGolden st + statCreatedGolden st + statSuccesses st
when (statCreatedGolden st > 0) (printf "Created %d golden values.\n" (statCreatedGolden st))
when (statUpdatedGolden st > 0) (printf "Updated %d golden values.\n" (statUpdatedGolden st))
when (statDisabled st > 0) (printf "Ignored %d disabled tests.\n" (statDisabled st))
case statFailures st of
0 -> do
ok $ printf "All %d tests passed (%.2fs)\n" total time
fs -> do
failure $ printf "%d out of %d tests failed (%.2fs)\n" fs total time
data FailureStatus
= Unknown
| Failed
| OK
instance Semigroup FailureStatus where
Failed <> _ = Failed
_ <> Failed = Failed
OK <> OK = OK
_ <> _ = Unknown
instance Monoid FailureStatus where
mempty = OK
mappend = (<>)
-- }}}
--------------------------------------------------
-- Console test reporter
--------------------------------------------------
-- | Report only failed tests
newtype HideSuccesses = HideSuccesses Bool
deriving (Eq, Ord, Typeable)
instance IsOption HideSuccesses where
defaultValue = HideSuccesses False
parseValue = fmap HideSuccesses . safeRead
optionName = return "hide-successes"
optionHelp = return "Do not print tests that passed successfully"
optionCLParser = flagCLParser Nothing (HideSuccesses True)
newtype AnsiTricks = AnsiTricks Bool
deriving Typeable
instance IsOption AnsiTricks where
defaultValue = AnsiTricks True
parseValue = fmap AnsiTricks . safeReadBool
optionName = return "ansi-tricks"
optionHelp = return $
-- Multiline literals don't work because of -XCPP.
"Enable various ANSI terminal tricks. " ++
"Can be set to 'true' (default) or 'false'."
-- | When to use color on the output
data UseColor
= Never | Always | Auto
deriving (Eq, Ord, Typeable)
-- | Control color output
instance IsOption UseColor where
defaultValue = Auto
parseValue = parseUseColor
optionName = return "color"
optionHelp = return "When to use colored output. Options are 'never', 'always' and 'auto' (default: 'auto')"
optionCLParser =
option parse
( long name
<> help (untag (optionHelp :: Tagged UseColor String))
)
where
name = untag (optionName :: Tagged UseColor String)
parse = str >>=
maybe (readerError $ "Could not parse " ++ name) pure <$> parseValue
-- | @useColor when isTerm@ decides if colors should be used,
-- where @isTerm@ denotes where @stdout@ is a terminal device.
useColor :: UseColor -> Bool -> Bool
useColor cond isTerm =
case cond of
Never -> False
Always -> True
Auto -> isTerm
parseUseColor :: String -> Maybe UseColor
parseUseColor s =
case map toLower s of
"never" -> return Never
"always" -> return Always
"auto" -> return Auto
_ -> Nothing
-- }}}
--------------------------------------------------
-- Various utilities
--------------------------------------------------
-- {{{
{-getResultWithGolden :: StatusMap -> GoldenStatusMap -> TestName -> Int -> IO (Result, ResultStatus)
getResultWithGolden smap gmap nm ix = do
r <- getResultFromTVar statusVar
gr <- atomically $ readTVar gmap
case nm `M.lookup` gr of
Just g@(GRDifferent {}) -> return (r, RMismatch g)
Just g@(GRNoGolden {}) -> return (r, RMismatch g)
_ | resultSuccessful r -> return (r, RPass)
_ | resultOutcome r
_ | otherwise -> return (r, RFail)
where statusVar =
fromMaybe (error "internal error: index out of bounds") $
IntMap.lookup ix smap
-}
getResultFromTVar :: TVar Status -> IO Result
getResultFromTVar statusVar = do
atomically $ do
status <- readTVar statusVar
case status of
Done r -> return r
_ -> retry
-- }}}
--------------------------------------------------
-- Formatting
--------------------------------------------------
-- {{{
indentSize :: Int
indentSize = 2
indent :: Int -> String
indent n = replicate (indentSize * n) ' '
-- handle multi-line result descriptions properly
formatDesc
:: Int -- indent
-> String
-> String
formatDesc n desc =
let
-- remove all trailing linebreaks
chomped = reverse . dropWhile (== '\n') . reverse $ desc
multiline = '\n' `elem` chomped
-- we add a leading linebreak to the description, to start it on a new
-- line and add an indentation
paddedDesc = flip concatMap chomped $ \c ->
if c == '\n'
then c : indent n
else [c]
in
if multiline
then paddedDesc
else chomped
data Maximum a
= Maximum a
| MinusInfinity
instance Ord a => Semigroup (Maximum a) where
Maximum a <> Maximum b = Maximum (a `max` b)
MinusInfinity <> a = a
a <> MinusInfinity = a
instance Ord a => Monoid (Maximum a) where
mempty = MinusInfinity
mappend = (<>)
-- | Compute the amount of space needed to align "OK"s and "FAIL"s
computeAlignment :: OptionSet -> TestTree -> Int
computeAlignment opts =
fromMonoid .
foldTestTree
trivialFold
{ foldSingle = \_ name _ level -> Maximum (length name + level)
, foldGroup = \_ _ m -> m . (+ indentSize)
}
opts
where
fromMonoid m =
case m 0 of
MinusInfinity -> 0
Maximum x -> x
-- (Potentially) colorful output
ok, warn, failure, infoOk, infoWarn, infoFail :: (?colors :: Bool) => String -> IO ()
ok = output NormalIntensity Dull Green
warn = output NormalIntensity Dull Yellow
failure = output BoldIntensity Vivid Red
infoOk = output NormalIntensity Dull White
infoWarn = output NormalIntensity Dull White
infoFail = output NormalIntensity Dull Red
output
:: (?colors :: Bool)
=> ConsoleIntensity
-> ColorIntensity
-> Color
-> String
-> IO ()
output bold intensity color st
| ?colors =
(do
setSGR
[ SetColor Foreground intensity color
, SetConsoleIntensity bold
]
putStr st
) `finally` setSGR []
| otherwise = putStr st
-- }}}
|
phile314/tasty-silver
|
Test/Tasty/Silver/Interactive.hs
|
mit
| 30,905
| 0
| 32
| 8,543
| 7,208
| 3,679
| 3,529
| 665
| 19
|
-- Starting with the number 1 and moving to the right in a clockwise
-- direction a 5 by 5 spiral is formed as follows:
-- 21 22 23 24 25
-- 20 7 8 9 10
-- 19 6 1 2 11
-- 18 5 4 3 12
-- 17 16 15 14 13
-- It can be verified that the sum of the numbers on the diagonals is
-- 101.
-- What is the sum of the numbers on the diagonals in a 1001 by 1001
-- spiral formed in the same way?
module Euler.Problem028
( solution
, ulamsSpiralDiagonalsFor
) where
solution :: Integral a => a -> a
solution = sum . ulamsSpiralDiagonalsFor
ulamsSpiralDiagonalsFor :: Integral a => a -> [a]
ulamsSpiralDiagonalsFor n = 1 : do
let kmax = (n + 1) `div` 2 - 1
k <- [1..kmax]
j <- [1..4]
return $ 4*k*k + (2*j - 4) * k + 1
|
whittle/euler
|
src/Euler/Problem028.hs
|
mit
| 747
| 0
| 14
| 201
| 169
| 94
| 75
| 11
| 1
|
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Text.HamletSpec (spec) where
import HamletTestTypes (ARecord(..))
import Test.HUnit hiding (Test)
import Test.Hspec hiding (Arg)
import Prelude hiding (reverse)
import Text.Hamlet
import Text.Hamlet.RT
import Data.List (intercalate)
import qualified Data.Text.Lazy as T
import qualified Data.List
import qualified Data.List as L
import Data.Text (Text, pack, unpack)
import Data.Monoid (mappend)
import qualified Data.Set as Set
import qualified Text.Blaze.Html.Renderer.Text
import Text.Blaze.Html (toHtml)
import Text.Blaze.Internal (preEscapedString)
import Text.Blaze
spec = do
it "empty" caseEmpty
it "static" caseStatic
it "tag" caseTag
it "var" caseVar
it "var chain " caseVarChain
it "url" caseUrl
it "url chain " caseUrlChain
it "embed" caseEmbed
it "embed chain " caseEmbedChain
it "if" caseIf
it "if chain " caseIfChain
it "else" caseElse
it "else chain " caseElseChain
it "elseif" caseElseIf
it "elseif chain " caseElseIfChain
it "list" caseList
it "list chain" caseListChain
it "with" caseWith
it "with multi" caseWithMulti
it "with chain" caseWithChain
it "with comma string" caseWithCommaString
it "with multi scope" caseWithMultiBindingScope
it "script not empty" caseScriptNotEmpty
it "meta empty" caseMetaEmpty
it "input empty" caseInputEmpty
it "multiple classes" caseMultiClass
it "attrib order" caseAttribOrder
it "nothing" caseNothing
it "nothing chain " caseNothingChain
it "just" caseJust
it "just chain " caseJustChain
it "constructor" caseConstructor
it "url + params" caseUrlParams
it "escape" caseEscape
it "empty statement list" caseEmptyStatementList
it "attribute conditionals" caseAttribCond
it "non-ascii" caseNonAscii
it "maybe function" caseMaybeFunction
it "trailing dollar sign" caseTrailingDollarSign
it "non leading percent sign" caseNonLeadingPercent
it "quoted attributes" caseQuotedAttribs
it "spaced derefs" caseSpacedDerefs
it "attrib vars" caseAttribVars
it "strings and html" caseStringsAndHtml
it "nesting" caseNesting
it "trailing space" caseTrailingSpace
it "currency symbols" caseCurrency
it "external" caseExternal
it "parens" caseParens
it "hamlet literals" caseHamletLiterals
it "hamlet' and xhamlet'" caseHamlet'
it "hamlet tuple" caseTuple
it "complex pattern" caseComplex
it "record pattern" caseRecord
it "record wildcard pattern #1" caseRecordWildCard
it "record wildcard pattern #2" caseRecordWildCard1
it "comments" $ do
-- FIXME reconsider Hamlet comment syntax?
helper "" [hamlet|$# this is a comment
$# another comment
$#a third one|]
it "ignores a blank line" $ do
helper "<p>foo</p>\n" [hamlet|
<p>
foo
|]
it "angle bracket syntax" $
helper "<p class=\"foo\" height=\"100\"><span id=\"bar\" width=\"50\">HELLO</span></p>"
[hamlet|
$newline never
<p.foo height="100">
<span #bar width=50>HELLO
|]
it "hamlet module names" $ do
let foo = "foo"
helper "oof oof 3.14 -5"
[hamlet|
$newline never
#{Data.List.reverse foo} #
#{L.reverse foo} #
#{show 3.14} #{show -5}|]
it "single dollar at and caret" $ do
helper "$@^" [hamlet|\$@^|]
helper "#{@{^{" [hamlet|#\{@\{^\{|]
it "dollar operator" $ do
let val = (1, (2, 3))
helper "2" [hamlet|#{ show $ fst $ snd val }|]
helper "2" [hamlet|#{ show $ fst $ snd $ val}|]
it "in a row" $ do
helper "1" [hamlet|#{ show $ const 1 2 }|]
it "embedded slash" $ do
helper "///" [hamlet|///|]
{- compile-time error
it "tag with slash" $ do
helper "" [hamlet|
<p>
Text
</p>
|]
-}
it "string literals" $ do
helper "string" [hamlet|#{"string"}|]
helper "string" [hamlet|#{id "string"}|]
helper "gnirts" [hamlet|#{L.reverse $ id "string"}|]
helper "str"ing" [hamlet|#{"str\"ing"}|]
helper "str<ing" [hamlet|#{"str<ing"}|]
it "interpolated operators" $ do
helper "3" [hamlet|#{show $ (+) 1 2}|]
helper "6" [hamlet|#{show $ sum $ (:) 1 ((:) 2 $ return 3)}|]
it "HTML comments" $ do
helper "<p>1</p><p>2 not ignored</p>" [hamlet|
$newline never
<p>1
<!-- ignored comment -->
<p>
2
<!-- ignored --> not ignored<!-- ignored -->
|]
it "Keeps SSI includes" $
helper "<!--# SSI -->" [hamlet|<!--# SSI -->|]
it "nested maybes" $ do
let muser = Just "User" :: Maybe String
mprof = Nothing :: Maybe Int
m3 = Nothing :: Maybe String
helper "justnothing" [hamlet|
$maybe user <- muser
$maybe profile <- mprof
First two are Just
$maybe desc <- m3
\ and left us a description:
<p>#{desc}
$nothing
and has left us no description.
$nothing
justnothing
$nothing
<h1>No such Person exists.
|]
it "maybe with qualified constructor" $ do
helper "5" [hamlet|
$maybe HamletTestTypes.ARecord x y <- Just $ ARecord 5 True
\#{x}
|]
it "record with qualified constructor" $ do
helper "5" [hamlet|
$maybe HamletTestTypes.ARecord {..} <- Just $ ARecord 5 True
\#{field1}
|]
it "conditional class" $ do
helper "<p class=\"current\"></p>\n"
[hamlet|<p :False:.ignored :True:.current>|]
helper "<p class=\"1 3 2 4\"></p>\n"
[hamlet|<p :True:.1 :True:class=2 :False:.a :False:class=b .3 class=4>|]
helper "<p class=\"foo bar baz\"></p>\n"
[hamlet|<p class=foo class=bar class=baz>|]
it "forall on Foldable" $ do
let set = Set.fromList [1..5 :: Int]
helper "12345" [hamlet|
$forall x <- set
#{x}
|]
it "non-poly HTML" $ do
helperHtml "<h1>HELLO WORLD</h1>\n" [shamlet|
<h1>HELLO WORLD
|]
helperHtml "<h1>HELLO WORLD</h1>\n" $(shamletFile "test/hamlets/nonpolyhtml.hamlet")
helper "<h1>HELLO WORLD</h1>\n" $(hamletFileReload "test/hamlets/nonpolyhtml.hamlet")
it "non-poly Hamlet" $ do
let embed = [hamlet|<p>EMBEDDED|]
helper "<h1>url</h1>\n<p>EMBEDDED</p>\n" [hamlet|
<h1>@{Home}
^{embed}
|]
helper "<h1>url</h1>\n" $(hamletFile "test/hamlets/nonpolyhamlet.hamlet")
helper "<h1>url</h1>\n" $(hamletFileReload "test/hamlets/nonpolyhamlet.hamlet")
it "non-poly IHamlet" $ do
let embed = [ihamlet|<p>EMBEDDED|]
ihelper "<h1>Adios</h1>\n<p>EMBEDDED</p>\n" [ihamlet|
<h1>_{Goodbye}
^{embed}
|]
ihelper "<h1>Hola</h1>\n" $(ihamletFile "test/hamlets/nonpolyihamlet.hamlet")
ihelper "<h1>Hola</h1>\n" $(ihamletFileReload "test/hamlets/nonpolyihamlet.hamlet")
it "pattern-match tuples: forall" $ do
let people = [("Michael", 26), ("Miriam", 25)]
helper "<dl><dt>Michael</dt><dd>26</dd><dt>Miriam</dt><dd>25</dd></dl>" [hamlet|
$newline never
<dl>
$forall (name, age) <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match tuples: maybe" $ do
let people = Just ("Michael", 26)
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline never
<dl>
$maybe (name, age) <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match tuples: with" $ do
let people = ("Michael", 26)
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline never
<dl>
$with (name, age) <- people
<dt>#{name}
<dd>#{show age}
|]
it "list syntax for interpolation" $ do
helper "<ul><li>1</li><li>2</li><li>3</li></ul>" [hamlet|
$newline never
<ul>
$forall num <- [1, 2, 3]
<li>#{show num}
|]
it "pattern-match list: maybe" $ do
let example :: [Int]
example = [1, 2, 3]
helper "<ul><li>1</li><li>2</li><li>3</li></ul>" [hamlet|
$newline never
<ul>
$case example
$of (:) x xs
<li>#{x}
$forall y <- xs
<li>#{y}
|]
it "infix operators" $
helper "5" [hamlet|#{show $ (4 + 5) - (2 + 2)}|]
it "infix operators with parens" $
helper "5" [hamlet|#{show ((+) 1 1 + 3)}|]
it "doctypes" $ helper "<!DOCTYPE html>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" [hamlet|
$newline never
$doctype 5
$doctype strict
|]
it "case on Maybe" $
let nothing = Nothing
justTrue = Just True
in helper "<br><br><br><br>" [hamlet|
$newline never
$case nothing
$of Just val
$of Nothing
<br>
$case justTrue
$of Just val
$if val
<br>
$of Nothing
$case (Just $ not False)
$of Nothing
$of Just val
$if val
<br>
$case Nothing
$of Just val
$of _
<br>
|]
it "case on Url" $
let url1 = Home
url2 = Sub SubUrl
in helper "<br>\n<br>\n" [hamlet|
$newline always
$case url1
$of Home
<br>
$of _
$case url2
$of Sub sub
$case sub
$of SubUrl
<br>
$of Home
|]
it "pattern-match constructors: forall" $ do
let people = [Pair "Michael" 26, Pair "Miriam" 25]
helper "<dl><dt>Michael</dt><dd>26</dd><dt>Miriam</dt><dd>25</dd></dl>" [hamlet|
$newline text
<dl>
$forall Pair name age <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match constructors: maybe" $ do
let people = Just $ Pair "Michael" 26
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline text
<dl>
$maybe Pair name age <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match constructors: with" $ do
let people = Pair "Michael" 26
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline text
<dl>
$with Pair name age <- people
<dt>#{name}
<dd>#{show age}
|]
it "multiline tags" $ helper
"<foo bar=\"baz\" bin=\"bin\">content</foo>\n" [hamlet|
<foo bar=baz
bin=bin>content
|]
it "*{...} attributes" $
let attrs = [("bar", "baz"), ("bin", "<>\"&")] in helper
"<foo bar=\"baz\" bin=\"<>"&\">content</foo>\n" [hamlet|
<foo *{attrs}>content
|]
it "blank attr values" $ helper
"<foo bar=\"\" baz bin=\"\"></foo>\n"
[hamlet|<foo bar="" baz bin=>|]
it "greater than in attr" $ helper
"<button data-bind=\"enable: someFunction() > 5\">hello</button>\n"
[hamlet|<button data-bind="enable: someFunction() > 5">hello|]
it "normal doctype" $ helper
"<!DOCTYPE html>\n"
[hamlet|<!DOCTYPE html>|]
it "newline style" $ helper
"<p>foo</p>\n<pre>bar\nbaz\nbin</pre>\n"
[hamlet|
$newline always
<p>foo
<pre>
bar
baz
bin
|]
it "avoid newlines" $ helper
"<p>foo</p><pre>barbazbin</pre>"
[hamlet|
$newline always
<p>foo#
<pre>#
bar#
baz#
bin#
|]
it "manual linebreaks" $ helper
"<p>foo</p><pre>bar\nbaz\nbin</pre>"
[hamlet|
$newline never
<p>foo
<pre>
bar
\
baz
\
bin
|]
it "indented newline" $ helper
"<p>foo</p><pre>bar\nbaz\nbin</pre>"
[hamlet|
$newline never
<p>foo
<pre>
bar
\
baz
\
bin
|]
it "case underscore" $
let num = 3
in helper "<p>Many</p>\n" [hamlet|
$case num
$of 1
<p>1
$of 2
<p>2
$of _
<p>Many
|]
it "optional and missing classes" $
helper "<i>foo</i>\n" [hamlet|<i :False:.not-present>foo|]
it "multiple optional and missing classes" $
helper "<i>foo</i>\n" [hamlet|<i :False:.not-present :False:.also-not-here>foo|]
it "optional and present classes" $
helper "<i class=\"present\">foo</i>\n" [hamlet|<i :False:.not-present :True:.present>foo|]
it "punctuation operators #115" $
helper "foo"
[hamlet|
$if True && True
foo
$else
bar
|]
it "list syntax" $
helper "123"
[hamlet|
$forall x <- []
ignored
$forall x <- [1, 2, 3]
#{show x}
|]
it "list in attribute" $
let myShow :: [Int] -> String
myShow = show
in helper "<a href=\"[]\">foo</a>\n<a href=\"[1,2]\">bar</a>\n"
[hamlet|
<a href=#{myShow []}>foo
<a href=#{myShow [1, 2]}>bar
|]
it "AngularJS attribute values #122" $
helper "<li ng-repeat=\"addr in msgForm.new.split(/\\\\s/)\">{{addr}}</li>\n"
[hamlet|<li ng-repeat="addr in msgForm.new.split(/\\s/)">{{addr}}|]
it "runtime Hamlet with caret interpolation" $ do
let toInclude render = render (5, [("hello", "world")])
let renderer x y = pack $ show (x :: Int, y :: [(Text, Text)])
template1 = "@?{url}"
template2 = "foo^{toInclude}bar"
toInclude <- parseHamletRT defaultHamletSettings template1
hamletRT <- parseHamletRT defaultHamletSettings template2
res <- renderHamletRT hamletRT
[ (["toInclude"], HDTemplate toInclude)
, (["url"], HDUrlParams 5 [(pack "hello", pack "world")])
] renderer
helperHtml "foo(5,[(\"hello\",\"world\")])bar" res
it "Hash in attribute value" $
helper "<a id=\"logoutbutton\" href=\"#\"></a>\n"
[hamlet|<a #logoutbutton href=#>|]
it "Hash in attribute value" $
helper "<a id=\"logoutbutton\" href=\"#\"></a>\n"
[hamlet|<a #logoutbutton href="#">|]
data Pair = Pair String Int
data Url = Home | Sub SubUrl
data SubUrl = SubUrl
render :: Url -> [(Text, Text)] -> Text
render Home qs = pack "url" `mappend` showParams qs
render (Sub SubUrl) qs = pack "suburl" `mappend` showParams qs
showParams :: [(Text, Text)] -> Text
showParams [] = pack ""
showParams z =
pack $ '?' : intercalate "&" (map go z)
where
go (x, y) = go' x ++ '=' : go' y
go' = concatMap encodeUrlChar . unpack
-- | Taken straight from web-encodings; reimplemented here to avoid extra
-- dependencies.
encodeUrlChar :: Char -> String
encodeUrlChar c
-- List of unreserved characters per RFC 3986
-- Gleaned from http://en.wikipedia.org/wiki/Percent-encoding
| 'A' <= c && c <= 'Z' = [c]
| 'a' <= c && c <= 'z' = [c]
| '0' <= c && c <= '9' = [c]
encodeUrlChar c@'-' = [c]
encodeUrlChar c@'_' = [c]
encodeUrlChar c@'.' = [c]
encodeUrlChar c@'~' = [c]
encodeUrlChar ' ' = "+"
encodeUrlChar y =
let (a, c) = fromEnum y `divMod` 16
b = a `mod` 16
showHex' x
| x < 10 = toEnum $ x + (fromEnum '0')
| x < 16 = toEnum $ x - 10 + (fromEnum 'A')
| otherwise = error $ "Invalid argument to showHex: " ++ show x
in ['%', showHex' b, showHex' c]
data Arg url = Arg
{ getArg :: Arg url
, var :: Html
, url :: Url
, embed :: HtmlUrl url
, true :: Bool
, false :: Bool
, list :: [Arg url]
, nothing :: Maybe String
, just :: Maybe String
, urlParams :: (Url, [(Text, Text)])
}
theArg :: Arg url
theArg = Arg
{ getArg = theArg
, var = toHtml "<var>"
, url = Home
, embed = [hamlet|embed|]
, true = True
, false = False
, list = [theArg, theArg, theArg]
, nothing = Nothing
, just = Just "just"
, urlParams = (Home, [(pack "foo", pack "bar"), (pack "foo1", pack "bar1")])
}
helperHtml :: String -> Html -> Assertion
helperHtml res h = do
let x = Text.Blaze.Html.Renderer.Text.renderHtml h
T.pack res @=? x
helper :: String -> HtmlUrl Url -> Assertion
helper res h = do
let x = Text.Blaze.Html.Renderer.Text.renderHtml $ h render
T.pack res @=? x
caseEmpty :: Assertion
caseEmpty = helper "" [hamlet||]
caseStatic :: Assertion
caseStatic = helper "some static content" [hamlet|some static content|]
caseTag :: Assertion
caseTag = do
helper "<p class=\"foo\"><div id=\"bar\">baz</div></p>" [hamlet|
$newline text
<p .foo>
<#bar>baz
|]
helper "<p class=\"foo.bar\"><div id=\"bar\">baz</div></p>" [hamlet|
$newline text
<p class=foo.bar>
<#bar>baz
|]
caseVar :: Assertion
caseVar = do
helper "<var>" [hamlet|#{var theArg}|]
caseVarChain :: Assertion
caseVarChain = do
helper "<var>" [hamlet|#{var (getArg (getArg (getArg theArg)))}|]
caseUrl :: Assertion
caseUrl = do
helper (unpack $ render Home []) [hamlet|@{url theArg}|]
caseUrlChain :: Assertion
caseUrlChain = do
helper (unpack $ render Home []) [hamlet|@{url (getArg (getArg (getArg theArg)))}|]
caseEmbed :: Assertion
caseEmbed = do
helper "embed" [hamlet|^{embed theArg}|]
helper "embed" $(hamletFileReload "test/hamlets/embed.hamlet")
ihelper "embed" $(ihamletFileReload "test/hamlets/embed.hamlet")
caseEmbedChain :: Assertion
caseEmbedChain = do
helper "embed" [hamlet|^{embed (getArg (getArg (getArg theArg)))}|]
caseIf :: Assertion
caseIf = do
helper "if" [hamlet|
$if true theArg
if
|]
caseIfChain :: Assertion
caseIfChain = do
helper "if" [hamlet|
$if true (getArg (getArg (getArg theArg)))
if
|]
caseElse :: Assertion
caseElse = helper "else" [hamlet|
$if false theArg
if
$else
else
|]
caseElseChain :: Assertion
caseElseChain = helper "else" [hamlet|
$if false (getArg (getArg (getArg theArg)))
if
$else
else
|]
caseElseIf :: Assertion
caseElseIf = helper "elseif" [hamlet|
$if false theArg
if
$elseif true theArg
elseif
$else
else
|]
caseElseIfChain :: Assertion
caseElseIfChain = helper "elseif" [hamlet|
$if false(getArg(getArg(getArg theArg)))
if
$elseif true(getArg(getArg(getArg theArg)))
elseif
$else
else
|]
caseList :: Assertion
caseList = do
helper "xxx" [hamlet|
$forall _x <- (list theArg)
x
|]
caseListChain :: Assertion
caseListChain = do
helper "urlurlurl" [hamlet|
$forall x <- list(getArg(getArg(getArg(getArg(getArg (theArg))))))
@{url x}
|]
caseWith :: Assertion
caseWith = do
helper "it's embedded" [hamlet|
$with n <- embed theArg
it's ^{n}ded
|]
caseWithMulti :: Assertion
caseWithMulti = do
helper "it's embedded" [hamlet|
$with n <- embed theArg, m <- true theArg
$if m
it's ^{n}ded
|]
caseWithChain :: Assertion
caseWithChain = do
helper "it's true" [hamlet|
$with n <- true(getArg(getArg(getArg(getArg theArg))))
$if n
it's true
|]
-- in multi-with binding, make sure that a comma in a string doesn't confuse the parser.
caseWithCommaString :: Assertion
caseWithCommaString = do
helper "it's , something" [hamlet|
$with n <- " , something"
it's #{n}
|]
caseWithMultiBindingScope :: Assertion
caseWithMultiBindingScope = do
helper "it's , something" [hamlet|
$with n <- " , something", y <- n
it's #{y}
|]
caseScriptNotEmpty :: Assertion
caseScriptNotEmpty = helper "<script></script>\n" [hamlet|<script>|]
caseMetaEmpty :: Assertion
caseMetaEmpty = do
helper "<meta>\n" [hamlet|<meta>|]
helper "<meta/>\n" [xhamlet|<meta>|]
caseInputEmpty :: Assertion
caseInputEmpty = do
helper "<input>\n" [hamlet|<input>|]
helper "<input/>\n" [xhamlet|<input>|]
caseMultiClass :: Assertion
caseMultiClass = helper "<div class=\"foo bar\"></div>\n" [hamlet|<.foo.bar>|]
caseAttribOrder :: Assertion
caseAttribOrder =
helper "<meta 1 2 3>\n" [hamlet|<meta 1 2 3>|]
caseNothing :: Assertion
caseNothing = do
helper "" [hamlet|
$maybe _n <- nothing theArg
nothing
|]
helper "nothing" [hamlet|
$maybe _n <- nothing theArg
something
$nothing
nothing
|]
caseNothingChain :: Assertion
caseNothingChain = helper "" [hamlet|
$maybe n <- nothing(getArg(getArg(getArg theArg)))
nothing #{n}
|]
caseJust :: Assertion
caseJust = helper "it's just" [hamlet|
$maybe n <- just theArg
it's #{n}
|]
caseJustChain :: Assertion
caseJustChain = helper "it's just" [hamlet|
$maybe n <- just(getArg(getArg(getArg theArg)))
it's #{n}
|]
caseConstructor :: Assertion
caseConstructor = do
helper "url" [hamlet|@{Home}|]
helper "suburl" [hamlet|@{Sub SubUrl}|]
let text = "<raw text>"
helper "<raw text>" [hamlet|#{preEscapedString text}|]
caseUrlParams :: Assertion
caseUrlParams = do
helper "url?foo=bar&foo1=bar1" [hamlet|@?{urlParams theArg}|]
caseEscape :: Assertion
caseEscape = do
helper "#this is raw\n " [hamlet|
$newline never
\#this is raw
\
\
|]
helper "$@^" [hamlet|\$@^|]
caseEmptyStatementList :: Assertion
caseEmptyStatementList = do
helper "" [hamlet|$if True|]
helper "" [hamlet|$maybe _x <- Nothing|]
let emptyList = []
helper "" [hamlet|$forall _x <- emptyList|]
caseAttribCond :: Assertion
caseAttribCond = do
helper "<select></select>\n" [hamlet|<select :False:selected>|]
helper "<select selected></select>\n" [hamlet|<select :True:selected>|]
helper "<meta var=\"foo:bar\">\n" [hamlet|<meta var=foo:bar>|]
helper "<select selected></select>\n"
[hamlet|<select :true theArg:selected>|]
helper "<select></select>\n" [hamlet|<select :False:selected>|]
helper "<select selected></select>\n" [hamlet|<select :True:selected>|]
helper "<meta var=\"foo:bar\">\n" [hamlet|<meta var=foo:bar>|]
helper "<select selected></select>\n"
[hamlet|<select :true theArg:selected>|]
caseNonAscii :: Assertion
caseNonAscii = do
helper "עִבְרִי" [hamlet|עִבְרִי|]
caseMaybeFunction :: Assertion
caseMaybeFunction = do
helper "url?foo=bar&foo1=bar1" [hamlet|
$maybe x <- Just urlParams
@?{x theArg}
|]
caseTrailingDollarSign :: Assertion
caseTrailingDollarSign =
helper "trailing space \ndollar sign #" [hamlet|
$newline never
trailing space #
\
dollar sign #\
|]
caseNonLeadingPercent :: Assertion
caseNonLeadingPercent =
helper "<span style=\"height:100%\">foo</span>" [hamlet|
$newline never
<span style=height:100%>foo
|]
caseQuotedAttribs :: Assertion
caseQuotedAttribs =
helper "<input type=\"submit\" value=\"Submit response\">" [hamlet|
$newline never
<input type=submit value="Submit response">
|]
caseSpacedDerefs :: Assertion
caseSpacedDerefs = do
helper "<var>" [hamlet|#{var theArg}|]
helper "<div class=\"<var>\"></div>\n" [hamlet|<.#{var theArg}>|]
caseAttribVars :: Assertion
caseAttribVars = do
helper "<div id=\"<var>\"></div>\n" [hamlet|<##{var theArg}>|]
helper "<div class=\"<var>\"></div>\n" [hamlet|<.#{var theArg}>|]
helper "<div f=\"<var>\"></div>\n" [hamlet|< f=#{var theArg}>|]
helper "<div id=\"<var>\"></div>\n" [hamlet|<##{var theArg}>|]
helper "<div class=\"<var>\"></div>\n" [hamlet|<.#{var theArg}>|]
helper "<div f=\"<var>\"></div>\n" [hamlet|< f=#{var theArg}>|]
caseStringsAndHtml :: Assertion
caseStringsAndHtml = do
let str = "<string>"
let html = preEscapedString "<html>"
helper "<string> <html>" [hamlet|#{str} #{html}|]
caseNesting :: Assertion
caseNesting = do
helper
"<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>"
[hamlet|
$newline never
<table>
<tbody>
$forall user <- users
<tr>
<td>#{user}
|]
helper
(concat
[ "<select id=\"foo\" name=\"foo\"><option selected></option>"
, "<option value=\"true\">Yes</option>"
, "<option value=\"false\">No</option>"
, "</select>"
])
[hamlet|
$newline never
<select #"#{name}" name=#{name}>
<option :isBoolBlank val:selected>
<option value=true :isBoolTrue val:selected>Yes
<option value=false :isBoolFalse val:selected>No
|]
where
users = ["1", "2"]
name = "foo"
val = 5 :: Int
isBoolBlank _ = True
isBoolTrue _ = False
isBoolFalse _ = False
caseTrailingSpace :: Assertion
caseTrailingSpace =
helper "" [hamlet| |]
caseCurrency :: Assertion
caseCurrency =
helper foo [hamlet|#{foo}|]
where
foo = "eg: 5, $6, €7.01, £75"
caseExternal :: Assertion
caseExternal = do
helper "foo\n<br>\n" $(hamletFile "test/hamlets/external.hamlet")
helper "foo\n<br/>\n" $(xhamletFile "test/hamlets/external.hamlet")
helper "foo\n<br>\n" $(hamletFileReload "test/hamlets/external.hamlet")
where
foo = "foo"
caseParens :: Assertion
caseParens = do
let plus = (++)
x = "x"
y = "y"
helper "xy" [hamlet|#{(plus x) y}|]
helper "xxy" [hamlet|#{plus (plus x x) y}|]
let alist = ["1", "2", "3"]
helper "123" [hamlet|
$forall x <- (id id id id alist)
#{x}
|]
caseHamletLiterals :: Assertion
caseHamletLiterals = do
helper "123" [hamlet|#{show 123}|]
helper "123.456" [hamlet|#{show 123.456}|]
helper "-123" [hamlet|#{show -123}|]
helper "-123.456" [hamlet|#{show -123.456}|]
helper' :: String -> Html -> Assertion
helper' res h = T.pack res @=? Text.Blaze.Html.Renderer.Text.renderHtml h
caseHamlet' :: Assertion
caseHamlet' = do
helper' "foo" [shamlet|foo|]
helper' "foo" [xshamlet|foo|]
helper "<br>\n" $ const $ [shamlet|<br>|]
helper "<br/>\n" $ const $ [xshamlet|<br>|]
-- new with generalized stuff
helper' "foo" [shamlet|foo|]
helper' "foo" [xshamlet|foo|]
helper "<br>\n" $ const $ [shamlet|<br>|]
helper "<br/>\n" $ const $ [xshamlet|<br>|]
instance Show Url where
show _ = "FIXME remove this instance show Url"
caseDiffBindNames :: Assertion
caseDiffBindNames = do
let list = words "1 2 3"
-- FIXME helper "123123" $(hamletFileReload "test/hamlets/external-debug3.hamlet")
error "test has been disabled"
caseTrailingSpaces :: Assertion
caseTrailingSpaces = helper "" [hamlet|
$if True
$elseif False
$else
$maybe x <- Nothing
$nothing
$forall x <- empty
|]
where
empty = []
caseTuple :: Assertion
caseTuple = do
helper "(1,1)" [hamlet| #{("1","1")}|]
helper "foo" [hamlet|
$with (a,b) <- ("foo","bar")
#{a}
|]
helper "url" [hamlet|
$with (a,b) <- (Home,Home)
@{a}
|]
helper "url" [hamlet|
$with p <- (Home,[])
@?{p}
|]
caseComplex :: Assertion
caseComplex = do
let z :: ((Int,Int),Maybe Int,(),Bool,[[Int]])
z = ((1,2),Just 3,(),True,[[4],[5,6]])
helper "1 2 3 4 5 61 2 3 4 5 6" [hamlet|
$with ((a,b),Just c, () ,True,d@[[e],[f,g]]) <- z
$forall h <- d
#{a} #{b} #{c} #{e} #{f} #{g}
|]
caseRecord :: Assertion
caseRecord = do
let z = ARecord 10 True
helper "10" [hamlet|
$with ARecord { field1, field2 = True } <- z
#{field1}
|]
caseRecordWildCard :: Assertion
caseRecordWildCard = do
let z = ARecord 10 True
helper "10 True" [hamlet|
$with ARecord {..} <- z
#{field1} #{field2}
|]
caseRecordWildCard1 :: Assertion
caseRecordWildCard1 = do
let z = ARecord 10 True
helper "10" [hamlet|
$with ARecord {field2 = True, ..} <- z
#{field1}
|]
caseCaseRecord :: Assertion
caseCaseRecord = do
let z = ARecord 10 True
helper "10\nTrue" [hamlet|
$case z
$of ARecord { field1, field2 = x }
#{field1}
#{x}
|]
data Msg = Hello | Goodbye
ihelper :: String -> HtmlUrlI18n Msg Url -> Assertion
ihelper res h = do
let x = Text.Blaze.Html.Renderer.Text.renderHtml $ h showMsg render
T.pack res @=? x
where
showMsg Hello = preEscapedString "Hola"
showMsg Goodbye = preEscapedString "Adios"
instance (ToMarkup a, ToMarkup b) => ToMarkup (a,b) where
toMarkup (a,b) = do
toMarkup "("
toMarkup a
toMarkup ","
toMarkup b
toMarkup ")"
|
yesodweb/shakespeare
|
test/Text/HamletSpec.hs
|
mit
| 27,717
| 0
| 17
| 6,761
| 5,650
| 3,026
| 2,624
| 567
| 2
|
module Control.Concurrent.FFI where
import Control.Concurrent (ThreadId,forkIO,myThreadId,killThread,
MVar,putMVar,takeMVar,newEmptyMVar)
import qualified Control.Concurrent.Chan as A
import Control.Concurrent.Chan.Synchronous
import Control.Monad
type AgdaUnit a = ()
type AgdaChan a b = A.Chan b
type AgdaSyncChan a b = Chan b
-- Beware! The following code has never been tested.
rival :: Chan a -> Chan a -> MVar ThreadId -> MVar ThreadId -> MVar a -> IO ()
rival cI cO me you mom = do
mine <- myThreadId
putMVar me mine
yours <- takeMVar you
x <- readChan cI
killThread yours
-- TODO. Can I make sure `yours` is dead now?
-- The process whose TID is `yours` must not be allowed to steal x!
writeChan cO x
putMVar mom x
-- `move` won't tell you *who* moved the data: you will not know in
-- which direction it was moved.
race :: Chan a -> Chan a -> MVar ThreadId -> MVar ThreadId -> MVar a -> IO a
race c1 c2 v1 v2 m = do
forkIO (rival c1 c2 v1 v2 m)
forkIO (rival c2 c1 v2 v1 m)
takeMVar m
-- TODO. Will fuse's forever make channels forever referenced, hence
-- uncollectable?
move :: Chan a -> Chan a -> IO a
move c1 c2 = do
v1 <- newEmptyMVar ; v2 <- newEmptyMVar ; m <- newEmptyMVar
race c1 c2 v1 v2 m
fuse :: Chan a -> Chan a -> IO ()
fuse c1 c2 = do
v1 <- newEmptyMVar ; v2 <- newEmptyMVar ; m <- newEmptyMVar
forever $ race c1 c2 v1 v2 m
|
ma82/concurrent-agda
|
ffi/Control/Concurrent/FFI.hs
|
mit
| 1,430
| 0
| 11
| 340
| 466
| 232
| 234
| 31
| 1
|
module Laika.Building.ByteString.Builder where
import Laika.Prelude
import Data.ByteString.Builder.Internal
import Foreign
import qualified Data.Text.Encoding as C
import qualified Laika.Building.ByteString.Builder.BoundedPrims as D
{-# INLINE byteListOfLength #-}
byteListOfLength :: Int -> [Word8] -> Builder
byteListOfLength length list =
ensureFree length <> builder stepUpdate
where
stepUpdate :: BuildStep a -> BuildStep a
stepUpdate nextStep (BufferRange ptr1 ptr2) =
do
newPtr1 <- foldlM (\ptr byte -> poke ptr byte $> plusPtr ptr 1) ptr1 list
nextStep $! BufferRange newPtr1 ptr2
{-# INLINE textInUTF8HTML #-}
textInUTF8HTML :: Text -> Builder
textInUTF8HTML =
C.encodeUtf8BuilderEscaped D.html
|
nikita-volkov/laika
|
library/Laika/Building/ByteString/Builder.hs
|
mit
| 744
| 0
| 14
| 127
| 187
| 103
| 84
| 19
| 1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-}
module Stackage.BuildPlanSpec (spec) where
import qualified Data.Map as Map
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Yaml
import qualified Data.Yaml as Y
import Distribution.Version
import Network.HTTP.Client
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Stackage.BuildConstraints
import Stackage.BuildPlan
import Stackage.CheckBuildPlan
import Stackage.PackageDescription
import Stackage.PackageIndex
import Stackage.Prelude
import Stackage.UpdateBuildPlan
import Test.Hspec
spec :: Spec
spec = do
it "simple package set" $ check testBuildConstraints $ makePackageSet
[("foo", [0, 0, 0], [("bar", thisV [0, 0, 0])])
,("bar", [0, 0, 0], [])]
it "bad version range on depdendency fails" $ badBuildPlan $ makePackageSet
[("foo", [0, 0, 0], [("bar", thisV [1, 1, 0])])
,("bar", [0, 0, 0], [])]
it "nonexistent package fails to check" $ badBuildPlan $ makePackageSet
[("foo", [0, 0, 0], [("nonexistent", thisV [0, 0, 0])])
,("bar", [0, 0, 0], [])]
it "mutual cycles fail to check" $ badBuildPlan $ makePackageSet
[("foo", [0, 0, 0], [("bar", thisV [0, 0, 0])])
,("bar", [0, 0, 0], [("foo", thisV [0, 0, 0])])]
it "nested cycles fail to check" $ badBuildPlan $ makePackageSet
[("foo", [0, 0, 0], [("bar", thisV [0, 0, 0])])
,("bar", [0, 0, 0], [("mu", thisV [0, 0, 0])])
,("mu", [0, 0, 0], [("foo", thisV [0, 0, 0])])]
{- Shouldn't be testing this actually
it "default package set checks ok" $
check defaultBuildConstraints getLatestAllowedPlans
-}
-- | Checking should be considered a bad build plan.
badBuildPlan :: (BuildConstraints -> IO (Map PackageName PackagePlan))
-> void
-> IO ()
badBuildPlan m _ = do
mu <- try (check testBuildConstraints m)
case mu of
Left (_ :: BadBuildPlan) ->
return ()
Right () ->
error "Expected bad build plan."
-- | Check build plan with the given package set getter.
check :: (Manager -> IO BuildConstraints)
-> (BuildConstraints -> IO (Map PackageName PackagePlan))
-> IO ()
check readPlanFile getPlans = do
man <- newManager tlsManagerSettings
bc <- readPlanFile man
plans <- getPlans bc
allCabalHashesCommit <- getAllCabalHashesCommit
bp <- newBuildPlan allCabalHashesCommit plans testLatestPackages bc
let bs = Y.encode bp
ebp' = Y.decodeEither bs
bp' <- either error return ebp'
let allPackages = Map.keysSet (bpPackages bp) ++ Map.keysSet (bpPackages bp')
forM_ allPackages $ \name ->
(name, lookup name (bpPackages bp')) `shouldBe`
(name, lookup name (bpPackages bp))
bpGithubUsers bp' `shouldBe` bpGithubUsers bp
when (bp' /= bp) $ error "bp' /= bp"
bp2 <- updateBuildPlan plans bp
when (dropVersionRanges bp2 /= dropVersionRanges bp) $ error "bp2 /= bp"
checkBuildPlan False bp
where
dropVersionRanges bp =
bp { bpPackages = map go $ bpPackages bp }
where
go pb = pb { ppConstraints = go' $ ppConstraints pb }
go' pc = pc { pcVersionRange = anyVersion }
-- | Make a package set from a convenient data structure.
makePackageSet
:: [(String,[Int],[(String,VersionRange)])]
-> BuildConstraints
-> IO (Map PackageName PackagePlan)
makePackageSet ps _ =
return $
M.fromList $
map
(\(name,ver,deps) ->
( mkPackageName name
, dummyPackage ver $
M.fromList $
map
(\(dname,dver) ->
( mkPackageName dname
, DepInfo {diComponents = S.fromList
[CompLibrary]
,diRange = dver}))
deps))
ps
where
dummyPackage v deps =
PackagePlan
{ppVersion = mkVersion v
,ppCabalFileInfo = Nothing
,ppSourceUrl = Nothing
,ppGithubPings = mempty
,ppUsers = mempty
,ppSimpleBuild = Nothing
,ppConstraints =
PackageConstraints
{pcVersionRange = anyV
,pcConfigureArgs = mempty
,pcMaintainer = Nothing
,pcTests = Don'tBuild
,pcHaddocks = Don'tBuild
,pcBenches = Don'tBuild
,pcFlagOverrides = mempty
,pcEnableLibProfile = False
,pcSkipBuild = False
,pcHide = False
,pcNonParallelBuild = False}
,ppDesc =
SimpleDesc
{sdPackages = deps
,sdTools = mempty
,sdProvidedExes = mempty
,sdModules = mempty
,sdCabalVersion = mempty
,sdSetupDeps = Nothing}}
-- | This exact version is required.
thisV :: [Int] -> VersionRange
thisV ver = thisVersion (mkVersion ver)
-- | Accept any version.
anyV :: VersionRange
anyV = anyVersion
-- | Test plan.
testBuildConstraints :: void -> IO BuildConstraints
testBuildConstraints _ =
decodeFileEither fp >>=
either throwIO toBC
where fp = "test/test-build-constraints.yaml"
-- | Test package set with versions.
testLatestPackages :: Map PackageName Version
testLatestPackages =
Map.fromList [ (mkPackageName n, mkVersion [0, 0, 0])
| n <- ["bar", "foo", "mu"] ]
|
fpco/stackage-curator
|
test/Stackage/BuildPlanSpec.hs
|
mit
| 5,906
| 0
| 18
| 2,023
| 1,590
| 895
| 695
| 134
| 2
|
{-|
Module: Flaw.Itch.WebApi
Description: Itch WebAPI.
License: MIT
-}
{-# LANGUAGE DeriveGeneric, GeneralizedNewtypeDeriving, OverloadedStrings, ViewPatterns #-}
module Flaw.Itch.WebApi
( ItchWebApiKey(..)
, itchWebApiMe
, itchWebApiDownloadKeys
, ItchUserId(..)
, ItchUser(..)
, ItchGameId(..)
, ItchDownloadKeyId(..)
, ItchDownloadKey(..)
) where
import Control.Monad
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import qualified Data.ByteString as B
import Data.Hashable
import Data.String
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word
import GHC.Generics(Generic)
import qualified Network.HTTP.Client as H
-- | Itch API key (normal API key or JWT token).
data ItchWebApiKey = ItchWebApiKey !T.Text !Bool
itchWebApiRequest :: H.Manager -> ItchWebApiKey -> B.ByteString -> [(B.ByteString, Maybe B.ByteString)] -> IO A.Value
itchWebApiRequest httpManager (ItchWebApiKey apiKey isKey) path params =
either fail return . A.eitherDecode' . H.responseBody =<< H.httpLbs (H.setQueryString params H.defaultRequest
{ H.method = "GET"
, H.secure = True
, H.host = "itch.io"
, H.port = 443
, H.path = "/api/1/" <> (if isKey then "key" else "jwt") <> path
, H.requestHeaders = [("Authorization", "Bearer " <> T.encodeUtf8 apiKey)]
}) httpManager
itchWebApiMe :: H.Manager -> ItchWebApiKey -> IO (Maybe (ItchUser, Maybe ItchGameId))
itchWebApiMe httpManager apiKey =
A.parseMaybe parseResponse <$> itchWebApiRequest httpManager apiKey "/me" []
where
parseResponse = A.withObject "response" $ \response -> do
user <- response A..: "user"
maybeGameId <- maybe (return Nothing) (A.withObject "issuer" (A..: "game_id") <=< A.withObject "api_key" (A..: "issuer")) =<< response A..:? "api_key"
return (user, maybeGameId)
itchWebApiDownloadKeys :: H.Manager -> ItchWebApiKey -> ItchGameId -> ItchUserId -> IO (Maybe ItchDownloadKey)
itchWebApiDownloadKeys httpManager apiKey (ItchGameId gameId) (ItchUserId userId) = do
A.parseMaybe parseResponse <$> itchWebApiRequest httpManager apiKey ("/game/" <> fromString (show gameId) <> "/download_keys")
[ ("user_id", Just $ fromString $ show userId)
]
where parseResponse = A.withObject "response" (A..: "download_key")
newtype ItchUserId = ItchUserId Word64 deriving (Eq, Ord, Hashable, Generic, Show, A.FromJSON, A.ToJSON)
data ItchUser = ItchUser
{ itchUser_id :: !ItchUserId
, itchUser_username :: !T.Text
, itchUser_url :: !T.Text
, itchUser_cover_url :: !(Maybe T.Text)
} deriving (Generic, Show)
instance A.FromJSON ItchUser where
parseJSON = A.genericParseJSON A.defaultOptions
{ A.fieldLabelModifier = drop 9
}
newtype ItchGameId = ItchGameId Word64 deriving (Eq, Ord, Hashable, Generic, Show, A.FromJSON, A.ToJSON)
newtype ItchDownloadKeyId = ItchDownloadKeyId Word64 deriving (Eq, Ord, Hashable, Generic, Show, A.FromJSON, A.ToJSON)
data ItchDownloadKey = ItchDownloadKey
{ itchDownloadKey_id :: !ItchDownloadKeyId
, itchDownloadKey_game_id :: {-# UNPACK #-} !ItchGameId
, itchDownloadKey_owner :: !ItchUser
} deriving (Generic, Show)
instance A.FromJSON ItchDownloadKey where
parseJSON = A.genericParseJSON A.defaultOptions
{ A.fieldLabelModifier = drop 16
}
|
quyse/flaw
|
flaw-itch-webapi/Flaw/Itch/WebApi.hs
|
mit
| 3,304
| 0
| 18
| 525
| 961
| 530
| 431
| 80
| 2
|
import System.Environment
import Data.List
import Data.List.Split -- Type 'cabal install split'
isoyg :: String -> [String]
isoyg s = endBy "your grave" s
splitAll :: [String] -> [[String]]
splitAll args = map isoyg args
splitAndJoin :: [String] -> String
splitAndJoin args =
let merge lns = foldr (\i r -> i ++ "\n" ++ r) "" lns
args2 = map merge $ splitAll args
in merge args2
main = do
args <- getArgs
putStr $ splitAndJoin args
|
suetanvil/isplitonyourgrave
|
isoyg.hs
|
mit
| 454
| 0
| 13
| 99
| 173
| 89
| 84
| 15
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module NFA.Quiz where
import Autolib.NFA
import qualified NFA.Property as A
import qualified Exp.Property as E
import Autolib.Reader
import Autolib.Symbol
import Autolib.ToDoc
import Data.Typeable
data NFAC c Int => From c = From_Exp [ E.Property c ]
| From_NFA [ A.Property c ]
deriving ( Typeable )
$(derives [makeToDoc] [''From])
-- damit wir die alten Records noch lesen können
instance ( Reader [c], Symbol c ) => Reader ( From c ) where
-- NOTE/HACK: ohne Reader[c] gehen Strings nicht mit Doppelquotes
reader = do my_reserved "From_Exp" ; fmap From_Exp reader
<|> do my_reserved "From_NFA" ; fmap From_NFA reader
<|> do {- früher -} fmap From_Exp reader
data NFAC c Int =>
Quiz c = Quiz { generate :: From c
, solve :: [ A.Property c ]
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Quiz])
example :: Quiz Char
example = Quiz { generate = From_Exp [ E.Alphabet $ mkSet "ab"
, E.Max_Size 10
, E.Simple
]
, solve = [ A.Alphabet $ mkSet "ab"
]
}
-- local variables;
-- mode: haskell;
-- end;
|
florianpilz/autotool
|
src/NFA/Quiz.hs
|
gpl-2.0
| 1,158
| 11
| 11
| 293
| 354
| 193
| 161
| -1
| -1
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : Testing of different parts of the EnCL Implementation
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : ewaryst.schulz@dfki.de
Stability : experimental
Portability : portable
Testing using QuickCheck of SetOrdering algos.
Mainly for instance generation of interesting data structures.
-}
import Data.List
import Numeric
import qualified Data.Set as Set
import Control.Monad
import Test.QuickCheck
import CSL.TreePO
import CSL.AS_BASIC_CSL
-- ----------------------------------------------------------------------
-- * Pretty printing
-- ----------------------------------------------------------------------
class Show' a where
show' :: a -> String
instance Show' a => Show' (SetOrInterval a) where
show' (Set s) = let l = intersperse "," $ map show' $ Set.toList s
in "{" ++ concat l ++ "}"
show' (IntVal (a, bA) (b, bB)) = let l = if bA then "[" else "]"
r = if bB then "]" else "["
in concat [l, show' a, ", ", show' b, r]
instance Show' a => Show' (CIType a) where
show' (CIType (x, e)) = case e of
Zero -> show' x
EpsLeft -> show' x ++ "-"
EpsRight -> show' x ++ "+"
instance Show' InfInt where
show' NegInf = "-oo"
show' PosInf = "oo"
show' (FinInt x) = show x
instance Show' a => Show' (Maybe a) where
show' (Just x) = show' x
show' Nothing = ""
instance Show' a => Show' (a, a) where
show' (x,y) = "(" ++ show' x ++ ", " ++ show' y ++ ")"
instance Show' SetOrdering where
show' = show
instance Show' GroundConstant where
show' (GCI x) = show x
show' (GCR x) = show' x
instance Show' APFloat where
show' x = showFFloat (Just 2) (fromRational x) ""
-- ----------------------------------------------------------------------
-- * Generator for test sets
-- ----------------------------------------------------------------------
gconst :: Gen GroundConstant
gconst = do
b <- arbitrary
if b then fmap GCI arbitrary else fmap GCR arbitrary
finborder :: Gen (InfInt, Bool)
finborder = do
b <- arbitrary
ii <- fmap FinInt arbitrary
return (ii, b)
border :: Gen (InfInt, Bool)
border = frequency [ (2, elements [(PosInf, False), (NegInf, False)])
, (23, finborder) ]
finset :: Gen (SetOrInterval InfInt)
finset = fmap (Set . Set.fromList . map FinInt) $ listOf1 arbitrary
-- finset = fmap (Set . Set.map FinInt) arbitrary
intval :: Gen (SetOrInterval InfInt)
intval = do
(x, bx) <- border
(y, by) <- border
let mkRes a ba b bb
| a == b = IntVal (a, True) (b, True)
| intsizeA a b == Just 2 && not (ba || bb) = mkRes a (not ba) b bb
| a > b = IntVal (b, bb) (a, ba)
| otherwise = IntVal (a, ba) (b, bb)
return $ mkRes x bx y by
finsetC :: (Ord a) => Gen a -> Gen (SetOrInterval a)
finsetC g = fmap (Set . Set.fromList) $ listOf1 g
-- finset = fmap (Set . Set.map FinInt) arbitrary
intvalC :: (Ord a) => Gen a -> Gen (SetOrInterval a)
intvalC g = do
x1 <- g
b1 <- arbitrary
x2 <- g
b2 <- arbitrary
let mkRes a ba b bb
| a == b = IntVal (a, True) (b, True)
| a > b = IntVal (b, bb) (a, ba)
| otherwise = IntVal (a, ba) (b, bb)
return $ mkRes x1 b1 x2 b2
-- main generator functions
soi :: Gen (SetOrInterval InfInt)
soi = oneof [finset, intval]
soiC :: Gen (SetOrInterval GroundConstant)
soiC = oneof [finsetC gconst, intvalC gconst]
comps :: Gen (SetOrInterval InfInt, SetOrInterval InfInt)
comps = do
soi1 <- soi
soi2 <- soi
return (soi1, soi2)
compsC :: Gen (SetOrInterval GroundConstant, SetOrInterval GroundConstant)
compsC = do
soi1 <- soiC
soi2 <- soiC
return (soi1, soi2)
-- run function f on many samples
onSmpl g f = do
l <- smpls g
mapM_ pr l
where pr x = do
putStrLn $ "Input: " ++ show' x
putStrLn $ " --> " ++ show' (f x)
-- get many samples
smpls :: Gen a -> IO [a]
smpls = fmap concat . replicateM 10 . sample'
-- show samples
insts :: Show a => Gen a -> IO ()
insts = replicateM_ 10 . sample
-- write samples to file
insts' :: Show' a => Gen a -> IO ()
insts' g = smpls g >>= writeFile "/tmp/qc" . unlines . map show'
|
nevrenato/Hets_Fork
|
CSL/quickchecks.hs
|
gpl-2.0
| 4,467
| 0
| 16
| 1,211
| 1,555
| 784
| 771
| 100
| 2
|
module BinTree
where
inTree :: (Ord a,Show a) => a -> BinTree a -> Bool
addTree :: (Ord a,Show a) => a -> BinTree a -> BinTree a
delTree :: (Ord a,Show a) => a -> BinTree a -> BinTree a
buildTree :: (Ord a,Show a) => [a] -> BinTree a
inorder :: (Ord a,Show a) => BinTree a -> [a]
data (Ord a) => BinTree a = EmptyBT
| NodeBT a (BinTree a) (BinTree a)
deriving Show
emptyTree = EmptyBT
inTree v' EmptyBT = False
inTree v' (NodeBT v lf rt) | v==v' = True
| v'<v = inTree v' lf
| v'>v = inTree v' rt
addTree v' EmptyBT = NodeBT v' EmptyBT EmptyBT
addTree v' (NodeBT v lf rt) | v'==v = NodeBT v lf rt
| v' < v = NodeBT v (addTree v' lf) rt
| otherwise = NodeBT v lf (addTree v' rt)
buildTree lf = foldr addTree EmptyBT lf
-- value not found
delTree v' EmptyBT = EmptyBT
-- one descendant
delTree v' (NodeBT v lf EmptyBT) | v'==v = lf
delTree v' (NodeBT v EmptyBT rt) | v'==v = rt
-- two descendants
delTree v' (NodeBT v lf rt)
| v'<v = NodeBT v (delTree v' lf) rt
| v'>v = NodeBT v lf (delTree v' rt)
| v'==v = let k = minTree rt
in NodeBT k lf (delTree k rt)
minTree (NodeBT v EmptyBT _) = v
minTree (NodeBT _ lf _) = minTree lf
inorder EmptyBT = []
inorder (NodeBT v lf rt) = inorder lf ++ [v] ++ inorder rt
|
collective/ECSpooler
|
backends/haskell/haskell_libs/BinTree.hs
|
gpl-2.0
| 1,567
| 0
| 10
| 623
| 678
| 332
| 346
| 31
| 1
|
-- | This module implements the parse-bib tool. It uses the UU-Parsinglib parser combinators
-- to allow for a forgiving, self-correcting Bib-parser. It is also quite readable, thanks to the advanced
-- library used.
module ParseBib.Parser where
--import Parsers etc...
import Text.ParserCombinators.UU
import Text.ParserCombinators.UU.BasicInstances
import Text.ParserCombinators.UU.Examples
import ParseBib.ParserUtils
import Common.BibTypes
import Char (isDigit)
-- | the top-level parser. Describes the grammar of a BibTex file,
-- namely 0 or more preamble keywords, and 1 or more bibtex entries. the definitions
-- here closely resemble the grammar, so it's easy to see what a file should look like,
-- by inspecting the parser functions.
parseBib :: Parser BibTex
parseBib = BibTex `pMerge` (pAtLeast 0 parsePreamble
<||> pMany parseBibEntry)
-- | Grammar for a bib entry. An entry has a type, a name, and a body.
parseBibEntry :: Parser Entry
parseBibEntry = Entry `pMerge` (pOne pType
<||> pOne pReference
<||> pOne pBibEntryBody
)
-- | A type of a bib entry is just a string of a-z, preceded by the '@' symbol.
-- Don't return the at-symbol, though.
pType :: Parser String
pType = (spaces *> pSym '@' *> pMunch1 (flip elem ['a'..'z']))
-- | Parse the name of the bib entry. Cheat by consuming the first opening brace as well.
pReference :: Parser String
pReference = pSym '{' *> spaces *> pBibKey <* spaces <* pToken "," <* spaces
-- | The body of a bib entry is a list of fields, separated by a comma and spaces. Finally consume
-- the closing brace when done.
pBibEntryBody :: Parser [Field]
pBibEntryBody = pList1Sep (pSym ',') pKeyValue <* spaces <* pSym '}' <* spaces
-- | a bib key (its reference) is a word containing [A-Za-z0-9].
pBibKey :: Parser String
pBibKey = pMunch (flip elem (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['-']))
-- | A parser for the preamble keywords. This is just a string preceded by @preamble and surrounded by braces and quotation marks. Unfortunately no support for @string variables yet.
parsePreamble :: Parser String
parsePreamble = spaces *> pToken "@preamble" *> spaces *> pSym '{' *> spaces *> pSym '"' *> pMunch (/= '"') <* pSym '"' <* spaces <* pSym '}' <* spaces
-- | A key-value parser. A key is a word, followed by =, and the value is surrounded by quotation marks;
-- if, however, the value is numeric, the quotation marks aren't required.
pKeyValue :: Parser Field
pKeyValue = Field <$>
(spaces *> pMunch1 (flip elem ['a'..'z']))
<*
(spaces *> pSym '=' *> spaces)
<*> ((pSym '"' *> pMunch (/= '"') <* pSym '"' ) --TODO: nongreedy munch?
<|>
(pMunch isDigit)
<|>
(pSym '{' *> pMunch (/= '}') <* pSym '}' )
)
|
toothbrush/cco-bibtex2html
|
ParseBib/Parser.hs
|
gpl-3.0
| 3,172
| 0
| 15
| 953
| 519
| 280
| 239
| 34
| 1
|
module Web.Last.Group where
import Control.Applicative
import Control.Arrow
import Web.Last.Types
import Web.Last.Request
import qualified Web.Last.Parsing as P
import Text.JSON.Combinators
getMembers :: String -> Last (Paged (User,[Image]))
getMembers group = pagedRequest "group.getmembers" [("group",group)] [] pa pno
where pa = objOf $ inObj "members" $ llArr "user" $ P.user &&& (objOf $ llArr "image" P.image)
pno = objOf $ inObj "members" $ P.readInt <$> ll "totalPages" strJS
-- String is playcount
getWeeklyAlbumChart :: String -> Maybe String -> Maybe String -> Last [(Album,String)]
getWeeklyAlbumChart group from to = anonRequest "group.getweeklyalbumchart" [("group",group)] [("from",from),("to",to)] pa
where pa = objOf $ inObj "weeklyalbumchart" $ llArr "album" $ P.album &&& (objOf $ ll "playcount" strJS)
-- String is playcount
getWeeklyArtistChart :: String -> Maybe String -> Maybe String -> Last [(Artist,String)]
getWeeklyArtistChart group from to = anonRequest "group.getweeklyartistchart" [("group",group)] [("from",from),("to",to)] pa
where pa = objOf $ inObj "weeklyartistchart" $ llArr "artist" $ P.artist &&& (objOf $ ll "playcount" strJS)
getWeeklyChartList :: String -> Last [(String,String)]
getWeeklyChartList group = anonRequest "group.getweeklychartlist" [("group",group)] [] pa
where pa = objOf $ inObj "weeklychartlist" $ llArr "chart" $ objOf $ (ll "from" strJS) &&& (ll "to" strJS)
-- String is playcount
getWeeklyTrackChart :: String -> Maybe String -> Maybe String -> Last [(Track,String)]
getWeeklyTrackChart group from to = anonRequest "group.getweeklytrackchart" [("group",group)] [("from",from),("to",to)] pa
where pa = objOf $ inObj "weeklytrackchart" $ llArr "track" $ P.track &&& (objOf $ ll "playcount" strJS)
|
jamii/hs-last
|
src/Web/Last/Group.hs
|
gpl-3.0
| 1,797
| 0
| 12
| 270
| 652
| 351
| 301
| 23
| 1
|
-- TabCode - A parser for the Tabcode lute tablature language
--
-- Copyright (C) 2015-2017 Richard Lewis
-- Author: Richard Lewis <richard@rjlewis.me.uk>
-- This file is part of TabCode
-- TabCode is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- TabCode is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with TabCode. If not, see <http://www.gnu.org/licenses/>.
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module TabCode.Parser
( parseTabcode
, parseTabcodeStdIn
, parseTabcodeFile ) where
import Data.Vector()
import qualified Data.Vector as V
import Prelude hiding (words)
import System.IO (hPutStrLn, stderr)
import System.Exit (exitFailure)
import TabCode.Types
import TabCode.Options
import Text.Parsec (ParsecT)
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Number
tablature :: ParseMode -> GenParser Char st TabCode
tablature mode = do
rls <- option [] rules
words <- (tabword mode) `sepEndBy` (skipMany1 space)
eof
return $ TabCode rls (V.fromList words)
rules :: GenParser Char st [Rule]
rules = do
-- FIXME We need to allow files to start with comments but also not
-- suppress errors in incorrect <rules>
rls <- option [] $ try $ between (string "{<rules>") (string "</rules>}") $ do
many1 $ (try $ rule "notation") <|> (try $ rule "title") <|> (try $ rule "tuning_named")
<|> (try $ rule "rhythm-font") <|> (try $ rule "pitch") <|> (try $ rule "bass_tuning")
<|> (try $ rule "tuning") <|> (try $ rule "rhythm_noteheads")
spaces
return rls
rule :: String -> GenParser Char st Rule
rule r = do
spaces
nt <- between (string $ "<" ++ r ++ ">") (string $ "</" ++ r ++ ">") $ many1 $ noneOf "<"
spaces
return $ Rule r nt
tabword :: ParseMode -> GenParser Char st TabWord
tabword Strict = (try rest) <|> (try barLine) <|> (try meter) <|> (try commentWord) <|> (try systemBreak) <|> (try pageBreak) <|> chord
tabword Permissive = (try rest) <|> (try barLine) <|> (try meter) <|> (try commentWord) <|> (try systemBreak) <|> (try pageBreak) <|> (try chord) <|> (try invalid)
endOfWord :: GenParser Char st ()
endOfWord = (lookAhead $ try (do { space; return () })) <|> eof--try (do { c <- try eof; unexpected (show c) } <|> return "")
invalid :: GenParser Char st TabWord
invalid = do
pos <- getPosition
wrd <- manyTill anyChar endOfWord
if (length wrd) > 0
then return $ Invalid (sourceName pos) (sourceLine pos) (sourceColumn pos) wrd
else fail "FIXME Just consume any trailing whitespace"
chord :: GenParser Char st TabWord
chord = do
pos <- getPosition
rs <- option Nothing $ do { r <- rhythmSign; return $ Just r }
ns <- uniqueNotes $ many1 note
cmt <- option Nothing $ do { c <- try comment; return $ Just c }
endOfWord
return $ Chord (sourceLine pos) (sourceColumn pos) rs ns cmt
uniqueNotes :: ParsecT s u m [Note] -> ParsecT s u m [Note]
uniqueNotes parser = do
ns <- parser
if duplicateCoursesInNotes ns
then fail $ "Chord contains duplicate courses: " ++ (show $ coursesFromNotes ns)
else return ns
rhythmSign :: GenParser Char st RhythmSign
rhythmSign = do
dur <- duration
bt <- beat
dts <- dots
beam <- openBeam <|> closeBeam
-- FIXME if beam, lookAhead for tabword with closing beam
return $ RhythmSign dur bt dts beam
dots :: GenParser Char st Dot
dots = option NoDot (do { _ <- many1 (char '.'); return Dot })
beat :: GenParser Char st Beat
beat = option Simple (do { _ <- char '3'; return Compound })
beams :: Char -> (Duration -> Beam Duration) -> GenParser Char st (Maybe (Beam Duration))
beams c mkBeam = option Nothing $ do
cs <- many1 (char c)
return $ Just $ mkBeam (beamDuration (length cs))
openBeam :: GenParser Char st (Maybe (Beam Duration))
openBeam = beams '[' BeamOpen
closeBeam :: GenParser Char st (Maybe (Beam Duration))
closeBeam = beams ']' BeamClose
duration :: GenParser Char st Duration
duration = do
d <- oneOf "ZYTSEQHWBF"
return $ case d of
'Z' -> Semihemidemisemiquaver
'Y' -> Hemidemisemiquaver
'T' -> Demisemiquaver
'S' -> Semiquaver
'E' -> Quaver
'Q' -> Crotchet
'H' -> Minim
'W' -> Semibreve
'B' -> Breve
'F' -> Fermata
_ -> error $ "Invalid duration " ++ (show d)
rest :: GenParser Char st TabWord
rest = do
pos <- getPosition
rs <- rhythmSign
cmt <- option Nothing $ do { c <- try comment; return $ Just c }
endOfWord
return $ Rest (sourceLine pos) (sourceColumn pos) rs cmt
barLine :: GenParser Char st TabWord
barLine = do
pos <- getPosition
leftRpt <- option False $ do { char ':'; return True }
line <- (try dbl) <|> (try sgl)
rightRpt <- option False $ do { char ':'; return True }
nonC <- option Counting $ do { char '0'; return NotCounting }
dash <- option NotDashed $ do { char '='; return Dashed }
rep <- option Nothing addition
cmt <- option Nothing $ do { c <- try comment; return $ Just c }
endOfWord
if line == "|"
then return $ BarLine (sourceLine pos) (sourceColumn pos) (SingleBar (combineRepeat leftRpt rightRpt) rep dash nonC) cmt
else return $ BarLine (sourceLine pos) (sourceColumn pos) (DoubleBar (combineRepeat leftRpt rightRpt) rep dash nonC) cmt
where
sgl = string "|"
dbl = string "||"
addition = (try reprise) <|> (try nthTime)
reprise = between (char '(') (char ')') $ do
string "T=:\\R"
return $ Just Reprise
nthTime = between (char '(') (char ')') $ do
string "T+:\\"
time <- int
return $ Just $ NthTime time
combineRepeat True True = Just RepeatBoth
combineRepeat True False = Just RepeatLeft
combineRepeat False True = Just RepeatRight
combineRepeat _ _ = Nothing
meter :: GenParser Char st TabWord
meter = do
pos <- getPosition
char 'M'
char '('
m1 <- do { m <- digit <|> mensurSign; return $ Just m }
c1 <- cuts
p1 <- prol
arr <- option Nothing $ do { a <- char ':' <|> char ';'; return $ Just a }
m2 <- option Nothing $ do { t <- digit <|> mensurSign; return $ Just t }
c2 <- cuts
p2 <- prol
char ')'
cmt <- option Nothing $ do { c <- try comment; return $ Just c }
endOfWord
return $ mkMS pos arr m1 c1 p1 m2 c2 p2 cmt
where
mensurSign = char 'O' <|> char 'C' <|> char 'D'
cuts = option Nothing $ do { cs <- many1 $ char '/'; return $ Just cs }
prol = option Nothing $ do { ds <- char '.'; return $ Just ds }
mkMS pos (Just arrangement) mensur1 cut1 prolation1 mensur2 cut2 prolation2
| arrangement == ':' = Meter (sourceLine pos) (sourceColumn pos) $ VerticalMeterSign (mkMensur mensur1 cut1 prolation1) (mkMensur mensur2 cut2 prolation2)
| arrangement == ';' = Meter (sourceLine pos) (sourceColumn pos) $ HorizontalMeterSign (mkMensur mensur1 cut1 prolation1) (mkMensur mensur2 cut2 prolation2)
mkMS _ (Just _) _ _ _ _ _ _ = error "Invalid meter arrangement symbol"
mkMS pos Nothing mensur1 cut1 prolation1 _ _ _
= Meter (sourceLine pos) (sourceColumn pos) $ SingleMeterSign (mkMensur mensur1 cut1 prolation1)
mkMensur (Just 'O') Nothing (Just '.') = PerfectMajor
mkMensur (Just 'O') Nothing Nothing = PerfectMinor
mkMensur (Just 'C') Nothing (Just '.') = ImperfectMajor
mkMensur (Just 'C') Nothing Nothing = ImperfectMinor
mkMensur (Just 'O') (Just ['/']) (Just '.') = HalfPerfectMajor
mkMensur (Just 'O') (Just ['/']) Nothing = HalfPerfectMinor
mkMensur (Just 'C') (Just ['/']) (Just '.') = HalfImperfectMajor
mkMensur (Just 'C') (Just ['/']) Nothing = HalfImperfectMinor
mkMensur (Just 'D') Nothing (Just '.') = HalfImperfectMajor
mkMensur (Just 'D') Nothing Nothing = HalfImperfectMinor
mkMensur (Just ms) _ _ = Beats $ ((read [ms]) :: Int)
mkMensur Nothing _ _ = error "Invalid mensuration sign"
note :: GenParser Char st Note
note = (try trebNote) <|> (try bassNote) <|> bassNoteOpenAbbr
unorderedPair :: GenParser Char st (Maybe a) -> GenParser Char st (Maybe a) -> GenParser Char st (Maybe a, Maybe a)
unorderedPair p q =
p >>= \r -> case r of
Just _ -> do { s <- q; return (r, s) }
Nothing -> do { t <- q; u <- p; return (t, u) }
trebNote :: GenParser Char st Note
trebNote = do
f <- fret
c <- course
fng <- unorderedPair fingeringLeft fingeringRight
orn <- ornament
art <- articulation
con <- connecting
return $ Note c f fng orn art con
fret :: GenParser Char st Fret
fret = do
f <- oneOf ['a'..'n']
return $ case f of
'a' -> A
'b' -> B
'c' -> C
'd' -> D
'e' -> E
'f' -> F
'g' -> G
'h' -> H
'i' -> I
'j' -> J
'k' -> K
'l' -> L
'm' -> M
'n' -> N
_ -> error $ "Invalid fret symbol: " ++ (show f)
course :: GenParser Char st Course
course = do
c <- oneOf "123456"
return $ case c of
'1' -> One
'2' -> Two
'3' -> Three
'4' -> Four
'5' -> Five
'6' -> Six
_ -> error $ "Invalid course number: " ++ (show c)
bassNote :: GenParser Char st Note
bassNote = do
char 'X'
f <- fret
c <- bassCourse
fng <- unorderedPair fingeringLeft fingeringRight
orn <- ornament
art <- articulation
con <- connecting
return $ Note c f fng orn art con
bassCourse :: GenParser Char st Course
bassCourse = do
c <- many (char '/')
return $ Bass $ (length c) + 1
bassNoteOpenAbbr :: GenParser Char st Note
bassNoteOpenAbbr = do
char 'X'
c <- int
fng <- unorderedPair fingeringLeft fingeringRight
orn <- ornament
art <- articulation
con <- connecting
return $ Note (Bass c) A fng orn art con
fingeringLeft :: GenParser Char st (Maybe Fingering)
fingeringLeft = option Nothing $ try $ do
string "(F"
optional $ char 'l'
f <- finger
a <- attachment
char ')'
return $ Just $ FingeringLeft f a
fingeringRight :: GenParser Char st (Maybe Fingering)
fingeringRight = option Nothing $ (try abbr) <|> (try full)
where
abbr = do
f <- (try fingeringDots) <|> (try finger2Abbr) <|> (try rhThumb) <|> rhFinger2
return $ Just $ FingeringRight f Nothing
full = do
string "(F"
optional $ char 'r'
f <- (try finger) <|> (try fingeringDots) <|> (try finger2Abbr) <|> (try rhThumb) <|> rhFinger2
a <- attachment
char ')'
return $ Just $ FingeringRight f a
finger :: GenParser Char st Finger
finger = do
n <- oneOf "1234"
return $ case n of
'1' -> FingerOne
'2' -> FingerTwo
'3' -> FingerThree
'4' -> FingerFour
_ -> error $ "Invalid finger number: " ++ (show n)
fingeringDots :: GenParser Char st Finger
fingeringDots = do
d <- many1 $ char '.'
if (length d) > 4
then fail $ "Invalid fingering dots: " ++ (show d)
else return $ case (length d) of
1 -> FingerOne
2 -> FingerTwo
3 -> FingerThree
4 -> FingerFour
_ -> error $ "Invalid fingering dots: " ++ (show d)
finger2Abbr :: GenParser Char st Finger
finger2Abbr = char ':' >> return FingerTwo
rhThumb :: GenParser Char st Finger
rhThumb = char '!' >> return Thumb
rhFinger2 :: GenParser Char st Finger
rhFinger2 = char '"' >> return FingerTwo
attachmentNoColon :: GenParser Char st Attachment
attachmentNoColon = do
pos <- oneOf "12345678"
return $ case pos of
'1' -> PosAboveLeft
'2' -> PosAbove
'3' -> PosAboveRight
'4' -> PosLeft
'5' -> PosRight
'6' -> PosBelowLeft
'7' -> PosBelow
'8' -> PosBelowRight
_ -> error $ "Invalid attachment position: " ++ (show pos)
attachment :: GenParser Char st (Maybe Attachment)
attachment = option Nothing $ do
char ':'
a <- attachmentNoColon
return $ Just a
ornament :: GenParser Char st (Maybe Ornament)
ornament = option Nothing $ (try abbr) <|> (try full)
where
abbr = do
o <- oA1 <|> oB <|> oC1 <|> oC2 <|> oE <|> oF <|> oH
return $ Just o
oA1 = do { (try $ char ','); return $ OrnA (Just 1) Nothing }
oB = do { (try $ string "(C)"); return $ OrnB Nothing Nothing }
oC1 = do { (try $ char 'u'); return $ OrnC (Just 1) Nothing }
oC2 = do { (try $ char '<'); return $ OrnC (Just 2) Nothing }
oE = do { (try $ char '#'); return $ OrnE Nothing Nothing }
oF = do { (try $ char 'x'); return $ OrnF Nothing Nothing }
oH = do { (try $ char '~'); return $ OrnH Nothing Nothing }
full = do
between (char '(') (char ')') $ do
char 'O'
t <- oneOf "abcdefghijklm"
s <- optionMaybe int
pos <- option Nothing $ attachment
return $ Just $ case t of
'a' -> OrnA s pos
'b' -> OrnB s pos
'c' -> OrnC s pos
'd' -> OrnD s pos
'e' -> OrnE s pos
'f' -> OrnF s pos
'g' -> OrnG s pos
'h' -> OrnH s pos
'i' -> OrnI s pos
'j' -> OrnJ s pos
'k' -> OrnK s pos
'l' -> OrnL s pos
'm' -> OrnM s pos
_ -> error $ "Invalid ornament: " ++ (show t)
articulation :: GenParser Char st (Maybe Articulation)
articulation = option Nothing $ separee <|> ensemble
ensemble :: GenParser Char st (Maybe Articulation)
ensemble = try $ do
between (char '(') (char ')') $ do
char 'E'
return $ Just Ensemble
separee :: GenParser Char st (Maybe Articulation)
separee = try $ do
between (char '(') (char ')') $ do
char 'S'
dir <- direction
pos <- position
return $ Just $ Separee dir pos
where
direction = option Nothing $ do
d <- oneOf "ud"
return $ Just $ case d of
'u' -> SepareeUp
'd' -> SepareeDown
_ -> error $ "Invalid separee direction: " ++ (show d)
position = option Nothing $ do
char ':'
p <- oneOf "lr"
return $ Just $ case p of
'l' -> SepareeLeft
'r' -> SepareeRight
_ -> error $ "Invalid separee position: " ++ (show p)
connecting :: GenParser Char st (Maybe Connecting)
connecting = option Nothing $ slur <|> straight <|> curved
slur :: GenParser Char st (Maybe Connecting)
slur = try $ do
between (char '(') (char ')') $ do
char 'C'
dir <- direction
return $ Just (Slur dir)
where
direction = option SlurDown $ do
d <- oneOf "ud"
return $ case d of
'u' -> SlurUp
'd' -> SlurDown
_ -> error $ "Invalid slur direction: " ++ (show d)
straight :: GenParser Char st (Maybe Connecting)
straight = try $ do
between (char '(') (char ')') $ do
char 'C'
cid <- int
pos <- attachment
if cid < 0
then return $ Just (StraightFrom cid pos)
else return $ Just (StraightTo cid pos)
curved :: GenParser Char st (Maybe Connecting)
curved = try $ do
between (char '(') (char ')') $ do
char 'C'
cid <- int
char ':'
dir <- oneOf "ud"
pos <- optionMaybe attachmentNoColon
return $ mkCurved cid dir pos
where
mkCurved i 'u' p
| i >= 0 = Just (CurvedUpFrom i p)
| i < 0 = Just (CurvedUpTo i p)
mkCurved i 'd' p
| i >= 0 = Just (CurvedDownFrom i p)
| i < 0 = Just (CurvedDownTo i p)
mkCurved _ d _ =
error $ "Invalid curved connecting line direction: " ++ (show d)
comment :: GenParser Char st Comment
comment = do
manyTill (char ' ') (try $ char '{')
notFollowedBy $ (try $ string "^}") <|> (try $ string ">}{^}")
c <- manyTill anyChar (try $ char '}')
return $ Comment c
commentWord :: GenParser Char st TabWord
commentWord = do
pos <- getPosition
c <- comment
endOfWord
return $ CommentWord (sourceLine pos) (sourceColumn pos) c
systemBreak :: GenParser Char st TabWord
systemBreak = do
pos <- getPosition
string "{^}"
cmt <- option Nothing $ do { c <- try comment; return $ Just c }
endOfWord
return $ SystemBreak (sourceLine pos) (sourceColumn pos) cmt
pageBreak :: GenParser Char st TabWord
pageBreak = do
pos <- getPosition
string "{>}{^}"
cmt <- option Nothing $ do { c <- try comment; return $ Just c }
endOfWord
return $ PageBreak (sourceLine pos) (sourceColumn pos) cmt
parseTabcode :: TCOptions -> String -> Either ParseError TabCode
parseTabcode opts s = parse (tablature $ parseMode opts) "" s
parseTabcodeStdIn :: TCOptions -> IO TabCode
parseTabcodeStdIn opts = getContents >>= (return . (parseTabcode opts)) >>= either reportErr return
parseTabcodeFile :: TCOptions -> FilePath -> IO TabCode
parseTabcodeFile opts fileName = parseFromFile (tablature $ parseMode opts) fileName >>= either reportErr return
reportErr :: ParseError -> IO a
reportErr err = do
hPutStrLn stderr $ "Error: " ++ show err
exitFailure
|
TransformingMusicology/tabcode-haskell
|
src/TabCode/Parser.hs
|
gpl-3.0
| 16,975
| 0
| 21
| 4,333
| 6,427
| 3,099
| 3,328
| 436
| 15
|
module Main where
import Hero.Game(runGame)
main :: IO ()
main = do putStr "Enter your name: "
name <- getLine
runGame name
|
brennie/hero-old
|
Main.hs
|
gpl-3.0
| 148
| 0
| 7
| 46
| 48
| 24
| 24
| 6
| 1
|
import System.IO
import Data.List
import GHC.Show
{-
fac 1 = 1
fac n = n * (fac (n-1))
main = print (fac 5)
-}
{-
fac n = if (n==1) then 1
else n * fac(n-1)
--main = print (fac 6)
-}
{-
imap f [] = []
imap f (x:xs) = f x: imap f xs
main = print (imap fac [1..10])
-}
{-
length1 [] = 0
length1 (x:xs) = 1 + length1 xs
main = print (length1 [1..10])
-}
{-
empty [] = True
empty _ = False
--main = print (empty [])
--main = print (empty ['1','2'])
--main = print (empty 'x')
-}
{-
x a b|(a>0) = 2
|(b>0) = 3
main = print (x (-1) 2)
-}
{-
--temp " "=[]
temp (x:xs)|(xs == ' ')=[x]
| otherwise=[x]++temp xs
main = print (temp "hieie")
-}
{-
iwords ""=[""]
iwords (x:xs)|(x ==' ') = "":(iwords xs)
|otherwise = (x:head (iwords xs)):tail (iwords xs)
--main = print (iwords "hi hello whatsup")
--a = [1,2,3]
--a = a ++ ([6,7])
--main = print (a)
-}
{-
iunwords []=""
iunwords [x]=x
iunwords (x:xs)=x++(" ")++(iunwords xs)
--main = print (iunwords (["hi","hello","ok"]))
-}
--temp :: [String]->[String]
{-
temp [""]=[""]
temp (x:xs)|(length xs)>1=[x,","]++(temp xs)
|otherwise=[x,"and",xs !! 0]
--main = print (temp ["hi","hello","oo"])
punctuate ""=""
punctuate x=(iunwords . temp . iwords) x
main = print (punctuate ("hi hello ok"))
-}
{-
type Point=(Double,Double)
temp::Point->Double
temp a=fst a + snd a
main = print (temp (1,2))
-}
{-
a=(1,2,3)
--temp [] = 0
temp (x1,x2,x3)=x1+x2+x3
main = print (temp a)
-}
{-
safeHead (x:xs)=Just x
safeHead _=Nothing
main = print (safeHead ([1,2]))
-}
{-
getInt :: IO Int
getInt = readLn
fac 1 = 1
fac n = n * (fac (n-1))
facPrint = print.fac
main = (getInt >>= facPrint)
-}
{-
getInt :: IO Int
getInt = readLn
nmod x|x>0 = x
|otherwise = 0-x
main = do putStrLn("Enter a number")
n <- getInt
m <- getInt
print(nmod (n+m))
-}
{-
--does not works!!
modsum x1 x2 = do v1 <- mod x1
v2 <- mod x2
return (v1+v2)
main = print (modsum (-2) 3)
-}
power x n
| n == 0 = 1
| x == 0 = 0
| (even n) == True = ( power x (n `div` 2) ) * ( power x (n `div` 2) )
| (odd n) == True = x * ( power x ((n - 1) `div` 2)) * ( power x ((n - 1) `div` 2) )
main = print (power 3 2)
{-
fib 0=0
fib 1=1
fib x = (fib (x-1)) + (fib (x-2))
main = print (fib 5)
-}
|
rahulaaj/ML-Library
|
src/Tutorials/factorial.hs
|
gpl-3.0
| 2,307
| 0
| 13
| 582
| 215
| 122
| 93
| 9
| 1
|
{- This file is part of PhoneDirectory.
Copyright (C) 2009 Michael Steele
PhoneDirectory is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PhoneDirectory is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PhoneDirectory. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE OverloadedStrings #-}
module Document
( Document (..)
, mkDocument
, renderDoc
, sortDoc
, toCSVRecords
) where
import Control.Applicative
import Control.Monad (foldM_, mzero)
import Data.Function
import Data.List
import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as A
import Graphics.PDF
import Text.CSV.ByteString (Record)
import LineItem
import ContactInfo as C
import Name
import qualified Organization as O
import PageProperties
import UnitConversion
-- |A Document contains a revision date and organizations to display.
data Document
= Document
{ -- |This gets set whenever the document is ready to be
-- printed. Because of this, it's not really necessary at this
-- point.
dRevised :: String
-- |Organizations to print.
, dOrganizations :: [O.Organization]
, pageProperties :: PageProperties
} deriving (Eq)
instance A.ToJSON Document where
toJSON d = A.object
[ "revised" .= A.toJSON (dRevised d)
, "organizations" .= A.toJSON (dOrganizations d)
, "pageProperties" .= A.toJSON (pageProperties d)]
instance A.FromJSON Document where
parseJSON (A.Object v) = Document
<$> v .: "revised"
<*> v .: "organizations"
<*> (v .: "pageProperties" <|> return mkPageProperties)
parseJSON _ = mzero
toCSVRecords :: Document -> [Record]
toCSVRecords (Document _ ox _) = concatMap O.toCSV ox
-- |Font used only for the title.
fontTitle :: PDFFont
fontTitle = PDFFont Times_Bold 18
-- |Font used for all header information besides the title.
fontSubtitle :: PDFFont
fontSubtitle = PDFFont Helvetica 10
titleString :: PDFString
titleString = toPDFString "PHONE DIRECTORY"
titleWidth :: PDFUnits
titleWidth = PDFUnits $ textWidth fontTitle titleString
-- |Distance from left edge to draw the date string.
dateInset :: PageProperties -> PDFUnits
dateInset p = asPDFUnits $ leftMargin p + Inches (1 / 16)
-- |Convenient way to make a Document.
mkDocument :: Document
mkDocument = Document
{ dRevised = ""
, dOrganizations = []
, pageProperties = mkPageProperties }
-- |Deep sort the document and all organizations that are a part of it.
sortDoc :: Strategy
-> Document -- ^Document to deep sort
-> Document -- ^An identical Document that has possibly been
-- rearranged.
sortDoc ns d =
d { dOrganizations = sortBy (C.compareCI ns `on` O.oInfo)
$ map (O.sortOrg ns) (dOrganizations d) }
-- | Draw a Document on its own page.
renderDoc :: Strategy
-> Document -- ^Document to append a page for.
-> String -- ^Subtitle
-> PDF()
renderDoc s d lbl=
let revised = toPDFString $ "Revised: " ++ dRevised d
columns = flowCols (intercalate [Divider] . map (O.toLineItems s) $ dOrganizations d) 4
dateRise = titleRise - (PDFUnits $ getHeight fontSubtitle)
- asPDFUnits sixteenthInch
gridRise = dateRise - asPDFUnits sixteenthInch
lbl' = toPDFString lbl
lblInset = (width - (PDFUnits $ textWidth fontSubtitle lbl')) / 2.0
prop = pageProperties d
colWidth = asPDFUnits $ (pageWidth prop - leftMargin prop - rightMargin prop) / 4.0
titleInset = (width - titleWidth) / 2.0
titleRise = height - (asPDFUnits . topMargin $ prop)
- (PDFUnits $ getHeight fontTitle)
width = asPDFUnits . pageWidth $ prop
height = asPDFUnits . pageHeight $ prop
in do
p <- addPage Nothing
drawWithPage p $ do
drawText $ text fontTitle (unPDFUnits titleInset)
(unPDFUnits titleRise) titleString
drawText $ text fontSubtitle (unPDFUnits . dateInset $ prop)
(unPDFUnits dateRise) revised
drawText $ text fontSubtitle (unPDFUnits lblInset)
(unPDFUnits dateRise) lbl'
foldM_ (drawColumn colWidth)
((unPDFUnits . asPDFUnits . leftMargin $ prop)
:+ unPDFUnits gridRise) columns
|
mikesteele81/Phone-Directory
|
src/Document.hs
|
gpl-3.0
| 4,742
| 0
| 18
| 1,155
| 999
| 538
| 461
| 92
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Css.FourOhFourCss where
import Clay
-- | CSS for the 404 page.
fourOhFourStyles :: Css
fourOhFourStyles = do
"#contentDiv" ? do
margin nil (px 25) nil (px 25)
"#picDiv" ? do
margin nil (px 25) nil (px 25)
"#links" ? do
"list-style-type" -: "none"
|
cchens/courseography
|
hs/Css/FourOhFourCss.hs
|
gpl-3.0
| 328
| 0
| 12
| 87
| 97
| 48
| 49
| 11
| 1
|
{- Copyright 2013 Gabriel Gonzalez
This file is part of the Suns Search Engine
The Suns Search Engine is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or (at your
option) any later version.
The Suns Search Engine is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
the Suns Search Engine. If not, see <http://www.gnu.org/licenses/>.
-}
{-| High-level Suns-specific AMQP routines designed to interface with the types
the search engine requires.
-}
{-# LANGUAGE OverloadedStrings #-}
module AMQP.Proxy
( -- * AMQP Interaction
Version
, AMQPHandle(..)
, withAMQP
) where
import qualified AMQP.Error as AE
import AMQP.Proxy.Core (listen)
import AMQP.Types (CorrelationID, ExchangeName, HostName, RoutingKey)
import Atom (Atom, atomToRecord)
import Control.Applicative ((<$>), (<*>))
import Control.Error (note)
import Control.Exception (bracket)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT(MaybeT))
import Data.Aeson (decode')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Monoid ((<>))
import Data.Text (Text)
import Log (debug, info, warn)
import qualified Network.AMQP as A
import qualified Network.AMQP.Types as A
import Password (Password, getPassword)
import PDB (PDBID)
import Pipes (Producer, for, every)
import Request (Request)
import Search (Response(..))
{-| A 'Text' string identifying the protocol version, used to connect clients
with the appropriate search engine when necessary to support old protocols.
-}
type Version = Text
validMessage :: A.Message -> MaybeT IO ((RoutingKey, CorrelationID), Request)
validMessage message = MaybeT $ do
let correlationID = A.msgCorrelationID message
e = (,)
<$> (note "Message missing \"replyTo\" field" $ A.msgReplyTo message)
<*> (note "Message parse failed" $ decode' $ A.msgBody $ message)
case e of
Left str -> do
warn str
return Nothing
Right (replyTo, req) -> return $ Just ((replyTo, correlationID), req)
publish
:: A.Channel
-> ExchangeName
-> ((RoutingKey, CorrelationID), Response (PDBID, [Atom]))
-> IO ()
publish channel exchangeName ((routingKey, correlationID), mAtoms) = do
let body = case mAtoms of
Done -> BL.singleton '0'
Result (pdbID, atoms) -> BL.concat
[ BL.singleton '1'
, BL.pack pdbID
, BL.fromChunks [BS.unlines $ map atomToRecord atoms]
]
Timeout -> BL.singleton '2'
Error str -> BL.cons '3' (BL.pack str)
message = A.newMsg
{ A.msgBody = body
, A.msgCorrelationID = correlationID
}
_ <- A.publishMsg channel exchangeName routingKey message
return ()
{-| A high-level wrapper around an AMQP connection providing a way to read
client requests and respond with search results
-}
data AMQPHandle = AMQPHandle
{ requests
:: Producer ((RoutingKey, CorrelationID), Request) IO ()
-- ^ A 'Producer' that outputs client requests from the message queue,
-- terminating if the connection is lost.
, respond
:: ((RoutingKey, CorrelationID), Response (PDBID, [Atom])) -> IO ()
-- ^ Command to publish a search result to the message queue
}
{-| Safely acquire an 'AMQPHandle'
Requires the server address, message queue password for @suns-server@ and
the protocol version
-}
withAMQP :: HostName -> Password -> Version -> (AMQPHandle -> IO r) -> IO r
withAMQP hostName password version k = bracket
(do connection <- A.openConnection
hostName
"suns-vhost"
"suns-server"
(getPassword password)
channel <- A.openChannel connection
let xReqs = "suns-exchange-requests"
AE.declareExchange channel $ A.newExchange
{ A.exchangeName = xReqs
, A.exchangeType = "direct"
, A.exchangePassive = True
, A.exchangeDurable = True
, A.exchangeAutoDelete = False
, A.exchangeInternal = False
}
let xResps = "suns-exchange-responses"
AE.declareExchange channel $ A.newExchange
{ A.exchangeName = xResps
, A.exchangeType = "direct"
, A.exchangePassive = True
, A.exchangeDurable = True
, A.exchangeAutoDelete = False
, A.exchangeInternal = False
}
let qName = "suns-queue-" <> version
AE.declareQueue channel $ A.QueueOpts
qName -- queueName
True -- queuePassive
True -- queueDurable
False -- queueExclusive
False -- queueAutoDelete
(A.FieldTable M.empty) -- queueHeaders
listener <- listen channel qName A.Ack
let close = A.closeConnection connection
return
( AMQPHandle
{ requests = for listener $ \(msg, _) -> do
lift $ info "Request received"
lift $ debug $ (++ "\n") $ BL.unpack $ A.msgBody msg
every (validMessage msg)
, respond = publish channel xResps
}
, close
) )
(\(_ , close) -> close )
(\(handle, _ ) -> k handle)
|
Gabriel439/suns-search
|
src/AMQP/Proxy.hs
|
gpl-3.0
| 6,023
| 0
| 20
| 1,850
| 1,234
| 690
| 544
| 109
| 4
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Drive.Changes.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists changes for a user.
--
-- /See:/ <https://developers.google.com/drive/ Drive API Reference> for @drive.changes.list@.
module Network.Google.Resource.Drive.Changes.List
(
-- * REST Resource
ChangesListResource
-- * Creating a Request
, changesList
, ChangesList
-- * Request Lenses
, clRestrictToMyDrive
, clSpaces
, clPageToken
, clPageSize
, clIncludeRemoved
) where
import Network.Google.Drive.Types
import Network.Google.Prelude
-- | A resource alias for @drive.changes.list@ method which the
-- 'ChangesList' request conforms to.
type ChangesListResource =
"drive" :>
"v3" :>
"changes" :>
QueryParam "pageToken" Text :>
QueryParam "restrictToMyDrive" Bool :>
QueryParam "spaces" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "includeRemoved" Bool :>
QueryParam "alt" AltJSON :> Get '[JSON] ChangeList
-- | Lists changes for a user.
--
-- /See:/ 'changesList' smart constructor.
data ChangesList = ChangesList'
{ _clRestrictToMyDrive :: !Bool
, _clSpaces :: !Text
, _clPageToken :: !Text
, _clPageSize :: !(Textual Int32)
, _clIncludeRemoved :: !Bool
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChangesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clRestrictToMyDrive'
--
-- * 'clSpaces'
--
-- * 'clPageToken'
--
-- * 'clPageSize'
--
-- * 'clIncludeRemoved'
changesList
:: Text -- ^ 'clPageToken'
-> ChangesList
changesList pClPageToken_ =
ChangesList'
{ _clRestrictToMyDrive = False
, _clSpaces = "drive"
, _clPageToken = pClPageToken_
, _clPageSize = 100
, _clIncludeRemoved = True
}
-- | Whether to restrict the results to changes inside the My Drive
-- hierarchy. This omits changes to files such as those in the Application
-- Data folder or shared files which have not been added to My Drive.
clRestrictToMyDrive :: Lens' ChangesList Bool
clRestrictToMyDrive
= lens _clRestrictToMyDrive
(\ s a -> s{_clRestrictToMyDrive = a})
-- | A comma-separated list of spaces to query within the user corpus.
-- Supported values are \'drive\', \'appDataFolder\' and \'photos\'.
clSpaces :: Lens' ChangesList Text
clSpaces = lens _clSpaces (\ s a -> s{_clSpaces = a})
-- | The token for continuing a previous list request on the next page. This
-- should be set to the value of \'nextPageToken\' from the previous
-- response or to the response from the getStartPageToken method.
clPageToken :: Lens' ChangesList Text
clPageToken
= lens _clPageToken (\ s a -> s{_clPageToken = a})
-- | The maximum number of changes to return per page.
clPageSize :: Lens' ChangesList Int32
clPageSize
= lens _clPageSize (\ s a -> s{_clPageSize = a}) .
_Coerce
-- | Whether to include changes indicating that items have left the view of
-- the changes list, for example by deletion or lost access.
clIncludeRemoved :: Lens' ChangesList Bool
clIncludeRemoved
= lens _clIncludeRemoved
(\ s a -> s{_clIncludeRemoved = a})
instance GoogleRequest ChangesList where
type Rs ChangesList = ChangeList
type Scopes ChangesList =
'["https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.appdata",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.metadata",
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.photos.readonly",
"https://www.googleapis.com/auth/drive.readonly"]
requestClient ChangesList'{..}
= go (Just _clPageToken) (Just _clRestrictToMyDrive)
(Just _clSpaces)
(Just _clPageSize)
(Just _clIncludeRemoved)
(Just AltJSON)
driveService
where go
= buildClient (Proxy :: Proxy ChangesListResource)
mempty
|
rueshyna/gogol
|
gogol-drive/gen/Network/Google/Resource/Drive/Changes/List.hs
|
mpl-2.0
| 4,974
| 0
| 16
| 1,208
| 644
| 381
| 263
| 98
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.CreateGroup
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new group.
--
-- For information about the number of groups you can create, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities>
-- in the /IAM User Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateGroup.html AWS API Reference> for CreateGroup.
module Network.AWS.IAM.CreateGroup
(
-- * Creating a Request
createGroup
, CreateGroup
-- * Request Lenses
, cgPath
, cgGroupName
-- * Destructuring the Response
, createGroupResponse
, CreateGroupResponse
-- * Response Lenses
, cgrsResponseStatus
, cgrsGroup
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createGroup' smart constructor.
data CreateGroup = CreateGroup'
{ _cgPath :: !(Maybe Text)
, _cgGroupName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cgPath'
--
-- * 'cgGroupName'
createGroup
:: Text -- ^ 'cgGroupName'
-> CreateGroup
createGroup pGroupName_ =
CreateGroup'
{ _cgPath = Nothing
, _cgGroupName = pGroupName_
}
-- | The path to the group. For more information about paths, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers>
-- in the /Using IAM/ guide.
--
-- This parameter is optional. If it is not included, it defaults to a
-- slash (\/).
cgPath :: Lens' CreateGroup (Maybe Text)
cgPath = lens _cgPath (\ s a -> s{_cgPath = a});
-- | The name of the group to create. Do not include the path in this value.
cgGroupName :: Lens' CreateGroup Text
cgGroupName = lens _cgGroupName (\ s a -> s{_cgGroupName = a});
instance AWSRequest CreateGroup where
type Rs CreateGroup = CreateGroupResponse
request = postQuery iAM
response
= receiveXMLWrapper "CreateGroupResult"
(\ s h x ->
CreateGroupResponse' <$>
(pure (fromEnum s)) <*> (x .@ "Group"))
instance ToHeaders CreateGroup where
toHeaders = const mempty
instance ToPath CreateGroup where
toPath = const "/"
instance ToQuery CreateGroup where
toQuery CreateGroup'{..}
= mconcat
["Action" =: ("CreateGroup" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"Path" =: _cgPath, "GroupName" =: _cgGroupName]
-- | Contains the response to a successful CreateGroup request.
--
-- /See:/ 'createGroupResponse' smart constructor.
data CreateGroupResponse = CreateGroupResponse'
{ _cgrsResponseStatus :: !Int
, _cgrsGroup :: !Group
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateGroupResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cgrsResponseStatus'
--
-- * 'cgrsGroup'
createGroupResponse
:: Int -- ^ 'cgrsResponseStatus'
-> Group -- ^ 'cgrsGroup'
-> CreateGroupResponse
createGroupResponse pResponseStatus_ pGroup_ =
CreateGroupResponse'
{ _cgrsResponseStatus = pResponseStatus_
, _cgrsGroup = pGroup_
}
-- | The response status code.
cgrsResponseStatus :: Lens' CreateGroupResponse Int
cgrsResponseStatus = lens _cgrsResponseStatus (\ s a -> s{_cgrsResponseStatus = a});
-- | Information about the group.
cgrsGroup :: Lens' CreateGroupResponse Group
cgrsGroup = lens _cgrsGroup (\ s a -> s{_cgrsGroup = a});
|
olorin/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/CreateGroup.hs
|
mpl-2.0
| 4,452
| 0
| 14
| 958
| 632
| 382
| 250
| 80
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module RenderDocs where
import CMark
import Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.Pretty (renderHtml)
import Text.Blaze.Internal (stringValue)
import Data.Text.Lazy as T
import Data.Text.Lazy.Encoding as E
import Data.Text as Text
import System.Directory
import qualified Data.Map as Map
import Debug.Trace
import Obj
import Types
import Util
saveDocsForEnvs :: Project -> [(SymPath, Env)] -> IO ()
saveDocsForEnvs ctx envs =
let dir = projectDocsDir ctx
title = projectTitle ctx
allEnvNames = (fmap (getModuleName . snd) envs)
in do mapM_ (saveDocsForEnv ctx allEnvNames) envs
writeFile (dir ++ "/" ++ title ++ "_index.html") (projectIndexPage ctx allEnvNames)
putStrLn ("Generated docs to '" ++ dir ++ "'")
projectIndexPage :: Project -> [String] -> String
projectIndexPage ctx moduleNames =
let logo = projectDocsLogo ctx
url = projectDocsURL ctx
css = projectDocsStyling ctx
htmlHeader = toHtml $ projectTitle ctx
htmlDoc = commonmarkToHtml [optSafe] $ Text.pack $ projectDocsPrelude ctx
html = renderHtml $ docTypeHtml $
do headOfPage css
H.body $
do H.div ! A.class_ "content" $
do H.a ! A.href (H.stringValue url) $
do H.div ! A.class_ "logo" $
do H.img ! A.src (H.stringValue logo) ! A.alt "Logo"
moduleIndex moduleNames
H.div $
do H.h1 htmlHeader
(preEscapedToHtml htmlDoc)
in html
headOfPage :: String -> H.Html
headOfPage css =
H.head $
do H.meta ! A.charset "UTF-8"
H.meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
H.link ! A.rel "stylesheet" ! A.href (H.stringValue css)
getModuleName :: Env -> String
getModuleName env =
case envModuleName env of
Just hasName -> hasName
Nothing -> "Global"
saveDocsForEnv :: Project -> [String] -> (SymPath, Env) -> IO ()
saveDocsForEnv ctx moduleNames (pathToEnv, env) =
do let SymPath _ moduleName = pathToEnv
dir = projectDocsDir ctx
fullPath = dir ++ "/" ++ moduleName ++ ".html"
string = renderHtml (envToHtml env ctx (show pathToEnv) moduleNames)
createDirectoryIfMissing False dir
writeFile fullPath string
envToHtml :: Env -> Project -> String -> [String] -> H.Html
envToHtml env ctx moduleName moduleNames =
let title = projectTitle ctx
css = projectDocsStyling ctx
in H.docTypeHtml $
do headOfPage css
H.body $
do H.div ! A.class_ "content" $
do H.div ! A.class_ "logo" $
do H.a ! A.href "http://github.com/carp-lang/Carp" $
do H.img ! A.src "logo.png"
--span_ "CARP DOCS FOR"
H.div ! A.class_ "title" $ (toHtml title)
moduleIndex moduleNames
H.h1 (toHtml moduleName)
mapM_ (binderToHtml . snd) (Prelude.filter shouldEmitDocsForBinder (Map.toList (envBindings env)))
shouldEmitDocsForBinder :: (String, Binder) -> Bool
shouldEmitDocsForBinder (name, Binder meta xobj) =
not (metaIsTrue meta "hidden")
moduleIndex :: [String] -> H.Html
moduleIndex moduleNames =
do H.div ! A.class_ "index" $
H.ul $ do mapM_ moduleLink moduleNames
moduleLink :: String -> H.Html
moduleLink name =
H.li $ H.a ! A.href (stringValue (name ++ ".html")) $ (toHtml name)
binderToHtml :: Binder -> H.Html
binderToHtml (Binder meta xobj) =
let name = getSimpleName xobj
maybeNameAndArgs = getSimpleNameWithArgs xobj
description = getBinderDescription xobj
typeSignature = case ty xobj of
Just t -> show t
Nothing -> ""
metaMap = getMeta meta
docString = case Map.lookup "doc" metaMap of
Just (XObj (Str s) _ _) -> s
Just found -> pretty found
Nothing -> ""
htmlDoc = commonmarkToHtml [optSafe] $ Text.pack docString
in do H.div ! A.class_ "binder" $
do H.a ! A.class_ "anchor" ! A.href (stringValue ("#" ++ name)) $
do H.h3 ! A.id (stringValue name) $ (toHtml name)
H.div ! A.class_ "description" $ (toHtml description)
H.p ! A.class_ "sig" $ (toHtml typeSignature)
case maybeNameAndArgs of
Just nameAndArgs -> H.pre ! A.class_ "args" $ toHtml nameAndArgs
Nothing -> H.span $ toHtml (""::String)
H.p ! A.class_ "doc" $ (preEscapedToHtml htmlDoc)
--p_ (toHtml (description))
|
eriksvedang/Carp
|
src/RenderDocs.hs
|
mpl-2.0
| 5,056
| 0
| 29
| 1,672
| 1,534
| 757
| 777
| 110
| 5
|
module Number where
import Debug.Trace
import Data.List (unfoldr)
import Data.Maybe (listToMaybe)
import System.Random
type Modulo = Integer
type Exponent = Integer
type Seed = StdGen
type Range = (Integer,Integer)
gcdx :: Integer -> Integer -> (Integer,Integer,Integer)
gcdx a b | a>=b = gcdx' a b
| otherwise = (d,t,s)
where (d,s,t)=gcdx' b a
gcdx' a b | r == 0 = (b,0,1)
| otherwise = (d,t,s-q*t)
where r = mod a b
q = div a b
(d,s,t) = gcdx' b r
divisible a d = mod a d == 0
factorPowers d n | divisible n d = (power+1,number)
| otherwise = (0,n)
where (power,number) = factorPowers d (div n d)
-- modularPower :: Integer -> Integer -> Modulo -> Integer
-- modularPower 0 n x = 1
-- modularPower a n x = mod (x* (modularPower (a-1) n x)) n
modularPowerLinear 0 n x = 1
modularPowerLinear a n x = mod ( x * (modularPower (a-1) n x ) ) n
-- x^a = x^(d*2+r) = (x^2)^d+r
modularPower :: Exponent -> Modulo -> Integer -> Integer
modularPower 0 n x = 1
modularPower a n x | r == 0 = mod call n
| otherwise = mod (call * x) n
where (d,r) = divMod a 2
call = (modularPower d n x' )
x' = mod (x*x) n
modularInverse :: Integer -> Modulo -> Integer
modularInverse a n = t
where (d,s,t)=gcdx n a
positiveModularInverse a n = positiveEquivalent inverse n
where inverse = modularInverse a n
-- positive equivalent of a mod n
positiveEquivalent a n | a >= 0 = a
| otherwise =(a + difference)
where q = abs $ div a n
difference = n * q
randomInteger :: Range -> Seed -> (Integer,Seed)
randomInteger r s = randomR r s
generateRandomNumberUntil :: (Integer -> Bool) -> (Integer,Integer) -> Seed -> (Integer,Seed)
generateRandomNumberUntil p range seed | p newRandom = (newRandom,seed')
| otherwise = generateRandomNumberUntil p range seed'
where (newRandom,seed') = randomInteger range seed
generateRandomNumber range seed = generateRandomNumberUntil (const True) range seed
generateRandomPrime = generateRandomNumberUntil isPrime
isOdd n = mod n 2 == 1
generateRandomOdd = generateRandomNumberUntil isOdd
generateRandomPrimeMillerRabin k range seed | result == ProbablyPrime = (newRandom,seed'')
| otherwise = generateRandomPrimeMillerRabin k range seed'
where (newRandom,seed') = generateRandomOdd range seed
(result,seed'')= millerRabin newRandom k seed'
hasInverseModulo n x = d==1
where (d,s,t) = gcdx n x
generateRandomWithInverse n = generateRandomNumberUntil (hasInverseModulo n)
data MillerRabinResult = ProbablyPrime | Composite deriving (Eq,Show)
millerRabin 1 k seed = (ProbablyPrime,seed)
millerRabin 2 k seed = (ProbablyPrime,seed)
millerRabin n k seed = millerRabin' (factorPowers 2 (n-1)) n k seed
-- 2^s * d = n
-- k= number of trials
millerRabin' (s,d) n 0 seed = (ProbablyPrime,seed)
millerRabin' (s,d) n k seed | composite == Composite = (Composite,seed')
| otherwise = millerRabin' (s,d) n (k-1) seed'
where (composite,seed') = checkCompositeness s d n seed
checkCompositeness s d n seed | x ==1 || x==n-1 = (ProbablyPrime,seed')
| otherwise = (checkCompositeness' s x n , seed')
where (a,seed') = generateRandomNumber (2,n-2) seed
x = (modularPower d n a)
checkCompositeness' 0 x n = Composite
checkCompositeness' s x n | x == 1 = Composite
| x == n-1 = ProbablyPrime
| otherwise = checkCompositeness' (s-1) x' n
where x'= modularPower 2 n x
bigRandom = [7919,49979687]
{- 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153,
614865347947412054998871912138166461049314312490725112873271296842414474254904548663296952332559110113044820194651149624596490803942453669130989178203975581114455363503708800628353373554758750709244049339485669,
290245329165570025116016487217740287508837913295571609463914348778319654489118435855243301969001872061575755804802874062021927719647357060447135321577028929269578574760547268310055056867386875959045119093967972205124270441648450825188877095173754196346551 952542599226295413057787340278528252358809329]
-}
testGcd = gcdx 8 20 == (4,-2,1)
testMillerBig = map (\n -> millerRabin n 1 (mkStdGen 0)) bigRandom
testMiller = millerRabin 7 1 (mkStdGen 0)
testGenerateRandomNumber = generateRandomNumber (2^512,2^1024) seed
where seed = mkStdGen 0
testCheckCompositeness n = (r,d,a)
where (s,d) = (factorPowers 2 n)
seed = mkStdGen 0
r = checkCompositeness s d n seed
a = modularPower d n 2
testCheckCompositeness2 n = checkCompositeness' s x n
where (s,d) = (factorPowers 2 n)
x= 3
-- deterministic isPrime
isPrime n = n > 1 && factors n == [n]
factors n = unfoldr (\(d,n) -> listToMaybe [(x, (x, div n x)) | n > 1,
x <- [d..isqrt n] ++ [n], rem n x == 0]) (2,n)
isqrt n = floor . sqrt . fromIntegral $ n
|
facundoq/toys
|
rsa/number.hs
|
agpl-3.0
| 5,722
| 0
| 14
| 1,706
| 1,771
| 927
| 844
| 92
| 1
|
{-# LANGUAGE ForeignFunctionInterface, TypeFamilies, MultiParamTypeClasses,
FlexibleInstances, TypeSynonymInstances,
EmptyDataDecls, ExistentialQuantification, ScopedTypeVariables #-}
module HEP.Jet.FastJet.Class.TNamed.RawType where
-- import Foreign.Ptr
import Foreign.ForeignPtr
-- import Foreign.Marshal.Array
import HEP.Jet.FastJet.TypeCast
data RawTNamed
newtype TNamed = TNamed (ForeignPtr RawTNamed) deriving (Eq, Ord, Show)
instance FPtr TNamed where
type Raw TNamed = RawTNamed
get_fptr (TNamed fptr) = fptr
cast_fptr_to_obj = TNamed
|
wavewave/HFastJet
|
oldsrc/HEP/Jet/FastJet/Class/TNamed/RawType.hs
|
lgpl-2.1
| 588
| 0
| 8
| 97
| 93
| 56
| 37
| -1
| -1
|
-- second to last elements of list
f :: [a] -> a
f [] = error "Empty list provided, requires length > 0"
f (x:y:[]) = x
f (x:xs) = f xs
|
ekalosak/haskell-practice
|
pr2.hs
|
lgpl-3.0
| 137
| 0
| 9
| 33
| 66
| 34
| 32
| 4
| 1
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-|
Module : Haskoin.Crypto.Hash
Copyright : No rights reserved
License : MIT
Maintainer : jprupp@protonmail.ch
Stability : experimental
Portability : POSIX
Hashing functions and corresponding data types. Uses functions from the
cryptonite library.
-}
module Haskoin.Crypto.Hash
( -- * Hashes
Hash512(getHash512)
, Hash256(getHash256)
, Hash160(getHash160)
, CheckSum32(getCheckSum32)
, sha512
, sha256
, ripemd160
, sha1
, doubleSHA256
, addressHash
, checkSum32
, hmac512
, hmac256
, split512
, join512
) where
import Control.DeepSeq
import Crypto.Hash (RIPEMD160 (..), SHA1 (..),
SHA256 (..), SHA512 (..), hashWith)
import Crypto.MAC.HMAC (HMAC, hmac)
import Data.Binary (Binary (..))
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray as BA
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Short (ShortByteString)
import qualified Data.ByteString.Short as BSS
import qualified Data.Bytes.Get as Get
import qualified Data.Bytes.Put as Put
import Data.Bytes.Serial (Serial (..))
import Data.Either (fromRight)
import Data.Hashable (Hashable)
import Data.Serialize (Serialize (..))
import Data.String (IsString, fromString)
import Data.String.Conversions (cs)
import Data.Word (Word32)
import GHC.Generics (Generic)
import Haskoin.Util
import Text.Read as R
-- | 'Word32' wrapped for type-safe 32-bit checksums.
newtype CheckSum32 = CheckSum32
{ getCheckSum32 :: Word32
} deriving (Eq, Ord, Serial, Show, Read, Hashable, Generic, NFData)
instance Serialize CheckSum32 where
put = serialize
get = deserialize
instance Binary CheckSum32 where
put = serialize
get = deserialize
-- | Type for 512-bit hashes.
newtype Hash512 = Hash512 { getHash512 :: ShortByteString }
deriving (Eq, Ord, Hashable, Generic, NFData)
-- | Type for 256-bit hashes.
newtype Hash256 = Hash256 { getHash256 :: ShortByteString }
deriving (Eq, Ord, Hashable, Generic, NFData)
-- | Type for 160-bit hashes.
newtype Hash160 = Hash160 { getHash160 :: ShortByteString }
deriving (Eq, Ord, Hashable, Generic, NFData)
instance Show Hash512 where
showsPrec _ = shows . encodeHex . BSS.fromShort . getHash512
instance Read Hash512 where
readPrec = do
R.String str <- lexP
maybe pfail return $ Hash512 . BSS.toShort <$> decodeHex (cs str)
instance Show Hash256 where
showsPrec _ = shows . encodeHex . BSS.fromShort . getHash256
instance Read Hash256 where
readPrec = do
R.String str <- lexP
maybe pfail return $ Hash256 . BSS.toShort <$> decodeHex (cs str)
instance Show Hash160 where
showsPrec _ = shows . encodeHex . BSS.fromShort . getHash160
instance Read Hash160 where
readPrec = do
R.String str <- lexP
maybe pfail return $ Hash160 . BSS.toShort <$> decodeHex (cs str)
instance IsString Hash512 where
fromString str =
case decodeHex $ cs str of
Nothing -> e
Just bs ->
case BS.length bs of
64 -> Hash512 (BSS.toShort bs)
_ -> e
where
e = error "Could not decode hash from hex string"
instance Serial Hash512 where
deserialize = Hash512 . BSS.toShort <$> Get.getByteString 64
serialize = Put.putByteString . BSS.fromShort . getHash512
instance Serialize Hash512 where
put = serialize
get = deserialize
instance Binary Hash512 where
put = serialize
get = deserialize
instance IsString Hash256 where
fromString str =
case decodeHex $ cs str of
Nothing -> e
Just bs ->
case BS.length bs of
32 -> Hash256 (BSS.toShort bs)
_ -> e
where
e = error "Could not decode hash from hex string"
instance Serial Hash256 where
deserialize = Hash256 . BSS.toShort <$> Get.getByteString 32
serialize = Put.putByteString . BSS.fromShort . getHash256
instance Serialize Hash256 where
put = serialize
get = deserialize
instance Binary Hash256 where
put = serialize
get = deserialize
instance IsString Hash160 where
fromString str =
case decodeHex $ cs str of
Nothing -> e
Just bs ->
case BS.length bs of
20 -> Hash160 (BSS.toShort bs)
_ -> e
where
e = error "Could not decode hash from hex string"
instance Serial Hash160 where
deserialize = Hash160 . BSS.toShort <$> Get.getByteString 20
serialize = Put.putByteString . BSS.fromShort . getHash160
instance Serialize Hash160 where
put = serialize
get = deserialize
instance Binary Hash160 where
put = serialize
get = deserialize
-- | Calculate SHA512 hash.
sha512 :: ByteArrayAccess b => b -> Hash512
sha512 = Hash512 . BSS.toShort . BA.convert . hashWith SHA512
-- | Calculate SHA256 hash.
sha256 :: ByteArrayAccess b => b -> Hash256
sha256 = Hash256 . BSS.toShort . BA.convert . hashWith SHA256
-- | Calculate RIPEMD160 hash.
ripemd160 :: ByteArrayAccess b => b -> Hash160
ripemd160 = Hash160 . BSS.toShort . BA.convert . hashWith RIPEMD160
-- | Claculate SHA1 hash.
sha1 :: ByteArrayAccess b => b -> Hash160
sha1 = Hash160 . BSS.toShort . BA.convert . hashWith SHA1
-- | Compute two rounds of SHA-256.
doubleSHA256 :: ByteArrayAccess b => b -> Hash256
doubleSHA256 =
Hash256 . BSS.toShort . BA.convert . hashWith SHA256 . hashWith SHA256
-- | Compute SHA-256 followed by RIPMED-160.
addressHash :: ByteArrayAccess b => b -> Hash160
addressHash =
Hash160 . BSS.toShort . BA.convert . hashWith RIPEMD160 . hashWith SHA256
{- CheckSum -}
-- | Computes a 32 bit checksum.
checkSum32 :: ByteArrayAccess b => b -> CheckSum32
checkSum32 = fromRight (error "Could not decode bytes as CheckSum32")
. Get.runGetS deserialize
. BS.take 4
. BA.convert
. hashWith SHA256
. hashWith SHA256
{- HMAC -}
-- | Computes HMAC over SHA-512.
hmac512 :: ByteString -> ByteString -> Hash512
hmac512 key msg =
Hash512 $ BSS.toShort $ BA.convert (hmac key msg :: HMAC SHA512)
-- | Computes HMAC over SHA-256.
hmac256 :: (ByteArrayAccess k, ByteArrayAccess m) => k -> m -> Hash256
hmac256 key msg =
Hash256 $ BSS.toShort $ BA.convert (hmac key msg :: HMAC SHA256)
-- | Split a 'Hash512' into a pair of 'Hash256'.
split512 :: Hash512 -> (Hash256, Hash256)
split512 h =
(Hash256 (BSS.toShort a), Hash256 (BSS.toShort b))
where
(a, b) = BS.splitAt 32 . BSS.fromShort $ getHash512 h
-- | Join a pair of 'Hash256' into a 'Hash512'.
join512 :: (Hash256, Hash256) -> Hash512
join512 (a, b) =
Hash512 .
BSS.toShort $
BSS.fromShort (getHash256 a) `BS.append` BSS.fromShort (getHash256 b)
|
haskoin/haskoin
|
src/Haskoin/Crypto/Hash.hs
|
unlicense
| 7,305
| 0
| 15
| 2,068
| 1,879
| 1,014
| 865
| 174
| 1
|
module Chapter06 where
-- CHAPTER 6. TYPECLASSES p. 206
data TisAnInteger =
TisAn Integer deriving (Show)
data TwoIntegers =
Two Integer Integer deriving (Show)
data StringOrInt =
TisAnInt Int
| TisAString String deriving (Show)
data Pair a =
Pair a a deriving (Show)
data Tuple a b =
Tuple a b
data Which a =
ThisOne a
| ThatOne a deriving (Show)
data EitherOr a b =
Hello a
| Goodbye b
instance Eq TisAnInteger where
(==) (TisAn z) (TisAn z') =
z == z'
instance Eq TwoIntegers where
(==) (Two m n) (Two m' n') =
m == m' && n == n'
-- *Chapter06> Two 1 2 == Two 1 2
-- True
instance Eq StringOrInt where
(==) (TisAnInt z) (TisAnInt z') = z == z'
(==) (TisAString z) (TisAString z') = z == z'
-- *Chapter06> TisAString "xyz" == TisAString "xyz"
-- True
-- *Chapter06> TisAString "xyz" == TisAString "xyzz"
-- False
instance Eq a => Eq (Pair a) where
(==) (Pair x y) (Pair x' y') = x == x' && y == y'
-- *Chapter06> (Pair 1 2) == (Pair 1 2)
-- True
instance (Eq a, Eq b) => Eq (Tuple a b) where
(==) (Tuple x y) (Tuple x' y') = x == x' && y == y'
-- *Chapter06> (Tuple 1 'a') == (Tuple 1 'a')
-- True
-- *Chapter06> (Tuple 1 'a') == (Tuple 2 'a')
-- False
instance Eq a => Eq (Which a) where
(==) (ThisOne x) (ThisOne x') = x == x'
(==) (ThatOne x) (ThatOne x') = x == x'
instance (Eq a, Eq b) => Eq (EitherOr a b) where
(==) (Hello x) (Hello x') = x == x'
(==) (Goodbye y) (Goodbye y') = y == y'
-- Type-Kwon-Do
chk :: Eq b => (a -> b) -> a -> b -> Bool
chk f a b = f a == b
-- Hint: use some arithmetic operation to
-- combine values of type 'b'. Pick one.
arith :: Num b => (a -> b) -> Integer -> a -> b
arith f n a = f a + fromInteger n
|
prt2121/haskell-practice
|
ch6-11-17-25/src/Chapter06.hs
|
apache-2.0
| 1,709
| 0
| 8
| 425
| 692
| 375
| 317
| 41
| 1
|
{-# Language OverloadedStrings #-}
module Command (
Command(..),
parse,
) where
import Control.Exception
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Functor
import System.IO
data Command
= Set ByteString Int Int ByteString
| Add ByteString Int Int ByteString
| Replace ByteString Int Int ByteString
| Append ByteString Int Int ByteString
| Prepend ByteString Int Int ByteString
| Cas
| Get [ByteString]
| Delete ByteString
| Incr ByteString Integer
| Decr ByteString Integer
| Stats
| Version
| Quit
deriving (Eq, Show)
parse :: Handle -> IO (Either String Command)
parse h = do
res <- try $ parse' h
return $ case res of
Left (SomeException e) -> Left $ show e
Right cmd -> Right cmd
parse' h = do
cmd <- BS.hGetLine h
putStrLn $ show cmd
case BS.words cmd of
"set" : key : flags : exptime : bytes : _ ->
Set key (readInt' flags) (readInt' exptime) <$> getStr h bytes
"add" : key : flags : exptime : bytes : _ ->
Add key (readInt' flags) (readInt' exptime) <$> getStr h bytes
"replace" : key : flags : exptime : bytes : _ ->
Replace key (readInt' flags) (readInt' exptime) <$> getStr h bytes
"append" : key : flags : exptime : bytes : _ ->
Append key (readInt' flags) (readInt' exptime) <$> getStr h bytes
"prepend" : key : flags : exptime : bytes : _ ->
Prepend key (readInt' flags) (readInt' exptime) <$> getStr h bytes
"get" : keys ->
return $ Get keys
"delete" : key : _ ->
return $ Delete key
"incr" : key : num : _ ->
return $ Incr key (readInteger' num)
"decr" : key : num : _ ->
return $ Decr key (readInteger' num)
"stats" : _ ->
return Stats
"version" : _ ->
return Version
"quit" : _ ->
return Quit
getStr h bytes =
BS.hGet h (readInt' bytes)
readInt' bs =
let Just (r, "") = BS.readInt bs in r
readInteger' bs =
let Just (r, "") = BS.readInteger bs in r
|
tanakh/hkvs
|
Command.hs
|
bsd-3-clause
| 2,010
| 0
| 14
| 528
| 795
| 397
| 398
| 64
| 12
|
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
module HYQLFinance(
symbols,
yqlParams,
yqlBuildUrl,
httpExceptionHandler,
getYqlXML,
getElementFromXML,
findStringsInElement,
getStocksFromElement,
refreshStocks
)where
--import Control.Monad
import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy as L
import Text.XML.Light
import Control.Exception as Exc
import Data.List.Utils as Utils (join)
getFinanceData :: IO ()
getFinanceData = do
putStrLn "getting finance data"
data Stock = Stock {
symbol :: String,
percentChange :: String
-- volume :: Int,
-- openPrice :: Double,
-- highPrice :: Double,
-- lowPrice :: Double,
-- closePrice :: Double,
-- percChange :: Double
} deriving (Eq, Show)
symbols :: [String]
symbols = ["\'AAPL\'", "\'GOOG\'"]
yqlParams :: [String]
yqlParams = ["Symbol", "Open", "PreviousClose", "PercentChange", "Volume", "AskRealtime", "DaysHigh", "DaysLow"]
-- | Build YQL Yahoo.Finance url string based on given parameters and symbols (of stocks)
yqlBuildUrl :: [String] -> [String] -> String
yqlBuildUrl paramsIn symbolsIn
| null paramsIn = ""
| null symbolsIn = ""
| otherwise = baseUrl ++ params ++ urlMiddle ++ symbols ++ urlEnd
where
params = Utils.join ", " paramsIn
symbols = Utils.join ", " symbolsIn
baseUrl = "http://query.yahooapis.com/v1/public/yql?q=select "
urlMiddle = " from yahoo.finance.quotes where symbol in ("
urlEnd = ")&env=store://datatables.org/alltableswithkeys"
-- | Exception handler for simpleHttp
httpExceptionHandler :: HttpException -> IO L.ByteString
httpExceptionHandler e = (putStrLn $ "Error: simpleHttp returned exception " ++ show e) >> (return L.empty)
-- | Get data from given url. Function will return empty Bytestring if exception occured
getYqlXML :: String -> IO L.ByteString
getYqlXML url = (simpleHttp url) `Exc.catch` httpExceptionHandler
-- | Parses raw XML into Element
getElementFromXML :: L.ByteString -> Either String Element
getElementFromXML xmlData
| xmlData == L.empty = Left "getStocksFromXML: received empty input data!"
| otherwise =
case parseXMLDoc xmlData of
Nothing -> Left "getStocksFromXML: error parsing content"
Just xmlElement -> Right xmlElement
-- | Find given String in Element. As a return is list of XML tags content
findStringsInElement :: Element -> String -> [String]
findStringsInElement el name
| name == [] = []
| otherwise = x
where
x = [cdData titleContent | [Text titleContent] <- [elContent element | element <- elements]]
where
elements = findElements (unqual name) $ el
-- | Parses given Element into a Stock list
getStocksFromElement :: Element -> [Stock]
getStocksFromElement el = zipWith Stock stocks percentChanges
where
stocks = findStringsInElement el "Symbol"
percentChanges = findStringsInElement el "PercentChange"
-- | Function will return list of Stocks from Yahoo.Finance server
refreshStocks :: IO (Either String [Stock])
refreshStocks = do
let yqlQuery = yqlBuildUrl yqlParams symbols
--putStrLn $ "querying: " ++ show yqlQuery
yqlXML <- getYqlXML yqlQuery
if yqlXML == L.empty
then return $ Left "getYqlXML: error getting XML!"
else do
case getElementFromXML yqlXML of
Left msg -> return $ Left msg
Right el -> do
let stocks = getStocksFromElement el
return $ Right stocks
|
mKarpis/hyql-finance
|
src/HYQLFinance.hs
|
bsd-3-clause
| 3,519
| 0
| 18
| 725
| 764
| 407
| 357
| 71
| 3
|
module Text.RDF.RDF4H.TurtleParser_ConformanceTest where
-- Testing imports
import Test.Framework.Providers.API
import Test.Framework.Providers.HUnit
import qualified Test.HUnit as TU
-- Import common libraries to facilitate tests
import Control.Monad (liftM)
import Data.RDF.GraphTestUtils
import Data.RDF.Query
import Data.RDF.TriplesGraph
import Data.RDF.Types
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as TIO
import Text.Printf
import Text.RDF.RDF4H.TurtleParser
tests :: [Test]
tests = [ testGroup "TurtleParser" allCTests ]
-- A list of other tests to run, each entry of which is (directory, fname_without_ext).
otherTestFiles :: [(String, String)]
otherTestFiles = [("data/ttl", "example1"),
("data/ttl", "example2"),
("data/ttl", "example3"),
("data/ttl", "example5"),
("data/ttl", "example6"),
-- ("data/ttl", "example7"), -- rdf4h URIs support RFC3986, not unicode IRIs in RFC3987
("data/ttl", "example8"),
("data/ttl", "fawlty1")
]
-- The Base URI to be used for all conformance tests:
testBaseUri :: String
testBaseUri = "http://www.w3.org/2001/sw/DataAccess/df1/tests/"
mtestBaseUri :: Maybe BaseUrl
mtestBaseUri = Just $ BaseUrl $ T.pack testBaseUri
fpath :: String -> Int -> String -> String
fpath name i ext = printf "data/ttl/conformance/%s-%02d.%s" name i ext :: String
allCTests :: [Test]
allCTests = ts1 ++ ts2 ++ ts3
where
ts1 = map (buildTest . checkGoodConformanceTest) [0..30]
ts2 = map (buildTest . checkBadConformanceTest) [0..14]
ts3 = map (buildTest . uncurry checkGoodOtherTest) otherTestFiles
checkGoodConformanceTest :: Int -> IO Test
checkGoodConformanceTest i =
do
expGr <- loadExpectedGraph "test" i
inGr <- loadInputGraph "test" i
doGoodConformanceTest expGr inGr (printf "test %d" i :: String)
checkGoodOtherTest :: String -> String -> IO Test
checkGoodOtherTest dir fname =
do
expGr <- loadExpectedGraph1 (printf "%s/%s.out" dir fname :: String)
inGr <- loadInputGraph1 dir fname
doGoodConformanceTest expGr inGr $ printf "test using file \"%s\"" fname
doGoodConformanceTest :: Either ParseFailure TriplesGraph ->
Either ParseFailure TriplesGraph ->
String -> IO Test
doGoodConformanceTest expGr inGr testname = do
let t1 = assertLoadSuccess (printf "expected (%s): " testname) expGr
t2 = assertLoadSuccess (printf " input (%s): " testname) inGr
t3 = assertEquivalent testname expGr inGr
return $ testGroup (printf "Conformance %s" testname) $ map (uncurry testCase) [("Loading expected graph data", t1), ("Loading input graph data", t2), ("Comparing graphs", t3)]
checkBadConformanceTest :: Int -> IO Test
checkBadConformanceTest i = do
let t = loadInputGraph "bad" i >>= assertLoadFailure (show i)
return $ testCase (printf "Loading test %d (negative)" i) t
-- Determines if graphs are equivalent, returning Nothing if so or else a diagnostic message.
-- First graph is expected graph, second graph is actual.
equivalent :: RDF rdf => Either ParseFailure rdf -> Either ParseFailure rdf -> Maybe String
equivalent (Left _) _ = Nothing
equivalent _ (Left _) = Nothing
equivalent (Right gr1) (Right gr2) = test $! zip gr1ts gr2ts
where
gr1ts = uordered $ triplesOf gr1
gr2ts = uordered $ triplesOf gr2
test [] = Nothing
test ((t1,t2):ts) =
case compareTriple t1 t2 of
Nothing -> test ts
err -> err
compareTriple t1 t2 =
if equalNodes s1 s2 && equalNodes p1 p2 && equalNodes o1 o2
then Nothing
else Just ("Expected:\n " ++ show t1 ++ "\nFound:\n " ++ show t2 ++ "\n")
where
(s1, p1, o1) = f t1
(s2, p2, o2) = f t2
f t = (subjectOf t, predicateOf t, objectOf t)
-- equalNodes (BNode fs1) (BNodeGen i) = T.reverse fs1 == T.pack ("_:genid" ++ show i)
equalNodes (BNode fs1) (BNodeGen i) = fs1 == T.pack ("_:genid" ++ show i)
equalNodes n1 n2 = n1 == n2
-- Returns a graph for a good ttl test that is intended to pass, and normalizes
-- triples into a format so that they can be compared with the expected output triples.
loadInputGraph :: String -> Int -> IO (Either ParseFailure TriplesGraph)
loadInputGraph name n =
TIO.readFile (fpath name n "ttl") >>=
return . parseString (TurtleParser mtestBaseUri (mkDocUrl testBaseUri name n)) >>= return . handleLoad
loadInputGraph1 :: String -> String -> IO (Either ParseFailure TriplesGraph)
loadInputGraph1 dir fname =
TIO.readFile (printf "%s/%s.ttl" dir fname :: String) >>=
return . parseString (TurtleParser mtestBaseUri (mkDocUrl1 testBaseUri fname)) >>= return . handleLoad
handleLoad :: Either ParseFailure TriplesGraph -> Either ParseFailure TriplesGraph
handleLoad res =
case res of
l@(Left _) -> l
(Right gr) -> Right $ mkRdf (map normalize (triplesOf gr)) (baseUrl gr) (prefixMappings gr)
normalize :: Triple -> Triple
normalize t = let s' = normalizeN $ subjectOf t
p' = normalizeN $ predicateOf t
o' = normalizeN $ objectOf t
in triple s' p' o'
normalizeN :: Node -> Node
normalizeN (BNodeGen i) = BNode (T.pack $ "_:genid" ++ show i)
normalizeN n = n
loadExpectedGraph :: String -> Int -> IO (Either ParseFailure TriplesGraph)
loadExpectedGraph name n = loadExpectedGraph1 (fpath name n "out")
loadExpectedGraph1 :: String -> IO (Either ParseFailure TriplesGraph)
loadExpectedGraph1 fname =
liftM (parseString (TurtleParser mtestBaseUri (mkDocUrl1 testBaseUri fname))) (TIO.readFile fname)
assertLoadSuccess, assertLoadFailure :: String -> Either ParseFailure TriplesGraph -> TU.Assertion
assertLoadSuccess idStr (Left (ParseFailure err)) = TU.assertFailure $ idStr ++ err
assertLoadSuccess _ (Right _) = return ()
assertLoadFailure _ (Left _) = return ()
assertLoadFailure idStr _ = TU.assertFailure $ "Bad test " ++ idStr ++ " loaded successfully."
assertEquivalent :: RDF rdf => String -> Either ParseFailure rdf -> Either ParseFailure rdf -> TU.Assertion
assertEquivalent testname r1 r2 =
case equiv of
Nothing -> TU.assert True
(Just msg) -> fail $ "Graph " ++ testname ++ " not equivalent to expected:\n" ++ msg
where equiv = equivalent r1 r2
mkDocUrl :: String -> String -> Int -> Maybe T.Text
mkDocUrl baseDocUrl fname testNum = Just $ T.pack $ printf "%s%s-%02d.ttl" baseDocUrl fname testNum
mkDocUrl1 :: String -> String -> Maybe T.Text
mkDocUrl1 baseDocUrl fname = Just $ T.pack $ printf "%s%s.ttl" baseDocUrl fname
|
ddssff/rdf4h
|
testsuite/tests/Text/RDF/RDF4H/TurtleParser_ConformanceTest.hs
|
bsd-3-clause
| 6,761
| 0
| 14
| 1,521
| 1,916
| 987
| 929
| 119
| 5
|
{-# LANGUAGE OverloadedStrings #-}
module CMUDict where
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Attoparsec.ByteString (Parser)
import qualified Data.Attoparsec.ByteString as AP
import qualified Data.Attoparsec.ByteString.Char8 as APC
import Data.Trie (Trie)
import qualified Data.Trie as Trie
import Data.Either (rights)
data Articulation =
Vowel
| RColored
| Stop
| Affricate
| Fricative
| Nasal
| Liquid
| Semivowel
deriving (Eq, Show)
data Phone =
-- Vowels
AO | AA | IY | UW | EH
| IH | UH | AH | AX | AE
| EY | AY | OW | AW | OY
-- RColored
| ER | AXR
-- Stops
| P | B | T | D | K | G
-- Affricates
| CH | JH
-- Fricatives
| F | V | TH | DH | S | Z | SH | ZH | HH
-- Nasals
| M | EM | N | EN | NG | ENG
-- Liquids
| L | EL | R | DX | NX
-- Semivowels
| Y | W | Q
deriving (Eq, Ord, Enum, Bounded, Show, Read)
data Stress = None | Primary | Secondary
deriving(Eq, Show)
type Phone_Str = (Phone, Maybe Stress)
classifyPhone :: Phone -> Articulation
classifyPhone x
| x <= OY = Vowel
| x <= AXR = RColored
| x <= G = Stop
| x <= JH = Affricate
| x <= HH = Fricative
| x <= ENG = Nasal
| x <= NX = Liquid
| otherwise = Semivowel
-- load entire cmudict file into memory
loadDict :: FilePath -> IO (Trie [Phone_Str])
loadDict path = do
file <- BS.readFile path
pure $ buildTrie file
buildTrie :: ByteString -> Trie [Phone_Str]
buildTrie input = Trie.fromList (either (\_ -> []) id $ AP.parseOnly dictFile input)
-- consume then discard comments
comment :: Parser ()
comment = AP.string ";;;" *> AP.takeTill APC.isEndOfLine *> APC.endOfLine
-- parse the word
word :: Parser ByteString
word = AP.takeTill APC.isSpace_w8 <* APC.skipSpace
intToStress :: Int -> Maybe Stress
intToStress (-1) = Nothing
intToStress 1 = Just Primary
intToStress 2 = Just Secondary
intToStress _ = Just None
bsToPhone :: ByteString -> Phone
bsToPhone = read . BS.unpack
-- parse a single pronunciation symbol
symbol :: Parser Phone_Str
symbol = do
p <- bsToPhone <$> AP.takeTill (\x -> APC.isDigit_w8 x || APC.isSpace_w8 x)
s <- intToStress <$> AP.option (-1) APC.decimal
pure(p, s)
-- parse the entire pronunciation for a word
pronunciation :: Parser [Phone_Str]
pronunciation = AP.sepBy symbol $ AP.word8 32
-- parse both the word and its pronunciation
entry :: Parser (ByteString, [Phone_Str])
entry = do
w <- word
p <- pronunciation
APC.endOfLine
pure (w, p)
--parse either an entry or a comment untill all input is consumed
dictFile :: Parser [(ByteString, [Phone_Str])]
dictFile = rights <$> AP.manyTill (AP.eitherP comment entry) AP.endOfInput
|
cmika/mnuh
|
src/CMUDict.hs
|
bsd-3-clause
| 2,763
| 0
| 14
| 646
| 933
| 519
| 414
| 77
| 1
|
module Bot.Modules.Hooks
( defaultHooks
, adjustHook
, matches
, execute
) where
import Bot.Core.Types
import Bot.Core.Base (io, reply)
import Bot.Modules.Records
import Interfaces.HTML (isHTML, titleHTML)
import Control.Monad.State (gets, when, modify)
import Text.Regex.Posix
import qualified Data.Map.Strict as Map
privmsg :: Predicate
privmsg = ((==) "PRIVMSG", msg)
userstate :: Predicate
userstate = (flip elem ["JOIN", "PART", "QUIT"], src)
defaultHooks = Map.fromList [
("seen", Hook All privmsg ".*" seenHook),
("http", Hook (Not ["#kitinfo"]) privmsg "https?://\\S+" httpHook),
("kitbot", Hook (Only ["#kitinfo"]) userstate "Kitbot" kitbotHook)
]
-- |Enable or disable a hook in the given map.
adjustHook :: String -> HookMap -> Access -> HookMap
adjustHook k m a = Map.adjust (\s -> s { haccess = a }) k m
-- |Return "True" if a Packet matches a given Hook, "False" otherwise.
matches :: Hook -> Packet -> Bool
matches h p = ctype h (cmd p) && (chunk h p =~ regex h)
where
ctype = fst . predicate
chunk = snd . predicate
-- |A convienence function that executes the "HookFunction" on a "Packet".
execute :: Hook -> Packet -> Bot ()
execute h = hook h (regex h)
seenHook r p = do
rec <- io $ composeRecord p
cs <- gets chans
let public = dst p `elem` cs in
when public $ updateWith (dst p, src p) rec
httpHook r p = do
valid <- io (isHTML s)
when valid (io (titleHTML s) >>= reply p)
where s = msg p =~ r :: String
kitbotHook r p = do
hs <- gets hooks
modify $ if cmd p == "JOIN" then
\s -> s { hooks = adjustHook "http" hs (Not ["#kitinfo"]) } else
\s -> s { hooks = adjustHook "http" hs All }
|
vehk/Indoril
|
src/Bot/Modules/Hooks.hs
|
bsd-3-clause
| 1,822
| 1
| 15
| 503
| 635
| 341
| 294
| 42
| 2
|
module Parse.TestHelpers where
import Elm.Utils ((|>))
import Test.HUnit (Assertion, assertEqual)
import Test.Framework
import Test.Framework.Providers.HUnit
import Parse.Helpers (IParser, iParse)
import Reporting.Annotation hiding (map, at)
import Reporting.Region
import Text.ParserCombinators.Parsec.Combinator (eof)
import qualified Data.List as List
import qualified Data.List.Split as List
parseFullInput :: IParser a -> IParser a
parseFullInput parser =
(\x _ -> x) <$> parser <*> eof
assertParse :: (Show a, Eq a) => IParser a -> String -> a -> Assertion
assertParse parser input expected =
let
output = iParse (parseFullInput parser) input
in
case output of
Left err ->
assertEqual (show err) False True
Right result ->
assertEqual input expected result
assertFailure :: (Show a, Eq a) => IParser a -> String -> Assertion
assertFailure parser input =
let
output = iParse (parseFullInput parser) input
in
case output of
Left err ->
assertEqual (show err) True True
Right result ->
assertEqual (show result) True False
nowhere = Region (Position 0 0) (Position 0 0)
at a b c d = A (Region (Position a b) (Position c d))
{-| Checks that removing indentation causes parsing to fail.
For each "\n " in the input string, a test case will be generated checking that
the given parser will fail if that "\n " is replaced by "\n".
-}
mustBeIndented parser input =
input
|> generateReplacements "\n " "\n"
|> List.map (testCase "" . assertFailure parser)
|> testGroup "must be indented"
generateReplacements :: (Eq a) => [a] -> [a] -> [a] -> [[a]]
generateReplacements needle replacement input =
input
|> List.splitOn needle
|> step'
where
step' rights =
case rights of
[] ->
[]
(next:rest) ->
step [] [next] rest
step acc lefts rights =
case rights of
[] ->
acc
(next:rest) ->
[lefts, rights]
|> List.map (List.intercalate needle)
|> List.intercalate replacement
|> flip (:) (step acc (lefts++[next]) rest)
|
fredcy/elm-format
|
tests/Parse/TestHelpers.hs
|
bsd-3-clause
| 2,396
| 0
| 16
| 788
| 698
| 365
| 333
| 59
| 3
|
-----------------------------------------------------------------------------
-- |
-- Module : Text.Parsec.Pos
-- Copyright : (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : derek.a.elkins@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Textual source positions.
--
-----------------------------------------------------------------------------
module Text.Parsec.Pos
( SourceName, Line, Column
, SourcePos
, sourceLine, sourceColumn, sourceName
, incSourceLine, incSourceColumn
, setSourceLine, setSourceColumn, setSourceName
, newPos, initialPos
, updatePosChar, updatePosString
) where
import Data.Generics
-- < Source positions: a file name, a line and a column
-- upper left is (1,1)
type SourceName = String
type Line = Int
type Column = Int
-- | The abstract data type @SourcePos@ represents source positions. It
-- contains the name of the source (i.e. file name), a line number and
-- a column number. @SourcePos@ is an instance of the 'Show', 'Eq' and
-- 'Ord' class.
data SourcePos = SourcePos SourceName !Line !Column
deriving ( Eq, Ord, Data, Typeable)
-- | Create a new 'SourcePos' with the given source name,
-- line number and column number.
newPos :: SourceName -> Line -> Column -> SourcePos
newPos name line column
= SourcePos name line column
-- | Create a new 'SourcePos' with the given source name,
-- and line number and column number set to 1, the upper left.
initialPos :: SourceName -> SourcePos
initialPos name
= newPos name 1 1
-- | Extracts the name of the source from a source position.
sourceName :: SourcePos -> SourceName
sourceName (SourcePos name _line _column) = name
-- | Extracts the line number from a source position.
sourceLine :: SourcePos -> Line
sourceLine (SourcePos _name line _column) = line
-- | Extracts the column number from a source position.
sourceColumn :: SourcePos -> Column
sourceColumn (SourcePos _name _line column) = column
-- | Increments the line number of a source position.
incSourceLine :: SourcePos -> Line -> SourcePos
incSourceLine (SourcePos name line column) n = SourcePos name (line+n) column
-- | Increments the column number of a source position.
incSourceColumn :: SourcePos -> Column -> SourcePos
incSourceColumn (SourcePos name line column) n = SourcePos name line (column+n)
-- | Set the name of the source.
setSourceName :: SourcePos -> SourceName -> SourcePos
setSourceName (SourcePos _name line column) n = SourcePos n line column
-- | Set the line number of a source position.
setSourceLine :: SourcePos -> Line -> SourcePos
setSourceLine (SourcePos name _line column) n = SourcePos name n column
-- | Set the column number of a source position.
setSourceColumn :: SourcePos -> Column -> SourcePos
setSourceColumn (SourcePos name line _column) n = SourcePos name line n
-- | The expression @updatePosString pos s@ updates the source position
-- @pos@ by calling 'updatePosChar' on every character in @s@, ie.
-- @foldl updatePosChar pos string@.
updatePosString :: SourcePos -> String -> SourcePos
updatePosString pos string
= foldl updatePosChar pos string
-- | Update a source position given a character. If the character is a
-- newline (\'\\n\') or carriage return (\'\\r\') the line number is
-- incremented by 1. If the character is a tab (\'\t\') the column
-- number is incremented to the nearest 8'th column, ie. @column + 8 -
-- ((column-1) \`mod\` 8)@. In all other cases, the column is
-- incremented by 1.
updatePosChar :: SourcePos -> Char -> SourcePos
updatePosChar (SourcePos name line column) c
= case c of
'\n' -> SourcePos name (line+1) 1
'\t' -> SourcePos name line (column + 8 - ((column-1) `mod` 8))
_ -> SourcePos name line (column + 1)
instance Show SourcePos where
show (SourcePos name line column)
| null name = showLineColumn
| otherwise = "\"" ++ name ++ "\" " ++ showLineColumn
where
showLineColumn = "(line " ++ show line ++
", column " ++ show column ++
")"
|
maurer/15-411-Haskell-Base-Code
|
src/Text/Parsec/Pos.hs
|
bsd-3-clause
| 4,188
| 0
| 14
| 860
| 741
| 406
| 335
| 56
| 3
|
-- | The Version of Jat.
module Jat.Utils.Version
(
version
)
where
-- | The current version.
version :: String
version = "1.1.0"
|
ComputationWithBoundedResources/jat
|
src/Jat/Utils/Version.hs
|
bsd-3-clause
| 139
| 0
| 4
| 32
| 24
| 16
| 8
| 5
| 1
|
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
module Data.Git.Types where
import Foreign.Ptr
import Foreign.ForeignPtr
import Bindings.Libgit2
newtype Repository = Repository {repoPrim :: ForeignPtr C'git_repository}
newtype ObjectDB = ObjectDB {odbPrim :: Ptr C'git_odb}
newtype Config = Config {confPrim :: ForeignPtr C'git_config}
newtype Index = Index {ixPrim :: ForeignPtr C'git_index}
newtype Tag = Tag {tagPrim :: ForeignPtr C'git_tag}
newtype IndexEntry = IndexEntry {ixePrim :: Ptr C'git_index_entry}
newtype IndexEntryUnmerged = IndexEntryUnmerged {ixeuPrim :: Ptr C'git_index_entry_unmerged}
toRepository ptr = do
fptr <- newForeignPtr p'git_repository_free ptr
return $! Repository fptr
toObjectDB ptr = return $! ObjectDB ptr
toIndex ptr = do
fptr <- newForeignPtr p'git_index_free ptr
return $! Index fptr
toConfig ptr = do
fptr <- newForeignPtr p'git_config_free ptr
return $! Config fptr
|
iand675/hgit
|
Data/Git/Types.hs
|
bsd-3-clause
| 954
| 0
| 8
| 164
| 240
| 131
| 109
| 22
| 1
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
************************************************************************
* *
\section[OccurAnal]{Occurrence analysis pass}
* *
************************************************************************
The occurrence analyser re-typechecks a core expression, returning a new
core expression with (hopefully) improved usage information.
-}
{-# LANGUAGE CPP, BangPatterns #-}
module OccurAnal (
occurAnalysePgm, occurAnalyseExpr, occurAnalyseExpr_NoBinderSwap
) where
#include "HsVersions.h"
import CoreSyn
import CoreFVs
import CoreUtils ( exprIsTrivial, isDefaultAlt, isExpandableApp,
stripTicksTopE, mkTicks )
import Id
import Name( localiseName )
import BasicTypes
import Module( Module )
import Coercion
import VarSet
import VarEnv
import Var
import Demand ( argOneShots, argsOneShots )
import Maybes ( orElse )
import Digraph ( SCC(..), stronglyConnCompFromEdgedVerticesUniqR )
import Unique
import UniqFM
import Util
import Outputable
import Data.List
import Control.Arrow ( second )
{-
************************************************************************
* *
\subsection[OccurAnal-main]{Counting occurrences: main function}
* *
************************************************************************
Here's the externally-callable interface:
-}
occurAnalysePgm :: Module -- Used only in debug output
-> (Activation -> Bool)
-> [CoreRule] -> [CoreVect] -> VarSet
-> CoreProgram -> CoreProgram
occurAnalysePgm this_mod active_rule imp_rules vects vectVars binds
| isEmptyVarEnv final_usage
= occ_anald_binds
| otherwise -- See Note [Glomming]
= WARN( True, hang (text "Glomming in" <+> ppr this_mod <> colon)
2 (ppr final_usage ) )
occ_anald_glommed_binds
where
init_env = initOccEnv active_rule
(final_usage, occ_anald_binds) = go init_env binds
(_, occ_anald_glommed_binds) = occAnalRecBind init_env imp_rule_edges
(flattenBinds occ_anald_binds)
initial_uds
-- It's crucial to re-analyse the glommed-together bindings
-- so that we establish the right loop breakers. Otherwise
-- we can easily create an infinite loop (Trac #9583 is an example)
initial_uds = addIdOccs emptyDetails
(rulesFreeVars imp_rules `unionVarSet`
vectsFreeVars vects `unionVarSet`
vectVars)
-- The RULES and VECTORISE declarations keep things alive! (For VECTORISE declarations,
-- we only get them *until* the vectoriser runs. Afterwards, these dependencies are
-- reflected in 'vectors' — see Note [Vectorisation declarations and occurrences].)
-- Note [Preventing loops due to imported functions rules]
imp_rule_edges = foldr (plusVarEnv_C unionVarSet) emptyVarEnv
[ mapVarEnv (const maps_to) (exprFreeIds arg `delVarSetList` ru_bndrs imp_rule)
| imp_rule <- imp_rules
, not (isBuiltinRule imp_rule) -- See Note [Plugin rules]
, let maps_to = exprFreeIds (ru_rhs imp_rule)
`delVarSetList` ru_bndrs imp_rule
, arg <- ru_args imp_rule ]
go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
go _ []
= (initial_uds, [])
go env (bind:binds)
= (final_usage, bind' ++ binds')
where
(bs_usage, binds') = go env binds
(final_usage, bind') = occAnalBind env imp_rule_edges bind bs_usage
occurAnalyseExpr :: CoreExpr -> CoreExpr
-- Do occurrence analysis, and discard occurrence info returned
occurAnalyseExpr = occurAnalyseExpr' True -- do binder swap
occurAnalyseExpr_NoBinderSwap :: CoreExpr -> CoreExpr
occurAnalyseExpr_NoBinderSwap = occurAnalyseExpr' False -- do not do binder swap
occurAnalyseExpr' :: Bool -> CoreExpr -> CoreExpr
occurAnalyseExpr' enable_binder_swap expr
= snd (occAnal env expr)
where
env = (initOccEnv all_active_rules) {occ_binder_swap = enable_binder_swap}
-- To be conservative, we say that all inlines and rules are active
all_active_rules = \_ -> True
{- Note [Plugin rules]
~~~~~~~~~~~~~~~~~~~~~~
Conal Elliott (Trac #11651) built a GHC plugin that added some
BuiltinRules (for imported Ids) to the mg_rules field of ModGuts, to
do some domain-specific transformations that could not be expressed
with an ordinary pattern-matching CoreRule. But then we can't extract
the dependencies (in imp_rule_edges) from ru_rhs etc, because a
BuiltinRule doesn't have any of that stuff.
So we simply assume that BuiltinRules have no dependencies, and filter
them out from the imp_rule_edges comprehension.
-}
{-
************************************************************************
* *
Bindings
* *
************************************************************************
Note [Recursive bindings: the grand plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we come across a binding group
Rec { x1 = r1; ...; xn = rn }
we treat it like this (occAnalRecBind):
1. Occurrence-analyse each right hand side, and build a
"Details" for each binding to capture the results.
Wrap the details in a Node (details, node-id, dep-node-ids),
where node-id is just the unique of the binder, and
dep-node-ids lists all binders on which this binding depends.
We'll call these the "scope edges".
See Note [Forming the Rec groups].
All this is done by makeNode.
2. Do SCC-analysis on these Nodes. Each SCC will become a new Rec or
NonRec. The key property is that every free variable of a binding
is accounted for by the scope edges, so that when we are done
everything is still in scope.
3. For each Cyclic SCC of the scope-edge SCC-analysis in (2), we
identify suitable loop-breakers to ensure that inlining terminates.
This is done by occAnalRec.
4. To do so we form a new set of Nodes, with the same details, but
different edges, the "loop-breaker nodes". The loop-breaker nodes
have both more and fewer depedencies than the scope edges
(see Note [Choosing loop breakers])
More edges: if f calls g, and g has an active rule that mentions h
then we add an edge from f -> h
Fewer edges: we only include dependencies on active rules, on rule
RHSs (not LHSs) and if there is an INLINE pragma only
on the stable unfolding (and vice versa). The scope
edges must be much more inclusive.
5. The "weak fvs" of a node are, by definition:
the scope fvs - the loop-breaker fvs
See Note [Weak loop breakers], and the nd_weak field of Details
6. Having formed the loop-breaker nodes
Note [Dead code]
~~~~~~~~~~~~~~~~
Dropping dead code for a cyclic Strongly Connected Component is done
in a very simple way:
the entire SCC is dropped if none of its binders are mentioned
in the body; otherwise the whole thing is kept.
The key observation is that dead code elimination happens after
dependency analysis: so 'occAnalBind' processes SCCs instead of the
original term's binding groups.
Thus 'occAnalBind' does indeed drop 'f' in an example like
letrec f = ...g...
g = ...(...g...)...
in
...g...
when 'g' no longer uses 'f' at all (eg 'f' does not occur in a RULE in
'g'). 'occAnalBind' first consumes 'CyclicSCC g' and then it consumes
'AcyclicSCC f', where 'body_usage' won't contain 'f'.
------------------------------------------------------------
Note [Forming Rec groups]
~~~~~~~~~~~~~~~~~~~~~~~~~
We put bindings {f = ef; g = eg } in a Rec group if "f uses g"
and "g uses f", no matter how indirectly. We do a SCC analysis
with an edge f -> g if "f uses g".
More precisely, "f uses g" iff g should be in scope wherever f is.
That is, g is free in:
a) the rhs 'ef'
b) or the RHS of a rule for f (Note [Rules are extra RHSs])
c) or the LHS or a rule for f (Note [Rule dependency info])
These conditions apply regardless of the activation of the RULE (eg it might be
inactive in this phase but become active later). Once a Rec is broken up
it can never be put back together, so we must be conservative.
The principle is that, regardless of rule firings, every variable is
always in scope.
* Note [Rules are extra RHSs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
keeps the specialised "children" alive. If the parent dies
(because it isn't referenced any more), then the children will die
too (unless they are already referenced directly).
To that end, we build a Rec group for each cyclic strongly
connected component,
*treating f's rules as extra RHSs for 'f'*.
More concretely, the SCC analysis runs on a graph with an edge
from f -> g iff g is mentioned in
(a) f's rhs
(b) f's RULES
These are rec_edges.
Under (b) we include variables free in *either* LHS *or* RHS of
the rule. The former might seems silly, but see Note [Rule
dependency info]. So in Example [eftInt], eftInt and eftIntFB
will be put in the same Rec, even though their 'main' RHSs are
both non-recursive.
* Note [Rule dependency info]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The VarSet in a RuleInfo is used for dependency analysis in the
occurrence analyser. We must track free vars in *both* lhs and rhs.
Hence use of idRuleVars, rather than idRuleRhsVars in occAnalBind.
Why both? Consider
x = y
RULE f x = v+4
Then if we substitute y for x, we'd better do so in the
rule's LHS too, so we'd better ensure the RULE appears to mention 'x'
as well as 'v'
* Note [Rules are visible in their own rec group]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want the rules for 'f' to be visible in f's right-hand side.
And we'd like them to be visible in other functions in f's Rec
group. E.g. in Note [Specialisation rules] we want f' rule
to be visible in both f's RHS, and fs's RHS.
This means that we must simplify the RULEs first, before looking
at any of the definitions. This is done by Simplify.simplRecBind,
when it calls addLetIdInfo.
------------------------------------------------------------
Note [Choosing loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Loop breaking is surprisingly subtle. First read the section 4 of
"Secrets of the GHC inliner". This describes our basic plan.
We avoid infinite inlinings by choosing loop breakers, and
ensuring that a loop breaker cuts each loop.
See also Note [Inlining and hs-boot files] in ToIface, which deals
with a closely related source of infinite loops.
Fundamentally, we do SCC analysis on a graph. For each recursive
group we choose a loop breaker, delete all edges to that node,
re-analyse the SCC, and iterate.
But what is the graph? NOT the same graph as was used for Note
[Forming Rec groups]! In particular, a RULE is like an equation for
'f' that is *always* inlined if it is applicable. We do *not* disable
rules for loop-breakers. It's up to whoever makes the rules to make
sure that the rules themselves always terminate. See Note [Rules for
recursive functions] in Simplify.hs
Hence, if
f's RHS (or its INLINE template if it has one) mentions g, and
g has a RULE that mentions h, and
h has a RULE that mentions f
then we *must* choose f to be a loop breaker. Example: see Note
[Specialisation rules].
In general, take the free variables of f's RHS, and augment it with
all the variables reachable by RULES from those starting points. That
is the whole reason for computing rule_fv_env in occAnalBind. (Of
course we only consider free vars that are also binders in this Rec
group.) See also Note [Finding rule RHS free vars]
Note that when we compute this rule_fv_env, we only consider variables
free in the *RHS* of the rule, in contrast to the way we build the
Rec group in the first place (Note [Rule dependency info])
Note that if 'g' has RHS that mentions 'w', we should add w to
g's loop-breaker edges. More concretely there is an edge from f -> g
iff
(a) g is mentioned in f's RHS `xor` f's INLINE rhs
(see Note [Inline rules])
(b) or h is mentioned in f's RHS, and
g appears in the RHS of an active RULE of h
or a transitive sequence of active rules starting with h
Why "active rules"? See Note [Finding rule RHS free vars]
Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
chosen as a loop breaker, because their RHSs don't mention each other.
And indeed both can be inlined safely.
Note again that the edges of the graph we use for computing loop breakers
are not the same as the edges we use for computing the Rec blocks.
That's why we compute
- rec_edges for the Rec block analysis
- loop_breaker_nodes for the loop breaker analysis
* Note [Finding rule RHS free vars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this real example from Data Parallel Haskell
tagZero :: Array Int -> Array Tag
{-# INLINE [1] tagZeroes #-}
tagZero xs = pmap (\x -> fromBool (x==0)) xs
{-# RULES "tagZero" [~1] forall xs n.
pmap fromBool <blah blah> = tagZero xs #-}
So tagZero's RHS mentions pmap, and pmap's RULE mentions tagZero.
However, tagZero can only be inlined in phase 1 and later, while
the RULE is only active *before* phase 1. So there's no problem.
To make this work, we look for the RHS free vars only for
*active* rules. That's the reason for the occ_rule_act field
of the OccEnv.
* Note [Weak loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~
There is a last nasty wrinkle. Suppose we have
Rec { f = f_rhs
RULE f [] = g
h = h_rhs
g = h
...more...
}
Remember that we simplify the RULES before any RHS (see Note
[Rules are visible in their own rec group] above).
So we must *not* postInlineUnconditionally 'g', even though
its RHS turns out to be trivial. (I'm assuming that 'g' is
not choosen as a loop breaker.) Why not? Because then we
drop the binding for 'g', which leaves it out of scope in the
RULE!
Here's a somewhat different example of the same thing
Rec { g = h
; h = ...f...
; f = f_rhs
RULE f [] = g }
Here the RULE is "below" g, but we *still* can't postInlineUnconditionally
g, because the RULE for f is active throughout. So the RHS of h
might rewrite to h = ...g...
So g must remain in scope in the output program!
We "solve" this by:
Make g a "weak" loop breaker (OccInfo = IAmLoopBreaker True)
iff g is a "missing free variable" of the Rec group
A "missing free variable" x is one that is mentioned in an RHS or
INLINE or RULE of a binding in the Rec group, but where the
dependency on x may not show up in the loop_breaker_nodes (see
note [Choosing loop breakers} above).
A normal "strong" loop breaker has IAmLoopBreaker False. So
Inline postInlineUnconditionally
strong IAmLoopBreaker False no no
weak IAmLoopBreaker True yes no
other yes yes
The **sole** reason for this kind of loop breaker is so that
postInlineUnconditionally does not fire. Ugh. (Typically it'll
inline via the usual callSiteInline stuff, so it'll be dead in the
next pass, so the main Ugh is the tiresome complication.)
Note [Rules for imported functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
f = /\a. B.g a
RULE B.g Int = 1 + f Int
Note that
* The RULE is for an imported function.
* f is non-recursive
Now we
can get
f Int --> B.g Int Inlining f
--> 1 + f Int Firing RULE
and so the simplifier goes into an infinite loop. This
would not happen if the RULE was for a local function,
because we keep track of dependencies through rules. But
that is pretty much impossible to do for imported Ids. Suppose
f's definition had been
f = /\a. C.h a
where (by some long and devious process), C.h eventually inlines to
B.g. We could only spot such loops by exhaustively following
unfoldings of C.h etc, in case we reach B.g, and hence (via the RULE)
f.
Note that RULES for imported functions are important in practice; they
occur a lot in the libraries.
We regard this potential infinite loop as a *programmer* error.
It's up the programmer not to write silly rules like
RULE f x = f x
and the example above is just a more complicated version.
Note [Preventing loops due to imported functions rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider:
import GHC.Base (foldr)
{-# RULES "filterList" forall p. foldr (filterFB (:) p) [] = filter p #-}
filter p xs = build (\c n -> foldr (filterFB c p) n xs)
filterFB c p = ...
f = filter p xs
Note that filter is not a loop-breaker, so what happens is:
f = filter p xs
= {inline} build (\c n -> foldr (filterFB c p) n xs)
= {inline} foldr (filterFB (:) p) [] xs
= {RULE} filter p xs
We are in an infinite loop.
A more elaborate example (that I actually saw in practice when I went to
mark GHC.List.filter as INLINABLE) is as follows. Say I have this module:
{-# LANGUAGE RankNTypes #-}
module GHCList where
import Prelude hiding (filter)
import GHC.Base (build)
{-# INLINABLE filter #-}
filter :: (a -> Bool) -> [a] -> [a]
filter p [] = []
filter p (x:xs) = if p x then x : filter p xs else filter p xs
{-# NOINLINE [0] filterFB #-}
filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b
filterFB c p x r | p x = x `c` r
| otherwise = r
{-# RULES
"filter" [~1] forall p xs. filter p xs = build (\c n -> foldr
(filterFB c p) n xs)
"filterList" [1] forall p. foldr (filterFB (:) p) [] = filter p
#-}
Then (because RULES are applied inside INLINABLE unfoldings, but inlinings
are not), the unfolding given to "filter" in the interface file will be:
filter p [] = []
filter p (x:xs) = if p x then x : build (\c n -> foldr (filterFB c p) n xs)
else build (\c n -> foldr (filterFB c p) n xs
Note that because this unfolding does not mention "filter", filter is not
marked as a strong loop breaker. Therefore at a use site in another module:
filter p xs
= {inline}
case xs of [] -> []
(x:xs) -> if p x then x : build (\c n -> foldr (filterFB c p) n xs)
else build (\c n -> foldr (filterFB c p) n xs)
build (\c n -> foldr (filterFB c p) n xs)
= {inline} foldr (filterFB (:) p) [] xs
= {RULE} filter p xs
And we are in an infinite loop again, except that this time the loop is producing an
infinitely large *term* (an unrolling of filter) and so the simplifier finally
dies with "ticks exhausted"
Because of this problem, we make a small change in the occurrence analyser
designed to mark functions like "filter" as strong loop breakers on the basis that:
1. The RHS of filter mentions the local function "filterFB"
2. We have a rule which mentions "filterFB" on the LHS and "filter" on the RHS
So for each RULE for an *imported* function we are going to add
dependency edges between the *local* FVS of the rule LHS and the
*local* FVS of the rule RHS. We don't do anything special for RULES on
local functions because the standard occurrence analysis stuff is
pretty good at getting loop-breakerness correct there.
It is important to note that even with this extra hack we aren't always going to get
things right. For example, it might be that the rule LHS mentions an imported Id,
and another module has a RULE that can rewrite that imported Id to one of our local
Ids.
Note [Specialising imported functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BUT for *automatically-generated* rules, the programmer can't be
responsible for the "programmer error" in Note [Rules for imported
functions]. In paricular, consider specialising a recursive function
defined in another module. If we specialise a recursive function B.g,
we get
g_spec = .....(B.g Int).....
RULE B.g Int = g_spec
Here, g_spec doesn't look recursive, but when the rule fires, it
becomes so. And if B.g was mutually recursive, the loop might
not be as obvious as it is here.
To avoid this,
* When specialising a function that is a loop breaker,
give a NOINLINE pragma to the specialised function
Note [Glomming]
~~~~~~~~~~~~~~~
RULES for imported Ids can make something at the top refer to something at the bottom:
f = \x -> B.g (q x)
h = \y -> 3
RULE: B.g (q x) = h x
Applying this rule makes f refer to h, although f doesn't appear to
depend on h. (And, as in Note [Rules for imported functions], the
dependency might be more indirect. For example, f might mention C.t
rather than B.g, where C.t eventually inlines to B.g.)
NOTICE that this cannot happen for rules whose head is a
locally-defined function, because we accurately track dependencies
through RULES. It only happens for rules whose head is an imported
function (B.g in the example above).
Solution:
- When simplifying, bring all top level identifiers into
scope at the start, ignoring the Rec/NonRec structure, so
that when 'h' pops up in f's rhs, we find it in the in-scope set
(as the simplifier generally expects). This happens in simplTopBinds.
- In the occurrence analyser, if there are any out-of-scope
occurrences that pop out of the top, which will happen after
firing the rule: f = \x -> h x
h = \y -> 3
then just glom all the bindings into a single Rec, so that
the *next* iteration of the occurrence analyser will sort
them all out. This part happens in occurAnalysePgm.
------------------------------------------------------------
Note [Inline rules]
~~~~~~~~~~~~~~~~~~~
None of the above stuff about RULES applies to Inline Rules,
stored in a CoreUnfolding. The unfolding, if any, is simplified
at the same time as the regular RHS of the function (ie *not* like
Note [Rules are visible in their own rec group]), so it should be
treated *exactly* like an extra RHS.
Or, rather, when computing loop-breaker edges,
* If f has an INLINE pragma, and it is active, we treat the
INLINE rhs as f's rhs
* If it's inactive, we treat f as having no rhs
* If it has no INLINE pragma, we look at f's actual rhs
There is a danger that we'll be sub-optimal if we see this
f = ...f...
[INLINE f = ..no f...]
where f is recursive, but the INLINE is not. This can just about
happen with a sufficiently odd set of rules; eg
foo :: Int -> Int
{-# INLINE [1] foo #-}
foo x = x+1
bar :: Int -> Int
{-# INLINE [1] bar #-}
bar x = foo x + 1
{-# RULES "foo" [~1] forall x. foo x = bar x #-}
Here the RULE makes bar recursive; but it's INLINE pragma remains
non-recursive. It's tempting to then say that 'bar' should not be
a loop breaker, but an attempt to do so goes wrong in two ways:
a) We may get
$df = ...$cfoo...
$cfoo = ...$df....
[INLINE $cfoo = ...no-$df...]
But we want $cfoo to depend on $df explicitly so that we
put the bindings in the right order to inline $df in $cfoo
and perhaps break the loop altogether. (Maybe this
b)
Example [eftInt]
~~~~~~~~~~~~~~~
Example (from GHC.Enum):
eftInt :: Int# -> Int# -> [Int]
eftInt x y = ...(non-recursive)...
{-# INLINE [0] eftIntFB #-}
eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
eftIntFB c n x y = ...(non-recursive)...
{-# RULES
"eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
"eftIntList" [1] eftIntFB (:) [] = eftInt
#-}
Note [Specialisation rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this group, which is typical of what SpecConstr builds:
fs a = ....f (C a)....
f x = ....f (C a)....
{-# RULE f (C a) = fs a #-}
So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
- the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
- fs is inlined (say it's small)
- now there's another opportunity to apply the RULE
This showed up when compiling Control.Concurrent.Chan.getChanContents.
-}
type ImpRuleEdges = IdEnv IdSet -- Mapping from FVs of imported RULE LHSs to RHS FVs
noImpRuleEdges :: ImpRuleEdges
noImpRuleEdges = emptyVarEnv
occAnalBind :: OccEnv -- The incoming OccEnv
-> ImpRuleEdges
-> CoreBind
-> UsageDetails -- Usage details of scope
-> (UsageDetails, -- Of the whole let(rec)
[CoreBind])
occAnalBind env top_env (NonRec binder rhs) body_usage
= occAnalNonRecBind env top_env binder rhs body_usage
occAnalBind env top_env (Rec pairs) body_usage
= occAnalRecBind env top_env pairs body_usage
-----------------
occAnalNonRecBind :: OccEnv -> ImpRuleEdges -> Var -> CoreExpr
-> UsageDetails -> (UsageDetails, [CoreBind])
occAnalNonRecBind env imp_rule_edges binder rhs body_usage
| isTyVar binder -- A type let; we don't gather usage info
= (body_usage, [NonRec binder rhs])
| not (binder `usedIn` body_usage) -- It's not mentioned
= (body_usage, [])
| otherwise -- It's mentioned in the body
= (body_usage' +++ rhs_usage4, [NonRec tagged_binder rhs'])
where
(body_usage', tagged_binder) = tagBinder body_usage binder
(rhs_usage1, rhs') = occAnalNonRecRhs env tagged_binder rhs
rhs_usage2 = addIdOccs rhs_usage1 (idUnfoldingVars binder)
rhs_usage3 = addIdOccs rhs_usage2 (idRuleVars binder)
-- See Note [Rules are extra RHSs] and Note [Rule dependency info]
rhs_usage4 = maybe rhs_usage3 (addIdOccs rhs_usage3) $
lookupVarEnv imp_rule_edges binder
-- See Note [Preventing loops due to imported functions rules]
-----------------
occAnalRecBind :: OccEnv -> ImpRuleEdges -> [(Var,CoreExpr)]
-> UsageDetails -> (UsageDetails, [CoreBind])
occAnalRecBind env imp_rule_edges pairs body_usage
= foldr occAnalRec (body_usage, []) sccs
-- For a recursive group, we
-- * occ-analyse all the RHSs
-- * compute strongly-connected components
-- * feed those components to occAnalRec
-- See Note [Recursive bindings: the grand plan]
where
bndr_set = mkVarSet (map fst pairs)
sccs :: [SCC (Node Details)]
sccs = {-# SCC "occAnalBind.scc" #-}
stronglyConnCompFromEdgedVerticesUniqR nodes
nodes :: [Node Details]
nodes = {-# SCC "occAnalBind.assoc" #-}
map (makeNode env imp_rule_edges bndr_set) pairs
type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
-- which is gotten from the Id.
data Details
= ND { nd_bndr :: Id -- Binder
, nd_rhs :: CoreExpr -- RHS, already occ-analysed
, nd_uds :: UsageDetails -- Usage from RHS, and RULES, and stable unfoldings
-- ignoring phase (ie assuming all are active)
-- See Note [Forming Rec groups]
, nd_inl :: IdSet -- Free variables of
-- the stable unfolding (if present and active)
-- or the RHS (if not)
-- but excluding any RULES
-- This is the IdSet that may be used if the Id is inlined
, nd_weak :: IdSet -- Binders of this Rec that are mentioned in nd_uds
-- but are *not* in nd_inl. These are the ones whose
-- dependencies might not be respected by loop_breaker_nodes
-- See Note [Weak loop breakers]
, nd_active_rule_fvs :: IdSet -- Free variables of the RHS of active RULES
}
instance Outputable Details where
ppr nd = text "ND" <> braces
(sep [ text "bndr =" <+> ppr (nd_bndr nd)
, text "uds =" <+> ppr (nd_uds nd)
, text "inl =" <+> ppr (nd_inl nd)
, text "weak =" <+> ppr (nd_weak nd)
, text "rule =" <+> ppr (nd_active_rule_fvs nd)
])
makeNode :: OccEnv -> ImpRuleEdges -> VarSet -> (Var, CoreExpr) -> Node Details
-- See Note [Recursive bindings: the grand plan]
makeNode env imp_rule_edges bndr_set (bndr, rhs)
= (details, varUnique bndr, nonDetKeysUFM node_fvs)
-- It's OK to use nonDetKeysUFM here as stronglyConnCompFromEdgedVerticesR
-- is still deterministic with edges in nondeterministic order as
-- explained in Note [Deterministic SCC] in Digraph.
where
details = ND { nd_bndr = bndr
, nd_rhs = rhs'
, nd_uds = rhs_usage3
, nd_weak = node_fvs `minusVarSet` inl_fvs
, nd_inl = inl_fvs
, nd_active_rule_fvs = active_rule_fvs }
-- Constructing the edges for the main Rec computation
-- See Note [Forming Rec groups]
(rhs_usage1, rhs') = occAnalRecRhs env rhs
rhs_usage2 = addIdOccs rhs_usage1 all_rule_fvs -- Note [Rules are extra RHSs]
-- Note [Rule dependency info]
rhs_usage3 = case mb_unf_fvs of
Just unf_fvs -> addIdOccs rhs_usage2 unf_fvs
Nothing -> rhs_usage2
node_fvs = udFreeVars bndr_set rhs_usage3
-- Finding the free variables of the rules
is_active = occ_rule_act env :: Activation -> Bool
rules = filterOut isBuiltinRule (idCoreRules bndr)
rules_w_fvs :: [(Activation, VarSet)] -- Find the RHS fvs
rules_w_fvs = maybe id (\ids -> ((AlwaysActive, ids):)) (lookupVarEnv imp_rule_edges bndr)
-- See Note [Preventing loops due to imported functions rules]
[ (ru_act rule, fvs)
| rule <- rules
, let fvs = exprFreeVars (ru_rhs rule)
`delVarSetList` ru_bndrs rule
, not (isEmptyVarSet fvs) ]
all_rule_fvs = rule_lhs_fvs `unionVarSet` rule_rhs_fvs
rule_rhs_fvs = mapUnionVarSet snd rules_w_fvs
rule_lhs_fvs = mapUnionVarSet (\ru -> exprsFreeVars (ru_args ru)
`delVarSetList` ru_bndrs ru) rules
active_rule_fvs = unionVarSets [fvs | (a,fvs) <- rules_w_fvs, is_active a]
-- Finding the free variables of the INLINE pragma (if any)
unf = realIdUnfolding bndr -- Ignore any current loop-breaker flag
mb_unf_fvs = stableUnfoldingVars unf
-- Find the "nd_inl" free vars; for the loop-breaker phase
inl_fvs = case mb_unf_fvs of
Nothing -> udFreeVars bndr_set rhs_usage1 -- No INLINE, use RHS
Just unf_fvs -> unf_fvs
-- We could check for an *active* INLINE (returning
-- emptyVarSet for an inactive one), but is_active
-- isn't the right thing (it tells about
-- RULE activation), so we'd need more plumbing
-----------------------------
occAnalRec :: SCC (Node Details)
-> (UsageDetails, [CoreBind])
-> (UsageDetails, [CoreBind])
-- The NonRec case is just like a Let (NonRec ...) above
occAnalRec (AcyclicSCC (ND { nd_bndr = bndr, nd_rhs = rhs, nd_uds = rhs_uds}, _, _))
(body_uds, binds)
| not (bndr `usedIn` body_uds)
= (body_uds, binds) -- See Note [Dead code]
| otherwise -- It's mentioned in the body
= (body_uds' +++ rhs_uds,
NonRec tagged_bndr rhs : binds)
where
(body_uds', tagged_bndr) = tagBinder body_uds bndr
-- The Rec case is the interesting one
-- See Note [Recursive bindings: the grand plan]
-- See Note [Loop breaking]
occAnalRec (CyclicSCC nodes) (body_uds, binds)
| not (any (`usedIn` body_uds) bndrs) -- NB: look at body_uds, not total_uds
= (body_uds, binds) -- See Note [Dead code]
| otherwise -- At this point we always build a single Rec
= -- pprTrace "occAnalRec" (vcat
-- [ text "weak_fvs" <+> ppr weak_fvs
-- , text "tagged details" <+> ppr tagged_details_s
-- , text "lb nodes" <+> ppr loop_breaker_nodes])
(final_uds, Rec pairs : binds)
where
details_s :: [Details]
details_s = map fstOf3 nodes
bndrs = [b | (ND { nd_bndr = b }) <- details_s]
bndr_set = mkVarSet bndrs
----------------------------
-- Tag the binders with their occurrence info
tagged_details_s :: [Details]
tagged_details_s = map tag_details details_s
total_uds = foldl add_uds body_uds details_s
final_uds = total_uds `minusVarEnv` bndr_set
add_uds usage_so_far nd = usage_so_far +++ nd_uds nd
tag_details :: Details -> Details
tag_details details@(ND { nd_bndr = bndr })
| let bndr1 = setBinderOcc total_uds bndr
= details { nd_bndr = bndr1 }
---------------------------
-- Now reconstruct the cycle
pairs :: [(Id,CoreExpr)]
pairs | isEmptyVarSet weak_fvs = reOrderNodes 0 bndr_set weak_fvs loop_breaker_nodes []
| otherwise = loopBreakNodes 0 bndr_set weak_fvs loop_breaker_nodes []
-- If weak_fvs is empty, the loop_breaker_nodes will include
-- all the edges in the original scope edges [remember,
-- weak_fvs is the difference between scope edges and
-- lb-edges], so a fresh SCC computation would yield a
-- single CyclicSCC result; and reOrderNodes deals with
-- exactly that case
weak_fvs :: VarSet
weak_fvs = mapUnionVarSet nd_weak details_s
-- See Note [Choosing loop breakers] for loop_breaker_nodes
loop_breaker_nodes :: [Node Details]
loop_breaker_nodes = map mk_lb_node tagged_details_s
mk_lb_node details@(ND { nd_bndr = b, nd_inl = inl_fvs })
= (details, varUnique b, nonDetKeysUFM (extendFvs_ rule_fv_env inl_fvs))
-- It's OK to use nonDetKeysUFM here as
-- stronglyConnCompFromEdgedVerticesR is still deterministic with edges
-- in nondeterministic order as explained in
-- Note [Deterministic SCC] in Digraph.
------------------------------------
rule_fv_env :: IdEnv IdSet
-- Maps a variable f to the variables from this group
-- mentioned in RHS of active rules for f
-- Domain is *subset* of bound vars (others have no rule fvs)
rule_fv_env = transClosureFV (mkVarEnv init_rule_fvs)
init_rule_fvs -- See Note [Finding rule RHS free vars]
= [ (b, trimmed_rule_fvs)
| ND { nd_bndr = b, nd_active_rule_fvs = rule_fvs } <- details_s
, let trimmed_rule_fvs = rule_fvs `intersectVarSet` bndr_set
, not (isEmptyVarSet trimmed_rule_fvs) ]
{-
@loopBreakSCC@ is applied to the list of (binder,rhs) pairs for a cyclic
strongly connected component (there's guaranteed to be a cycle). It returns the
same pairs, but
a) in a better order,
b) with some of the Ids having a IAmALoopBreaker pragma
The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
that the simplifier can guarantee not to loop provided it never records an inlining
for these no-inline guys.
Furthermore, the order of the binds is such that if we neglect dependencies
on the no-inline Ids then the binds are topologically sorted. This means
that the simplifier will generally do a good job if it works from top bottom,
recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
-}
type Binding = (Id,CoreExpr)
mk_loop_breaker :: Node Details -> Binding
mk_loop_breaker (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
= (setIdOccInfo bndr strongLoopBreaker, rhs)
mk_non_loop_breaker :: VarSet -> Node Details -> Binding
-- See Note [Weak loop breakers]
mk_non_loop_breaker weak_fvs (ND { nd_bndr = bndr, nd_rhs = rhs}, _, _)
| bndr `elemVarSet` weak_fvs = (setIdOccInfo bndr weakLoopBreaker, rhs)
| otherwise = (bndr, rhs)
udFreeVars :: VarSet -> UsageDetails -> VarSet
-- Find the subset of bndrs that are mentioned in uds
udFreeVars bndrs uds = intersectUFM_C (\b _ -> b) bndrs uds
loopBreakNodes :: Int
-> VarSet -- All binders
-> VarSet -- Binders whose dependencies may be "missing"
-- See Note [Weak loop breakers]
-> [Node Details]
-> [Binding] -- Append these to the end
-> [Binding]
-- Return the bindings sorted into a plausible order, and marked with loop breakers.
loopBreakNodes depth bndr_set weak_fvs nodes binds
= go (stronglyConnCompFromEdgedVerticesUniqR nodes) binds
where
go [] binds = binds
go (scc:sccs) binds = loop_break_scc scc (go sccs binds)
loop_break_scc scc binds
= case scc of
AcyclicSCC node -> mk_non_loop_breaker weak_fvs node : binds
CyclicSCC nodes -> reOrderNodes depth bndr_set weak_fvs nodes binds
reOrderNodes :: Int -> VarSet -> VarSet -> [Node Details] -> [Binding] -> [Binding]
-- Choose a loop breaker, mark it no-inline,
-- do SCC analysis on the rest, and recursively sort them out
reOrderNodes _ _ _ [] _ = panic "reOrderNodes"
reOrderNodes _ _ _ [node] binds = mk_loop_breaker node : binds
reOrderNodes depth bndr_set weak_fvs (node : nodes) binds
= -- pprTrace "reOrderNodes" (text "unchosen" <+> ppr unchosen $$
-- text "chosen" <+> ppr chosen_nodes) $
loopBreakNodes new_depth bndr_set weak_fvs unchosen $
(map mk_loop_breaker chosen_nodes ++ binds)
where
(chosen_nodes, unchosen) = choose_loop_breaker (score node) [node] [] nodes
approximate_loop_breaker = depth >= 2
new_depth | approximate_loop_breaker = 0
| otherwise = depth+1
-- After two iterations (d=0, d=1) give up
-- and approximate, returning to d=0
choose_loop_breaker :: Int -- Best score so far
-> [Node Details] -- Nodes with this score
-> [Node Details] -- Nodes with higher scores
-> [Node Details] -- Unprocessed nodes
-> ([Node Details], [Node Details])
-- This loop looks for the bind with the lowest score
-- to pick as the loop breaker. The rest accumulate in
choose_loop_breaker _ loop_nodes acc []
= (loop_nodes, acc) -- Done
-- If approximate_loop_breaker is True, we pick *all*
-- nodes with lowest score, else just one
-- See Note [Complexity of loop breaking]
choose_loop_breaker loop_sc loop_nodes acc (node : nodes)
| sc < loop_sc -- Lower score so pick this new one
= choose_loop_breaker sc [node] (loop_nodes ++ acc) nodes
| approximate_loop_breaker && sc == loop_sc
= choose_loop_breaker loop_sc (node : loop_nodes) acc nodes
| otherwise -- Higher score so don't pick it
= choose_loop_breaker loop_sc loop_nodes (node : acc) nodes
where
sc = score node
score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
score (ND { nd_bndr = bndr, nd_rhs = rhs }, _, _)
| not (isId bndr) = 100 -- A type or cercion variable is never a loop breaker
| isDFunId bndr = 9 -- Never choose a DFun as a loop breaker
-- Note [DFuns should not be loop breakers]
| Just be_very_keen <- hasStableCoreUnfolding_maybe (idUnfolding bndr)
= if be_very_keen then 6 -- Note [Loop breakers and INLINE/INLINABLE pragmas]
else 3
-- Data structures are more important than INLINE pragmas
-- so that dictionary/method recursion unravels
-- Note that this case hits all stable unfoldings, so we
-- never look at 'rhs' for stable unfoldings. That's right, because
-- 'rhs' is irrelevant for inlining things with a stable unfolding
| is_con_app rhs = 5 -- Data types help with cases: Note [Constructor applications]
| exprIsTrivial rhs = 10 -- Practically certain to be inlined
-- Used to have also: && not (isExportedId bndr)
-- But I found this sometimes cost an extra iteration when we have
-- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
-- where df is the exported dictionary. Then df makes a really
-- bad choice for loop breaker
-- If an Id is marked "never inline" then it makes a great loop breaker
-- The only reason for not checking that here is that it is rare
-- and I've never seen a situation where it makes a difference,
-- so it probably isn't worth the time to test on every binder
-- | isNeverActive (idInlinePragma bndr) = -10
| isOneOcc (idOccInfo bndr) = 2 -- Likely to be inlined
| canUnfold (realIdUnfolding bndr) = 1
-- The Id has some kind of unfolding
-- Ignore loop-breaker-ness here because that is what we are setting!
| otherwise = 0
-- Checking for a constructor application
-- Cheap and cheerful; the simplifier moves casts out of the way
-- The lambda case is important to spot x = /\a. C (f a)
-- which comes up when C is a dictionary constructor and
-- f is a default method.
-- Example: the instance for Show (ST s a) in GHC.ST
--
-- However we *also* treat (\x. C p q) as a con-app-like thing,
-- Note [Closure conversion]
is_con_app (Var v) = isConLikeId v
is_con_app (App f _) = is_con_app f
is_con_app (Lam _ e) = is_con_app e
is_con_app (Tick _ e) = is_con_app e
is_con_app _ = False
{-
Note [Complexity of loop breaking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The loop-breaking algorithm knocks out one binder at a time, and
performs a new SCC analysis on the remaining binders. That can
behave very badly in tightly-coupled groups of bindings; in the
worst case it can be (N**2)*log N, because it does a full SCC
on N, then N-1, then N-2 and so on.
To avoid this, we switch plans after 2 (or whatever) attempts:
Plan A: pick one binder with the lowest score, make it
a loop breaker, and try again
Plan B: pick *all* binders with the lowest score, make them
all loop breakers, and try again
Since there are only a small finite number of scores, this will
terminate in a constant number of iterations, rather than O(N)
iterations.
You might thing that it's very unlikely, but RULES make it much
more likely. Here's a real example from Trac #1969:
Rec { $dm = \d.\x. op d
{-# RULES forall d. $dm Int d = $s$dm1
forall d. $dm Bool d = $s$dm2 #-}
dInt = MkD .... opInt ...
dInt = MkD .... opBool ...
opInt = $dm dInt
opBool = $dm dBool
$s$dm1 = \x. op dInt
$s$dm2 = \x. op dBool }
The RULES stuff means that we can't choose $dm as a loop breaker
(Note [Choosing loop breakers]), so we must choose at least (say)
opInt *and* opBool, and so on. The number of loop breakders is
linear in the number of instance declarations.
Note [Loop breakers and INLINE/INLINABLE pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Avoid choosing a function with an INLINE pramga as the loop breaker!
If such a function is mutually-recursive with a non-INLINE thing,
then the latter should be the loop-breaker.
It's vital to distinguish between INLINE and INLINABLE (the
Bool returned by hasStableCoreUnfolding_maybe). If we start with
Rec { {-# INLINABLE f #-}
f x = ...f... }
and then worker/wrapper it through strictness analysis, we'll get
Rec { {-# INLINABLE $wf #-}
$wf p q = let x = (p,q) in ...f...
{-# INLINE f #-}
f x = case x of (p,q) -> $wf p q }
Now it is vital that we choose $wf as the loop breaker, so we can
inline 'f' in '$wf'.
Note [DFuns should not be loop breakers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's particularly bad to make a DFun into a loop breaker. See
Note [How instance declarations are translated] in TcInstDcls
We give DFuns a higher score than ordinary CONLIKE things because
if there's a choice we want the DFun to be the non-looop breker. Eg
rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
$fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
{-# DFUN #-}
$fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
}
Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
if we can't unravel the DFun first.
Note [Constructor applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's really really important to inline dictionaries. Real
example (the Enum Ordering instance from GHC.Base):
rec f = \ x -> case d of (p,q,r) -> p x
g = \ x -> case d of (p,q,r) -> q x
d = (v, f, g)
Here, f and g occur just once; but we can't inline them into d.
On the other hand we *could* simplify those case expressions if
we didn't stupidly choose d as the loop breaker.
But we won't because constructor args are marked "Many".
Inlining dictionaries is really essential to unravelling
the loops in static numeric dictionaries, see GHC.Float.
Note [Closure conversion]
~~~~~~~~~~~~~~~~~~~~~~~~~
We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
The immediate motivation came from the result of a closure-conversion transformation
which generated code like this:
data Clo a b = forall c. Clo (c -> a -> b) c
($:) :: Clo a b -> a -> b
Clo f env $: x = f env x
rec { plus = Clo plus1 ()
; plus1 _ n = Clo plus2 n
; plus2 Zero n = n
; plus2 (Succ m) n = Succ (plus $: m $: n) }
If we inline 'plus' and 'plus1', everything unravels nicely. But if
we choose 'plus1' as the loop breaker (which is entirely possible
otherwise), the loop does not unravel nicely.
@occAnalRhs@ deals with the question of bindings where the Id is marked
by an INLINE pragma. For these we record that anything which occurs
in its RHS occurs many times. This pessimistically assumes that ths
inlined binder also occurs many times in its scope, but if it doesn't
we'll catch it next time round. At worst this costs an extra simplifier pass.
ToDo: try using the occurrence info for the inline'd binder.
[March 97] We do the same for atomic RHSs. Reason: see notes with loopBreakSCC.
[June 98, SLPJ] I've undone this change; I don't understand it. See notes with loopBreakSCC.
-}
occAnalRecRhs :: OccEnv -> CoreExpr -- Rhs
-> (UsageDetails, CoreExpr)
-- Returned usage details covers only the RHS,
-- and *not* the RULE or INLINE template for the Id
occAnalRecRhs env rhs = occAnal (rhsCtxt env) rhs
occAnalNonRecRhs :: OccEnv
-> Id -> CoreExpr -- Binder and rhs
-- Binder is already tagged with occurrence info
-> (UsageDetails, CoreExpr)
-- Returned usage details covers only the RHS,
-- and *not* the RULE or INLINE template for the Id
occAnalNonRecRhs env bndr rhs
= occAnal rhs_env rhs
where
-- See Note [Cascading inlines]
env1 | certainly_inline = env
| otherwise = rhsCtxt env
-- See Note [Use one-shot info]
rhs_env = env1 { occ_one_shots = argOneShots OneShotLam dmd }
certainly_inline -- See Note [Cascading inlines]
= case idOccInfo bndr of
OneOcc in_lam one_br _ -> not in_lam && one_br && active && not_stable
_ -> False
dmd = idDemandInfo bndr
active = isAlwaysActive (idInlineActivation bndr)
not_stable = not (isStableUnfolding (idUnfolding bndr))
addIdOccs :: UsageDetails -> VarSet -> UsageDetails
addIdOccs usage id_set = nonDetFoldUFM addIdOcc usage id_set
-- It's OK to use nonDetFoldUFM here because addIdOcc commutes
addIdOcc :: Id -> UsageDetails -> UsageDetails
addIdOcc v u | isId v = addOneOcc u v NoOccInfo
| otherwise = u
-- Give a non-committal binder info (i.e NoOccInfo) because
-- a) Many copies of the specialised thing can appear
-- b) We don't want to substitute a BIG expression inside a RULE
-- even if that's the only occurrence of the thing
-- (Same goes for INLINE.)
{-
Note [Cascading inlines]
~~~~~~~~~~~~~~~~~~~~~~~~
By default we use an rhsCtxt for the RHS of a binding. This tells the
occ anal n that it's looking at an RHS, which has an effect in
occAnalApp. In particular, for constructor applications, it makes
the arguments appear to have NoOccInfo, so that we don't inline into
them. Thus x = f y
k = Just x
we do not want to inline x.
But there's a problem. Consider
x1 = a0 : []
x2 = a1 : x1
x3 = a2 : x2
g = f x3
First time round, it looks as if x1 and x2 occur as an arg of a
let-bound constructor ==> give them a many-occurrence.
But then x3 is inlined (unconditionally as it happens) and
next time round, x2 will be, and the next time round x1 will be
Result: multiple simplifier iterations. Sigh.
So, when analysing the RHS of x3 we notice that x3 will itself
definitely inline the next time round, and so we analyse x3's rhs in
an ordinary context, not rhsCtxt. Hence the "certainly_inline" stuff.
Annoyingly, we have to approximate SimplUtils.preInlineUnconditionally.
If we say "yes" when preInlineUnconditionally says "no" the simplifier iterates
indefinitely:
x = f y
k = Just x
inline ==>
k = Just (f y)
float ==>
x1 = f y
k = Just x1
This is worse than the slow cascade, so we only want to say "certainly_inline"
if it really is certain. Look at the note with preInlineUnconditionally
for the various clauses.
Expressions
~~~~~~~~~~~
-}
occAnal :: OccEnv
-> CoreExpr
-> (UsageDetails, -- Gives info only about the "interesting" Ids
CoreExpr)
occAnal _ expr@(Type _) = (emptyDetails, expr)
occAnal _ expr@(Lit _) = (emptyDetails, expr)
occAnal env expr@(Var v) = (mkOneOcc env v False, expr)
-- At one stage, I gathered the idRuleVars for v here too,
-- which in a way is the right thing to do.
-- But that went wrong right after specialisation, when
-- the *occurrences* of the overloaded function didn't have any
-- rules in them, so the *specialised* versions looked as if they
-- weren't used at all.
occAnal _ (Coercion co)
= (addIdOccs emptyDetails (coVarsOfCo co), Coercion co)
-- See Note [Gather occurrences of coercion variables]
{-
Note [Gather occurrences of coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to gather info about what coercion variables appear, so that
we can sort them into the right place when doing dependency analysis.
-}
occAnal env (Tick tickish body)
| tickish `tickishScopesLike` SoftScope
= (usage, Tick tickish body')
| Breakpoint _ ids <- tickish
= (usage_lam +++ mkVarEnv (zip ids (repeat NoOccInfo)), Tick tickish body')
-- never substitute for any of the Ids in a Breakpoint
| otherwise
= (usage_lam, Tick tickish body')
where
!(usage,body') = occAnal env body
-- for a non-soft tick scope, we can inline lambdas only
usage_lam = mapVarEnv markInsideLam usage
occAnal env (Cast expr co)
= case occAnal env expr of { (usage, expr') ->
let usage1 = markManyIf (isRhsEnv env) usage
usage2 = addIdOccs usage1 (coVarsOfCo co)
-- See Note [Gather occurrences of coercion variables]
in (usage2, Cast expr' co)
-- If we see let x = y `cast` co
-- then mark y as 'Many' so that we don't
-- immediately inline y again.
}
occAnal env app@(App _ _)
= occAnalApp env (collectArgsTicks tickishFloatable app)
-- Ignore type variables altogether
-- (a) occurrences inside type lambdas only not marked as InsideLam
-- (b) type variables not in environment
occAnal env (Lam x body) | isTyVar x
= case occAnal env body of { (body_usage, body') ->
(body_usage, Lam x body')
}
-- For value lambdas we do a special hack. Consider
-- (\x. \y. ...x...)
-- If we did nothing, x is used inside the \y, so would be marked
-- as dangerous to dup. But in the common case where the abstraction
-- is applied to two arguments this is over-pessimistic.
-- So instead, we just mark each binder with its occurrence
-- info in the *body* of the multiple lambda.
-- Then, the simplifier is careful when partially applying lambdas.
occAnal env expr@(Lam _ _)
= case occAnal env_body body of { (body_usage, body') ->
let
(final_usage, tagged_binders) = tagLamBinders body_usage binders'
-- Use binders' to put one-shot info on the lambdas
really_final_usage
| all isOneShotBndr binders' = final_usage
| otherwise = mapVarEnv markInsideLam final_usage
in
(really_final_usage, mkLams tagged_binders body') }
where
(binders, body) = collectBinders expr
(env_body, binders') = oneShotGroup env binders
occAnal env (Case scrut bndr ty alts)
= case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
let
alts_usage = foldr combineAltsUsageDetails emptyDetails alts_usage_s
(alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
total_usage = scrut_usage +++ alts_usage1
in
total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
where
-- Note [Case binder usage]
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- The case binder gets a usage of either "many" or "dead", never "one".
-- Reason: we like to inline single occurrences, to eliminate a binding,
-- but inlining a case binder *doesn't* eliminate a binding.
-- We *don't* want to transform
-- case x of w { (p,q) -> f w }
-- into
-- case x of w { (p,q) -> f (p,q) }
tag_case_bndr usage bndr
= case lookupVarEnv usage bndr of
Nothing -> (usage, setIdOccInfo bndr IAmDead)
Just _ -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
alt_env = mkAltEnv env scrut bndr
occ_anal_alt = occAnalAlt alt_env
occ_anal_scrut (Var v) (alt1 : other_alts)
| not (null other_alts) || not (isDefaultAlt alt1)
= (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
-- in an interesting context; the case has
-- at least one non-default alternative
occ_anal_scrut (Tick t e) alts
| t `tickishScopesLike` SoftScope
-- No reason to not look through all ticks here, but only
-- for soft-scoped ticks we can do so without having to
-- update returned occurance info (see occAnal)
= second (Tick t) $ occ_anal_scrut e alts
occ_anal_scrut scrut _alts
= occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
occAnal env (Let bind body)
= case occAnal env body of { (body_usage, body') ->
case occAnalBind env noImpRuleEdges bind body_usage of { (final_usage, new_binds) ->
(final_usage, mkLets new_binds body') }}
occAnalArgs :: OccEnv -> [CoreExpr] -> [OneShots] -> (UsageDetails, [CoreExpr])
occAnalArgs _ [] _
= (emptyDetails, [])
occAnalArgs env (arg:args) one_shots
| isTypeArg arg
= case occAnalArgs env args one_shots of { (uds, args') ->
(uds, arg:args') }
| otherwise
= case argCtxt env one_shots of { (arg_env, one_shots') ->
case occAnal arg_env arg of { (uds1, arg') ->
case occAnalArgs env args one_shots' of { (uds2, args') ->
(uds1 +++ uds2, arg':args') }}}
{-
Applications are dealt with specially because we want
the "build hack" to work.
Note [Arguments of let-bound constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f x = let y = expensive x in
let z = (True,y) in
(case z of {(p,q)->q}, case z of {(p,q)->q})
We feel free to duplicate the WHNF (True,y), but that means
that y may be duplicated thereby.
If we aren't careful we duplicate the (expensive x) call!
Constructors are rather like lambdas in this way.
-}
occAnalApp :: OccEnv
-> (Expr CoreBndr, [Arg CoreBndr], [Tickish Id])
-> (UsageDetails, Expr CoreBndr)
occAnalApp env (Var fun, args, ticks)
| null ticks = (uds, mkApps (Var fun) args')
| otherwise = (uds, mkTicks ticks $ mkApps (Var fun) args')
where
uds = fun_uds +++ final_args_uds
!(args_uds, args') = occAnalArgs env args one_shots
!final_args_uds = markManyIf (isRhsEnv env && is_exp) args_uds
-- We mark the free vars of the argument of a constructor or PAP
-- as "many", if it is the RHS of a let(rec).
-- This means that nothing gets inlined into a constructor argument
-- position, which is what we want. Typically those constructor
-- arguments are just variables, or trivial expressions.
--
-- This is the *whole point* of the isRhsEnv predicate
-- See Note [Arguments of let-bound constructors]
n_val_args = valArgCount args
fun_uds = mkOneOcc env fun (n_val_args > 0)
is_exp = isExpandableApp fun n_val_args
-- See Note [CONLIKE pragma] in BasicTypes
-- The definition of is_exp should match that in
-- Simplify.prepareRhs
one_shots = argsOneShots (idStrictness fun) n_val_args
-- See Note [Use one-shot info]
occAnalApp env (fun, args, ticks)
= (fun_uds +++ args_uds, mkTicks ticks $ mkApps fun' args')
where
!(fun_uds, fun') = occAnal (addAppCtxt env args) fun
-- The addAppCtxt is a bit cunning. One iteration of the simplifier
-- often leaves behind beta redexs like
-- (\x y -> e) a1 a2
-- Here we would like to mark x,y as one-shot, and treat the whole
-- thing much like a let. We do this by pushing some True items
-- onto the context stack.
!(args_uds, args') = occAnalArgs env args []
markManyIf :: Bool -- If this is true
-> UsageDetails -- Then do markMany on this
-> UsageDetails
markManyIf True uds = mapVarEnv markMany uds
markManyIf False uds = uds
{-
Note [Use one-shot information]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The occurrrence analyser propagates one-shot-lambda information in two
situations:
* Applications: eg build (\c n -> blah)
Propagate one-shot info from the strictness signature of 'build' to
the \c n.
This strictness signature can come from a module interface, in the case of
an imported function, or from a previous run of the demand analyser.
* Let-bindings: eg let f = \c. let ... in \n -> blah
in (build f, build f)
Propagate one-shot info from the demanand-info on 'f' to the
lambdas in its RHS (which may not be syntactically at the top)
This information must have come from a previous run of the demanand
analyser.
Previously, the demand analyser would *also* set the one-shot information, but
that code was buggy (see #11770), so doing it only in on place, namely here, is
saner.
Note [Binders in case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case x of y { (a,b) -> f y }
We treat 'a', 'b' as dead, because they don't physically occur in the
case alternative. (Indeed, a variable is dead iff it doesn't occur in
its scope in the output of OccAnal.) It really helps to know when
binders are unused. See esp the call to isDeadBinder in
Simplify.mkDupableAlt
In this example, though, the Simplifier will bring 'a' and 'b' back to
life, beause it binds 'y' to (a,b) (imagine got inlined and
scrutinised y).
-}
occAnalAlt :: (OccEnv, Maybe (Id, CoreExpr))
-> CoreAlt
-> (UsageDetails, Alt IdWithOccInfo)
occAnalAlt (env, scrut_bind) (con, bndrs, rhs)
= case occAnal env rhs of { (rhs_usage1, rhs1) ->
let
(alt_usg, tagged_bndrs) = tagLamBinders rhs_usage1 bndrs
-- See Note [Binders in case alternatives]
(alt_usg', rhs2) =
wrapAltRHS env scrut_bind alt_usg tagged_bndrs rhs1
in
(alt_usg', (con, tagged_bndrs, rhs2)) }
wrapAltRHS :: OccEnv
-> Maybe (Id, CoreExpr) -- proxy mapping generated by mkAltEnv
-> UsageDetails -- usage for entire alt (p -> rhs)
-> [Var] -- alt binders
-> CoreExpr -- alt RHS
-> (UsageDetails, CoreExpr)
wrapAltRHS env (Just (scrut_var, let_rhs)) alt_usg bndrs alt_rhs
| occ_binder_swap env
, scrut_var `usedIn` alt_usg -- bndrs are not be present in alt_usg so this
-- handles condition (a) in Note [Binder swap]
, not captured -- See condition (b) in Note [Binder swap]
= ( alt_usg' +++ let_rhs_usg
, Let (NonRec tagged_scrut_var let_rhs') alt_rhs )
where
captured = any (`usedIn` let_rhs_usg) bndrs
-- The rhs of the let may include coercion variables
-- if the scrutinee was a cast, so we must gather their
-- usage. See Note [Gather occurrences of coercion variables]
(let_rhs_usg, let_rhs') = occAnal env let_rhs
(alt_usg', tagged_scrut_var) = tagBinder alt_usg scrut_var
wrapAltRHS _ _ alt_usg _ alt_rhs
= (alt_usg, alt_rhs)
{-
************************************************************************
* *
OccEnv
* *
************************************************************************
-}
data OccEnv
= OccEnv { occ_encl :: !OccEncl -- Enclosing context information
, occ_one_shots :: !OneShots -- Tells about linearity
, occ_gbl_scrut :: GlobalScruts
, occ_rule_act :: Activation -> Bool -- Which rules are active
-- See Note [Finding rule RHS free vars]
, occ_binder_swap :: !Bool -- enable the binder_swap
-- See CorePrep Note [Dead code in CorePrep]
}
type GlobalScruts = IdSet -- See Note [Binder swap on GlobalId scrutinees]
-----------------------------
-- OccEncl is used to control whether to inline into constructor arguments
-- For example:
-- x = (p,q) -- Don't inline p or q
-- y = /\a -> (p a, q a) -- Still don't inline p or q
-- z = f (p,q) -- Do inline p,q; it may make a rule fire
-- So OccEncl tells enought about the context to know what to do when
-- we encounter a constructor application or PAP.
data OccEncl
= OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
-- Don't inline into constructor args here
| OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
-- Do inline into constructor args here
instance Outputable OccEncl where
ppr OccRhs = text "occRhs"
ppr OccVanilla = text "occVanilla"
type OneShots = [OneShotInfo]
-- [] No info
--
-- one_shot_info:ctxt Analysing a function-valued expression that
-- will be applied as described by one_shot_info
initOccEnv :: (Activation -> Bool) -> OccEnv
initOccEnv active_rule
= OccEnv { occ_encl = OccVanilla
, occ_one_shots = []
, occ_gbl_scrut = emptyVarSet
, occ_rule_act = active_rule
, occ_binder_swap = True }
vanillaCtxt :: OccEnv -> OccEnv
vanillaCtxt env = env { occ_encl = OccVanilla, occ_one_shots = [] }
rhsCtxt :: OccEnv -> OccEnv
rhsCtxt env = env { occ_encl = OccRhs, occ_one_shots = [] }
argCtxt :: OccEnv -> [OneShots] -> (OccEnv, [OneShots])
argCtxt env []
= (env { occ_encl = OccVanilla, occ_one_shots = [] }, [])
argCtxt env (one_shots:one_shots_s)
= (env { occ_encl = OccVanilla, occ_one_shots = one_shots }, one_shots_s)
isRhsEnv :: OccEnv -> Bool
isRhsEnv (OccEnv { occ_encl = OccRhs }) = True
isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
oneShotGroup :: OccEnv -> [CoreBndr]
-> ( OccEnv
, [CoreBndr] )
-- The result binders have one-shot-ness set that they might not have had originally.
-- This happens in (build (\c n -> e)). Here the occurrence analyser
-- linearity context knows that c,n are one-shot, and it records that fact in
-- the binder. This is useful to guide subsequent float-in/float-out tranformations
oneShotGroup env@(OccEnv { occ_one_shots = ctxt }) bndrs
= go ctxt bndrs []
where
go ctxt [] rev_bndrs
= ( env { occ_one_shots = ctxt, occ_encl = OccVanilla }
, reverse rev_bndrs )
go [] bndrs rev_bndrs
= ( env { occ_one_shots = [], occ_encl = OccVanilla }
, reverse rev_bndrs ++ bndrs )
go ctxt (bndr:bndrs) rev_bndrs
| isId bndr
= case ctxt of
[] -> go [] bndrs (bndr : rev_bndrs)
(one_shot : ctxt) -> go ctxt bndrs (bndr': rev_bndrs)
where
bndr' = updOneShotInfo bndr one_shot
-- Use updOneShotInfo, not setOneShotInfo, as pre-existing
-- one-shot info might be better than what we can infer, e.g.
-- due to explicit use of the magic 'oneShot' function.
-- See Note [The oneShot function]
| otherwise
= go ctxt bndrs (bndr:rev_bndrs)
addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
addAppCtxt env@(OccEnv { occ_one_shots = ctxt }) args
= env { occ_one_shots = replicate (valArgCount args) OneShotLam ++ ctxt }
transClosureFV :: UniqFM VarSet -> UniqFM VarSet
-- If (f,g), (g,h) are in the input, then (f,h) is in the output
-- as well as (f,g), (g,h)
transClosureFV env
| no_change = env
| otherwise = transClosureFV (listToUFM new_fv_list)
where
(no_change, new_fv_list) = mapAccumL bump True (nonDetUFMToList env)
-- It's OK to use nonDetUFMToList here because we'll forget the
-- ordering by creating a new set with listToUFM
bump no_change (b,fvs)
| no_change_here = (no_change, (b,fvs))
| otherwise = (False, (b,new_fvs))
where
(new_fvs, no_change_here) = extendFvs env fvs
-------------
extendFvs_ :: UniqFM VarSet -> VarSet -> VarSet
extendFvs_ env s = fst (extendFvs env s) -- Discard the Bool flag
extendFvs :: UniqFM VarSet -> VarSet -> (VarSet, Bool)
-- (extendFVs env s) returns
-- (s `union` env(s), env(s) `subset` s)
extendFvs env s
| isNullUFM env
= (s, True)
| otherwise
= (s `unionVarSet` extras, extras `subVarSet` s)
where
extras :: VarSet -- env(s)
extras = nonDetFoldUFM unionVarSet emptyVarSet $
-- It's OK to use nonDetFoldUFM here because unionVarSet commutes
intersectUFM_C (\x _ -> x) env s
{-
************************************************************************
* *
Binder swap
* *
************************************************************************
Note [Binder swap]
~~~~~~~~~~~~~~~~~~
We do these two transformations right here:
(1) case x of b { pi -> ri }
==>
case x of b { pi -> let x=b in ri }
(2) case (x |> co) of b { pi -> ri }
==>
case (x |> co) of b { pi -> let x = b |> sym co in ri }
Why (2)? See Note [Case of cast]
In both cases, in a particular alternative (pi -> ri), we only
add the binding if
(a) x occurs free in (pi -> ri)
(ie it occurs in ri, but is not bound in pi)
(b) the pi does not bind b (or the free vars of co)
We need (a) and (b) for the inserted binding to be correct.
For the alternatives where we inject the binding, we can transfer
all x's OccInfo to b. And that is the point.
Notice that
* The deliberate shadowing of 'x'.
* That (a) rapidly becomes false, so no bindings are injected.
The reason for doing these transformations here is because it allows
us to adjust the OccInfo for 'x' and 'b' as we go.
* Suppose the only occurrences of 'x' are the scrutinee and in the
ri; then this transformation makes it occur just once, and hence
get inlined right away.
* If we do this in the Simplifier, we don't know whether 'x' is used
in ri, so we are forced to pessimistically zap b's OccInfo even
though it is typically dead (ie neither it nor x appear in the
ri). There's nothing actually wrong with zapping it, except that
it's kind of nice to know which variables are dead. My nose
tells me to keep this information as robustly as possible.
The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
{x=b}; it's Nothing if the binder-swap doesn't happen.
There is a danger though. Consider
let v = x +# y
in case (f v) of w -> ...v...v...
And suppose that (f v) expands to just v. Then we'd like to
use 'w' instead of 'v' in the alternative. But it may be too
late; we may have substituted the (cheap) x+#y for v in the
same simplifier pass that reduced (f v) to v.
I think this is just too bad. CSE will recover some of it.
Note [Case of cast]
~~~~~~~~~~~~~~~~~~~
Consider case (x `cast` co) of b { I# ->
... (case (x `cast` co) of {...}) ...
We'd like to eliminate the inner case. That is the motivation for
equation (2) in Note [Binder swap]. When we get to the inner case, we
inline x, cancel the casts, and away we go.
Note [Binder swap on GlobalId scrutinees]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When the scrutinee is a GlobalId we must take care in two ways
i) In order to *know* whether 'x' occurs free in the RHS, we need its
occurrence info. BUT, we don't gather occurrence info for
GlobalIds. That's the reason for the (small) occ_gbl_scrut env in
OccEnv is for: it says "gather occurrence info for these".
ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
has an External Name. See, for example, SimplEnv Note [Global Ids in
the substitution].
Note [Zap case binders in proxy bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From the original
case x of cb(dead) { p -> ...x... }
we will get
case x of cb(live) { p -> let x = cb in ...x... }
Core Lint never expects to find an *occurrence* of an Id marked
as Dead, so we must zap the OccInfo on cb before making the
binding x = cb. See Trac #5028.
Historical note [no-case-of-case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We *used* to suppress the binder-swap in case expressions when
-fno-case-of-case is on. Old remarks:
"This happens in the first simplifier pass,
and enhances full laziness. Here's the bad case:
f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
If we eliminate the inner case, we trap it inside the I# v -> arm,
which might prevent some full laziness happening. I've seen this
in action in spectral/cichelli/Prog.hs:
[(m,n) | m <- [1..max], n <- [1..max]]
Hence the check for NoCaseOfCase."
However, now the full-laziness pass itself reverses the binder-swap, so this
check is no longer necessary.
Historical note [Suppressing the case binder-swap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This old note describes a problem that is also fixed by doing the
binder-swap in OccAnal:
There is another situation when it might make sense to suppress the
case-expression binde-swap. If we have
case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
...other cases .... }
We'll perform the binder-swap for the outer case, giving
case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
...other cases .... }
But there is no point in doing it for the inner case, because w1 can't
be inlined anyway. Furthermore, doing the case-swapping involves
zapping w2's occurrence info (see paragraphs that follow), and that
forces us to bind w2 when doing case merging. So we get
case x of w1 { A -> let w2 = w1 in e1
B -> let w2 = w1 in e2
...other cases .... }
This is plain silly in the common case where w2 is dead.
Even so, I can't see a good way to implement this idea. I tried
not doing the binder-swap if the scrutinee was already evaluated
but that failed big-time:
data T = MkT !Int
case v of w { MkT x ->
case x of x1 { I# y1 ->
case x of x2 { I# y2 -> ...
Notice that because MkT is strict, x is marked "evaluated". But to
eliminate the last case, we must either make sure that x (as well as
x1) has unfolding MkT y1. The straightforward thing to do is to do
the binder-swap. So this whole note is a no-op.
It's fixed by doing the binder-swap in OccAnal because we can do the
binder-swap unconditionally and still get occurrence analysis
information right.
-}
mkAltEnv :: OccEnv -> CoreExpr -> Id -> (OccEnv, Maybe (Id, CoreExpr))
-- Does two things: a) makes the occ_one_shots = OccVanilla
-- b) extends the GlobalScruts if possible
-- c) returns a proxy mapping, binding the scrutinee
-- to the case binder, if possible
mkAltEnv env@(OccEnv { occ_gbl_scrut = pe }) scrut case_bndr
= case stripTicksTopE (const True) scrut of
Var v -> add_scrut v case_bndr'
Cast (Var v) co -> add_scrut v (Cast case_bndr' (mkSymCo co))
-- See Note [Case of cast]
_ -> (env { occ_encl = OccVanilla }, Nothing)
where
add_scrut v rhs = ( env { occ_encl = OccVanilla, occ_gbl_scrut = pe `extendVarSet` v }
, Just (localise v, rhs) )
case_bndr' = Var (zapIdOccInfo case_bndr) -- See Note [Zap case binders in proxy bindings]
localise scrut_var = mkLocalIdOrCoVar (localiseName (idName scrut_var)) (idType scrut_var)
-- Localise the scrut_var before shadowing it; we're making a
-- new binding for it, and it might have an External Name, or
-- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
-- Also we don't want any INLINE or NOINLINE pragmas!
{-
************************************************************************
* *
\subsection[OccurAnal-types]{OccEnv}
* *
************************************************************************
-}
type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
-- INVARIANT: never IAmDead
-- (Deadness is signalled by not being in the map at all)
(+++), combineAltsUsageDetails
:: UsageDetails -> UsageDetails -> UsageDetails
(+++) usage1 usage2
= plusVarEnv_C addOccInfo usage1 usage2
combineAltsUsageDetails usage1 usage2
= plusVarEnv_C orOccInfo usage1 usage2
addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
addOneOcc usage id info
= plusVarEnv_C addOccInfo usage (unitVarEnv id info)
-- ToDo: make this more efficient
emptyDetails :: UsageDetails
emptyDetails = (emptyVarEnv :: UsageDetails)
usedIn :: Id -> UsageDetails -> Bool
v `usedIn` details = isExportedId v || v `elemVarEnv` details
type IdWithOccInfo = Id
tagLamBinders :: UsageDetails -- Of scope
-> [Id] -- Binders
-> (UsageDetails, -- Details with binders removed
[IdWithOccInfo]) -- Tagged binders
-- Used for lambda and case binders
-- It copes with the fact that lambda bindings can have a
-- stable unfolding, used for join points
tagLamBinders usage binders = usage' `seq` (usage', bndrs')
where
(usage', bndrs') = mapAccumR tag_lam usage binders
tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
where
usage1 = usage `delVarEnv` bndr
usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
| otherwise = usage1
tagBinder :: UsageDetails -- Of scope
-> Id -- Binders
-> (UsageDetails, -- Details with binders removed
IdWithOccInfo) -- Tagged binders
tagBinder usage binder
= let
usage' = usage `delVarEnv` binder
binder' = setBinderOcc usage binder
in
usage' `seq` (usage', binder')
setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
setBinderOcc usage bndr
| isTyVar bndr = bndr
| isExportedId bndr = case idOccInfo bndr of
NoOccInfo -> bndr
_ -> setIdOccInfo bndr NoOccInfo
-- Don't use local usage info for visible-elsewhere things
-- BUT *do* erase any IAmALoopBreaker annotation, because we're
-- about to re-generate it and it shouldn't be "sticky"
| otherwise = setIdOccInfo bndr occ_info
where
occ_info = lookupVarEnv usage bndr `orElse` IAmDead
{-
************************************************************************
* *
\subsection{Operations over OccInfo}
* *
************************************************************************
-}
mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
mkOneOcc env id int_cxt
| isLocalId id
= unitVarEnv id (OneOcc False True int_cxt)
| id `elemVarEnv` occ_gbl_scrut env
= unitVarEnv id NoOccInfo
| otherwise
= emptyDetails
markMany, markInsideLam :: OccInfo -> OccInfo
markMany _ = NoOccInfo
markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
markInsideLam occ = occ
addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
addOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
NoOccInfo -- Both branches are at least One
-- (Argument is never IAmDead)
-- (orOccInfo orig new) is used
-- when combining occurrence info from branches of a case
orOccInfo (OneOcc in_lam1 _ int_cxt1)
(OneOcc in_lam2 _ int_cxt2)
= OneOcc (in_lam1 || in_lam2)
False -- False, because it occurs in both branches
(int_cxt1 && int_cxt2)
orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
NoOccInfo
|
mettekou/ghc
|
compiler/simplCore/OccurAnal.hs
|
bsd-3-clause
| 80,282
| 0
| 16
| 22,168
| 7,995
| 4,372
| 3,623
| 570
| 7
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[Constants]{Info about this compilation}
-}
module ETA.Main.Constants where
hiVersion :: Integer
hiVersion = read (cProjectVersionInt ++ cProjectPatchLevel) :: Integer
cProjectName, cProjectVersion, cProjectVersionInt, cProjectPatchLevel, cProjectPatchLevel1,
cProjectPatchLevel2, cProjectHomeURL, cProjectIssueReportURL, ghcProjectVersion,
ghcProjectVersionInt, ghcprojectPatchLevel, ghcProjectPatchLevel1, ghcProjectPatchLevel2
:: String
cProjectName = "The Eta programming language compiler"
-- @VERSION_CHANGE@
cProjectVersion = "0.0.5"
cProjectVersionInt = "000"
cProjectPatchLevel = "1"
cProjectPatchLevel1 = "1"
cProjectPatchLevel2 = ""
cProjectHomeURL = "http://github.org/typelead/eta"
cProjectIssueReportURL = cProjectHomeURL ++ "/issues"
ghcProjectVersion = "7.10.3"
ghcProjectVersionInt = "710"
ghcprojectPatchLevel = "3"
ghcProjectPatchLevel1 = "3"
ghcProjectPatchLevel2 = ""
-- All pretty arbitrary:
mAX_TUPLE_SIZE :: Int
mAX_TUPLE_SIZE = 62 -- Should really match the number
-- of decls in Data.Tuple
mAX_CONTEXT_REDUCTION_DEPTH :: Int
mAX_CONTEXT_REDUCTION_DEPTH = 100
-- Trac #5395 reports at least one library that needs depth 37 here
mAX_TYPE_FUNCTION_REDUCTION_DEPTH :: Int
mAX_TYPE_FUNCTION_REDUCTION_DEPTH = 200
-- Needs to be much higher than mAX_CONTEXT_REDUCTION_DEPTH; see Trac #5395
wORD64_SIZE :: Int
wORD64_SIZE = 8
tARGET_MAX_CHAR :: Int
tARGET_MAX_CHAR = 0x10ffff
mAX_INTLIKE, mIN_INTLIKE, mAX_CHARLIKE, mIN_CHARLIKE, mAX_SPEC_AP_SIZE :: Int
mIN_INTLIKE = -16
mAX_INTLIKE = 16
mIN_CHARLIKE = 0
mAX_CHARLIKE = 255
mAX_SPEC_AP_SIZE = 7
|
alexander-at-github/eta
|
compiler/ETA/Main/Constants.hs
|
bsd-3-clause
| 1,676
| 0
| 7
| 222
| 225
| 150
| 75
| 36
| 1
|
module Tests.Data (dataTests)
where
import Test.HUnit
import EPseudocode.Lexer
import EPseudocode.Data
dataTests = TestList [
"list" ~:
"{1, 2}" ~=? showExpr (List [Int 1, Int 2])
, "nested list" ~:
"{1, {4, 5}, 3}" ~=? showExpr (List [Int 1, List [Int 4, Int 5], Int 3])
, "float" ~:
"42.42" ~=? showExpr (Float 42.42)
, "string" ~:
"\"foobar\"" ~=? showExpr (String "foobar")
, "bool true" ~:
tTrue ~=? showExpr (Bool True)
, "bool false" ~:
tFalse ~=? showExpr (Bool False)
, "unary expr unminus" ~:
"UnExpr UnMinus (Int 42)" ~=? showExpr (UnExpr UnMinus (Int 42))
, "unary expr not" ~:
"UnExpr Not (Bool True)" ~=? showExpr (UnExpr Not (Bool True))
]
|
paulbarbu/ePseudocode
|
test/Tests/Data.hs
|
bsd-3-clause
| 703
| 0
| 14
| 158
| 252
| 129
| 123
| 21
| 1
|
#!/usr/bin/runhaskell
module Main (main) where
import Distribution.Simple
main :: IO ()
main = defaultMain
|
jwiegley/svndump
|
Setup.hs
|
bsd-3-clause
| 110
| 0
| 6
| 17
| 30
| 18
| 12
| 4
| 1
|
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
mylen :: [a] -> Int
mylen [] = 0
mylen (_:xs) = 1 + mylen xs
mymap f [] = []
mymap f (x:xs) = (f x) : (mymap f xs)
zs :: [Int]
zs = [1..100]
prop2 = liquidAssertB (n1 == n2)
where n1 = mylen zs
n2 = mylen $ mymap (+ 1) zs
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/meas3.hs
|
bsd-3-clause
| 353
| 0
| 9
| 106
| 166
| 90
| 76
| 13
| 1
|
-----------------------------------------------------------
-- Daan Leijen (c) 1999-2000, daan@cs.uu.nl
-----------------------------------------------------------
module MonParser ( parseMondrian
, parseMondrianFromFile
, prettyFile
, ParseError
) where
import Char
import Monad
import Mondrian
import Utils (groupLambdas)
-- Parsec
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language (mondrianDef)
--testing
import qualified SimpleMondrianPrinter as Pretty
-----------------------------------------------------------
--
-----------------------------------------------------------
parseMondrianFromFile :: String -> IO (Either ParseError CompilationUnit)
parseMondrianFromFile fname =
parseFromFile compilationUnit fname
parseMondrian sourceName source =
parse compilationUnit sourceName source
-- testing
prettyFile fname
= do{ result <- parseMondrianFromFile fname
; case result of
Left err -> putStr ("parse error at: " ++ show err)
Right x -> print (Pretty.compilationUnit x)
}
-----------------------------------------------------------
-- GRAMMAR ELEMENTS
-----------------------------------------------------------
compilationUnit :: Parser CompilationUnit
compilationUnit =
do{ whiteSpace
; reserved "package"
; name <- option [""] packageName
; decls <- option [] declarations
; eof
; return $ Package name decls
}
-----------------------------------------------------------
-- Declarations
-----------------------------------------------------------
declarations =
braces (semiSep1 declaration)
declaration =
importDeclaration
<|> classDeclaration
<|> variableSignatureDeclaration
<?> "declaration"
variableSignatureDeclaration =
do{ name <- variableName
; variableDeclaration name <|> signatureDeclaration name
}
variableDeclaration name =
do{ symbol "="
; expr <- expression
; return $ VarDecl name expr
}
<?> "variable declaration"
importDeclaration =
do{ reserved "import"
; name <- packageName
; star <- option [] (do{ symbol "."
; symbol "*"
; return ["*"]
})
; return $ ImportDecl (name ++ star)
}
classDeclaration =
do{ reserved "class"
; name <- className
; extends <- option [] (do{ reserved "extends"
; n <- className
; return [n]
})
; decls <- option [] declarations
; return $ ClassDecl name extends decls
}
signatureDeclaration name =
do{ symbol "::"
; texpr <- typeExpression
; return $ SigDecl name texpr
}
<?> "type declaration"
-----------------------------------------------------------
-- Expressions
-----------------------------------------------------------
expression :: Parser Expr
expression =
lambdaExpression
<|> letExpression
<|> newExpression
<|> infixExpression
<?> "expression"
lambdaExpression =
do{ symbol "\\"
; name <- variableName
; symbol "->"
; expr <- expression
; return $ groupLambdas (Lambda [name] expr)
}
letExpression =
do{ reserved "let"
; decls <- declarations
; reserved "in"
; expr <- expression
; return $ Let decls expr
}
newExpression =
do{ reserved "new"
; name <- className
; decls <- option [] declarations
; return $ New name decls
}
-----------------------------------------------------------
-- Infix expression
-----------------------------------------------------------
infixExpression =
buildExpressionParser operators applyExpression
operators =
[ [ prefix "-", prefix "+" ]
, [ op "^" AssocRight ]
, [ op "*" AssocLeft, op "/" AssocLeft ]
, [ op "+" AssocLeft, op "-" AssocLeft ]
, [ op "==" AssocNone, op "/=" AssocNone, op "<" AssocNone
, op "<=" AssocNone, op ">" AssocNone, op ">=" AssocNone ]
, [ op "&&" AssocNone ]
, [ op "||" AssocNone ]
]
where
op name assoc = Infix (do{ var <- try (symbol name)
; return (\x y -> App (App (Var [var]) x) y)
}) assoc
prefix name = Prefix (do{ var <- try (symbol name)
; return (\x -> App (Var [var,"unary"]) x)
})
applyExpression =
do{ exprs <- many1 simpleExpression
; return (foldl1 App exprs)
}
{-
infixExpression =
do{ (e,es) <- chain simpleExpression operator "infix expression"
; return $ if null es then e else (unChain (Chain e es))
}
-}
simpleExpression :: Parser Expr
simpleExpression =
literal
<|> parens expression
<|> caseExpression
<|> variable
<?> "simple expression"
-----------------------------------------------------------
-- Case expression
-----------------------------------------------------------
caseExpression =
do{ reserved "case"
; expr <- variable
; reserved "of"
; alts <- alternatives
; return $ Case expr alts
}
alternatives =
braces (semiSep1 arm)
arm =
do{ pat <- pattern
; symbol "->"
; expr <- expression
; return (pat,expr)
}
pattern =
do{ reserved "default"
; return Default
}
<|> do{ name <- patternName
; decls <- option [] declarations
; return $ Pattern name decls
}
<?> "pattern"
-----------------------------------------------------------
-- Type expression
-----------------------------------------------------------
{-
typeExpression =
do{ (e,es) <- chain simpleType typeOperator "type expression"
; return $ if null es then e else Chain e es
}
<?> "type expression"
-}
typeExpression :: Parser Expr
typeExpression =
do{ exprs <- sepBy1 simpleType (symbol "->")
; return (foldl1 (\x y -> App (App (Var ["->"]) x) y) exprs)
}
simpleType :: Parser Expr
simpleType =
parens typeExpression
<|> variable
<?> "simple type"
-----------------------------------------------------------
-- LEXICAL ELEMENTS
-----------------------------------------------------------
-----------------------------------------------------------
-- Identifiers & Reserved words
-----------------------------------------------------------
variable =
do{ name <- variableName
; return $ Var name
}
patternName = qualifiedName <?> "pattern variable"
variableName = qualifiedName <?> "identifier"
className = qualifiedName <?> "class name"
packageName = qualifiedName <?> "package name"
qualifiedName =
identifier `sepBy1` (symbol "." <?> "")
-----------------------------------------------------------
-- Literals
-----------------------------------------------------------
literal =
do{ v <- intLiteral <|> chrLiteral <|> strLiteral
; return $ Lit v
}
<?> "literal"
intLiteral = do{ n <- natural; return (IntLit n) }
chrLiteral = do{ c <- charLiteral; return (CharLit c) }
strLiteral = do{ s <- stringLiteral; return (StringLit s) }
-----------------------------------------------------------
-- Tokens
-- Use qualified import to have token parsers on toplevel
-----------------------------------------------------------
mondrian = P.makeTokenParser mondrianDef
parens = P.parens mondrian
braces = P.braces mondrian
semiSep1 = P.semiSep1 mondrian
whiteSpace = P.whiteSpace mondrian
symbol = P.symbol mondrian
identifier = P.identifier mondrian
reserved = P.reserved mondrian
natural = P.natural mondrian
charLiteral = P.charLiteral mondrian
stringLiteral = P.stringLiteral mondrian
|
FranklinChen/hugs98-plus-Sep2006
|
packages/parsec/examples/Mondrian/MonParser.hs
|
bsd-3-clause
| 8,503
| 6
| 19
| 2,524
| 1,756
| 922
| 834
| 172
| 2
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.AMD.BlendMinmaxFactor
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/AMD/blend_minmax_factor.txt AMD_blend_minmax_factor> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.AMD.BlendMinmaxFactor (
-- * Enums
gl_FACTOR_MAX_AMD,
gl_FACTOR_MIN_AMD
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/AMD/BlendMinmaxFactor.hs
|
bsd-3-clause
| 689
| 0
| 4
| 81
| 40
| 33
| 7
| 4
| 0
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Model where
import Control.Monad.Reader (ask)
import Control.Monad.State (modify)
import Data.Acid (Query, Update, makeAcidic)
import Data.IntMap (IntMap, elems, insert, maxViewWithKey,
singleton)
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.SafeCopy (base, deriveSafeCopy)
import Data.Text.Lazy (Text)
import Data.Time.Clock (UTCTime)
import Data.Typeable (Typeable)
import Prelude hiding (max)
{-|
Represents the Message entity
-}
data Message =
Message { -- | sender login
sender :: Text,
-- | recepient login
recepient :: Text,
-- | text of the Message
text :: Text,
-- | time of receipt
time :: UTCTime
} deriving (Show, Typeable)
{-|
Storage for messages
-}
newtype MessagesDb = MessagesDb { allMessages :: IntMap Message }
deriving (Typeable)
{-|
Represents context of the chat ui
-}
data ChatContext =
ChatContext { -- | login of the current sender
login :: Text,
-- | login of the current recepient
activeChat :: Text
} deriving (Show, Typeable)
{-|
Storage for the ui context
-}
newtype ChatContextDb = ChatContextDb { chatContext :: ChatContext }
deriving (Typeable)
deriveSafeCopy 0 'base ''Message
deriveSafeCopy 0 'base ''MessagesDb
deriveSafeCopy 0 'base ''ChatContext
deriveSafeCopy 0 'base ''ChatContextDb
{-|
Gets all messages from its storage
-}
getMessages :: Query MessagesDb [Message]
getMessages = sortBy (comparing time) . elems . allMessages <$> ask
{-|
Gets lask k messages from the curtain dialog
-}
lastKChatMessages :: Text -> Int -> Query MessagesDb [Message]
lastKChatMessages to k =
reverse .
take k .
sortBy (flip (comparing time)) .
filter (\m -> recepient m == to || sender m == to) .
elems . allMessages <$> ask
{-|
Puts new message to the storage
-}
addMessage :: Message -> Update MessagesDb ()
addMessage message = modify go
where
go (MessagesDb db) = MessagesDb $
case maxViewWithKey db of
Just ((max, _), _) -> insert (max + 1) message db
Nothing -> singleton 1 message
makeAcidic ''MessagesDb ['addMessage, 'getMessages, 'lastKChatMessages]
{-|
Gets the chat context from its storage
-}
getChatContext :: Query ChatContextDb ChatContext
getChatContext = chatContext <$> ask
{-|
Updates the chat context & saves it to its storage
-}
updateChatContext :: ChatContext -> Update ChatContextDb ()
updateChatContext ctx = modify go
where
go _ = ChatContextDb $ ChatContext (login ctx) (activeChat ctx)
makeAcidic ''ChatContextDb ['getChatContext, 'updateChatContext]
|
alexchekmenev/haskell-exam
|
src/Model.hs
|
bsd-3-clause
| 3,102
| 0
| 15
| 887
| 687
| 385
| 302
| 60
| 2
|
module CS173.Tourney where
import Paths_CS173Tourney -- created by Cabal
import Data.IORef
import Data.Maybe (fromJust)
import qualified Data.Maybe as Y
import System.Log.Logger
import Text.JSON
import System.Directory
import System.Process
import System.Timeout
import System.IO
import Control.Concurrent
import Database.CouchDB
import System.Exit
import Control.Monad.Trans
import Control.Exception (finally)
import System.FilePath (takeFileName)
import CS173.Data
import CS173.Actions
import CS173.Config
import CS173.NormalizeSubmissions
numTests s = case readsPrec 1 s of
(n,_):rest -> n
[] -> 1
substCommand :: String -- ^assignment's command string
-> String -- ^PLAI root path (collects/plai)
-> String -- ^path to solution
-> String -- ^path to test suite
-> String
substCommand cmd plai solution testSuite =
unesc . (subst 'p' plai) . (subst 's' solution) . (subst 't' testSuite) $ cmd
where subst ch sub [] = []
subst ch sub ('%':ch':rest)
| ch == ch' = sub ++ rest
| otherwise = '%':ch':(subst ch sub rest)
subst ch sub (x:xs) = x:(subst ch sub xs)
unesc ('%':'%':rest) = '%':(unesc rest)
unesc (x:xs) = x:(unesc xs)
unesc [] = []
runCommandTimed :: String
-> Int -- ^time limit
-> IO (Maybe (Int,String,String))
runCommandTimed commandString timeLimit = do
infoM "tourney" ("Running command: " ++ commandString)
mv <- newEmptyMVar
let doRun = do
(stdin,stdout,stderr,process) <- runInteractiveCommand commandString
code <- waitForProcess process
hSetBinaryMode stdout False
hSetBinaryMode stderr False
errs <- hGetContents stderr
outs <- hGetContents stdout
hClose stdin
length errs `seq` hClose stderr -- hGetContents leaks memory
length outs `seq` hClose stdout
putMVar mv (code,outs,errs)
forkOS doRun
(code,out,err) <- takeMVar mv
case code of
ExitSuccess -> return $ Just (0,out,err) -- UNIX!!!
ExitFailure n -> return $ Just (n,out,err)
collectErrors :: [TestStatus]
-> String
collectErrors results = concatMap f results where
f (TestError s) = s ++ "\n\n"
f _ = ""
withTempFile :: FilePath -> FilePath -> (FilePath-> Handle -> IO a) -> IO a
withTempFile dir template action = do
(path,handle) <- openTempFile dir template
action path handle `finally` (hClose handle >> removeFile path)
executeTest :: String -- ^test command
-> String -- ^solution body
-> String -- ^test suite body
-> IO (Either String ()) -- ^ report for student on errors
executeTest testCmd solutionBody testBody = do
plaiTest <- getDataDir
dir <- getTemporaryDirectory
result <- withTempFile dir "solution.ss" $ \solutionPath hSolution -> do
withTempFile dir "test-suite.ss" $ \testSuitePath hTestSuite -> do
let cmd = substCommand testCmd plaiTest (takeFileName solutionPath)
(takeFileName testSuitePath)
hPutStr hSolution solutionBody >> hFlush hSolution >> hClose hSolution
hPutStr hTestSuite testBody >> hFlush hTestSuite >> hClose hTestSuite
setCurrentDirectory dir
-- Run for at most 60 seconds of real time. The test script is expected
-- to limit the CPU time and memory consumption.
runCommandTimed cmd 60
case result of
Nothing -> return (Left "Took too much time (> 60 seconds of real time)")
Just (0,stdoutStr,stderrStr) -> return (Right ())
Just (_,stdoutStr,stderrStr) -> return (Left stderrStr)
runTest :: String -- ^test command
-> String -- ^ test suite
-> String -- ^ program
-> Doc -- ^test id
-> Doc -- ^soln id
-> ServerM TestStatus
runTest testCommand testText progText testId progId = do
plaiTest <- plaiTestPath
now <- getTime
r <- liftIO $ do
dir <- getTemporaryDirectory
withTempFile dir "solution.ss" $ \solutionPath hSolution -> do
withTempFile dir "test-suite.ss" $ \testSuitePath hTestSuite -> do
hPutStr hSolution progText
hFlush hSolution
hClose hSolution
hPutStr hTestSuite testText
hFlush hTestSuite
hClose hTestSuite
setCurrentDirectory dir
-- Run for at most 60 seconds of real time. The test script is expected
-- to limit the CPU time and memory consumption.
runCommandTimed (substCommand testCommand plaiTest
(takeFileName solutionPath)
(takeFileName testSuitePath))
60
lift $ runCouchDB' $ do
test <- getTestSuite testId
prog <- getProgram progId
let asgnId = programAssignmentId prog
let mkRep s n = Report testId progId asgnId n s now (testSuiteUserId test)
(programUserId prog) (programTime prog)
(testSuiteTime test)
case r of
Nothing -> do
newDoc dbRep (mkRep "Your test suite took too long." (-1))
return (TestError "running the test took too long.")
Just (0,out,err) -> do
newDoc dbRep (mkRep "" 0)
return TestOK
Just (_,outs,errs) -> do
newDoc dbRep (mkRep errs (numTests errs))
return (TestError errs)
checkTestSuite :: Doc -> ServerM ()
checkTestSuite testId = do
plaiTest <- plaiTestPath
liftIO $ infoM "tourney.tester" ("running on test suite " ++ show testId)
liftIO $ runCouchDB' $ do
now <- getTime
testSuite <- getTestSuite testId
assignment <- getAssignment (testSuiteAssignmentId testSuite)
(Just testSuiteText') <- getSubmission (testSuiteSubmissionId testSuite)
let testSuiteText = case asgnTestLang assignment of
"" -> testSuiteText'
lang -> standardizeLang lang testSuiteText'
(Just goldSolutionText) <- getSubmission (assignmentSolutionId assignment)
r <- liftIO $ do
dir <- getTemporaryDirectory
withTempFile dir "solution.ss" $ \solutionPath hSolution -> do
withTempFile dir "test-suite.ss" $ \testSuitePath hTestSuite -> do
hPutStr hSolution goldSolutionText
hFlush hSolution
hClose hSolution
hPutStr hTestSuite testSuiteText
hFlush hTestSuite
hClose hTestSuite
setCurrentDirectory dir
let cmd = substCommand (asgnTestCmd assignment) plaiTest
(takeFileName solutionPath)
(takeFileName testSuitePath)
runCommandTimed cmd 60 -- at most 60 seconds of real time
case r of
Nothing -> do
liftIO $ infoM "tourney.tester" (show testId ++ " took too long.")
updateTestSuiteStatus (const $ TestSuiteMachineCheckError
"Your test suite took too long.")
testId
Just (0,outs,errs) -> do
liftIO $ infoM "tourney.tester" (show testId ++ " passed gold.")
updateTestSuiteStatus (const TestSuiteMachineCheckOK) testId
Just (code,outs,errs) -> do
liftIO $ infoM "tourney.tester" $ show testId ++
" raised errors (exit code: " ++ show code ++ ")"
updateTestSuiteStatus (const $ TestSuiteMachineCheckError errs) testId
return ()
testSuiteTesterThread config = do
liftIO $ debugM "tourney.tester" "Checking for new jobs..."
lst <- liftIO $ runCouchDB' $ queryViewKeys dbSuites (doc "suites")
(doc "pending") []
thisDoc <- liftIO $ newIORef Nothing
waitVar <- liftIO $ newEmptyMVar
let checkTestSuites = do
mapM_ (\testId -> do writeIORef thisDoc (Just testId)
runConfig config $ checkTestSuite testId) lst
writeIORef thisDoc Nothing
liftIO $ do
forkOS (checkTestSuites `finally` putMVar waitVar ())
takeMVar waitVar
failed <- readIORef thisDoc
case failed of
Nothing -> return ()
Just testId -> do
errorM "tourney.tester" $ "GHC assplosion on " ++ show testId
runCouchDB' $ updateTestSuiteStatus
(const $ TestSuiteMachineCheckError "out of time/memory") testId
errorM "tourney.tester" $ "Successfully killed " ++ (show testId)
lst <- liftIO $ runCouchDB' $ queryViewKeys dbPrograms
(doc "programs") (doc "pending") []
mapM_ checkProgram lst
liftIO $ threadDelay (20 * 1000000)
testSuiteTesterThread config
getTestBody (_,subId) = do
(Just testBody) <- getSubmission subId
return testBody
checkProgram :: Doc -> ServerM ()
checkProgram progId = do
liftIO $ infoM "tourney.tester" ("running on solution " ++ show progId)
(prog,progBody,tests,testBodies,testCmd) <- liftIO $ runCouchDB' $ do
prog <- getProgram progId
asgn <- getAssignment (programAssignmentId prog)
let testCmd = asgnSolnCmd asgn
(Just progBody') <- getSubmission (programSubmissionId prog)
let progBody = standardizeLang (asgnSolnLang asgn) progBody'
tests <- getAvailableTests (programAssignmentId prog)
testBodies <- mapM getTestBody tests
let testIds = map fst tests
return (prog,progBody,tests,zip testBodies testIds,testCmd)
testResults <- mapM (\(testBody,testId) ->
runTest testCmd testBody progBody testId progId)
testBodies
let testErrors = collectErrors testResults
liftIO $ runCouchDB' $ updateProgramStatus progId $ case testErrors of
"" -> TestOK
otherwise -> TestError testErrors
|
jesboat/173tourney
|
server-src/CS173/Tourney.hs
|
bsd-3-clause
| 9,615
| 0
| 27
| 2,651
| 2,743
| 1,312
| 1,431
| 221
| 5
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Utils.Utils where
{-
Some utility functions, often used to program 'left to right'
-}
import Control.Monad
import Data.Either
import Data.Foldable
import Data.Maybe
import Data.List (intercalate, isPrefixOf)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.List (dropWhileEnd)
import Data.Char (toUpper, isSpace)
import Data.Set (Set)
import qualified Data.Set as Set
import Lens.Micro.Extras as LME
import System.Random
get = LME.view
genRandoms :: (RandomGen random) => random -> [random]
genRandoms r = let (r0, r1) = split r
in
r0:genRandoms r1
-------------------- usefull types -------------------------------------------------------
type Name = String
-- Represents some path in some tree
type Path = [Int]
class Check a where
check :: a -> Either String ()
check a = return ()
class Check' info a where
check' :: info -> a -> Either String ()
check' info a
= return ()
------------------- Left to Right programming helpers -----------------------------------
(&) = flip ($)
(|>) :: Functor f => f a -> (a -> b) -> f b
(|>) = flip fmap
(||>>) :: (Functor f, Functor g) => f (g a) -> (a -> b) -> f (g b)
(||>>) container f
= container |> (|> f)
(|+>) :: (Monad m, Traversable t) => t a -> (a -> m b) -> m (t b)
(|+>) = forM
(|++>) :: (Monad m, Traversable t) => m (t a) -> (a -> m b) -> m (t b)
(|++>) mta f
= do ta <- mta
ta |+> f
inParens str = "("++str++")"
inDQ str = "\""++str++"\""
inHeader prefix str chr msg
= let title = " "++str++" "
line = title |> const chr
in
unlines $ if msg == "" then ["", prefix ++ title, prefix ++ line]
else ["", prefix ++ title, prefix ++ line, "", msg]
inHeader' s
= inHeader "" s '='
showComma :: Show a => [a] -> String
showComma as = as |> show & commas
commas = intercalate ", "
allCombinations :: [[a]] -> [[a]]
allCombinations [] = [[]]
allCombinations (a:as)
= do tails <- allCombinations as
head <- a
return (head:tails)
------------------- Maybe, Either and other Monad helpers ------------------------------------
pass :: Monad m => m ()
pass = return ()
sndEffect :: Monad m => (a, m b) -> m (a, b)
sndEffect (a, mb)
= do b <- mb
return (a, b)
fstEffect :: Monad m => (m a, b) -> m (a, b)
fstEffect (ma, b)
= do a <- ma
return (a, b)
ifJust' :: (a -> b -> IO ()) -> Maybe a -> b -> IO ()
ifJust' f Nothing b = return ()
ifJust' f (Just a) b = f a b
ifJust :: (a -> IO ()) -> Maybe a -> IO ()
ifJust _ Nothing = return ()
ifJust f (Just a) = f a
firstJusts :: [Maybe a] -> Maybe a
firstJusts maybes
= let as = catMaybes maybes in
if null as then Nothing else Just $ head as
-- Gives the first right value. If none of the values is Right, concats the 'error messages' (with newlines and indentation)
firstRight :: [Either String b] -> Either String b
firstRight vals = let r = rights vals in
if null r then
Left (pack $ lefts vals) else
Right (head r)
where pack vals = vals |> lines ||>> (" "++) |> unlines & unlines
trim = dropWhileEnd isSpace . dropWhile isSpace
-- Checks wether all are right, and returns those. Gives messages for failed values
allRight :: Show b => [Either String b] -> Either String [b]
allRight eithers
| all isRight eithers = Right $ rights eithers
| otherwise = eithers |> either id ((++) "Successfull: " . show) & unlines & Left
allRight_ :: [Either String ()] -> Either String ()
allRight_ eithers
= eithers & filter isLeft & allRight >> return ()
allRight' :: [Either String b] -> Either String [b]
allRight' eithers
= do let failed = lefts eithers
unless (null failed) $ Left $ unlines failed
return $ rights eithers
indent = indentWith " "
indentWith _ [] = []
indentWith str msg
= msg & lines |> (str++) & unlines & init
-- Stack message for Either Monad
inMsg :: String -> Either String a -> Either String a
inMsg msg (Left msg')
= Left (msg ++ ":\n"++ indent msg')
inMsg _ right = right
ammendMsg :: (e -> e) -> Either e a -> Either e a
ammendMsg f (Left e)
= Left $ f e
ammendMsg _ a = a
assert :: Monad m => (String -> m ()) -> Bool -> String -> m ()
assert c False msg = c msg
assert c True _ = pass
----------------------- Tuple Tools ------------------
fst3 :: (a, b, c) -> a
fst3 (a, _, _) = a
snd3 :: (a, b, c) -> b
snd3 (_, b, _) = b
trd3 :: (a, b, c) -> c
trd3 (_, _, c) = c
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c)
= f a b c
dropFst3 :: (a, b, c) -> (b, c)
dropFst3 (_, b, c) = (b, c)
dropSnd3 :: (a, b, c) -> (a, c)
dropSnd3 (a, _, c) = (a, c)
dropTrd3 :: (a, b, c) -> (a, b)
dropTrd3 (a, b, _) = (a, b)
merge3l :: (a, b, c) -> ((a, b), c)
merge3l (a, b, c) = ((a, b), c)
merge3r :: (a, b, c) -> (a, (b, c))
merge3r (a, b, c) = (a, (b, c))
unmerge3r :: (a, (b, c)) -> (a, b, c)
unmerge3r (a, (b, c)) = (a, b, c)
unmerge3l :: ((a, b), c) -> (a, b, c)
unmerge3l ((a, b), c) = (a, b, c)
mapBoth f (a, a') = (f a, f a')
onBoth = mapBoth
both f (a, a') = f a && f a'
swap (a, b) = (b, a)
----------------------- List tools --------------------
chain :: (Traversable t) => t (a -> a) -> a -> a
chain fs a = foldl (&) a fs
validLines :: String -> [String]
validLines fileConts
= fileConts & lines & filter (not . null) & filter (not . ("#" `isPrefixOf`))
replaceN :: Int -> a -> [a] -> [a]
replaceN 0 a (_:as)
= a : as
replaceN i _ [] = error $ "Replace at index N: index to large. Overshoot: "++show i
replaceN i a (h:as)
= h : replaceN (i-1) a as
onHead :: (a -> a) -> [a] -> [a]
onHead f [] = []
onHead f (a:as) = f a : as
camelCase :: String -> String
camelCase (' ':str)
= camelCase $ onHead toUpper str
camelCase (c:str)
= c : camelCase str
camelCase [] = []
-- Replaces each element of origs by a choice of pointwise (from a respective column. If a pointwise is empty, the original element is returned
replacePointwise :: [a] -> [[a]] -> [[a]]
replacePointwise origs pointwise
| length origs /= length pointwise
= error $ "Replace pointwise: lengths don't match, got "++show (length origs)++" original elements and "++show (length pointwise)++" lists of choices to choose from"
| otherwise
= do i <- [0..length origs -1]
choice <- pointwise & safeIndex "Pointswise: origs has length " i
return $ replaceN i choice origs
length' :: Int -> String -> Int
length' runningLength []
= runningLength
length' runningLength ('\t':rest)
= length' (runningLength & (+ 8) & (`div` 8) & (* 8) ) rest
length' runningLength (a:as)
= length' (runningLength + 1) as
merge :: Eq a => [(a,b)] -> [(a,[b])]
merge [] = []
merge ((a,b):ls)
= let bs = map snd $ filter ((==) a . fst) ls in
(a,b:bs): merge (filter ((/=) a . fst) ls)
merge' :: Eq b => [(a,b)] -> [([a],b)]
merge' = map swap . merge . map swap
unmerge :: [(a,[b])] -> [(a,b)]
unmerge = concatMap (\(a,bs) -> [(a,b) | b <- bs])
dubbles :: Eq a => [a] -> [a]
dubbles [] = []
dubbles (a:as) = (if a `elem` as then (a:) else id) $ dubbles as
checkNoDuplicates :: (Eq a) => [a] -> ([a] -> String) -> Either String ()
checkNoDuplicates as msg
= do let dups = dubbles as
unless (null dups) $ Left $ msg dups
checkNoCommon :: (Ord k) => Map k v -> Map k v -> ([(k, (v, v))] -> String) -> Either String ()
checkNoCommon dict1 dict2 errMsg
= do let common = Map.intersection dict1 dict2 & Map.keys
let v1s = common |> (dict1 Map.!)
let v2s = common |> (dict2 Map.!)
let msg = errMsg $ zip common $ zip v1s v2s
unless (null common) $ Left msg
checkNoExists :: (Ord k) => k -> Map k v -> String -> Either String ()
checkNoExists k dict msg
| k `Map.notMember` dict = return ()
| otherwise = Left msg
checkExists :: (Ord k) => k -> Map k v -> String -> Either String v
checkExists k dict msg
| k `Map.member` dict
= return $ dict Map.! k
| otherwise = Left msg
checkExistsSugg :: (Ord k) => (k -> String) -> k -> Map k v -> String -> Either String v
checkExistsSugg show k dict msg
= do let available = dict & Map.keys |> show & intercalate ", "
checkExists k dict (msg ++ "\nAvailable options are " ++ available)
checkAllExists :: (Ord k) => [k] -> Map k v -> (k -> String) -> Either String [v]
checkAllExists ks dict msg
= ks |+> (\k -> checkExists k dict (msg k))
padL :: Int -> a -> [a] -> [a]
padL i filler as
= replicate (i - length as) filler ++ as
padR :: Int -> a -> [a] -> [a]
padR i filler as
= as ++ replicate (i - length as) filler
padR' :: (Monoid a) => Int -> (a -> Int) -> a -> a -> a
padR' i length filler as
= as `mappend` (replicate (i - length as) filler & mconcat)
equalizeLength :: a -> [[a]] -> [[a]]
equalizeLength a ass
= let longest = ass |> length & maximum
append as = as ++ replicate (longest - length as) a
in
ass |> append
stitch :: a -> [[a]] -> [[a]] -> [[a]]
stitch eq a b = let la = length a
lb = length b
longest = max la lb
a' = replicate (longest - la) [] ++ a
b' = replicate (longest - lb) [] ++ b in
zipWith (++) (equalizeLength eq a') b'
mapi :: [a] -> [(Int, a)]
mapi = zip [0..]
invertDict :: (Eq b, Ord b, Ord a) => Map a (Set b) -> Map b (Set a)
invertDict = fmap Set.fromList . Map.fromList . merge . map swap . unmerge . Map.toList . fmap Set.toList
invertDict' :: (Ord a, Ord b, Eq b) => Map a b -> Map b [a]
invertDict' = Map.fromList . merge . map swap . Map.toList
specialChars = "+*?[]\\^$.()"
translateRegex :: String -> String
translateRegex str
= str >>= (\c -> if c `elem` specialChars then "\\"++[c] else [c])
bar :: Bool -> Int -> Int -> String -> Int -> String
bar withCounter width total msg' current
| total < current
= bar withCounter width current msg' total
| otherwise
= let current'= fromIntegral current :: Float
total' = fromIntegral total :: Float
width' = fromIntegral width :: Float
perc' = (current' / total') * (width' - 2)
perc = round perc'
max = show total
counter = " (" ++ padL (length max) ' ' (show current) ++ "/" ++ max ++ ") "
msg = "--"++take (width - 2) ( if withCounter then counter++ msg' else msg')
preMsg = take perc msg
postMsg = drop perc msg
bars = take perc $ preMsg ++ repeat '-'
conts = bars++"█"++postMsg++repeat ' ' in
"["++ take (width-2) conts ++"]"
{- Ugly hack.
Consider a list of values [a], with associated message.
An a takes some time to evaluate.
We'd like to show a fancy bar, showing progress.
Solution:
let msg = fancyString"endMessage" [(someA, "Calculating first a"), (someOtherA, "Calculationg second a")]
putStrLn msg
As fancyString "endMessage" [(someA, "Calculating first a"), (someOtherA, "Calculationg second a")]
evaluates to (as, "[0% ]\r[--50% ]\rendMessage", we'll get a fancy bar!)
-}
fancyString :: String -> [a] -> [String] -> String
fancyString endMsg [] _
= "\r" ++ endMsg
fancyString endMsg as []
= fancyString endMsg as [""]
fancyString endMsg (a:as) (msg:msgs)
= let msg' = seq a msg
restMsg = fancyString endMsg as msgs
in
"\r" ++ msg'++ restMsg
fancyString' :: Bool -> String -> [a] -> [String] -> String
fancyString' withCounter endMsg as msgs
= let l = length as
msgs' = padR l "" msgs
prepTuple (i, msg)
= bar withCounter 80 l msg i
endMsg' = padR 80 ' ' endMsg
in
fancyString endMsg' as (mapi msgs' |> prepTuple)
todo = error "TODO"
safeIndex :: String -> Int -> [a] -> a
safeIndex msg i as
| i < length as
= as !! i -- When grepping on !!; this safe-index... Don't panic :p; Safe !!
| otherwise = error $ "Safe index: index to large: "++show i++"("++show (length as)++" available elements) , msg: "++msg
|
pietervdvn/ALGT
|
src/Utils/Utils.hs
|
bsd-3-clause
| 11,634
| 614
| 14
| 2,653
| 5,663
| 3,047
| 2,616
| 286
| 2
|
--{-#LANGUAGE GeneralizedNewtypeDeriving#-}
module IRC.Bot.BotData
(BotData(..)
,BotDataIO
,BotDataV
,BotDataVIO
,writeMessage
) where
import Control.Monad.Reader (runReaderT, ask, liftIO)
import Network
import System.IO
import Control.Monad.Reader
import Text.Printf
import Data.Maybe
import Text.Regex
import qualified Data.Text as T
import qualified IRC.Data.Command as ID
import qualified IRC.Data.ServerClientMessage as ID
import qualified IRC.Agent as IA
import qualified IRC.Bot.ChannelUser as IBCU
import qualified Control.Concurrent.STM.TVar as TV
import qualified Control.Concurrent.STM as TV
-- # Basic Idea around IRC Bot
-- The IRC Bot should make a connection to the server with the given
-- information. The Bot should then start reading in input from the server. The
-- Server will give instructions to the Bot if there are any errors. After
-- performing those instructions, the bot will start listening for instructions
-- given from chat. Each instruction should be parsed. Parsing possibly should
-- be performed before forking, but could be after. The Forked thread will
-- perform a number of operations, after which the thread will end. The Main
-- read loop must not be blocked.
data BotData = BotData
{ agent :: IA.Agent
, messages :: [ID.UserMsg]
, users :: [IBCU.ChannelUser]
, actions :: [Action]
}
type BotDataIO = ReaderT BotData IO
type BotDataV = TV.TVar BotData
type BotDataVIO = ReaderT BotDataV IO
-- Write the UserMsg to the Log
writeMessage :: ID.UserMsg -> BotDataVIO ()
writeMessage msg = do
dv <- ask
d <- liftIO $ TV.readTVarIO dv
liftIO $ TV.atomically $ TV.writeTVar dv
(d { messages = ( msg:(messages d)) })
data Action = Action
{ group :: IBCU.Group -- Security Level
, regexAsString :: T.Text-- What causes it
, compiledRegex :: Regex
, action :: BotDataVIO ()
}
-- User is authorized if it his group is less than what it required for
-- usage.
userIsAuthorized :: IBCU.ChannelUser -> Action -> Bool
userIsAuthorized cu a = (group a) >= (IBCU.group cu)
-- Creates the action. It compiles the supplied expression ( supplied as
-- Text) to regex.
createAction :: IBCU.Group -> T.Text -> BotDataVIO() -> Action
createAction g r b = Action
{ group = g
, regexAsString = r
, compiledRegex = mkRegex $ T.unpack r
, action = b
}
-- Runs regex matching against the Text supplied and performs the action.
-- It does not check whether the user has authorization to perform the
-- action.
runAction :: T.Text -> Action -> BotDataVIO Bool
runAction txt a = do
let str = T.unpack txt
case (matchRegex (compiledRegex a) str) of
Nothing -> return False
Just _ -> do
action a
return True
|
TheRedPepper/YBot
|
src/IRC/Bot/BotData.hs
|
bsd-3-clause
| 2,809
| 0
| 15
| 613
| 579
| 338
| 241
| 55
| 2
|
{- |
Provide a class that renders multiple Haskell values in a text form
that is accessible by gnuplot.
Maybe we add a method for the binary interface to gnuplot later.
-}
module Graphics.Gnuplot.Value.Tuple (
C(text, columnCount),
ColumnCount(ColumnCount),
) where
import System.Locale (defaultTimeLocale, )
import qualified Data.Time as Time
import Data.Word (Word8, Word16, Word32, Word64, )
import Data.Int (Int8, Int16, Int32, Int64, )
import Data.Ratio (Ratio, )
class C a where
{- |
For values that are also in Atom class,
'text' must generate a singleton list.
-}
text :: a -> [ShowS]
{- |
It must hold @ColumnCount (length (text x)) == columnCount@.
-}
columnCount :: ColumnCount a
columnCount = ColumnCount 1
{- |
Count numbers of gnuplot data columns for the respective type.
Somehow a writer monad with respect to Sum monoid
without material monadic result.
Cf. ColumnSet module.
-}
newtype ColumnCount a = ColumnCount Int
deriving (Eq, Ord, Show)
{-
Functor and Applicative instances would be useful
for combining column sets,
but they are dangerous, because they can bring
type and column columnCount out of sync.
-}
pure :: a -> ColumnCount a
pure _ = ColumnCount 0
(<*>) :: ColumnCount (a -> b) -> ColumnCount a -> ColumnCount b
ColumnCount n <*> ColumnCount m = ColumnCount (n+m)
singleton :: a -> [a]
singleton = (:[])
instance C Float where text = singleton . shows
instance C Double where text = singleton . shows
instance C Int where text = singleton . shows
instance C Integer where text = singleton . shows
instance (Integral a) => C (Ratio a) where
text = singleton . shows . (id :: Double->Double) . realToFrac
instance C Int8 where text = singleton . shows
instance C Int16 where text = singleton . shows
instance C Int32 where text = singleton . shows
instance C Int64 where text = singleton . shows
instance C Word8 where text = singleton . shows
instance C Word16 where text = singleton . shows
instance C Word32 where text = singleton . shows
instance C Word64 where text = singleton . shows
instance C Time.Day where
text d = text $ Time.UTCTime d 0
instance C Time.UTCTime where
text = singleton . showString . Time.formatTime defaultTimeLocale "%s"
instance (C a, C b) => C (a,b) where
text (a,b) = text a ++ text b
columnCount =
pure (,)
<*> columnCount
<*> columnCount
instance (C a, C b, C c) => C (a,b,c) where
text (a,b,c) = text a ++ text b ++ text c
columnCount =
pure (,,)
<*> columnCount
<*> columnCount
<*> columnCount
instance (C a, C b, C c, C d) => C (a,b,c,d) where
text (a,b,c,d) = text a ++ text b ++ text c ++ text d
columnCount =
pure (,,,)
<*> columnCount
<*> columnCount
<*> columnCount
<*> columnCount
|
wavewave/gnuplot
|
src/Graphics/Gnuplot/Value/Tuple.hs
|
bsd-3-clause
| 2,855
| 0
| 11
| 666
| 868
| 474
| 394
| 63
| 1
|
module Main where
import qualified Data.Map as M
import Htn
data Term' = HasTarget Bool
| HasAmmo Bool
| HasMagazine Bool
| CanSeeTarget Bool
| AtTarget Bool
deriving (Eq, Ord, Show)
data PrimitiveTask' = Melee
| Shot
| Reload
| MoveToTarget
| MoveToShootingPoint
deriving (Eq, Ord, Enum, Show)
data CompoundTask' = KillTarget
| PrepareShooting
deriving (Eq, Ord, Enum, Show)
type Condition = [Term']
instance Term Term'
instance PrimitiveTask PrimitiveTask'
instance CompoundTask CompoundTask'
main :: IO ()
main = do
let startCondition = [HasTarget True, HasAmmo False, HasMagazine True, CanSeeTarget False, AtTarget False]
print "------------- domain ----------------"
print buildDomain
print "------------- target ----------------"
print $ "start: " ++ show startCondition
print "------------- plan ----------------"
let (tasks, cond) = htn buildDomain startCondition [Compound KillTarget]
mapM_ print tasks
print cond
buildDomain :: Domain PrimitiveTask' CompoundTask' Term'
buildDomain = Domain buildPrimitiveMap buildCompoundMap
where
buildPrimitiveMap = M.fromList $ map buildDomainPrimitive [Melee ..]
buildCompoundMap = M.fromList $ map buildDomainCompound [KillTarget ..]
buildDomainPrimitive :: PrimitiveTask' -> (PrimitiveTask', [(Condition, Condition)])
buildDomainPrimitive task@Melee = (task, [(pre, post)])
where pre = [HasTarget True, AtTarget True]
post = [HasTarget False, AtTarget False]
buildDomainPrimitive task@Shot = (task, [(pre, post)])
where pre = [HasTarget True, HasAmmo True, CanSeeTarget True]
post = [HasTarget False, HasAmmo False, CanSeeTarget False]
buildDomainPrimitive task@Reload = (task, [(pre, post)])
where pre = [HasAmmo False, HasMagazine True]
post = [HasAmmo True, HasMagazine False]
buildDomainPrimitive task@MoveToTarget = (task, [(pre, post)])
where pre = [AtTarget False]
post = [AtTarget True]
buildDomainPrimitive task@MoveToShootingPoint = (task, [(pre, post)])
where pre = [CanSeeTarget False]
post = [CanSeeTarget True]
buildDomainCompound :: CompoundTask' -> (CompoundTask', [(Condition, [Task PrimitiveTask' CompoundTask'])])
buildDomainCompound task@KillTarget = (task,
[ ([HasAmmo True], [Compound PrepareShooting, Primitive Shot])
, ([HasMagazine True], [Compound PrepareShooting, Primitive Shot])
, ([AtTarget True], [Primitive Melee])
, ([], [Primitive MoveToTarget, Primitive Melee])
])
buildDomainCompound task@PrepareShooting = (task,
[ ([HasAmmo True, CanSeeTarget True], [])
, ([HasAmmo False, HasMagazine True], [Primitive Reload, Compound PrepareShooting])
, ([HasAmmo True, CanSeeTarget False], [Primitive MoveToShootingPoint, Compound PrepareShooting])
, ([], [Invalid "cant prepare shooting"])
])
|
y-kamiya/ai-samples
|
app/AttackHtn.hs
|
bsd-3-clause
| 3,001
| 0
| 12
| 659
| 947
| 520
| 427
| 64
| 1
|
{-# LANGUAGE TypeApplications #-}
module Test.Spec.NewPayment (
spec
-- Public to be used by other testing modules.
, Fixture (..)
, withFixture
, withPayment
) where
import Universum
import Control.Lens (to)
import Test.Hspec (Spec, describe, shouldBe, shouldSatisfy)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck (arbitrary, choose, withMaxSuccess)
import Test.QuickCheck.Monadic (PropertyM, monadicIO, pick)
import qualified Data.ByteString as B
import qualified Data.Map.Strict as M
import Data.Acid (update)
import Formatting (build, formatToString, sformat)
import Pos.Chain.Txp (TxOut (..), TxOutAux (..))
import Pos.Core (Address, Coin (..), IsBootstrapEraAddr (..),
deriveLvl2KeyPair, mkCoin)
import Pos.Core.NetworkMagic (NetworkMagic (..), makeNetworkMagic)
import Pos.Crypto (EncryptedSecretKey, ProtocolMagic,
ShouldCheckPassphrase (..), emptyPassphrase,
safeDeterministicKeyGen)
import Test.Spec.CoinSelection.Generators (InitialBalance (..),
Pay (..), genPayeeWithNM, genUtxoWithAtLeast)
import qualified Cardano.Wallet.API.V1.Types as V1
import qualified Cardano.Wallet.Kernel as Kernel
import Cardano.Wallet.Kernel.CoinSelection.FromGeneric
(CoinSelectionOptions (..), ExpenseRegulation (..),
InputGrouping (..), newOptions)
import Cardano.Wallet.Kernel.DB.AcidState
import Cardano.Wallet.Kernel.DB.HdWallet (AssuranceLevel (..),
HasSpendingPassword (..), HdAccountId (..),
HdAccountIx (..), HdAddressIx (..), HdRootId (..),
WalletName (..), eskToHdRootId, hdAccountIdIx)
import Cardano.Wallet.Kernel.DB.HdWallet.Create (initHdRoot)
import Cardano.Wallet.Kernel.DB.HdWallet.Derivation
(HardeningMode (..), deriveIndex)
import Cardano.Wallet.Kernel.DB.InDb (InDb (..))
import Cardano.Wallet.Kernel.Internal (ActiveWallet, PassiveWallet,
wallets)
import qualified Cardano.Wallet.Kernel.Keystore as Keystore
import qualified Cardano.Wallet.Kernel.NodeStateAdaptor as Node
import qualified Cardano.Wallet.Kernel.PrefilterTx as Kernel
import qualified Cardano.Wallet.Kernel.Transactions as Kernel
import Cardano.Wallet.Kernel.Types (AccountId (..), WalletId (..))
import qualified Cardano.Wallet.Kernel.Wallets as Kernel
import Cardano.Wallet.WalletLayer (ActiveWalletLayer)
import qualified Cardano.Wallet.WalletLayer as WalletLayer
import qualified Cardano.Wallet.WalletLayer.Kernel.Conv as Kernel.Conv
import qualified Test.Spec.Fixture as Fixture
import Util.Buildable (ShowThroughBuild (..))
import qualified Cardano.Wallet.API.V1.Handlers.Transactions as Handlers
import Control.Monad.Except (runExceptT)
import Servant.Server
{-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-}
data Fixture = Fixture {
fixtureHdRootId :: HdRootId
, fixtureESK :: EncryptedSecretKey
, fixtureAccountId :: AccountId
, fixturePw :: PassiveWallet
, fixturePayees :: NonEmpty (Address, Coin)
}
-- | Prepare some fixtures using the 'PropertyM' context to prepare the data,
-- and execute the 'acid-state' update once the 'PassiveWallet' gets into
-- scope (after the bracket initialisation).
prepareFixtures :: NetworkMagic
-> InitialBalance
-> Pay
-> Fixture.GenActiveWalletFixture Fixture
prepareFixtures nm initialBalance toPay = do
let (_, esk) = safeDeterministicKeyGen (B.pack $ replicate 32 0x42) mempty
let newRootId = eskToHdRootId nm esk
newRoot <- initHdRoot <$> pure newRootId
<*> pure (WalletName "A wallet")
<*> pure NoSpendingPassword
<*> pure AssuranceLevelNormal
<*> (InDb <$> pick arbitrary)
newAccountId <- HdAccountId newRootId <$> deriveIndex (pick . choose) HdAccountIx HardDerivation
utxo <- pick (genUtxoWithAtLeast initialBalance)
-- Override all the addresses of the random Utxo with something meaningful,
-- i.e. with 'Address'(es) generated in a principled way, and not random.
utxo' <- foldlM (\acc (txIn, (TxOutAux (TxOut _ coin))) -> do
newIndex <- deriveIndex (pick . choose) HdAddressIx HardDerivation
let Just (addr, _) = deriveLvl2KeyPair nm
(IsBootstrapEraAddr True)
(ShouldCheckPassphrase True)
mempty
esk
(newAccountId ^. hdAccountIdIx . to getHdAccountIx)
(getHdAddressIx newIndex)
return $ M.insert txIn (TxOutAux (TxOut addr coin)) acc
) M.empty (M.toList utxo)
payees <- fmap (\(TxOut addr coin) -> (addr, coin)) <$> pick (genPayeeWithNM nm utxo toPay)
return $ \keystore aw -> do
liftIO $ Keystore.insert (WalletIdHdRnd newRootId) esk keystore
let pw = Kernel.walletPassive aw
let accounts = Kernel.prefilterUtxo nm newRootId esk utxo'
hdAccountId = Kernel.defaultHdAccountId newRootId
hdAddress = Kernel.defaultHdAddress nm esk emptyPassphrase newRootId
void $ liftIO $ update (pw ^. wallets) (CreateHdWallet newRoot hdAccountId hdAddress accounts)
return $ Fixture {
fixtureHdRootId = newRootId
, fixtureAccountId = AccountIdHdRnd newAccountId
, fixtureESK = esk
, fixturePw = pw
, fixturePayees = payees
}
withFixture :: MonadIO m
=> ProtocolMagic
-> InitialBalance
-> Pay
-> ( Keystore.Keystore
-> ActiveWalletLayer m
-> ActiveWallet
-> Fixture
-> IO a
)
-> PropertyM IO a
withFixture pm initialBalance toPay cc =
Fixture.withActiveWalletFixture pm (prepareFixtures nm initialBalance toPay) cc
where
nm = makeNetworkMagic pm
-- | A constant fee calculation.
constantFee :: Int -> NonEmpty Coin -> Coin
constantFee _ _ = mkCoin 10
-- | Helper function to facilitate payments via the Layer or Servant.
withPayment :: MonadIO n
=> ProtocolMagic
-> InitialBalance
-- ^ How big the wallet Utxo must be
-> Pay
-- ^ How big the payment must be
-> (ActiveWalletLayer n -> V1.Payment -> IO ())
-- ^ The action to run.
-> PropertyM IO ()
withPayment pm initialBalance toPay action = do
withFixture pm initialBalance toPay $ \keystore activeLayer _ Fixture{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let (HdRootId (InDb rootAddress)) = fixtureHdRootId
let sourceWallet = V1.WalletId (sformat build rootAddress)
let accountIndex = Kernel.Conv.toAccountId hdAccountId
let destinations =
fmap (\(addr, coin) -> V1.PaymentDistribution (V1.V1 addr) (V1.V1 coin)
) fixturePayees
let newPayment = V1.Payment {
pmtSource = V1.PaymentSource sourceWallet accountIndex
, pmtDestinations = destinations
, pmtGroupingPolicy = Nothing
, pmtSpendingPassword = Nothing
}
action activeLayer newPayment
spec :: Spec
spec = describe "NewPayment" $ do
describe "Generating a new payment (wallet layer)" $ do
prop "pay works (realSigner, SenderPaysFee)" $ withMaxSuccess 5 $ do
monadicIO $ do
pm <- pick arbitrary
withPayment pm (InitialADA 10000) (PayLovelace 10) $ \activeLayer newPayment -> do
res <- liftIO ((WalletLayer.pay activeLayer) mempty
IgnoreGrouping
SenderPaysFee
newPayment
)
liftIO ((bimap STB STB res) `shouldSatisfy` isRight)
describe "Generating a new payment (kernel)" $ do
prop "newTransaction works (real signer, SenderPaysFee)" $ withMaxSuccess 5 $ do
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) (PayLovelace 10) $ \_ _ aw Fixture{..} -> do
policy <- Node.getFeePolicy (Kernel.walletPassive aw ^. Kernel.walletNode)
let opts = (newOptions (Kernel.cardanoFee policy)) {
csoExpenseRegulation = SenderPaysFee
, csoInputGrouping = IgnoreGrouping
}
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
res <- liftIO (Kernel.newTransaction aw
mempty
opts
hdAccountId
fixturePayees
)
liftIO ((bimap STB (const $ STB ()) res) `shouldSatisfy` isRight)
prop "newTransaction works (ReceiverPaysFee)" $ withMaxSuccess 5 $ do
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) (PayADA 1) $ \_ _ aw Fixture{..} -> do
policy <- Node.getFeePolicy (Kernel.walletPassive aw ^. Kernel.walletNode)
let opts = (newOptions (Kernel.cardanoFee policy)) {
csoExpenseRegulation = ReceiverPaysFee
, csoInputGrouping = IgnoreGrouping
}
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
res <- liftIO (Kernel.newTransaction aw
mempty
opts
hdAccountId
fixturePayees
)
liftIO ((bimap STB (const $ STB ()) res) `shouldSatisfy` isRight)
describe "Generating a new payment (Servant)" $ do
prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withPayment pm (InitialADA 1000) (PayADA 1) $ \activeLayer newPayment -> do
res <- liftIO (runExceptT . runHandler' $ Handlers.newTransaction activeLayer newPayment)
liftIO ((bimap identity STB res) `shouldSatisfy` isRight)
describe "EstimateFees" $ do
describe "Estimating fees (wallet layer)" $ do
prop "estimating fees works (SenderPaysFee)" $ withMaxSuccess 5 $ do
monadicIO $ do
pm <- pick arbitrary
withPayment pm (InitialADA 10000) (PayLovelace 10) $ \activeLayer newPayment -> do
res <- liftIO ((WalletLayer.estimateFees activeLayer) IgnoreGrouping
SenderPaysFee
newPayment
)
case res of
Left e -> fail (formatToString build e)
Right fee ->
fee `shouldSatisfy` (> (Coin 0))
describe "Estimating fees (kernel)" $ do
prop "estimating fees works (SenderPaysFee)" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) (PayADA 1) $ \_ _ aw Fixture{..} -> do
let opts = (newOptions constantFee) {
csoExpenseRegulation = SenderPaysFee
, csoInputGrouping = IgnoreGrouping
}
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
res <- liftIO (Kernel.estimateFees aw
opts
hdAccountId
fixturePayees
)
case res of
Left e -> fail (formatToString build e)
Right x -> x `shouldBe` Coin 10
prop "estimating fees works (kernel, ReceiverPaysFee)" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) (PayADA 1) $ \_ _ aw Fixture{..} -> do
let opts = (newOptions constantFee) {
csoExpenseRegulation = SenderPaysFee
, csoInputGrouping = IgnoreGrouping
}
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
res <- liftIO (Kernel.estimateFees aw
opts
hdAccountId
fixturePayees
)
case res of
Left e -> fail (formatToString build e)
Right x -> x `shouldBe` Coin 10
prop "estimating fees works (kernel, SenderPaysFee, cardanoFee)" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) (PayADA 1) $ \_ _ aw Fixture{..} -> do
policy <- Node.getFeePolicy (Kernel.walletPassive aw ^. Kernel.walletNode)
let opts = (newOptions (Kernel.cardanoFee policy)) {
csoExpenseRegulation = SenderPaysFee
, csoInputGrouping = IgnoreGrouping
}
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
res <- liftIO (Kernel.estimateFees aw
opts
hdAccountId
fixturePayees
)
case res of
Left e -> fail (formatToString build e)
Right x -> x `shouldSatisfy` (> (Coin 0))
describe "Estimating fees (Servant)" $ do
prop "works as expected in the happy path scenario" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withPayment pm (InitialADA 1000) (PayADA 1) $ \activeLayer newPayment -> do
res <- liftIO (runExceptT . runHandler' $ Handlers.estimateFees activeLayer newPayment)
liftIO ((bimap identity STB res) `shouldSatisfy` isRight)
-- The 'estimateFee' endpoint doesn't require a spendingPassword, but
-- the 'Payment' type does come with an optional 'spendingPassword' field.
-- Here we want to check this is completely ignored.
prop "ignores completely the spending password in Payment" $ withMaxSuccess 5 $
monadicIO $ do
randomPass <- pick arbitrary
pm <- pick arbitrary
withPayment pm (InitialADA 1000) (PayADA 1) $ \activeLayer newPayment -> do
-- mangle the spending password to be something arbitrary, check
-- that this doesn't hinder our ability to estimate fees.
let pmt = newPayment { V1.pmtSpendingPassword = randomPass }
res <- liftIO (runExceptT . runHandler' $ Handlers.estimateFees activeLayer pmt)
liftIO ((bimap identity STB res) `shouldSatisfy` isRight)
|
input-output-hk/pos-haskell-prototype
|
wallet/test/unit/Test/Spec/NewPayment.hs
|
mit
| 17,388
| 0
| 30
| 7,344
| 3,494
| 1,824
| 1,670
| -1
| -1
|
import Rest.Top ( main )
|
florianpilz/autotool
|
src/rest.hs
|
gpl-2.0
| 24
| 0
| 5
| 4
| 11
| 6
| 5
| 1
| 0
|
-----------------------------------------------------------
-- Daan Leijen (c) 2000, http://www.cs.uu.nl/~daan
--
-- $version: $
--
-- Pretty print module based on Philip Wadlers "prettier printer"
-- "A prettier printer"
-- Draft paper, April 1997, revised March 1998.
-- http://cm.bell-labs.com/cm/cs/who/wadler/papers/prettier/prettier.ps
--
-- Haskell98 compatible
-----------------------------------------------------------
{- From the documentation distributed with this library: Copyright
2000, Daan Leijen. All rights reserved. Redistribution and use in
source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution. This software is provided by the copyright holders
"as is" and any express or implied warranties, including, but not
limited to, the implied warranties of merchantability and fitness
for a particular purpose are disclaimed. In no event shall the
copyright holders be liable for any direct, indirect, incidental,
special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of
use, data, or profits; or business interruption) however caused and
on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out
of the use of this software, even if advised of the possibility of
such damage. -}
module PPrint
( Doc
, Pretty, pretty
, show, putDoc, hPutDoc
, (<>)
, (<+>)
, (</>), (<//>)
, (<$>), (<$$>)
, sep, fillSep, hsep, vsep
, cat, fillCat, hcat, vcat
, punctuate
, align, hang, indent
, fill, fillBreak
, list, tupled, semiBraces, encloseSep
, angles, langle, rangle
, parens, lparen, rparen
, braces, lbrace, rbrace
, brackets, lbracket, rbracket
, dquotes, dquote, squotes, squote
, comma, space, dot, backslash
, semi, colon, equals
, string, bool, int, integer, float, double, rational
, softline, softbreak
, empty, char, text, line, linebreak, nest, group
, column, nesting, width
, SimpleDoc(..)
, renderPretty, renderCompact
, displayS, displayIO
) where
import IO (Handle,hPutStr,hPutChar,stdout)
infixr 5 </>,<//>,<$>,<$$>
infixr 6 <>,<+>
-----------------------------------------------------------
-- list, tupled and semiBraces pretty print a list of
-- documents either horizontally or vertically aligned.
-----------------------------------------------------------
list = encloseSep lbracket rbracket comma
tupled = encloseSep lparen rparen comma
semiBraces = encloseSep lbrace rbrace semi
encloseSep left right sep ds
= case ds of
[] -> left <> right
[d] -> left <> d <> right
_ -> align (cat (zipWith (<>) (left : repeat sep) ds) <> right)
-----------------------------------------------------------
-- punctuate p [d1,d2,...,dn] => [d1 <> p,d2 <> p, ... ,dn]
-----------------------------------------------------------
punctuate p [] = []
punctuate p [d] = [d]
punctuate p (d:ds) = (d <> p) : punctuate p ds
-----------------------------------------------------------
-- high-level combinators
-----------------------------------------------------------
sep = group . vsep
fillSep = fold (</>)
hsep = fold (<+>)
vsep = fold (<$>)
cat = group . vcat
fillCat = fold (<//>)
hcat = fold (<>)
vcat = fold (<$$>)
fold f [] = empty
fold f ds = foldr1 f ds
x <> y = x `beside` y
x <+> y = x <> space <> y
x </> y = x <> softline <> y
x <//> y = x <> softbreak <> y
x <$> y = x <> line <> y
x <$$> y = x <> linebreak <> y
softline = group line
softbreak = group linebreak
squotes = enclose squote squote
dquotes = enclose dquote dquote
braces = enclose lbrace rbrace
parens = enclose lparen rparen
angles = enclose langle rangle
brackets = enclose lbracket rbracket
enclose l r x = l <> x <> r
lparen = char '('
rparen = char ')'
langle = char '<'
rangle = char '>'
lbrace = char '{'
rbrace = char '}'
lbracket = char '['
rbracket = char ']'
squote = char '\''
dquote = char '"'
semi = char ';'
colon = char ':'
comma = char ','
space = char ' '
dot = char '.'
backslash = char '\\'
equals = char '='
-----------------------------------------------------------
-- Combinators for prelude types
-----------------------------------------------------------
-- string is like "text" but replaces '\n' by "line"
string "" = empty
string ('\n':s) = line <> string s
string s = case (span (/='\n') s) of
(xs,ys) -> text xs <> string ys
bool :: Bool -> Doc
bool b = text (show b)
int :: Int -> Doc
int i = text (show i)
integer :: Integer -> Doc
integer i = text (show i)
float :: Float -> Doc
float f = text (show f)
double :: Double -> Doc
double d = text (show d)
rational :: Rational -> Doc
rational r = text (show r)
-----------------------------------------------------------
-- overloading "pretty"
-----------------------------------------------------------
class Pretty a where
pretty :: a -> Doc
prettyList :: [a] -> Doc
prettyList = list . map pretty
instance Pretty a => Pretty [a] where
pretty = prettyList
instance Pretty Doc where
pretty = id
instance Pretty () where
pretty () = text "()"
instance Pretty Bool where
pretty b = bool b
instance Pretty Char where
pretty c = char c
prettyList s = string s
instance Pretty Int where
pretty i = int i
instance Pretty Integer where
pretty i = integer i
instance Pretty Float where
pretty f = float f
instance Pretty Double where
pretty d = double d
--instance Pretty Rational where
-- pretty r = rational r
instance (Pretty a,Pretty b) => Pretty (a,b) where
pretty (x,y) = tupled [pretty x, pretty y]
instance (Pretty a,Pretty b,Pretty c) => Pretty (a,b,c) where
pretty (x,y,z)= tupled [pretty x, pretty y, pretty z]
instance Pretty a => Pretty (Maybe a) where
pretty Nothing = empty
pretty (Just x) = pretty x
-----------------------------------------------------------
-- semi primitive: fill and fillBreak
-----------------------------------------------------------
fillBreak f x = width x (\w ->
if (w > f) then nest f linebreak
else text (spaces (f - w)))
fill f d = width d (\w ->
if (w >= f) then empty
else text (spaces (f - w)))
width d f = column (\k1 -> d <> column (\k2 -> f (k2 - k1)))
-----------------------------------------------------------
-- semi primitive: Alignment and indentation
-----------------------------------------------------------
indent i d = hang i (text (spaces i) <> d)
hang i d = align (nest i d)
align d = column (\k ->
nesting (\i -> nest (k - i) d)) --nesting might be negative :-)
-----------------------------------------------------------
-- Primitives
-----------------------------------------------------------
data Doc = Empty
| Char Char -- invariant: char is not '\n'
| Text !Int String -- invariant: text doesn't contain '\n'
| Line !Bool -- True <=> when undone by group, do not insert a space
| Cat Doc Doc
| Nest !Int Doc
| Union Doc Doc -- invariant: first lines of first doc longer than the first lines of the second doc
| Column (Int -> Doc)
| Nesting (Int -> Doc)
data SimpleDoc = SEmpty
| SChar Char SimpleDoc
| SText !Int String SimpleDoc
| SLine !Int SimpleDoc
empty = Empty
char '\n' = line
char c = Char c
text "" = Empty
text s = Text (length s) s
line = Line False
linebreak = Line True
beside x y = Cat x y
nest i x = Nest i x
column f = Column f
nesting f = Nesting f
group x = Union (flatten x) x
flatten :: Doc -> Doc
flatten (Cat x y) = Cat (flatten x) (flatten y)
flatten (Nest i x) = Nest i (flatten x)
flatten (Line break) = if break then Empty else Text 1 " "
flatten (Union x y) = flatten x
flatten (Column f) = Column (flatten . f)
flatten (Nesting f) = Nesting (flatten . f)
flatten other = other --Empty,Char,Text
-----------------------------------------------------------
-- Renderers
-----------------------------------------------------------
-----------------------------------------------------------
-- renderPretty: the default pretty printing algorithm
-----------------------------------------------------------
-- list of indentation/document pairs; saves an indirection over [(Int,Doc)]
data Docs = Nil
| Cons !Int Doc Docs
renderPretty :: Float -> Int -> Doc -> SimpleDoc
renderPretty rfrac w x
= best 0 0 (Cons 0 x Nil)
where
-- r :: the ribbon width in characters
r = max 0 (min w (round (fromIntegral w * rfrac)))
-- best :: n = indentation of current line
-- k = current column
-- (ie. (k >= n) && (k - n == count of inserted characters)
best n k Nil = SEmpty
best n k (Cons i d ds)
= case d of
Empty -> best n k ds
Char c -> let k' = k+1 in seq k' (SChar c (best n k' ds))
Text l s -> let k' = k+l in seq k' (SText l s (best n k' ds))
Line _ -> SLine i (best i i ds)
Cat x y -> best n k (Cons i x (Cons i y ds))
Nest j x -> let i' = i+j in seq i' (best n k (Cons i' x ds))
Union x y -> nicest n k (best n k (Cons i x ds))
(best n k (Cons i y ds))
Column f -> best n k (Cons i (f k) ds)
Nesting f -> best n k (Cons i (f i) ds)
--nicest :: r = ribbon width, w = page width,
-- n = indentation of current line, k = current column
-- x and y, the (simple) documents to chose from.
-- precondition: first lines of x are longer than the first lines of y.
nicest n k x y | fits width x = x
| otherwise = y
where
width = min (w - k) (r - k + n)
fits w x | w < 0 = False
fits w SEmpty = True
fits w (SChar c x) = fits (w - 1) x
fits w (SText l s x) = fits (w - l) x
fits w (SLine i x) = True
-----------------------------------------------------------
-- renderCompact: renders documents without indentation
-- fast and fewer characters output, good for machines
-----------------------------------------------------------
renderCompact :: Doc -> SimpleDoc
renderCompact x
= scan 0 [x]
where
scan k [] = SEmpty
scan k (d:ds) = case d of
Empty -> scan k ds
Char c -> let k' = k+1 in seq k' (SChar c (scan k' ds))
Text l s -> let k' = k+l in seq k' (SText l s (scan k' ds))
Line _ -> SLine 0 (scan 0 ds)
Cat x y -> scan k (x:y:ds)
Nest j x -> scan k (x:ds)
Union x y -> scan k (y:ds)
Column f -> scan k (f k:ds)
Nesting f -> scan k (f 0:ds)
-----------------------------------------------------------
-- Displayers: displayS and displayIO
-----------------------------------------------------------
displayS :: SimpleDoc -> ShowS
displayS SEmpty = id
displayS (SChar c x) = showChar c . displayS x
displayS (SText l s x) = showString s . displayS x
displayS (SLine i x) = showString ('\n':indentation i) . displayS x
displayIO :: Handle -> SimpleDoc -> IO ()
displayIO handle simpleDoc
= display simpleDoc
where
display SEmpty = return ()
display (SChar c x) = do{ hPutChar handle c; display x}
display (SText l s x) = do{ hPutStr handle s; display x}
display (SLine i x) = do{ hPutStr handle ('\n':indentation i); display x}
-----------------------------------------------------------
-- default pretty printers: show, putDoc and hPutDoc
-----------------------------------------------------------
instance Show Doc where
showsPrec d doc = displayS (renderPretty 0.4 80 doc)
putDoc :: Doc -> IO ()
putDoc doc = hPutDoc stdout doc
hPutDoc :: Handle -> Doc -> IO ()
hPutDoc handle doc = displayIO handle (renderPretty 0.4 80 doc)
-----------------------------------------------------------
-- insert spaces
-- "indentation" used to insert tabs but tabs seem to cause
-- more trouble than they solve :-)
-----------------------------------------------------------
spaces n | n <= 0 = ""
| otherwise = replicate n ' '
indentation n = spaces n
--indentation n | n >= 8 = '\t' : indentation (n-8)
-- | otherwise = spaces n
|
jaapweel/bloop
|
PPrint.hs
|
gpl-2.0
| 14,805
| 0
| 16
| 5,089
| 3,686
| 1,923
| 1,763
| 248
| 10
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module File
(
#ifdef GRID_PLATFORM_IOS
module File.IOS,
#endif
#ifdef GRID_PLATFORM_GLFW
module File.GLFW,
#endif
module System.Directory,
module System.FilePath,
) where
#ifdef GRID_PLATFORM_IOS
import File.IOS
#endif
#ifdef GRID_PLATFORM_GLFW
import File.GLFW
#endif
import System.Directory
import System.FilePath
|
karamellpelle/grid
|
source/File.hs
|
gpl-3.0
| 1,093
| 0
| 5
| 197
| 77
| 59
| 18
| 6
| 0
|
module DataDupCon2 where
data A = A
data B = A
|
roberth/uu-helium
|
test/staticerrors/DataDupCon2.hs
|
gpl-3.0
| 49
| 0
| 5
| 13
| 18
| 11
| 7
| 3
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CloudSearch.IndexDocuments
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Tells the search domain to start indexing its documents using the latest
-- indexing options. This operation must be invoked to activate options
-- whose OptionStatus is 'RequiresIndexDocuments'.
--
-- /See:/ <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_IndexDocuments.html AWS API Reference> for IndexDocuments.
module Network.AWS.CloudSearch.IndexDocuments
(
-- * Creating a Request
indexDocuments
, IndexDocuments
-- * Request Lenses
, idDomainName
-- * Destructuring the Response
, indexDocumentsResponse
, IndexDocumentsResponse
-- * Response Lenses
, idrsFieldNames
, idrsResponseStatus
) where
import Network.AWS.CloudSearch.Types
import Network.AWS.CloudSearch.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Container for the parameters to the 'IndexDocuments' operation.
-- Specifies the name of the domain you want to re-index.
--
-- /See:/ 'indexDocuments' smart constructor.
newtype IndexDocuments = IndexDocuments'
{ _idDomainName :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'IndexDocuments' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'idDomainName'
indexDocuments
:: Text -- ^ 'idDomainName'
-> IndexDocuments
indexDocuments pDomainName_ =
IndexDocuments'
{ _idDomainName = pDomainName_
}
-- | Undocumented member.
idDomainName :: Lens' IndexDocuments Text
idDomainName = lens _idDomainName (\ s a -> s{_idDomainName = a});
instance AWSRequest IndexDocuments where
type Rs IndexDocuments = IndexDocumentsResponse
request = postQuery cloudSearch
response
= receiveXMLWrapper "IndexDocumentsResult"
(\ s h x ->
IndexDocumentsResponse' <$>
(x .@? "FieldNames" .!@ mempty >>=
may (parseXMLList "member"))
<*> (pure (fromEnum s)))
instance ToHeaders IndexDocuments where
toHeaders = const mempty
instance ToPath IndexDocuments where
toPath = const "/"
instance ToQuery IndexDocuments where
toQuery IndexDocuments'{..}
= mconcat
["Action" =: ("IndexDocuments" :: ByteString),
"Version" =: ("2013-01-01" :: ByteString),
"DomainName" =: _idDomainName]
-- | The result of an 'IndexDocuments' request. Contains the status of the
-- indexing operation, including the fields being indexed.
--
-- /See:/ 'indexDocumentsResponse' smart constructor.
data IndexDocumentsResponse = IndexDocumentsResponse'
{ _idrsFieldNames :: !(Maybe [Text])
, _idrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'IndexDocumentsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'idrsFieldNames'
--
-- * 'idrsResponseStatus'
indexDocumentsResponse
:: Int -- ^ 'idrsResponseStatus'
-> IndexDocumentsResponse
indexDocumentsResponse pResponseStatus_ =
IndexDocumentsResponse'
{ _idrsFieldNames = Nothing
, _idrsResponseStatus = pResponseStatus_
}
-- | The names of the fields that are currently being indexed.
idrsFieldNames :: Lens' IndexDocumentsResponse [Text]
idrsFieldNames = lens _idrsFieldNames (\ s a -> s{_idrsFieldNames = a}) . _Default . _Coerce;
-- | The response status code.
idrsResponseStatus :: Lens' IndexDocumentsResponse Int
idrsResponseStatus = lens _idrsResponseStatus (\ s a -> s{_idrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-cloudsearch/gen/Network/AWS/CloudSearch/IndexDocuments.hs
|
mpl-2.0
| 4,418
| 0
| 15
| 927
| 579
| 349
| 230
| 72
| 1
|
{-# LANGUAGE Rank2Types #-}
module Model.Issue where
import Import
import Data.Filter
import Data.Order
import Widgets.Tag (pickForegroundColor)
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Github.Issues as GH
import Numeric (readHex)
import Text.Printf
-- An Issue abstracts a Snowdrift ticket, Github issue, etc.
class Issue a where
issueWidget :: a -> Widget
issueFilterable :: a -> Filterable
issueOrderable :: a -> Orderable
-- Existentially quantified Issue.
newtype SomeIssue =
SomeIssue { unSomeIssue :: forall b. (forall a. Issue a => a -> b) -> b }
mkSomeIssue :: Issue a => a -> SomeIssue
mkSomeIssue issue = SomeIssue (\k -> k issue)
instance Issue SomeIssue where
issueWidget (SomeIssue k) = k issueWidget
issueFilterable (SomeIssue k) = k issueFilterable
issueOrderable (SomeIssue k) = k issueOrderable
instance Issue GH.Issue where
issueWidget github_issue =
[whamlet|
<tr>
<td>
$maybe url <- GH.issueHtmlUrl github_issue
<a href=#{url}>
GH-#{GH.issueNumber github_issue}
$nothing
GH-#{GH.issueNumber github_issue}
<td>
#{GH.issueTitle github_issue}
<td>
$forall tag <- GH.issueLabels github_issue
^{githubIssueTagWidget tag}
|]
where
githubIssueTagWidget :: GH.IssueLabel -> Widget
githubIssueTagWidget tag = do
[whamlet|
<form .tag>
#{GH.labelName tag}
|]
toWidget [cassius|
.tag
background-color: ##{GH.labelColor tag}
color: ##{fg $ GH.labelColor tag}
font-size: xx-small
|]
fg :: String -> String
fg = printf "%06x"
. pickForegroundColor
. maybe 0 fst
. listToMaybe
. readHex
issueFilterable = mkFromGithubIssue Filterable
issueOrderable = mkFromGithubIssue Orderable
mkFromGithubIssue
:: ((Text -> Bool)
-> (Text -> Bool)
-> (Text -> Set UTCTime)
-> (Text -> Bool)
-> t)
-> GH.Issue
-> t
mkFromGithubIssue c i = c is_claimed has_tag get_named_ts search_literal
where
has_issue_assignee = isJust $ GH.issueAssignee i
is_claimed "CLAIMED" = has_issue_assignee
-- | inverted in 'Data.Filter' and 'Data.Order'
is_claimed "UNCLAIMED" = has_issue_assignee
is_claimed cmd = error $ "Unrecognized command " <> T.unpack cmd
has_tag t = elem (T.unpack t) $ map GH.labelName $ GH.issueLabels i
get_named_ts "CREATED" =
S.singleton $ GH.fromGithubDate $ GH.issueCreatedAt i
get_named_ts "LAST UPDATED" =
S.singleton $ GH.fromGithubDate $ GH.issueUpdatedAt i
get_named_ts name = error $ "Unrecognized time name " ++ T.unpack name
search_literal str =
not (null $ T.breakOnAll str $ T.pack $ GH.issueTitle i)
|| fromMaybe False (null . T.breakOnAll str . T.pack <$> GH.issueBody i)
|
chreekat/snowdrift
|
Model/Issue.hs
|
agpl-3.0
| 3,219
| 0
| 14
| 1,047
| 677
| 356
| 321
| -1
| -1
|
import Distribution.ArchLinux.AUR
import Control.Monad
--
-- packages maintained by arch-haskell
--
me = "arch-haskell"
main = do
packages <- maintainer me
forM_ packages $ putStrLn . packageName
|
archhaskell/archlinux-web
|
scripts/mypackages.hs
|
bsd-3-clause
| 207
| 2
| 9
| 38
| 55
| 26
| 29
| 6
| 1
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.String.HTML (
-- * The HTML Widget
HTMLWidget,
-- * Constructor
mkHTMLWidget) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (when, join)
import Data.Aeson
import Data.IORef (newIORef)
import Data.Text (Text)
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
-- | A 'HTMLWidget' represents a HTML widget from IPython.html.widgets.
type HTMLWidget = IPythonWidget HTMLType
-- | Create a new HTML widget
mkHTMLWidget :: IO HTMLWidget
mkHTMLWidget = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultStringWidget "HTMLView"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
initData = object ["model_name" .= str "WidgetModel", "widget_class" .= str "IPython.HTML"]
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget initData $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay HTMLWidget where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget HTMLWidget where
getCommUUID = uuid
|
FranklinChen/IHaskell
|
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/String/HTML.hs
|
mit
| 1,562
| 0
| 13
| 358
| 283
| 158
| 125
| 33
| 1
|
{-
Copyright 2015 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 PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Text.Printf (module M) where
import "base" Text.Printf as M
|
xwysp/codeworld
|
codeworld-base/src/Text/Printf.hs
|
apache-2.0
| 737
| 0
| 4
| 136
| 23
| 17
| 6
| 4
| 0
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Stack.Solver
( cabalSolver
, getGhcVersion
, solveExtraDeps
) where
import Control.Exception.Enclosed (tryIO)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Aeson.Extended (object, (.=), toJSON, logJSONWarnings)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Either
import qualified Data.HashMap.Strict as HashMap
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import qualified Data.Yaml as Yaml
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Stack.BuildPlan
import Stack.Types
import System.Directory (copyFile,
createDirectoryIfMissing,
getTemporaryDirectory)
import qualified System.FilePath as FP
import System.IO.Temp
import System.Process.Read
cabalSolver :: (MonadIO m, MonadLogger m, MonadMask m, MonadBaseControl IO m, MonadReader env m, HasConfig env)
=> [Path Abs Dir] -- ^ cabal files
-> [String] -- ^ additional arguments, usually constraints
-> m (MajorVersion, Map PackageName (Version, Map FlagName Bool))
cabalSolver cabalfps cabalArgs = withSystemTempDirectory "cabal-solver" $ \dir -> do
configLines <- getCabalConfig dir
let configFile = dir FP.</> "cabal.config"
liftIO $ S.writeFile configFile $ encodeUtf8 $ T.unlines configLines
menv <- getMinimalEnvOverride
ghcMajorVersion <- getGhcMajorVersion menv
-- Run from a temporary directory to avoid cabal getting confused by any
-- sandbox files, see:
-- https://github.com/commercialhaskell/stack/issues/356
--
-- In theory we could use --ignore-sandbox, but not all versions of cabal
-- support it.
tmpdir <- liftIO getTemporaryDirectory >>= parseAbsDir
let args = ("--config-file=" ++ configFile)
: "install"
: "-v"
: "--dry-run"
: "--only-dependencies"
: "--reorder-goals"
: "--max-backjumps=-1"
: "--package-db=clear"
: "--package-db=global"
: cabalArgs ++
(map toFilePath cabalfps)
$logInfo "Asking cabal to calculate a build plan, please wait"
bs <- readProcessStdout (Just tmpdir) menv "cabal" args
let ls = drop 1
$ dropWhile (not . T.isPrefixOf "In order, ")
$ T.lines
$ decodeUtf8 bs
(errs, pairs) = partitionEithers $ map parseLine ls
if null errs
then return (ghcMajorVersion, Map.fromList pairs)
else error $ "Could not parse cabal-install output: " ++ show errs
where
parseLine t0 = maybe (Left t0) Right $ do
-- get rid of (new package) and (latest: ...) bits
ident':flags' <- Just $ T.words $ T.takeWhile (/= '(') t0
PackageIdentifier name version <-
parsePackageIdentifierFromString $ T.unpack ident'
flags <- mapM parseFlag flags'
Just (name, (version, Map.fromList flags))
parseFlag t0 = do
flag <- parseFlagNameFromString $ T.unpack t1
return (flag, enabled)
where
(t1, enabled) =
case T.stripPrefix "-" t0 of
Nothing ->
case T.stripPrefix "+" t0 of
Nothing -> (t0, True)
Just x -> (x, True)
Just x -> (x, False)
getGhcVersion :: (MonadLogger m, MonadCatch m, MonadBaseControl IO m, MonadIO m)
=> EnvOverride -> m Version
getGhcVersion menv = do
bs <- readProcessStdout Nothing menv "ghc" ["--numeric-version"]
parseVersion $ S8.takeWhile isValid bs
where
isValid c = c == '.' || ('0' <= c && c <= '9')
getGhcMajorVersion :: (MonadLogger m, MonadCatch m, MonadBaseControl IO m, MonadIO m)
=> EnvOverride -> m MajorVersion
getGhcMajorVersion menv = do
version <- getGhcVersion menv
return $ getMajorVersion version
getCabalConfig :: (MonadReader env m, HasConfig env, MonadIO m, MonadThrow m)
=> FilePath -- ^ temp dir
-> m [Text]
getCabalConfig dir = do
indices <- asks $ configPackageIndices . getConfig
remotes <- mapM goIndex indices
let cache = T.pack $ "remote-repo-cache: " ++ dir
return $ cache : remotes
where
goIndex index = do
src <- configPackageIndex $ indexName index
let dstdir = dir FP.</> T.unpack (indexNameText $ indexName index)
dst = dstdir FP.</> "00-index.tar"
liftIO $ void $ tryIO $ do
createDirectoryIfMissing True dstdir
copyFile (toFilePath src) dst
return $ T.concat
[ "remote-repo: "
, indexNameText $ indexName index
, ":http://0.0.0.0/fake-url"
]
-- | Determine missing extra-deps
solveExtraDeps :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadMask m, MonadLogger m, MonadBaseControl IO m, HasHttpManager env)
=> Bool -- ^ modify stack.yaml?
-> m ()
solveExtraDeps modStackYaml = do
$logInfo "This command is not guaranteed to give you a perfect build plan"
$logInfo "It's possible that even with the changes generated below, you will still need to do some manual tweaking"
bconfig <- asks getBuildConfig
snapshot <-
case bcResolver bconfig of
ResolverSnapshot snapName -> liftM mbpPackages $ loadMiniBuildPlan snapName
ResolverGhc _ -> return Map.empty
ResolverCustom _ url -> liftM mbpPackages $ parseCustomMiniBuildPlan
(bcStackYaml bconfig)
url
let packages = Map.union
(bcExtraDeps bconfig)
(fmap mpiVersion snapshot)
constraints = map
(\(k, v) -> concat
[ "--constraint="
, packageNameString k
, "=="
, versionString v
])
(Map.toList packages)
(_ghc, extraDeps) <- cabalSolver
(Map.keys $ bcPackages bconfig)
constraints
let newDeps = extraDeps `Map.difference` packages
newFlags = Map.filter (not . Map.null) $ fmap snd newDeps
if Map.null newDeps
then $logInfo "No needed changes found"
else do
let o = object
$ ("extra-deps" .= (map fromTuple $ Map.toList $ fmap fst newDeps))
: (if Map.null newFlags
then []
else ["flags" .= newFlags])
mapM_ $logInfo $ T.lines $ decodeUtf8 $ Yaml.encode o
when modStackYaml $ do
let fp = toFilePath $ bcStackYaml bconfig
obj <- liftIO (Yaml.decodeFileEither fp) >>= either throwM return
(ProjectAndConfigMonoid project _, warnings) <-
liftIO (Yaml.decodeFileEither fp) >>= either throwM return
logJSONWarnings fp warnings
let obj' =
HashMap.insert "extra-deps"
(toJSON $ map fromTuple $ Map.toList
$ Map.union (projectExtraDeps project) (fmap fst newDeps))
$ HashMap.insert ("flags" :: Text)
(toJSON $ Map.union (projectFlags project) newFlags)
obj
liftIO $ Yaml.encodeFile fp obj'
$logInfo $ T.pack $ "Updated " ++ fp
|
wskplho/stack
|
src/Stack/Solver.hs
|
bsd-3-clause
| 8,052
| 0
| 23
| 2,680
| 1,968
| 999
| 969
| 166
| 5
|
{-
******************************************************************************
* H M T C *
* *
* Module: SrcPos *
* Purpose: Source-code positions and related definitions *
* Authors: Henrik Nilsson *
* *
* Copyright (c) Henrik Nilsson, 2006 - 2012 *
* *
******************************************************************************
-}
-- |Source-code positions and related definitions
module SrcPos (
SrcPos (..), -- Not abstract. Instances: Eq, Ord, Show.
HasSrcPos (..)
) where
-- | Representation of source-code positions
data SrcPos
= NoSrcPos -- ^ Unknown source-code position
| SrcPos {
spLine :: Int, -- ^ Line number
spCol :: Int -- ^ Character column number
}
deriving (Eq, Ord)
instance Show SrcPos where
showsPrec _ NoSrcPos = showString "unknown position"
showsPrec _ (SrcPos {spLine = l, spCol = c }) =
showString "line "
. shows l
. showString ", column "
. shows c
-- | Class of types that have a source-code position as a stored or computed
-- attribute.
class HasSrcPos a where
srcPos :: a -> SrcPos
-- A list of entities that have source positions also has a source position.
instance HasSrcPos a => HasSrcPos [a] where
srcPos [] = NoSrcPos
srcPos (x:_) = srcPos x
|
jbracker/supermonad-plugin
|
examples/monad/hmtc/original/SrcPos.hs
|
bsd-3-clause
| 1,796
| 0
| 10
| 801
| 202
| 113
| 89
| 21
| 0
|
-- In this example, the first import declaration should be removed.
module B3 (myFringe)where
import C1 hiding (myFringe)
import C1 (Tree(Leaf,Branch))
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe right
sumSquares (x:xs)= x^2 + sumSquares xs
sumSquares [] =0
|
kmate/HaRe
|
old/testing/cleanImports/B3.hs
|
bsd-3-clause
| 332
| 0
| 7
| 74
| 120
| 67
| 53
| 8
| 1
|
module M1 where
--Any type/data constructor name declared in this module can be renamed.
--Any type variable can be renamed.
--Rename type Constructor 'BTree' to 'MyBTree'
data BTree a = Empty | T a (BTree a) (BTree a)
deriving Show
buildtree :: (Monad m, Ord a) => [a] -> m (BTree a)
buildtree [] = return Empty
buildtree (x:xs) = do
res1 <- buildtree xs
res <- insert x res1
return res
insert :: (Monad m, Ord a) => a -> BTree a -> m (BTree a)
insert val v2 = do
case v2 of
T val Empty Empty
| val == val -> return Empty
| otherwise -> return (T val Empty (T val Empty Empty))
T val (T val2 Empty Empty) Empty -> return Empty
_ -> return v2
main :: IO ()
main = do
n@(T val Empty Empty) <- buildtree [3, 1, 2]
putStrLn $ (show (T val Empty Empty))
|
kmate/HaRe
|
old/testing/unfoldAsPatterns/M1_TokOut.hs
|
bsd-3-clause
| 1,013
| 0
| 15
| 417
| 351
| 174
| 177
| 21
| 3
|
{-# LANGUAGE ScopedTypeVariables #-}
-- | Low-level bytestring builders. Most users want to use the more
-- type-safe 'Data.Csv.Incremental' module instead.
module Data.Csv.Builder
(
-- * Encoding single records and headers
encodeHeader
, encodeRecord
, encodeNamedRecord
, encodeDefaultOrderedNamedRecord
-- ** Encoding options
, encodeHeaderWith
, encodeRecordWith
, encodeNamedRecordWith
, encodeDefaultOrderedNamedRecordWith
) where
import Data.Monoid
import Blaze.ByteString.Builder as Builder
import Data.Csv.Conversion
import qualified Data.Csv.Encoding as Encoding
import Data.Csv.Encoding (EncodeOptions(..))
import Data.Csv.Types hiding (toNamedRecord)
-- | Encode a header.
encodeHeader :: Header -> Builder.Builder
encodeHeader = encodeRecord
-- | Encode a single record.
encodeRecord :: ToRecord a => a -> Builder.Builder
encodeRecord = encodeRecordWith Encoding.defaultEncodeOptions
-- | Encode a single named record, given the field order.
encodeNamedRecord :: ToNamedRecord a =>
Header -> a -> Builder.Builder
encodeNamedRecord = encodeNamedRecordWith Encoding.defaultEncodeOptions
-- | Encode a single named record, using the default field order.
encodeDefaultOrderedNamedRecord ::
(DefaultOrdered a, ToNamedRecord a) => a -> Builder.Builder
encodeDefaultOrderedNamedRecord =
encodeDefaultOrderedNamedRecordWith Encoding.defaultEncodeOptions
-- | Like 'encodeHeader', but lets you customize how the CSV data is
-- encoded.
encodeHeaderWith :: EncodeOptions -> Header -> Builder.Builder
encodeHeaderWith = encodeRecordWith
-- | Like 'encodeRecord', but lets you customize how the CSV data is
-- encoded.
encodeRecordWith :: ToRecord a => EncodeOptions -> a -> Builder.Builder
encodeRecordWith opts r =
Encoding.encodeRecord (encQuoting opts) (encDelimiter opts) (toRecord r)
<> Encoding.recordSep (encUseCrLf opts)
-- | Like 'encodeNamedRecord', but lets you customize how the CSV data
-- is encoded.
encodeNamedRecordWith :: ToNamedRecord a =>
EncodeOptions -> Header -> a -> Builder.Builder
encodeNamedRecordWith opts hdr nr =
Encoding.encodeNamedRecord hdr (encQuoting opts) (encDelimiter opts)
(toNamedRecord nr) <> Encoding.recordSep (encUseCrLf opts)
-- | Like 'encodeDefaultOrderedNamedRecord', but lets you customize
-- how the CSV data is encoded.
encodeDefaultOrderedNamedRecordWith ::
forall a. (DefaultOrdered a, ToNamedRecord a) =>
EncodeOptions -> a -> Builder.Builder
encodeDefaultOrderedNamedRecordWith opts =
encodeNamedRecordWith opts (headerOrder (undefined :: a))
|
jb55/cassava
|
Data/Csv/Builder.hs
|
bsd-3-clause
| 2,643
| 0
| 9
| 444
| 453
| 254
| 199
| 44
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module App where
import Database.Persist.Sqlite
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
import API.Contact
import DB
import Model
type ServerAPI = "contacts" :> ContactsAPI
server :: Server ServerAPI
server = contactsServer
app :: Application
app = serve (Proxy :: (Proxy ServerAPI)) server
main :: IO ()
main = do
runDB $ runMigration migrateAll
run 3000 app
|
lexi-lambda/haskell-rolodex
|
src/App.hs
|
isc
| 455
| 0
| 8
| 74
| 121
| 69
| 52
| 19
| 1
|
-- Existential type
-- ref: https://wiki.haskell.org/Existential_type
-- trac: https://prime.haskell.org/wiki/ExistentialQuantification
-- 1. Intro
-- Normally when creating a new type using type, newtype, data, etc., every type variable that appears on the right-hand side must also appear on the left-hand side. Existential types are a way of turning this off.
-- monomorphism restriction
-- no data Worker b x y = Worker {buffer :: b, input :: x, output :: y}
data Worker x y = forall b. Buffer b => Worker {buffer :: b, input :: x, output :: y}
-- In general, when you use a 'hidden' type in this way, you will usually want that type to belong to a specific class, or you will want to pass some functions along that can work on that type. Otherwise you'll have some value belonging to a random unknown type, and you won't be able to do anything to it!
-- Note: You can use existential types to convert a more specific type into a less specific one. (See the examples below.) There is no way to perform the reverse conversion!
-- 2. Examples
data Obj = forall a. (Show a) => Obj a
xs :: [Obj]
xs = [Obj 1, Obj "foo", Obj 'c']
doShow :: [Obj] -> String
doShow [] = ""
doShow ((Obj x):xs) = show x ++ doShow xs
-- raytracer
-- In a raytracer, a requirement is to be able to render several different objects (like a ball, mesh or whatever).
class Renderable a where
boundingSphere :: a -> Sphere
hit :: a -> [Fragment] -- returns the "fragments" of all hits with ray
{- ... etc ... -}
hits :: Renderable a => [a] -> [Fragment]
hits xs = sortByDistance $ concatMap hit xs
-- However, this does not work as written since the elements of the list can be of SEVERAL different types (like a sphere and a polygon and a mesh etc. etc.) but lists need to have elements of the same type.
-- solutions
{-# OPTIONS -fglasgow-exts #-}
data AnyRenderable = forall a. Renderable a => AnyRenderable a
instance Renderable AnyRenderable where
boundingSphere (AnyRenderable a) = boundingSphere a
hit (AnyRenderable a) = hit a
-- Dynamic dispatch of OOP
-- Existential types in conjunction with type classes can be used to emulate the dynamic dispatch mechanism of object oriented programming languages. To illustrate this concept I show how a classic example from object oriented programming can be encoded in Haskell.
class Shape_ a where
perimeter :: a -> Double
area :: a -> Double
data Shape = forall a. Shape_ a => Shape a
type Radius = Double
type Side = Double
data Circle = Circle Radius
data Rectangle = Rectangle Side Side
data Square = Square Side
instance Shape_ Circle where
perimeter (Circle r) = 2 * pi * r
area (Circle r) = pi * r * r
instance Shape_ Rectangle where
perimeter (Rectangle x y) = 2*(x + y)
area (Rectangle x y) = x * y
instance Shape_ Square where
perimeter (Square s) = 4*s
area (Square s) = s*s
instance Shape_ Shape where
perimeter (Shape shape) = perimeter shape
area (Shape shape) = area shape
--
-- Smart constructor
--
circle :: Radius -> Shape
circle r = Shape (Circle r)
rectangle :: Side -> Side -> Shape
rectangle x y = Shape (Rectangle x y)
square :: Side -> Shape
square s = Shape (Square s)
shapes :: [Shape]
shapes = [circle 2.4, rectangle 3.1 4.4, square 2.1]
-- GADT parse
-- Exceptions
-- Control.Exception (see documentation) provides extensible exceptions by making the core exception type, SomeException, an existential:
class (Show e, Typeable e) => Exception e where
toException :: e -> SomeException
fromException :: SomeException -> Maybe e
data SomeException = forall a. Exception a => SomeException a
-- You can define your own exceptions by making them an instance of the Exception class.
{-
Then there are two basic ways of dealing with exceptions:
If you have a SomeException value, use fromException. This returns Just e if the exception is the type you want. If it's something else, you get Nothing. You could check multiple types using a guard. This is what you'll have to use if you're dealing with SomeExceptions in pure code.
If you're in IO and have an expression that might throw an exception, catch lets you catch it. (There's also a version generalised to other instances of MonadIO in the lifted-base package). Its second argument takes a handler, which is a function accepting an exception of the type you want. If the first argument throws an exception, catch uses the Typeable library's typesafe cast to try to convert it to the type you want, then (if it succeeded) passes it to the handler. You can apply catch many times to the same expression with handlers for different exception types.
Even if fromException doesn't turn up an exception type you know, and catch doesn't catch an exception type you know, you can still show the unknown exception, maybe after catching SomeException.
-}
-- 3. Alternate methods
-- 3.1 Concrete data types
-- 3.1.1 Universal instance of a Class
-- Here one way to simulate existentials (Hawiki note: (Borrowed from somewhere...))
type Point = (Float,Float)
class Shape a where
draw :: a -> IO ()
translate :: a-> Point -> a
-- Then we can pack shapes up into a concrete data type like this:
data SHAPE = SHAPE (IO ()) (Point -> SHAPE)
-- with a function like this
packShape :: Shape a => a -> SHAPE
packShape s = SHAPE (draw s) (\(x,y) -> packShape (translate s (x,y)))
instance Shape SHAPE where
draw (SHAPE d t) = d
translate (SHAPE d t) = t
-- 3.1.2 Using constructors and combinators
data Shape = Shape {
draw :: IO()
translate :: (Int, Int) -> Shape
}
-- Then you can create a library of shape constructors and combinators that each have defined "draw" and "translate" in their "where" clauses.
circle :: (Int, Int) -> Int -> Shape
circle (x,y) r =
Shape draw1 translate1
where
draw1 = ...
translate1 (x1,y1) = circle (x+x1, y+y1) r
shapeGroup :: [Shape] -> Shape
shapeGroup shapes = Shape draw1 translate1
where
draw1 = mapM_ draw shapes
translate1 v = shapeGroup $ map (translate v) shapes
-- 3.2 Cases that really require existentials
data Expr a = Val a | forall b . Apply (Expr (b -> a)) (Expr b)
data Action = forall b . Act (IORef b) (b -> IO ())
-- (Maybe this last one could be done as a type Act (IORef b) (IORef b -> IO ()) then we could hide the IORef as above, that is go ahead and apply the second argument to the first)
-- 3.3 Existentials in terms of "forall"
-- It is also possible to express existentials as type expressions directly (without a data declaration) with RankNTypes.
data Obj = forall a. (Show a) => Obj a
-- the type Obj is equivalent to:
-- forall r. (forall a. Show a => a -> r) -> r
-- (the leading forall r. is optional unless the expression is part of another expression). The conversions are:
fromObj :: Obj
-> forall r. (forall a. Show a => a -> r) -> r
fromObj (Obj x) k = k x
toObj :: (forall r. (forall a. Show a => a -> r) -> r)
-> Obj
toObj f = f Obj
|
Airtnp/Freshman_Simple_Haskell_Lib
|
Idioms/Existential-type.hs
|
mit
| 7,118
| 23
| 13
| 1,569
| 1,440
| 747
| 693
| -1
| -1
|
{-# OPTIONS_GHC -Wall #-}
module ExprT where
data ExprT = Lit Integer
| Add ExprT ExprT
| Mul ExprT ExprT
deriving (Show, Eq)
|
tamasgal/haskell_exercises
|
CIS-194/homework-05/ExprT.hs
|
mit
| 151
| 0
| 6
| 48
| 39
| 23
| 16
| 6
| 0
|
module Demo where
import BreveLang
import BreveEval
import Synth
import qualified Data.Map.Lazy as Map
import Data.Maybe (fromJust)
-- Sample program:
-- Define the program
-- Parse it to get the statements
-- eval it to get the traces
-- Make an update for it
-- Synthesize!!
-- Woops, didn't get what we expected
-- Why? Synth choose limited subset of variables to try to solve. Synthesis
-- itself works, but input to it is limited at the moment
-- Play original program, play new program
-- We can undo it!
-- Perform restored
fibo = "fibo = (\\ n -> if n <= 1 then n else fibo(n-1) + fibo(n-2)); main = fibo(5);"
program = "dfsa = arpeggio([0,4,7], (D 4 1/2));\nmain = line(dfsa) :+: (rest 1/4) :+: chord(dfsa);"
states = parse program
traces = snd $ parseEval program
showAll :: Show a => [a] -> IO ()
showAll = mapM_ print
update = [Vp (read "F") (TrOp Add (TrLoc (1,29)) (TrLoc (1,21)))
,Vn 4 (TrLoc (1,34))]
synthed = fromJust $ synthesize Faithful AdHoc traces update
-- This returns [TraceMap]. We need to combine them to get the full substitution
-- that combines the updates.
-- combos = map Map.fromList $ sequence $ map Map.toList synthed
combos = map Map.fromList $ mapM Map.toList synthed
newprog = map (show . (`updateProgram` states)) combos
-- When this Demo was written, Synth would return the C# chord version of the
-- synthesized program first. Thanks to the Ad Hoc ranking, it now returns the D
-- minor chord version first instead.
-- To preserve the output of the Demo as it once was, I've rewritten the
-- following few lines to "restore" only the C# chord version.
-- Restore gives us two programs: The original (D major chord) and a C# sus 4
-- chord. Neat.
newState = parse (newprog !! 1)
newTraces = snd $ parseEval (newprog !! 1)
undo = [Vp (read "Fs") (TrOp Add (TrLoc (1,32)) (TrLoc (1,22)))]
restoringUpdates = map Map.fromList $ mapM Map.toList $ fromJust $ synthesize Faithful AdHoc newTraces undo
restored = map (show . (`updateProgram` newState)) restoringUpdates
main = do
putStrLn "The original program:"
putStrLn program
getLine
perform program
getLine
putStrLn "The traces of the program: (numeric and expression)"
showAll traces
getLine
putStrLn "The update we want: Turn the F# into an F"
print update
getLine
putStrLn "Here's the results of synthesis:"
mapM_ (\p -> putStrLn p >> getLine >> perform p >> getLine) newprog
putStrLn "\nTwo different programs! One does what we expect (changes the 4 into a 3, giving us a D minor chord)"
putStrLn "The other turns the root note (D) into a C#, giving us a C# major chord!"
putStrLn "You'll notice both have quarter notes (1/4) instead of half notes (1/2)"
putStrLn "\nHere's the original program for comparison:"
putStrLn program
getLine
putStrLn "Synthesis can be undone, too."
print undo
putStrLn "This update will turn the F back into an F#."
getLine
putStrLn "Here's the results:"
mapM_ putStrLn restored
putStrLn "The first one changes the 4 into a 5, and keeps the C# root note. (C# sus. 4 chord! Crunchy.)"
putStrLn "The synthesis ranking put this one first because it only changes 2 values: the 4 -> 5 and the resulting C# + 5 -> F#"
putStrLn "The second program has a D instead of a C#, giving us the original program back."
putStrLn "Three values are changed: D + 0 -> D, D + 4 -> F# and D + 7 -> A."
getLine
mapM_ (\p -> putStrLn p >> getLine >> perform p >> getLine) restored
|
Solumin/ScriptNScribe
|
src/Demo.hs
|
mit
| 3,534
| 0
| 13
| 749
| 625
| 314
| 311
| 54
| 1
|
module Main where
import AST
import Control.Monad.Reader
import Control.Monad.Trans.Except
import Data.List (intercalate)
import Data.Maybe (fromJust, listToMaybe, mapMaybe)
import Data.Monoid
import Parser (parse)
import System.Environment (getArgs)
type ExceptReader = ExceptT String (Reader Environment) Int
eval :: Expr -> ExceptReader
eval (Number x) = return x
eval (Inc x) = liftM (1+) (eval x)
eval (Constant n) = ask >>= \env ->
case lookupEnv n env of
Just (ConstDef _ n' form') -> withExceptT (++ "\n\nin constant " ++ form') (eval n')
_ -> throwE $ "Unknown parameter " ++ n ++ "\n"
eval (Call f args) = do
env <- ask
args' <- mapExceptT (return . (`runReader` env)) (sequence (map eval args))
insts <- case (lookupEnv f env) of
Just (FuncDef _ is) -> return is
Nothing -> throwE $ "unknown function " ++ show f
case listToMaybe $ mapMaybe (\i -> matchesInst i args' mempty) insts of
Just (f', env') -> mapExceptT (return . (`runReader` (env' <> env))) (eval f')
Nothing -> throwE $ "No suitable instance of " ++ show f
++ " among these:\n\t"
++ intercalate "\n\t" (map frm insts) ++ "\n\n"
++ "found for arg(s):\n\t"
++ intercalate "\n\t" (map (\a -> showIntAsNat a ++ " : " ++ show a) args')
where frm (_,_,x) = x
findEnvs :: [Name] -> Environment -> [Form]
findEnvs = go []
where go forms [] _ = forms
go forms (n:ns) env = go (defForm (fromJust (lookupEnv n env)) ++ forms) ns env
-- For the "f(a,a) implies a=a"-feature, there's a little bit too much implicit knowledge about the env being empty and only containing Numbers, but for now it works
matchesInst :: Instance -> [Int] -> Environment -> Maybe (Expr, Environment)
matchesInst ([],f,_) [] env = Just (f, env)
matchesInst (LiteralParam p : pars, f, form) (a:as) env
| p == a = matchesInst (pars, f, form) as env
| otherwise = Nothing
matchesInst (FreeParam p : pars, f, form) (a:as) env =
case lookupEnv p env of
Just (ConstDef _ (Number e) _) -> if e == a then continue else Nothing
Nothing -> continue
where continue = matchesInst (pars,f,form) as (insertEnv (ConstDef p (Number a) form) env)
matchesInst (PatternParam (Binding p) : pars, f, form) (a:as) env =
case lookupEnv p env of
Just (ConstDef _ (Number e) _) -> if e == a then continue else Nothing
Nothing -> continue
where continue = matchesInst (pars,f,form) as (insertEnv (ConstDef p (Number a) form) env)
matchesInst (PatternParam (Succ _) : _, _, _) (0:_) _ = Nothing
matchesInst (PatternParam (Succ s) : pars, f, form) (a:as) env =
matchesInst (PatternParam s : pars, f, form) (a-1:as) env
matchesInst (WildcardParam : pars, f, form) (_:as) env = matchesInst (pars, f, form) as env
matchesInst _ _ _ = Nothing
run :: Program -> Either String Int
run defs = case runReader (runExceptT prog) mempty of
Right i -> Right i
Left err -> Left err
where prog = do
let env = foldl (flip insertEnv) mempty defs
case lookupEnv "main" env of
Just (FuncDef _ [(_,m,_)]) -> local (env <>) (eval m)
Just (ConstDef _ m _) -> local (env <>) (eval m)
_ -> error "No unique main function found."
main :: IO ()
main = do
args <- getArgs
when (length args /= 1) (error "Supply the name of the file to run as the sole argument")
ast <- parse (head args)
case ast of
Just prog -> either putStrLn print (run prog)
Nothing -> return ()
|
andreasfrom/natlang
|
Main.hs
|
mit
| 3,626
| 0
| 18
| 954
| 1,500
| 775
| 725
| 73
| 5
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad (forM, when)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Control (liftBaseOp)
import Control.Monad.Trans.Except (runExceptT, ExceptT(..), throwE)
import Data.Functor ((<$>))
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as VM
import Foreign.C.Types
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.Ptr (Ptr)
import qualified Language.C.Inline.Nag as C
import System.IO.Unsafe (unsafePerformIO)
C.context C.nagCtx
C.include "<math.h>"
C.include "<nag.h>"
C.include "<nagd02.h>"
C.include "<stdio.h>"
data Method
= RK_2_3
| RK_4_5
| RK_7_8
deriving (Eq, Show)
data SolveOptions = SolveOptions
{ _soMethod :: Method
, _soTolerance :: CDouble
, _soInitialStepSize :: CDouble
} deriving (Eq, Show)
{-# NOINLINE solve #-}
solve
:: SolveOptions
-> (CDouble -> V.Vector CDouble -> V.Vector CDouble)
-- ^ ODE to solve
-> [CDouble]
-- ^ @x@ values at which to approximate the solution.
-> V.Vector CDouble
-- ^ The initial values of the solution.
-> Either String [(CDouble, V.Vector CDouble)]
-- ^ Either an error, or the @y@ values corresponding to the @x@
-- values input.
solve (SolveOptions method tol hstart) f xs y0 = unsafePerformIO $ runExceptT $ do
when (length xs < 2) $
throwE "You have to provide a minimum of 2 values for @x@"
let tstart = head xs
let tend = last xs
iwsav <- lift $ VM.new liwsav
rwsav <- lift $ VM.new lrwsav
let thresh = V.replicate n 0
methodInt <- lift $ case method of
RK_2_3 -> [C.exp| int{ Nag_RK_2_3 } |]
RK_4_5 -> [C.exp| int{ Nag_RK_4_5 } |]
RK_7_8 -> [C.exp| int{ Nag_RK_7_8 } |]
ExceptT $ C.withNagError $ \fail_ ->
[C.exp| void{ nag_ode_ivp_rkts_setup(
$(Integer n_c), $(double tstart), $(double tend), $vec-ptr:(double *y0),
$(double tol), $vec-ptr:(double *thresh), $(int methodInt),
Nag_ErrorAssess_off, $(double hstart), $vec-ptr:(Integer *iwsav),
$vec-ptr:(double *rwsav), $(NagError *fail_))
} |]
ygot <- lift $ VM.new n
ypgot <- lift $ VM.new n
ymax <- lift $ VM.new n
let fIO :: CDouble -> C.Nag_Integer -> Ptr CDouble -> Ptr CDouble -> Ptr C.Nag_Comm -> IO ()
fIO t n y _yp _comm = do
yFore <- newForeignPtr_ y
let yVec = VM.unsafeFromForeignPtr0 yFore $ fromIntegral n
ypImm <- f t <$> V.unsafeFreeze yVec
V.copy yVec ypImm
liftBaseOp C.initNagError $ \fail_ -> do
-- Tail because the first point is the start
ys <- forM (tail xs) $ \t -> do
ExceptT $ C.checkNagError fail_ $ [C.block| void {
double tgot;
nag_ode_ivp_rkts_range(
$fun:(void (*fIO)(double t, Integer n, const double y[], double yp[], Nag_Comm *comm)),
$(Integer n_c), $(double t), &tgot, $vec-ptr:(double *ygot),
$vec-ptr:(double *ypgot), $vec-ptr:(double *ymax), NULL,
$vec-ptr:(Integer *iwsav), $vec-ptr:(double *rwsav),
$(NagError *fail_));
} |]
y <- lift $ V.freeze ygot
return (t, y)
return $ (tstart, y0) : ys
where
n = V.length y0
liwsav = 130
lrwsav = 350 + 32 * n
n_c = fromIntegral n
main :: IO ()
main = do
let opts = SolveOptions RK_4_5 1e-8 0
let f _t y = V.fromList [y V.! 1, -(y V.! 0)]
case solve opts f [0,pi/4..pi] (V.fromList [0, 1]) of
Left err -> putStrLn err
Right x -> print x
|
fpco/inline-c-nag
|
examples/ode-runge-kutta.hs
|
mit
| 3,600
| 0
| 20
| 891
| 980
| 510
| 470
| 77
| 3
|
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module Unit (unitTests) where
import Data.Aeson
import Data.Attoparsec.Text (eitherResult, parse)
import Data.ByteString.Lazy (ByteString, fromStrict)
import Data.Maybe (fromJust)
import Data.Text (Text, pack)
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Calendar (Day(..))
import Data.Time.Clock (UTCTime)
import Data.Time.ISO8601 (parseISO8601)
import Data.Time.LocalTime (LocalTime(..), TimeZone, TimeOfDay(..), hoursToTimeZone, utcToLocalTime)
import NeatInterpolation
import Test.Tasty
import Test.Tasty.HUnit
import Web.DeutscheBahn.API.Schedule
import Web.DeutscheBahn.API.Schedule.Data
import Web.DeutscheBahn.API.Schedule.JourneyRefURIParser
unitTests = testGroup "Unit Test Parsing"
[
testCase "parse JourneyDetailRef" $
Right ref @=? (eitherDecode refJSON :: Either String JourneyRef)
, testCase "parse Departure" $
Right departure @=? (eitherDecode departureJSON :: Either String Departure)
, testCase "parse StopLocation" $
Right frankfurtHbf @=? (eitherDecode stopLocationJSON :: Either String StopLocation)
, testCase "parse JourneyRef URI format" $
(Right refURIDetails) @=? (parseJourneyRefURI refURI)
]
departureJSON :: ByteString
departureJSON = fromStrict $ encodeUtf8 [text|
{
"name":"RE 15306",
"type":"RE",
"stopid":"8000105",
"stop":"Frankfurt(Main)Hbf",
"time":"15:01",
"date":"2016-02-22",
"direction":"Limburg(Lahn)",
"track":"3",
"JourneyDetailRef":{
"ref":"http://DOMAINE-TOBE-DEFI-NED.de/bin/"
}
}|]
-- | +1 UTC non-summer
germanyTimeZone :: TimeZone
germanyTimeZone = hoursToTimeZone 1
departureTime :: LocalTime
departureTime = utcToLocalTime germanyTimeZone departureUTC
where departureUTC = fromJust $ parseISO8601 "2016-02-22T14:01:00Z"
departure :: Departure
departure = Departure "RE 15306" RE (StopId "8000105") departureTime "Frankfurt(Main)Hbf" "Limburg(Lahn)" (Just "3") ref
refJSON :: ByteString
refJSON = fromStrict $ encodeUtf8 [text|
{
"ref":"http://DOMAINE-TOBE-DEFI-NED.de/bin/"
}|]
ref :: JourneyRef
ref = JourneyRef "http://DOMAINE-TOBE-DEFI-NED.de/bin/"
stopLocationJSON :: ByteString
stopLocationJSON = fromStrict $ encodeUtf8 [text|
{
"name":"Frankfurt(Main)Hbf",
"lon":"8.663785",
"lat":"50.107149",
"id":"008000105"
}|]
frankfurtCoord :: Coordinate
frankfurtCoord = Coordinate 50.107149 8.663785
frankfurtHbf :: StopLocation
frankfurtHbf = StopLocation (StopId "008000105") "Frankfurt(Main)Hbf" frankfurtCoord
refURI :: Text
refURI = "http://open-api.bahn.de/bin/rest.exe/v1.0/journeyDetail?ref=227691%2F79221%2F324378%2F86292%2F80%3Fdate%3D2016-03-22%26station_evaId%3D8000105%26station_type%3Darr%26authKey%3DDBhackFrankfurt0316%26lang%3Dde%26format%3Djson%26"
refURIDetails :: RefDetails
refURIDetails = RefDetails (parseApiDate "2016-03-22") (Ref "227691/79221/324378/86292/80") (EvaId "8000105") "arr"
|
muhbaasu/haskell-db-fahrplan-api
|
tests/Unit.hs
|
mit
| 3,083
| 0
| 10
| 519
| 554
| 317
| 237
| 51
| 1
|
module Main where
double x = x + x
main = putStrLn "Hello, World !!\n"
|
skywind3000/language
|
haskell/double.hs
|
mit
| 88
| 0
| 5
| 32
| 24
| 13
| 11
| 3
| 1
|
module GHCJS.DOM.SVGUseElement (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/SVGUseElement.hs
|
mit
| 43
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
module C where
import Unbound.Generics.LocallyNameless hiding (prec,empty,Data,Refl,Val)
import Unbound.Generics.LocallyNameless.Internal.Fold (toListOf)
import Unbound.Generics.LocallyNameless.Alpha
import Control.Monad
import Control.Monad.Except
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Util
import Text.PrettyPrint as PP
------------------
-- should move to Unbound.LocallyNameless.Ops
-- patUnbind :: (Alpha p, Alpha t) => p -> Bind p t -> t
-- patUnbind p (B _ t) = openT p t
------------------
-- System C
type TyName = Name Ty
type TmName = Name Tm
type ValName = Name Val
data Ty = TyVar TyName
| TyInt
| All (Bind [TyName] [Ty])
| TyProd [Ty]
| Exists (Bind TyName Ty) -- new
deriving (Show, Generic)
data Val = TmInt Int
| TmVar ValName
| Fix (Bind (ValName, [TyName]) (Bind [(ValName, Embed Ty)] Tm))
| TmProd [AnnVal]
| TApp AnnVal Ty -- new
| Pack Ty AnnVal -- new
deriving (Show, Generic)
data AnnVal = Ann Val Ty
deriving (Show, Generic)
data Decl =
DeclVar ValName (Embed AnnVal)
| DeclPrj Int ValName (Embed AnnVal)
| DeclPrim ValName (Embed (AnnVal, Prim, AnnVal))
| DeclUnpack TyName ValName (Embed AnnVal) -- new
deriving (Show, Generic)
data Tm = Let (Bind Decl Tm)
| App AnnVal [AnnVal] -- updated
| TmIf0 AnnVal Tm Tm
| Halt Ty AnnVal
deriving (Show, Generic)
-- For H
newtype Heap = Heap (Map ValName AnnVal)
deriving (Show, Semigroup, Monoid)
------------------------------------------------------
instance Alpha Ty
instance Alpha Val
instance Alpha AnnVal
instance Alpha Decl
instance Alpha Tm
instance Subst Ty Ty where
isvar (TyVar x) = Just (SubstName x)
isvar _ = Nothing
instance Subst Ty Prim
instance Subst Ty Tm
instance Subst Ty AnnVal
instance Subst Ty Decl
instance Subst Ty Val
instance Subst Val Prim
instance Subst Val Ty
instance Subst Val AnnVal
instance Subst Val Decl
instance Subst Val Tm
instance Subst Val Val where
isvar (TmVar x) = Just (SubstName x)
isvar _ = Nothing
------------------------------------------------------
-- Helper functions
------------------------------------------------------
mkTyApp :: (MonadError String m, Fresh m) => AnnVal -> [Ty] -> m AnnVal
mkTyApp av [] = return av
mkTyApp av@(Ann _ (All bnd)) (ty:tys) = do
(as, atys) <- unbind bnd
case as of
a:as' ->
let atys' = subst a ty atys in
mkTyApp (Ann (TApp av ty) (All (bind as' atys'))) tys
_ -> throwError "type error: not a polymorphic All"
mkTyApp (Ann _ ty) _ = throwError "type error: not an All"
mkProd :: [AnnVal] -> AnnVal
mkProd vs = Ann (TmProd vs) (TyProd tys) where
tys = map (\(Ann _ ty) -> ty) vs
-----------------------------------------------------------------
-- Free variables, with types
-----------------------------------------------------------------
x :: Name Tm
y :: Name Tm
z :: Name Tm
(x,y,z) = (string2Name "x", string2Name "y", string2Name "z")
a :: Name Ty
b :: Name Ty
c :: Name Ty
(a,b,c) = (string2Name "a", string2Name "b", string2Name "c")
-----------------------------------------------------------------
-- Typechecker
-----------------------------------------------------------------
type Delta = [ TyName ]
type Gamma = [ (ValName, Ty) ]
data Ctx = Ctx { getDelta :: Delta , getGamma :: Gamma }
emptyCtx = Ctx { getDelta = [], getGamma = [] }
checkTyVar :: Ctx -> TyName -> M ()
checkTyVar g v = do
if v `List.elem` getDelta g then
return ()
else
throwError $ "Type variable not found " ++ show v
lookupTmVar :: Ctx -> ValName -> M Ty
lookupTmVar g v = do
case lookup v (getGamma g) of
Just s -> return s
Nothing -> throwError $ "Term variable notFound " ++ show v
extendTy :: TyName -> Ctx -> Ctx
extendTy n ctx = ctx { getDelta = n : getDelta ctx }
extendTys :: [TyName] -> Ctx -> Ctx
extendTys ns ctx = foldr extendTy ctx ns
extendTm :: ValName -> Ty -> Ctx -> Ctx
extendTm n ty ctx = ctx { getGamma = (n, ty) : getGamma ctx }
extendTms :: [ValName] -> [Ty] -> Ctx -> Ctx
extendTms [] [] ctx = ctx
extendTms (n:ns) (ty:tys) ctx = extendTm n ty (extendTms ns tys ctx)
extendDecl :: Decl -> Ctx -> Ctx
extendDecl (DeclVar x (Embed (Ann _ ty))) = extendTm x ty
extendDecl (DeclPrj i x (Embed (Ann _ (TyProd tys)))) = extendTm x (tys !! i)
extendDecl (DeclPrim x _) = extendTm x TyInt
extendDecl (DeclUnpack b x (Embed (Ann _ (Exists bnd)))) =
extendTy b . extendTm x (patUnbind b bnd)
tcty :: Ctx -> Ty -> M ()
tcty g (TyVar x) =
checkTyVar g x
tcty g (All b) = do
(xs, tys) <- unbind b
let g' = extendTys xs g -- XX
mapM_ (tcty g') tys
tcty g TyInt = return ()
tcty g (TyProd tys) = do
mapM_ (tcty g) tys
tcty g (Exists b) = do
(a, ty) <- unbind b
tcty (extendTy a g) ty
typecheckVal :: Ctx -> Val -> M Ty
typecheckVal g (TmVar x) = lookupTmVar g x
typecheckVal g (Fix bnd) = do
((f, as), bnd2) <- unbind bnd
(xtys, e) <- unbind bnd2
let g' = extendTys as g
let (xs,tys) = unzip $ map (\(x,Embed y) -> (x,y)) xtys
mapM_ (tcty g') tys
let fty = All (bind as tys)
typecheck (extendTm f fty (extendTms xs tys g')) e
return fty
typecheckVal g (TmProd es) = do
tys <- mapM (typecheckAnnVal g) es
return $ TyProd tys
typecheckVal g (TmInt i) = return TyInt
typecheckVal g (TApp av ty) = do
tcty g ty
ty' <- typecheckAnnVal g av
case ty' of
All bnd -> do
(as, bs) <- unbind bnd
case as of
[] -> throwError "can't instantiate non-polymorphic function"
(a:as') -> do
let bs' = subst a ty bs
return (All (bind as' bs'))
typecheckAnnVal g (Ann (Pack ty1 av) ty) = do
case ty of
Exists bnd -> do
(a, ty2) <- unbind bnd
tcty g ty1
ty' <- typecheckAnnVal g av
if not (ty' `aeq` subst a ty1 ty2)
then throwError "type error"
else return ty
typecheckAnnVal g (Ann v ty) = do
tcty g ty
ty' <- typecheckVal g v
if ty `aeq` ty'
then return ty
else throwError $ "wrong annotation on: " ++ pp v ++ "\nInferred: " ++ pp ty ++ "\nAnnotated: " ++ pp ty'
typecheckDecl g (DeclVar x (Embed av)) = do
ty <- typecheckAnnVal g av
return $ extendTm x ty g
typecheckDecl g (DeclPrj i x (Embed av)) = do
ty <- typecheckAnnVal g av
case ty of
TyProd tys | i < length tys ->
return $ extendTm x (tys !! i) g
_ -> throwError "cannot project"
typecheckDecl g (DeclPrim x (Embed (av1, _, av2))) = do
ty1 <- typecheckAnnVal g av1
ty2 <- typecheckAnnVal g av2
case (ty1 , ty2) of
(TyInt, TyInt) -> return $ extendTm x TyInt g
_ -> throwError "TypeError"
typecheckDecl g (DeclUnpack a x (Embed av)) = do
tya <- typecheckAnnVal g av
case tya of
Exists bnd -> do
let ty = patUnbind a bnd
return $ extendTy a (extendTm x ty g)
_ -> throwError "TypeError"
typecheck :: Ctx -> Tm -> M ()
typecheck g (Let bnd) = do
(d,e) <- unbind bnd
g' <- typecheckDecl g d
typecheck g' e
typecheck g (App av es) = do
ty <- typecheckAnnVal g av
case ty of
(All bnd) -> do
(as, argtys) <- unbind bnd
argtys' <- mapM (typecheckAnnVal g) es
if not (null as)
then throwError "must use type application"
else
if length argtys /= length argtys'
then throwError "incorrect args"
else unless (and (zipWith aeq argtys argtys')) $
throwError "arg mismatch"
typecheck g (TmIf0 av e1 e2) = do
ty0 <- typecheckAnnVal g av
typecheck g e1
typecheck g e2
if ty0 `aeq` TyInt then
return ()
else
throwError "TypeError"
typecheck g (Halt ty av) = do
ty' <- typecheckAnnVal g av
unless (ty `aeq` ty') $
throwError "type error"
-----------------------------------------------------------------
heapvalcheck g ann@(Ann (Fix bnd) _) =
typecheckAnnVal g ann
heapvalcheck g (Ann _ _) =
throwError "type error: only code in heap"
hoistcheck (tm, Heap m) = do
let g' =
Map.foldlWithKey (\ctx x (Ann _ ty) -> extendTm x ty ctx)
emptyCtx m
mapM_ (heapvalcheck g') (Map.elems m)
typecheck g' tm
-----------------------------------------------------------------
-- Small-step semantics
-----------------------------------------------------------------
mkSubst :: Decl -> M (Tm -> Tm)
mkSubst (DeclVar x (Embed (Ann v _))) = return $ subst x v
mkSubst (DeclPrj i x (Embed (Ann (TmProd avs) _))) | i < length avs =
let Ann vi _ = avs !! i in return $ subst x vi
mkSubst (DeclPrim x (Embed (Ann (TmInt i1) _, p, Ann (TmInt i2) _))) =
let v = TmInt (evalPrim p i1 i2) in
return $ subst x v
mkSubst (DeclUnpack a x (Embed (Ann (Pack ty (Ann u _)) _))) =
return $ subst a ty . subst x u
mkSubst (DeclPrj i x (Embed av)) =
throwError $ "invalid prj " ++ pp i ++ ": " ++ pp av
mkSubst (DeclUnpack a x (Embed av)) =
throwError $ "invalid unpack:" ++ pp av
step :: Tm -> M Tm
step (Let bnd) = do
(d, e) <- unbind bnd
ss <- mkSubst d
return $ ss e
step (App (Ann e1@(Fix bnd) _) avs) = do
((f, as), bnd2) <- unbind bnd
(xtys, e) <- unbind bnd2
let us = map (\(Ann u _) -> u) avs
let xs = map fst xtys
return $ substs ((f,e1):zip xs us) e
step (TmIf0 (Ann (TmInt i) _) e1 e2) = if i==0 then return e1 else return e2
step _ = throwError "cannot step"
evaluate :: Tm -> M Val
evaluate (Halt _ (Ann v _)) = return v
evaluate e = do
e' <- step e
evaluate e'
-----------------------------------------------------------------
-- Pretty-printer
-----------------------------------------------------------------
instance Display Ty where
display (TyVar n) = display n
display TyInt = return $ text "Int"
display (All bnd) = lunbind bnd $ \ (as,tys) -> do
da <- displayList as
dt <- displayList tys
if null as
then return $ parens dt <+> text "-> void"
else prefix "forall" (brackets da PP.<> text "." <+> parens dt <+> text "-> void")
display (TyProd tys) = displayTuple tys
display (Exists bnd) = lunbind bnd $ \ (a,ty) -> do
da <- display a
dt <- display ty
prefix "exists" (da PP.<> text "." <+> dt)
instance Display (ValName,Embed Ty) where
display (n, Embed ty) = do
dn <- display n
dt <- display ty
return $ dn PP.<> colon PP.<> dt
instance Display Val where
display (TmInt i) = return $ int i
display (TmVar n) = display n
display (Fix bnd) = lunbind bnd $ \((f, as), bnd2) -> lunbind bnd2 $ \(xtys, e) -> do
df <- display f
ds <- displayList as
dargs <- displayList xtys
de <- withPrec (precedence "fix") $ display e
let tyArgs = if null as then empty else brackets ds
let tmArgs = if null xtys then empty else parens dargs
if f `elem` (toListOf fv e :: [ValName])
then prefix "fix" (df <+> tyArgs PP.<> tmArgs PP.<> text "." $$ de)
else prefix "\\" (tyArgs PP.<> tmArgs PP.<> text "." $$ de)
display (TmProd es) = displayTuple es
display (Pack ty e) = do
dty <- display ty
de <- display e
prefix "pack" (brackets (dty PP.<> comma PP.<> de))
display (TApp av ty) = do
dv <- display av
dt <- display ty
return $ dv <+> brackets dt
instance Display AnnVal where
{- display (Ann av ty) = do
da <- display av
dt <- display ty
return $ parens (da PP.<> text ":" PP.<> dt) -}
display (Ann av _) = display av
instance Display Tm where
display (App av args) = do
da <- display av
dargs <- displayList args
let tmArgs = if null args then empty else space PP.<> parens dargs
return $ da PP.<> tmArgs
display (Halt ty v) = do
dv <- display v
--dt <- display ty
return $ text "halt" <+> dv -- <+> text ":" <+> dt
display (Let bnd) = lunbind bnd $ \(d, e) -> do
dd <- display d
de <- display e
return (text "let" <+> dd <+> text "in" $$ de)
display (TmIf0 e0 e1 e2) = do
d0 <- display e0
d1 <- display e1
d2 <- display e2
prefix "if0" $ parens $ sep [d0 PP.<> comma , d1 PP.<> comma, d2]
instance Display Decl where
display (DeclVar x (Embed av)) = do
dx <- display x
dv <- display av
return $ dx <+> text "=" <+> dv
display (DeclPrj i x (Embed av)) = do
dx <- display x
dv <- display av
return $ dx <+> text "=" <+> text "pi" PP.<> int i <+> dv
display (DeclPrim x (Embed (e1, p, e2))) = do
dx <- display x
let str = show p
d1 <- display e1
d2 <- display e2
return $ dx <+> text "=" <+> d1 <+> text str <+> d2
display (DeclUnpack a x (Embed av)) = do
da <- display a
dx <- display x
dav <- display av
return $ brackets (da PP.<> comma PP.<> dx) <+> text "=" <+> dav
--------------------------------------------
-- C to H (actually C) Hoisting
--------------------------------------------
displayCode (Ann v ty) = display v
instance Display Heap where
display (Heap m) = do
fcns <- mapM (\(d,v) -> do
dn <- display d
dv <- displayCode v
return (dn, dv)) (Map.toList m)
return $ hang (text "letrec") 2 $
vcat [ n <+> text "=" <+> dv | (n,dv) <- fcns ]
instance Display (Tm, Heap) where
display (tm,h) = do
dh <- display h
dt <- display tm
return $ dh $$ text "in" <+> dt
|
sweirich/tal
|
src/C.hs
|
mit
| 13,598
| 0
| 21
| 3,685
| 5,654
| 2,788
| 2,866
| -1
| -1
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
import Data.Aeson
import Data.Decimal
import Data.Word8
parse precision (Number n) = return $ Data.Decimal.realFracToDecimal precision n
parse precision x = fail $ "Expectig a number in the JSON to parse to a Decimal. Received " ++ (show x)
newtype Decimal_1 = Decimal_1 Data.Decimal.Decimal
newtype Decimal_2 = Decimal_2 Data.Decimal.Decimal
instance ToJSON Decimal_1 where
toJSON (Decimal_1 d) = toJSON $ show d
instance FromJSON Decimal_1 where
parseJSON = Decimal_1 $ parse $ fromInteger 1
instance FromJSON Decimal_2 where
parseJSON = Decimal_2 $ parse $ fromInteger 2
main = print (decode "4" :: Maybe Decimal_1)
|
michalc/haskell-experiments
|
json.hs
|
mit
| 744
| 0
| 8
| 121
| 190
| 100
| 90
| 17
| 1
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
Module : Orville.PostgreSQL.Expr.Name.IndexName
Copyright : Flipstone Technology Partners 2021
License : MIT
-}
module Orville.PostgreSQL.Internal.Expr.Name.IndexName
( IndexName,
indexName,
)
where
import Orville.PostgreSQL.Internal.Expr.Name.Identifier (Identifier, IdentifierExpression, identifier)
import qualified Orville.PostgreSQL.Internal.RawSql as RawSql
newtype IndexName
= IndexName Identifier
deriving (RawSql.SqlExpression, IdentifierExpression)
indexName :: String -> IndexName
indexName = IndexName . identifier
|
flipstone/orville
|
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/Expr/Name/IndexName.hs
|
mit
| 597
| 0
| 7
| 75
| 90
| 60
| 30
| 11
| 1
|
merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge xs@(x:xt) ys@(y:yt)
| x <= y = x : merge xt ys
| otherwise = y : merge xs yt
mergesort :: Ord a => [a] -> [a]
mergesort [] = []
mergesort [x] = [x]
mergesort list =
merge left right
where
half = div (length list) 2
left = mergesort (take half list)
right = mergesort (drop half list)
|
dzeban/cs
|
sorting/mergesort.hs
|
mit
| 454
| 0
| 9
| 176
| 232
| 118
| 114
| 14
| 1
|
module Lesson05 where
-- Today's lesson is all about *style*. I bet you're tired of running these
-- little apps in the bottom of the IDE. Wouldn't it be cool to have a fully
-- powered website instead? Also, the display of a hand is pretty verbose.
-- Let's make our hand display prettier.
import Helper
import Helper.Multiplayer -- New import- it's a helper module for this tutorial.
import System.Random.Shuffle
import Data.List -- also a new import, needed for intercalate below
import Safe -- needed for readMay
-- Alright, prettier cards first. Instead of saying "Card Heart Jack", let's say
-- "JH." And so and and so forth. This is just a bunch of repetitive code really:
prettySuit Club = "C"
prettySuit Diamond = "D"
prettySuit Heart = "H"
prettySuit Spade = "S"
prettyRank Two = "2"
prettyRank Three = "3"
prettyRank Four = "4"
prettyRank Five = "5"
prettyRank Six = "6"
prettyRank Seven = "7"
prettyRank Eight = "8"
prettyRank Nine = "9"
prettyRank Ten = "10"
prettyRank Jack = "J"
prettyRank Queen = "Q"
prettyRank King = "K"
prettyRank Ace = "A"
prettyCard (Card suit rank) = prettyRank rank ++ prettySuit suit
-- This part is interesting. A hand is a list of cards. We want to do two things
-- to this list:
--
-- 1. Convert each card to its pretty form using prettyCard.
--
-- 2. Combine the five individual Strings together into one big String, with commas
-- between each one.
--
-- The function map is perfect for handling the first point, and the scarily-named
-- function intercalate does the second.
prettyHand = intercalate ", " . map prettyCard
-- And now to make this web-based. The Helper.Multiplayer module is something
-- I wrote just for this tutorial. It makes it easy to have multiplayer, text
-- based web games. For now, we'll be sticking to single player, but we'll come
-- back to more impressive things later.
--
-- Let's take our code from the previous tutorial and tweak it to:
--
-- 1. Use our prettyHand function above.
--
-- 2. Instead of putStrLn, getLine, and readLn, use the special functions
-- askPlayer, tellPlayer, and getPlayers, which Helper.Multiplayer provides.
--
-- We're also going to make our code a little bit more robust, by checking for
-- invalid input. We'll start that off with a better way of getting bets.
getWager chips = do
[player] <- getPlayers
wagerString <- askPlayer player "Please enter your wager"
-- We'll use readMay to try to read the wager string as an
-- integer.
case readMay wagerString of
Nothing -> do
tellPlayer player "Your wager must be a valid integer."
getWager chips
Just wager
| wager < 0 -> do
tellPlayer player "Your wager must not be negative."
getWager chips
| wager > chips -> do
tellPlayer player "You cannot bet more than your total chips."
getWager chips
| otherwise -> do
tellPlayer player ("You have wagered: " ++ show wager)
return wager
playHand chips = do
[player] <- getPlayers
shuffled <- shuffleM deck
let (hand, rest) = splitAt 5 shuffled
dealer = take 5 rest
tellPlayer player ("Your hand is: " ++ prettyHand hand)
bet <- getWager chips
tellPlayer player ("The dealer has: " ++ prettyHand dealer)
answer <- askPlayer player "Did you win? (y/n)"
if answer == "y"
then return bet -- you won
else return (- bet) -- you lost
playGame chips = do
[player] <- getPlayers
tellPlayer player ("Your current chip count: " ++ show chips)
chipChange <- playHand chips
let newChips = chips + chipChange
if newChips > 0
-- We have some chips left, so let's play the game again based on the
-- new chip count.
then playGame newChips
else tellPlayer player "You're out of chips. Goodbye!"
-- And now our main function needs to use the special playMultiplayerGame provided
-- by Helper.Multiplayer. We need to tell it a name for the game and how many players
-- per game.
main = playMultiplayerGame "five card stud against the house" 1 (playGame 10)
{-
Exercises:
Behind the scenes:
FIXME: function composition, higher order functions, case statements, guards
-}
|
snoyberg/haskell-impatient-poker-players
|
src/Lesson05.hs
|
mit
| 4,275
| 0
| 16
| 1,013
| 642
| 324
| 318
| 63
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-retentionperiod.html
module Stratosphere.ResourceProperties.IoTAnalyticsDatastoreRetentionPeriod where
import Stratosphere.ResourceImports
-- | Full data type definition for IoTAnalyticsDatastoreRetentionPeriod. See
-- 'ioTAnalyticsDatastoreRetentionPeriod' for a more convenient constructor.
data IoTAnalyticsDatastoreRetentionPeriod =
IoTAnalyticsDatastoreRetentionPeriod
{ _ioTAnalyticsDatastoreRetentionPeriodNumberOfDays :: Maybe (Val Integer)
, _ioTAnalyticsDatastoreRetentionPeriodUnlimited :: Maybe (Val Bool)
} deriving (Show, Eq)
instance ToJSON IoTAnalyticsDatastoreRetentionPeriod where
toJSON IoTAnalyticsDatastoreRetentionPeriod{..} =
object $
catMaybes
[ fmap (("NumberOfDays",) . toJSON) _ioTAnalyticsDatastoreRetentionPeriodNumberOfDays
, fmap (("Unlimited",) . toJSON) _ioTAnalyticsDatastoreRetentionPeriodUnlimited
]
-- | Constructor for 'IoTAnalyticsDatastoreRetentionPeriod' containing
-- required fields as arguments.
ioTAnalyticsDatastoreRetentionPeriod
:: IoTAnalyticsDatastoreRetentionPeriod
ioTAnalyticsDatastoreRetentionPeriod =
IoTAnalyticsDatastoreRetentionPeriod
{ _ioTAnalyticsDatastoreRetentionPeriodNumberOfDays = Nothing
, _ioTAnalyticsDatastoreRetentionPeriodUnlimited = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-retentionperiod.html#cfn-iotanalytics-datastore-retentionperiod-numberofdays
itadstrpNumberOfDays :: Lens' IoTAnalyticsDatastoreRetentionPeriod (Maybe (Val Integer))
itadstrpNumberOfDays = lens _ioTAnalyticsDatastoreRetentionPeriodNumberOfDays (\s a -> s { _ioTAnalyticsDatastoreRetentionPeriodNumberOfDays = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-datastore-retentionperiod.html#cfn-iotanalytics-datastore-retentionperiod-unlimited
itadstrpUnlimited :: Lens' IoTAnalyticsDatastoreRetentionPeriod (Maybe (Val Bool))
itadstrpUnlimited = lens _ioTAnalyticsDatastoreRetentionPeriodUnlimited (\s a -> s { _ioTAnalyticsDatastoreRetentionPeriodUnlimited = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/IoTAnalyticsDatastoreRetentionPeriod.hs
|
mit
| 2,318
| 0
| 12
| 205
| 264
| 151
| 113
| 27
| 1
|
module Command.Transfer (transferCommand) where
import Database.HDBC
import Database.HDBC.Sqlite3
import Util
transferCommand :: [String] -> String -> IO ()
transferCommand (amountString:envelope:[]) flags = do
conn <- getDbConnection
let positiveAmount = readInteger100 amountString
let amount = if 'r' `elem` flags then -1 * positiveAmount else positiveAmount
currentAmountResult <- quickQuery' conn "SELECT amount FROM envelope WHERE name = ?" [toSql envelope]
let currentAmount = fromSql . head . head $ currentAmountResult
let totalAmount = currentAmount + amount
run conn "UPDATE envelope SET amount = ? WHERE name = ?" [toSql totalAmount, toSql envelope]
commit conn
disconnect conn
transferCommand _ _ = putStrLn "Command takes 2 arguments"
|
jpotterm/manila-hs
|
src/Command/Transfer.hs
|
cc0-1.0
| 793
| 0
| 12
| 147
| 218
| 108
| 110
| 16
| 2
|
module Configure where
import Linear.V2
-- one unit is equal to 10 meters
data Ball = Ball {name :: String, mass :: Double, semidiameter :: Double, speed :: V2 Double, location :: V2 Double, step :: V2 Double} deriving (Eq, Show, Read)
radius1 :: Double
radius1 = 0.05
radius2 :: Double
radius2 = 0.05
mass1 :: Double
mass1 = 1.0
mass2 :: Double
mass2 = 1.0
{-
-- ^Y
-- <- Y |
-- ^ <-
-- \ R R
pInit1 :: V2 Double
pInit1 = V2 0 0
vInit1 :: V2 Double
vInit1 = V2 (-0.1) 0
pInit2 :: V2 Double
pInit2 = V2 (-0.05) (-(sqrt 3 * 0.05 + 0.001)/2)
vInit2 :: V2 Double
vInit2 = V2 0 0.1
-}
{-
-- ^R
-- <- R |
-- ^ <-
-- \ Y Y
pInit2 :: V2 Double
pInit2 = V2 0 0
vInit2 :: V2 Double
vInit2 = V2 (-0.1) 0
pInit1 :: V2 Double
pInit1 = V2 (-0.05) (-(sqrt 3 * 0.05 + 0.001)/2)
vInit1 :: V2 Double
vInit1 = V2 0 0.1
-}
{-
-- Y
-- <- Y ->
-- ^ |
-- | R Rv
pInit2 :: V2 Double
pInit2 = V2 0 0
vInit2 :: V2 Double
vInit2 = V2 0.1 0
pInit1 :: V2 Double
pInit1 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit1 :: V2 Double
vInit1 = V2 0 (-0.1)
-}
{-
-- | R R
-- v ->
-- -> |
-- Y Yv
pInit1 :: V2 Double
pInit1 = V2 0 0
vInit1 :: V2 Double
vInit1 = V2 0.1 0
pInit2 :: V2 Double
pInit2 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit2 :: V2 Double
vInit2 = V2 0 (-0.1)
-}
{-
-- / Y
-- V
-- -> <- \ Y
-- R R v
pInit2 :: V2 Double
pInit2 = V2 0 0
vInit2 :: V2 Double
vInit2 = V2 0.1 0
pInit1 :: V2 Double
pInit1 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit1 :: V2 Double
vInit1 = V2 (-0.1) (-0.05)
-}
{-
-- / R
-- V
-- -> <- \ R
-- Y Y v
pInit1 :: V2 Double
pInit1 = V2 0 0
vInit1 :: V2 Double
vInit1 = V2 0.1 0
pInit2 :: V2 Double
pInit2 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit2 :: V2 Double
vInit2 = V2 (-0.1) (-0.05)
-}
{-
-- / Y Y
-- V ->
-- -> /
-- R v R
pInit2 :: V2 Double
pInit2 = V2 0 0
vInit2 :: V2 Double
vInit2 = V2 0.1 0
pInit1 :: V2 Double
pInit1 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit1 :: V2 Double
vInit1 = V2 (-0.1) (-0.1)
-}
{-
-- / R R
-- V ->
-- -> /
-- Y v Y
pInit1 :: V2 Double
pInit1 = V2 0 0
vInit1 :: V2 Double
vInit1 = V2 0.1 0
pInit2 :: V2 Double
pInit2 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit2 :: V2 Double
vInit2 = V2 (-0.1) (-0.1)
-}
{-
-- / Y
-- V
-- -> <- \ Y
-- R R v
pInit2 :: V2 Double
pInit2 = V2 0 0
vInit2 :: V2 Double
vInit2 = V2 0.1 0
pInit1 :: V2 Double
pInit1 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit1 :: V2 Double
vInit1 = V2 (-0.05) (-0.1)
-}
{-
-- / R
-- V
-- -> <- \ R
-- Y Y v
pInit1 :: V2 Double
pInit1 = V2 0 0
vInit1 :: V2 Double
vInit1 = V2 0.1 0
pInit2 :: V2 Double
pInit2 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit2 :: V2 Double
vInit2 = V2 (-0.05) (-0.1)
-}
{-
-- Y ^ Y
-- <- /
-- -> /
-- R v R
pInit2 :: V2 Double
pInit2 = V2 0 0
vInit2 :: V2 Double
vInit2 = V2 0.1 0
pInit1 :: V2 Double
pInit1 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit1 :: V2 Double
vInit1 = V2 (-0.1) 0
-}
{-
-- R ^ R
-- <- /
-- -> /
-- Y v Y
pInit1 :: V2 Double
pInit1 = V2 0 0
vInit1 :: V2 Double
vInit1 = V2 0.1 0
pInit2 :: V2 Double
pInit2 = V2 0.05 ((sqrt 3 * 0.05 + 0.001)/2)
vInit2 :: V2 Double
vInit2 = V2 (-0.1) 0
-}
{-
pInit1 :: V2 Double
pInit1 = V2 0 0.095
vInit1 :: V2 Double
vInit1 = V2 (-0.6) 0
pInit2 :: V2 Double
pInit2 = V2 (-0.75) 0
vInit2 :: V2 Double
vInit2 = V2 0.2 0
-}
{-
pInit1 :: V2 Double
pInit1 = V2 0.5 0
vInit1 :: V2 Double
vInit1 = V2 (-0.3) 0
pInit2 :: V2 Double
pInit2 = V2 0.75 0
vInit2 :: V2 Double
vInit2 = V2 (-0.4) 0
-}
{-
pInit1 :: V2 Double
pInit1 = V2 (-0.75) 0
vInit1 :: V2 Double
vInit1 = V2 0.2 0
pInit2 :: V2 Double
pInit2 = V2 0.75 0
vInit2 :: V2 Double
vInit2 = V2 (-0.1) 0
-}
pInit1 :: V2 Double
pInit1 = V2 0.5 0.5
vInit1 :: V2 Double
vInit1 = V2 0.2 (-0.3)
pInit2 :: V2 Double
pInit2 = V2 (-0.5) 0.75
vInit2 :: V2 Double
vInit2 = V2 0.1 (-0.4)
data BallC = BallC {ballC :: Bool, name1 :: String, nextV1 :: V2 Double , nextP1 :: V2 Double, name2 :: String, nextV2 :: V2 Double, nextP2 :: V2 Double} deriving (Eq, Show, Read)
data WallC = WallC {hittingV1 :: Bool, hittingV2 :: Bool, hittingH1 :: Bool, hittingH2 :: Bool} deriving (Eq, Show, Read)
data NextS = NextS {colliding :: BallC, ball1 :: Ball, ball2 :: Ball, hitting :: WallC} deriving (Eq, Show, Read)
wallV :: Double
wallV = 0.9
wallH :: Double
wallH = 0.9
|
bitterharvest/BilliardBalls
|
src/Configure.hs
|
gpl-2.0
| 4,813
| 0
| 9
| 1,619
| 415
| 246
| 169
| 26
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Sandbox
-- Copyright : 2007-2014 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL
--
-- Maintainer : Juergen Nicklisch-Franken <info@leksah.org>
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Sandbox (
sandboxInit
, sandboxInitShared
, sandboxDelete
, sandboxAddSource
, sandboxDeleteSource
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (when, void)
import Control.Monad.Trans.Class (lift)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Reader (ask)
import System.Exit (ExitCode(..))
import System.FilePath (dropFileName)
import qualified Data.Conduit as C (Sink, ZipSink(..), getZipSink)
import qualified Data.Conduit.List as CL (fold)
import IDE.Utils.Tool (ToolOutput(..))
import IDE.Utils.GUIUtils (showDialogOptions, __, chooseDir)
import IDE.Core.State
(reflectIDE, reifyIDE, PackageAction, readIDE, prefs,
ipdPackageDir, getMainWindow, Workspace, wsFile, liftIDE,
IDEPackage, IDEM, runPackage, LogLaunch)
import IDE.Pane.Log (getDefaultLogLaunch)
import IDE.Utils.ExternalTool (runExternalTool')
import IDE.LogRef (logOutput)
import IDE.Pane.PackageEditor (choosePackageFile)
import IDE.Workspaces (workspaceTryQuiet)
import IDE.Package (refreshPackage)
import Data.Monoid ((<>))
import qualified Data.Text as T (pack)
import IDE.Core.Types (runWorkspace, IDE(..), PackageM)
import System.Directory (doesFileExist)
import System.FilePath.Windows ((</>))
import GI.Gtk.Enums (MessageType(..))
import GI.Gtk.Objects.Window (Window(..))
-- | Get the last item
sinkLast = CL.fold (\_ a -> Just a) Nothing
sandboxTry :: PackageAction -> PackageAction
sandboxTry action = do
sandbox <- hasSandbox
pkg <- ask
if sandbox then action else do
ideRef <- lift $ lift ask
Just ws <- readIDE workspace
let packageToIO = (`reflectIDE` ideRef) .
(`runWorkspace` ws) .
(`runPackage` pkg)
liftIO $ showDialogOptions
"This action requires a sandboxed package database. Would you like to initialize a sandbox for this package?"
MessageTypeQuestion
[ ("Initialize New Sandbox", packageToIO $ sandboxInit >> action)
, ("Use Existing Sandbox", packageToIO $ sandboxInitShared >> action)
, ("Cancel", return ())]
(Just 0)
hasSandbox :: PackageM Bool
hasSandbox = do
pkg <- ask
liftIO $ doesFileExist (ipdPackageDir pkg </> "cabal.sandbox.config")
logSandbox :: IDEPackage -> LogLaunch -> C.Sink ToolOutput IDEM ()
logSandbox package logLaunch = do
let log = logOutput logLaunch
mbLastOutput <- C.getZipSink $ const <$> C.ZipSink sinkLast <*> C.ZipSink log
when (mbLastOutput == Just (ToolExit ExitSuccess)) .
lift $ workspaceTryQuiet (runPackage (void $ refreshPackage log) package)
sandboxInit :: PackageAction
sandboxInit = do
package <- ask
logLaunch <- getDefaultLogLaunch
runExternalTool' (__ "Sandbox Init")
"cabal" ["sandbox", "init"]
(ipdPackageDir package) (logSandbox package logLaunch)
chooseSandboxDir :: Window -> Maybe FilePath -> IO (Maybe FilePath)
chooseSandboxDir window = chooseDir window (__ "Select sandbox folder")
sandboxInitShared :: PackageAction
sandboxInitShared = do
package <- ask
ws <- lift ask
window <- liftIDE getMainWindow
mbDir <- liftIO $ chooseSandboxDir window Nothing
case mbDir of
Nothing -> return ()
Just dir -> do
logLaunch <- getDefaultLogLaunch
runExternalTool' (__ "Sandbox Init")
"cabal" ["sandbox", "init", "--sandbox=" <> T.pack dir]
(ipdPackageDir package) (logSandbox package logLaunch)
sandboxDelete :: PackageAction
sandboxDelete = sandboxTry $ do
package <- ask
logLaunch <- getDefaultLogLaunch
runExternalTool' (__ "Sandbox Delete")
"cabal" ["sandbox", "delete"]
(ipdPackageDir package) (logSandbox package logLaunch)
chooseSandboxSourceDir :: Window -> Maybe FilePath -> IO (Maybe FilePath)
chooseSandboxSourceDir window = chooseDir window (__ "Select source folder")
sandboxAddSource :: Bool -> PackageAction
sandboxAddSource snapshot = sandboxTry $ do
package <- ask
ws <- lift ask
let path = dropFileName (wsFile ws)
window <- liftIDE getMainWindow
mbFilePath <- liftIO $ chooseSandboxSourceDir window (Just path)
case mbFilePath of
Nothing -> return ()
Just fp -> do
logLaunch <- getDefaultLogLaunch
runExternalTool' (__ "Sandbox Add Source")
"cabal" (["sandbox", "add-source", T.pack fp] ++ ["--snapshot" | snapshot])
(ipdPackageDir package) (logSandbox package logLaunch)
sandboxDeleteSource :: FilePath -> PackageAction
sandboxDeleteSource dir = sandboxTry $ do
package <- ask
logLaunch <- getDefaultLogLaunch
runExternalTool' (__ "Sandbox Delete Source")
"cabal" ["sandbox", "delete-source", T.pack dir]
(ipdPackageDir package) (logSandbox package logLaunch)
|
JPMoresmau/leksah
|
src/IDE/Sandbox.hs
|
gpl-2.0
| 5,318
| 0
| 18
| 1,097
| 1,403
| 761
| 642
| 115
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Vim.TestExCommandParsers (tests) where
import Control.Applicative
import Data.List (inits)
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Test.QuickCheck
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Ex
import qualified Yi.Keymap.Vim.Ex.Commands.Buffer as Buffer
import qualified Yi.Keymap.Vim.Ex.Commands.BufferDelete as BufferDelete
import qualified Yi.Keymap.Vim.Ex.Commands.Delete as Delete
import qualified Yi.Keymap.Vim.Ex.Commands.Registers as Registers
import qualified Yi.Keymap.Vim.Ex.Commands.Nohl as Nohl
data CommandParser = CommandParser
{ cpDescription :: String
, cpParser :: String -> Maybe ExCommand
, cpNames :: [String]
, cpAcceptsBang :: Bool
, cpAcceptsCount :: Bool
, cpArgs :: Gen String
}
addingSpace :: Gen String -> Gen String
addingSpace = fmap (" " <>)
numberString :: Gen String
numberString = (\(NonNegative n) -> show n) <$> (arbitrary :: Gen (NonNegative Int))
-- | QuickCheck Generator of buffer identifiers.
--
-- A buffer identifier is either an empty string, a "%" character, a "#"
-- character, a string containing only numbers (optionally preceeded by
-- a space), or a string containing any chars preceeded by a space. E.g.,
--
-- ["", "%", "#", " myBufferName", " 45", "45"]
--
-- TODO Don't select "", "%", "#" half of the time.
bufferIdentifier :: Gen String
bufferIdentifier =
oneof [ addingSpace arbitrary
, addingSpace numberString
, numberString
, oneof [pure "%", pure " %"]
, oneof [pure "#", pure " #"]
, pure ""
]
-- | QuickCheck generator of strings suitable for use as register names in Vim
-- ex command lines. Does not include a preceding @"@.
registerName :: Gen String
registerName =
(:[]) <$> oneof [ elements ['0'..'9']
, elements ['a'..'z']
, elements ['A'..'Z']
, elements ['"', '-', '=', '*', '+', '~', '_', '/']
-- TODO Should the read-only registers be included here?
-- , element [':', '.', '%', '#']
]
-- | QuickCheck generator of strings suitable for use as counts in Vim ex
-- command lines
count :: Gen String
count = numberString
commandParsers :: [CommandParser]
commandParsers =
[ CommandParser
"Buffer.parse"
(Buffer.parse . Ev . T.pack)
["buffer", "buf", "bu", "b"]
True
True
bufferIdentifier
, CommandParser
"BufferDelete.parse"
(BufferDelete.parse . Ev . T.pack)
["bdelete", "bdel", "bd"]
True
False
(unwords <$> listOf bufferIdentifier)
, CommandParser
"Delete.parse"
(Delete.parse . Ev . T.pack)
["delete", "del", "de", "d"]
-- XXX TODO support these weird abbreviations too?
-- :dl, :dell, :delel, :deletl, :deletel
-- :dp, :dep, :delp, :delep, :deletp, :deletep
True
False
(oneof [ pure ""
, addingSpace registerName
, addingSpace count
, (<>) <$> addingSpace registerName <*> addingSpace count
])
, CommandParser
"Registers.parse"
(Registers.parse . Ev . T.pack)
[ "reg"
, "regi"
, "regis"
, "regist"
, "registe"
, "register"
, "registers"
]
False
False
(pure "")
, CommandParser
"Nohl.parse"
(Nohl.parse . Ev . T.pack)
(drop 3 $ inits "nohlsearch")
False
False
(pure "")
]
commandString :: CommandParser -> Gen String
commandString cp = do
name <- elements $ cpNames cp
bang <- if cpAcceptsBang cp
then elements ["!", ""]
else pure ""
count' <- if cpAcceptsCount cp
then count
else pure ""
args <- cpArgs cp
return $ concat [count', name, bang, args]
expectedParserParses :: CommandParser -> TestTree
expectedParserParses commandParser =
testProperty (cpDescription commandParser <> " parses expected input") $
forAll (commandString commandParser)
(isJust . cpParser commandParser)
expectedParserSelected :: CommandParser -> TestTree
expectedParserSelected expectedCommandParser =
testProperty testName $
forAll (commandString expectedCommandParser) $ \s ->
let expectedName = expectedCommandName (Ev $ T.pack s)
actualName = actualCommandName (Ev $ T.pack s)
in counterexample (errorMessage s actualName)
(expectedName == actualName)
where
unE = T.unpack . _unEv
expectedCommandName = commandNameFor [cpParser expectedCommandParser . unE]
actualCommandName = commandNameFor defExCommandParsers
commandNameFor parsers s =
cmdShow <$> evStringToExCommand parsers s
errorMessage s actualName =
"Parsed " <> show s <> " to " <> show actualName <> " command"
testName =
cpDescription expectedCommandParser <> " selected for expected input"
-- | Tests for the Ex command parsers in the Vim Keymap.
--
-- Tests that the parsers parse the strings they are expected to and that
-- the expected parser is selected for string.
--
-- The actions of the ex commands are not tested here.
tests :: TestTree
tests =
testGroup "Vim keymap ex command parsers"
[ testGroup "Expected parser parses" $
map expectedParserParses commandParsers
, testGroup "Expected parser selected" $
map expectedParserSelected commandParsers
]
|
formrre/yi
|
yi-keymap-vim/tests/Vim/TestExCommandParsers.hs
|
gpl-2.0
| 5,978
| 0
| 15
| 1,843
| 1,203
| 670
| 533
| 130
| 3
|
-- Copyright (C) 2002-2005,2007 David Roundy
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-deprecations #-}
{-# LANGUAGE CPP #-}
module Darcs.Test.Patch.Examples.Set1
( knownCommutes, knownCantCommutes, knownMerges
, knownMergeEquivs, knownCanons, mergePairs2
, validPatches, commutePairs, mergePairs
, primitiveTestPatches, testPatches, testPatchesNamed
, primitiveCommutePairs ) where
import System.IO.Unsafe ( unsafePerformIO )
import qualified Data.ByteString.Char8 as BC ( pack )
import qualified Data.ByteString as B ( empty )
import Darcs.Patch
( commute, invert, merge
, Named, namepatch
, readPatch, fromPrim
, adddir, addfile, hunk, binary, rmdir, rmfile, tokreplace )
import Darcs.Patch.Prim ( PrimOf, FromPrim )
import Darcs.Patch.Prim.V1 ( Prim )
import qualified Darcs.Patch.V1 as V1 ( Patch )
import Darcs.Test.Patch.Properties.Check( checkAPatch )
import Darcs.Patch.Witnesses.Ordered
import Darcs.Patch.Witnesses.Sealed ( unsafeUnseal )
import Darcs.Patch.Witnesses.Unsafe ( unsafeCoerceP, unsafeCoercePEnd )
#include "impossible.h"
type Patch = V1.Patch Prim
-- The unit tester function is really just a glorified map for functions that
-- return lists, in which the lists get concatenated (where map would end up
-- with a list of lists).
quickmerge :: (FL Patch :\/: FL Patch) wX wY -> FL Patch wY wZ
quickmerge (p1:\/:p2) = case merge (p1:\/:p2) of
_ :/\: p1' -> unsafeCoercePEnd p1'
-- ----------------------------------------------------------------------
-- * Show/Read tests
-- ----------------------------------------------------------------------
-- | This test involves calling 'show' to print a string describing a patch,
-- and then using readPatch to read it back in, and making sure the patch we
-- read in is the same as the original. Useful for making sure that I don't
-- have any stupid IO bugs.
-- ----------------------------------------------------------------------
-- * Canonization tests
-- ----------------------------------------------------------------------
knownCanons :: [(FL Patch wX wY,FL Patch wX wY)]
knownCanons =
[(quickhunk 1 "abcde" "ab" :>: NilFL, quickhunk 3 "cde" "" :>: NilFL),
(quickhunk 1 "abcde" "bd" :>: NilFL,
quickhunk 1 "a" "" :>:
quickhunk 2 "c" "" :>:
quickhunk 3 "e" "" :>: NilFL),
(quickhunk 4 "a" "b" :>:
quickhunk 1 "c" "d" :>: NilFL,
quickhunk 1 "c" "d" :>:
quickhunk 4 "a" "b" :>: NilFL),
(quickhunk 1 "a" "" :>:
quickhunk 1 "" "b" :>: NilFL,
quickhunk 1 "a" "b" :>: NilFL),
(quickhunk 1 "ab" "c" :>:
quickhunk 1 "cd" "e" :>: NilFL,
quickhunk 1 "abd" "e" :>: NilFL),
(quickhunk 1 "abcde" "cde" :>: NilFL, quickhunk 1 "ab" "" :>: NilFL),
(quickhunk 1 "abcde" "acde" :>: NilFL, quickhunk 2 "b" "" :>: NilFL)]
quickhunk :: (FromPrim p, PrimOf p ~ Prim) => Int -> String -> String -> p wX wY
quickhunk l o n = fromPrim $ hunk "test" l (map (\c -> BC.pack [c]) o)
(map (\c -> BC.pack [c]) n)
-- ----------------------------------------------------------------------
-- * Merge/unmgerge tests
-- ----------------------------------------------------------------------
-- | It should always be true that if two patches can be unmerged, then merging
-- the resulting patches should give them back again.
mergePairs :: [(FL Patch :\/: FL Patch) wX wY]
mergePairs =
take 400 [(p1:\/:p2)|
i <- [0..(length testPatches)-1],
p1<-[testPatches!!i],
p2<-drop i testPatches,
checkAPatch (invert p2 :>: p1 :>: NilFL)]
-- ----------------------------------------------------------------------
-- * Commute/recommute tests
-- ----------------------------------------------------------------------
-- | Here we test to see if commuting patch A and patch B and then commuting
-- the result gives us patch A and patch B again. The set of patches (A,B)
-- is chosen from the set of all pairs of test patches by selecting those which
-- commute with one another.
commutePairs :: [(FL Patch :> FL Patch) wX wY]
commutePairs =
take 200 [(p1:>p2)|
p1<-testPatches,
p2<-filter (\p->checkAPatch (p1:>:p:>:NilFL)) testPatches,
commute (p1:>p2) /= Nothing]
primitiveCommutePairs :: [(FL Patch :> FL Patch) wX wY]
primitiveCommutePairs =
[(p2:>p1)|
p1<-primitiveTestPatches,
p2<-primitiveTestPatches,
commute (p2:>p1) /= Nothing,
checkAPatch (p2:>:p1:>:NilFL)]
-- ----------------------------------------------------------------------
-- * Commute tests
-- ----------------------------------------------------------------------
-- | Here we provide a set of known interesting commutes.
knownCommutes :: [((FL Patch:<FL Patch) wX wY,(FL Patch:<FL Patch) wX wY)]
knownCommutes = [
(testhunk 1 [] ["A"]:<
testhunk 2 [] ["B"],
testhunk 3 [] ["B"]:<
testhunk 1 [] ["A"]),
(fromPrim (tokreplace "test" "A-Za-z_" "old" "new"):<
testhunk 2
["hello world all that is old is good old_"]
["I don't like old things"],
testhunk 2
["hello world all that is new is good old_"]
["I don't like new things"]:<
fromPrim (tokreplace "test" "A-Za-z_" "old" "new")),
(testhunk 1 ["A"] ["B"]:<
testhunk 2 ["C"] ["D"],
testhunk 2 ["C"] ["D"]:<
testhunk 1 ["A"] ["B"]),
(fromPrim (rmfile "NwNSO"):<
(quickmerge (fromPrim (addfile "hello"):\/:fromPrim (addfile "hello"))),
(quickmerge (fromPrim (addfile "hello"):\/:fromPrim (addfile "hello"))):<
fromPrim (rmfile "NwNSO")),
(quickmerge (testhunk 3 ["o"] ["n"]:\/:
testhunk 3 ["o"] ["v"]):<
testhunk 1 [] ["a"],
testhunk 1 [] ["a"]:<
quickmerge (testhunk 2 ["o"] ["n"]:\/:
testhunk 2 ["o"] ["v"])),
(testhunk 1 ["A"] []:<
testhunk 3 ["B"] [],
testhunk 2 ["B"] []:<
testhunk 1 ["A"] []),
(testhunk 1 ["A"] ["B"]:<
testhunk 2 ["B"] ["C"],
testhunk 2 ["B"] ["C"]:<
testhunk 1 ["A"] ["B"]),
(testhunk 1 ["A"] ["B"]:<
testhunk 3 ["B"] ["C"],
testhunk 3 ["B"] ["C"]:<
testhunk 1 ["A"] ["B"]),
(testhunk 1 ["A"] ["B","C"]:<
testhunk 2 ["B"] ["C","D"],
testhunk 3 ["B"] ["C","D"]:<
testhunk 1 ["A"] ["B","C"])]
where testhunk l o n = fromPrim $ hunk "test" l (map BC.pack o) (map BC.pack n)
knownCantCommutes :: [(FL Patch:< FL Patch) wX wY]
knownCantCommutes = [
(testhunk 2 ["o"] ["n"]:<
testhunk 1 [] ["A"]),
(testhunk 1 [] ["A"]:<
testhunk 1 ["o"] ["n"]),
(quickmerge (testhunk 2 ["o"] ["n"]:\/:
testhunk 2 ["o"] ["v"]):<
testhunk 1 [] ["a"]),
(fromPrim (hunk "test" 1 ([BC.pack "a"]) ([BC.pack "b"])):<
fromPrim (addfile "test"))]
where testhunk l o n = fromPrim $ hunk "test" l (map BC.pack o) (map BC.pack n)
-- ----------------------------------------------------------------------
-- * Merge tests
-- ----------------------------------------------------------------------
-- | Here we provide a set of known interesting merges.
knownMerges :: [((FL Patch:\/:FL Patch) wX wY,FL Patch wY wZ)]
knownMerges = [
(testhunk 2 [BC.pack "c"] [BC.pack "d",BC.pack "e"]:\/:
testhunk 1 [BC.pack "x"] [BC.pack "a",BC.pack "b"],
testhunk 3 [BC.pack "c"] [BC.pack "d",BC.pack "e"]),
(testhunk 1 [BC.pack "x"] [BC.pack "a",BC.pack "b"]:\/:
testhunk 2 [BC.pack "c"] [BC.pack "d",BC.pack "e"],
testhunk 1 [BC.pack "x"] [BC.pack "a",BC.pack "b"]),
(testhunk 3 [BC.pack "A"] []:\/:
testhunk 1 [BC.pack "B"] [],
testhunk 2 [BC.pack "A"] []),
(fromPrim (rmdir "./test/world"):\/:
fromPrim (hunk "./world" 3 [BC.pack "A"] []),
fromPrim (rmdir "./test/world")),
((quickhunk 1 "a" "bc" :>:
quickhunk 6 "d" "ef" :>: NilFL):\/:
(quickhunk 3 "a" "bc" :>:
quickhunk 8 "d" "ef" :>: NilFL),
(quickhunk 1 "a" "bc" :>:
quickhunk 7 "d" "ef" :>: NilFL)),
(testhunk 1 [BC.pack "A"] [BC.pack "B"]:\/:
testhunk 2 [BC.pack "B"] [BC.pack "C"],
testhunk 1 [BC.pack "A"] [BC.pack "B"]),
(testhunk 2 [BC.pack "A"] [BC.pack "B",BC.pack "C"]:\/:
testhunk 1 [BC.pack "B"] [BC.pack "C",BC.pack "D"],
testhunk 3 [BC.pack "A"] [BC.pack "B",BC.pack "C"])]
where testhunk l o n = fromPrim $ hunk "test" l o n
knownMergeEquivs :: [((FL Patch :\/: FL Patch) wX wY, FL Patch wY wZ)]
knownMergeEquivs = [
-- The following tests are going to be failed by the
-- Conflictor code as a cleanup.
--(addfile "test":\/:
-- adddir "test",
-- joinPatches (adddir "test" :>:
-- addfile "test-conflict" :>: NilFL)),
--(move "silly" "test":\/:
-- adddir "test",
-- joinPatches (adddir "test" :>:
-- move "silly" "test-conflict" :>: NilFL)),
--(addfile "test":\/:
-- move "old" "test",
-- joinPatches (addfile "test" :>:
-- move "old" "test-conflict" :>: NilFL)),
--(move "a" "test":\/:
-- move "old" "test",
-- joinPatches (move "a" "test" :>:
-- move "old" "test-conflict" :>: NilFL)),
(fromPrim (hunk "test" 1 [] [BC.pack "A"]) :\/:
fromPrim (hunk "test" 1 [] [BC.pack "B"]),
fromPrim (hunk "test" 1 [] [BC.pack "A", BC.pack "B"])),
(fromPrim (hunk "test" 1 [] [BC.pack "a"]):\/:
fromPrim (hunk "test" 1 [BC.pack "b"] []),
unsafeCoerceP NilFL),
--hunk "test" 1 [] [BC.pack "v v v v v v v",
-- BC.pack "*************",
-- BC.pack "a",
-- BC.pack "b",
-- BC.pack "^ ^ ^ ^ ^ ^ ^"]),
(quickhunk 4 "a" "" :\/:
quickhunk 3 "a" "",
quickhunk 3 "aa" ""),
((quickhunk 1 "a" "bc" :>:
quickhunk 6 "d" "ef" :>: NilFL) :\/:
(quickhunk 3 "a" "bc" :>:
quickhunk 8 "d" "ef" :>: NilFL),
quickhunk 3 "a" "bc" :>:
quickhunk 8 "d" "ef" :>:
quickhunk 1 "a" "bc" :>:
quickhunk 7 "d" "ef" :>: NilFL),
(quickmerge (quickhunk 2 "" "bd":\/:quickhunk 2 "" "a") :\/:
quickmerge (quickhunk 2 "" "c":\/:quickhunk 2 "" "a"),
quickhunk 2 "" "abdc")
]
-- | It also is useful to verify that it doesn't matter which order we specify
-- the patches when we merge.
mergePairs2 :: [(FL Patch wX wY, FL Patch wX wZ)]
mergePairs2 = [(p1, p2) |
p1<-primitiveTestPatches,
p2<-primitiveTestPatches,
checkAPatch (invert p1:>:p2:>:NilFL)
]
-- ----------------------------------------------------------------------
-- Patch test data
-- This is where we define the set of patches which we run our tests on. This
-- should be kept up to date with as many interesting permutations of patch
-- types as possible.
-- ----------------------------------------------------------------------
testPatches :: [FL Patch wX wY]
testPatchesNamed :: [Named Patch wX wY]
testPatchesAddfile :: [FL Patch wX wY]
testPatchesRmfile :: [FL Patch wX wY]
testPatchesHunk :: [FL Patch wX wY]
primitiveTestPatches :: [FL Patch wX wY]
testPatchesBinary :: [FL Patch wX wY]
testPatchesCompositeNocom :: [FL Patch wX wY]
testPatchesComposite :: [FL Patch wX wY]
testPatchesTwoCompositeHunks :: [FL Patch wX wY]
testPatchesCompositeHunks :: [FL Patch wX wY]
testPatchesCompositeFourHunks :: [FL Patch wX wY]
testPatchesMerged :: [FL Patch wX wY]
validPatches :: [FL Patch wX wY]
testPatchesNamed = [unsafePerformIO $
namepatch "date is" "patch name" "David Roundy" []
(fromPrim $ addfile "test"),
unsafePerformIO $
namepatch "Sat Oct 19 08:31:13 EDT 2002"
"This is another patch" "David Roundy"
["This log file has","two lines in it"]
(fromPrim $ rmfile "test")]
testPatchesAddfile = map fromPrim
[addfile "test",adddir "test",addfile "test/test"]
testPatchesRmfile = map invert testPatchesAddfile
testPatchesHunk =
[fromPrim (hunk file line old new) |
file <- ["test"],
line <- [1,2],
old <- map (map BC.pack) partials,
new <- map (map BC.pack) partials,
old /= new
]
where partials = [["A"],["B"],[],["B","B2"]]
primitiveTestPatches = testPatchesAddfile ++
testPatchesRmfile ++
testPatchesHunk ++
[unsafeUnseal.fromJust.readPatch $
BC.pack "move ./test/test ./hello",
unsafeUnseal.fromJust.readPatch $
BC.pack "move ./test ./hello"] ++
testPatchesBinary
testPatchesBinary =
[fromPrim $ binary "./hello"
(BC.pack $ "agadshhdhdsa75745457574asdgg" ++
"a326424677373735753246463gadshhdhdsaasdgg" ++
"a326424677373735753246463gadshhdhdsaasdgg" ++
"a326424677373735753246463gadshhdhdsaasdgg")
(BC.pack $ "adafjttkykrehhtrththrthrthre" ++
"a326424677373735753246463gadshhdhdsaasdgg" ++
"a326424677373735753246463gadshhdhdsaasdgg" ++
"a326424677373735753246463gadshhdhdsaagg"),
fromPrim $ binary "./hello"
B.empty
(BC.pack "adafjttkykrere")]
testPatchesCompositeNocom =
take 50 [p1+>+p2|
p1<-primitiveTestPatches,
p2<-filter (\p->checkAPatch (p1:>:p:>:NilFL)) primitiveTestPatches,
commute (p1:>p2) == Nothing]
testPatchesComposite =
take 100 [p1+>+p2|
p1<-primitiveTestPatches,
p2<-filter (\p->checkAPatch (p1:>:p:>:NilFL)) primitiveTestPatches,
commute (p1:>p2) /= Nothing,
commute (p1:>p2) /= Just (unsafeCoerceP p2:>unsafeCoerceP p1)]
testPatchesTwoCompositeHunks =
take 100 [p1+>+p2|
p1<-testPatchesHunk,
p2<-filter (\p->checkAPatch (p1:>:p:>:NilFL)) testPatchesHunk]
testPatchesCompositeHunks =
take 100 [p1+>+p2+>+p3|
p1<-testPatchesHunk,
p2<-filter (\p->checkAPatch (p1:>:p:>:NilFL)) testPatchesHunk,
p3<-filter (\p->checkAPatch (p1:>:p2:>:p:>:NilFL)) testPatchesHunk]
testPatchesCompositeFourHunks =
take 100 [p1+>+p2+>+p3+>+p4|
p1<-testPatchesHunk,
p2<-filter (\p->checkAPatch (p1:>:p:>:NilFL)) testPatchesHunk,
p3<-filter (\p->checkAPatch (p1:>:p2:>:p:>:NilFL)) testPatchesHunk,
p4<-filter (\p->checkAPatch (p1:>:p2:>:p3:>:p:>:NilFL)) testPatchesHunk]
testPatchesMerged =
take 200
[p2+>+quickmerge (p1:\/:p2) |
p1<-take 10 (drop 15 testPatchesCompositeHunks)++primitiveTestPatches
++take 10 (drop 15 testPatchesTwoCompositeHunks)
++ take 2 (drop 4 testPatchesCompositeFourHunks),
p2<-take 10 testPatchesCompositeHunks++primitiveTestPatches
++take 10 testPatchesTwoCompositeHunks
++take 2 testPatchesCompositeFourHunks,
checkAPatch (invert p1 :>: p2 :>: NilFL),
commute (p2:>p1) /= Just (p1:>p2)
]
testPatches = primitiveTestPatches ++
testPatchesComposite ++
testPatchesCompositeNocom ++
testPatchesMerged
-- ----------------------------------------------------------------------
-- * Check patch test
-- ----------------------------------------------------------------------
validPatches = [(quickhunk 4 "a" "b" :>:
quickhunk 1 "c" "d" :>: NilFL),
(quickhunk 1 "a" "bc" :>:
quickhunk 1 "b" "d" :>: NilFL),
(quickhunk 1 "a" "b" :>:
quickhunk 1 "b" "d" :>: NilFL)]++testPatches
|
DavidAlphaFox/darcs
|
harness/Darcs/Test/Patch/Examples/Set1.hs
|
gpl-2.0
| 18,259
| 0
| 17
| 5,861
| 4,753
| 2,516
| 2,237
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables, NoMonomorphismRestriction, RecordWildCards #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Monad.Error
import Control.Monad.Reader
import Control.Monad.State
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.Traversable as T
import qualified Data.HashMap.Lazy as HM
import Data.Maybe
import System.Directory
import System.Environment
import System.FilePath ((</>))
import System.IO
import System.Log.Logger
--
import HEP.Automation.EventChain.Driver
import HEP.Automation.EventChain.File
import HEP.Automation.EventChain.LHEConn
import HEP.Automation.EventChain.Type.Skeleton
import HEP.Automation.EventChain.Type.Spec
import HEP.Automation.EventChain.Type.Process
import HEP.Automation.EventChain.SpecDSL
import HEP.Automation.EventChain.Simulator
import HEP.Automation.EventChain.Process
import HEP.Automation.EventChain.Process.Generator
import HEP.Automation.EventGeneration.Config
import HEP.Automation.EventGeneration.Type
import HEP.Automation.EventGeneration.Work
import HEP.Automation.MadGraph.Model.ADMXQLD111
import HEP.Automation.MadGraph.Run
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Type
import HEP.Parser.LHE.Type
import HEP.Parser.LHE.Sanitizer.Type
import HEP.Storage.WebDAV
--
import qualified Paths_madgraph_auto as PMadGraph
import qualified Paths_madgraph_auto_model as PModel
jets = [1,2,3,4,-1,-2,-3,-4,21]
leptons = [11,13,-11,-13]
lepplusneut = [11,12,13,14,-11,-12,-13,-14]
adms = [9000201,-9000201,9000202,-9000202]
sup = [1000002,-1000002]
sdownR = [2000001,-2000001]
p_gluino = d ([1000021], [t lepplusneut, t jets, t jets, t adms])
p_sdownR :: DDecay
p_sdownR = d (sdownR, [t lepplusneut, t jets, t adms])
p_sqsg_2l3j2x :: DCross
p_sqsg_2l3j2x = x (t proton, t proton, [p_gluino, p_sdownR])
idx_sqsg_2l3j2x :: CrossID ProcSmplIdx
idx_sqsg_2l3j2x = mkCrossIDIdx (mkDICross p_sqsg_2l3j2x)
map_sqsg_2l3j2x :: ProcSpecMap
map_sqsg_2l3j2x =
HM.fromList [(Nothing , MGProc [] [ "p p > go dr QED=0"
, "p p > go dr~ QED=0" ])
,(Just (3,1000021,[]), MGProc [ "define lep = e+ e- mu+ mu- ve ve~ vm vm~ "
, "define sxx = sxxp sxxp~ "]
[ "go > lep j j sxx " ] )
,(Just (4,-2000001,[]), MGProc [] [ "dr~ > u~ e+ sxxp~ "
, "dr~ > d~ ve~ sxxp~ " ])
,(Just (4,2000001,[]) , MGProc [] [ "dr > u e- sxxp "
, "dr > d ve sxxp " ])
]
modelparam mgl msq msl mneut = ADMXQLD111Param mgl msq msl mneut
-- |
mgrunsetup :: Int -> RunSetup
mgrunsetup n =
RS { numevent = n
, machine = LHC8 ATLAS
, rgrun = Auto
, rgscale = 200.0
, match = NoMatch
, cut = NoCut
, pythia = RunPYTHIA
, lhesanitizer = LHESanitize (Replace [(9000201,1000022),(-9000201,1000022)])
, pgs = RunPGS (AntiKTJet 0.4,NoTau)
, uploadhep = NoUploadHEP
, setnum = 1
}
worksets = [ (mgl,msq,50000,50000, 10000) | (mgl,msq) <- [ (500,900),(500,1000),(500,1100),(500,1200) ] ]
-- mgl <- [100,200..2000], msq <- [100,200..2000] ]
main :: IO ()
main = do
args <- getArgs
let fp = args !! 0
n1 = read (args !! 1) :: Int
n2 = read (args !! 2) :: Int
-- fp <- (!! 0) <$> getArgs
updateGlobalLogger "MadGraphAuto" (setLevel DEBUG)
-- print (length worksets)
mapM_ (scanwork fp) (drop (n1-1) . take n2 $ worksets )
{-
-- |
getScriptSetup :: FilePath -- ^ sandbox directory
-> FilePath -- ^ mg5base
-> FilePath -- ^ main montecarlo run
-> IO ScriptSetup
getScriptSetup dir_sb dir_mg5 dir_mc = do
dir_mdl <- (</> "template") <$> PModel.getDataDir
dir_tmpl <- (</> "template") <$> PMadGraph.getDataDir
return $
SS { modeltmpldir = dir_mdl
, runtmpldir = dir_tmpl
, sandboxdir = dir_sb
, mg5base = dir_mg5
, mcrundir = dir_mc
}
-}
scanwork :: FilePath -> (Double,Double,Double,Double,Int) -> IO ()
scanwork fp (mgl,msq,msl,mneut,n) = do
homedir <- getHomeDirectory
getConfig fp >>=
maybe (return ()) (\ec -> do
let ssetup = evgen_scriptsetup ec
whost = evgen_webdavroot ec
pkey = evgen_privatekeyfile ec
pswd = evgen_passwordstore ec
Just cr <- getCredential pkey pswd
let wdavcfg = WebDAVConfig { webdav_credential = cr
, webdav_baseurl = whost }
param = modelparam mgl msq msl mneut
mgrs = mgrunsetup n
evchainGen ADMXQLD111
ssetup
("Work20130610_sqsg","sqsg_2l3j2x")
param
map_sqsg_2l3j2x p_sqsg_2l3j2x
mgrs
let wsetup' = getWorkSetupCombined ADMXQLD111 ssetup param ("Work20130610_sqsg","sqsg_2l3j2x") mgrs
wsetup = wsetup' { ws_storage = WebDAVRemoteDir "montecarlo/admproject/XQLD/8TeV/scan_sqsg_2l3j2x"}
putStrLn "phase2work start"
phase2work wsetup
putStrLn "phase3work start"
phase3work wdavcfg wsetup
)
phase2work :: WorkSetup ADMXQLD111 -> IO ()
phase2work wsetup = do
r <- flip runReaderT wsetup . runErrorT $ do
ws <- ask
let (ssetup,psetup,param,rsetup) =
((,,,) <$> ws_ssetup <*> ws_psetup <*> ws_param <*> ws_rsetup) ws
cardPrepare
case (lhesanitizer rsetup,pythia rsetup) of
(NoLHESanitize,_) -> return ()
(LHESanitize pid, RunPYTHIA) -> do
sanitizeLHE
runPYTHIA
runPGS
runClean
(LHESanitize pid, NoPYTHIA) -> do
sanitizeLHE
cleanHepFiles
print r
return ()
-- |
phase3work :: WebDAVConfig -> WorkSetup ADMXQLD111 -> IO ()
phase3work wdav wsetup = do
uploadEventFull NoUploadHEP wdav wsetup
return ()
|
wavewave/lhc-analysis-collection
|
exe/2013-06-10-XQLD-sqsg.hs
|
gpl-3.0
| 6,264
| 0
| 20
| 1,832
| 1,577
| 898
| 679
| 135
| 3
|
module Main where
import Data.List
import Data.Char
-- |The core IO part of the code
main =
do
dictionary <- readFile "src/linuxwords.txt"
let list = (lines dictionary)
putStrLn "1. Words containing string"
putStrLn "2. Words starting with string"
putStrLn "3. Words ending with string"
putStrLn "4. Words that contain certain letters somewhere"
putStrLn "5. Quit"
strChoice <- getLine
if(strChoice == "1")
then do
putStrLn "Give me a string"
putStrLn "Use '$' as a wildcard"
str <- getLine
let matches = map (containsWildcard str) list
let hits = contains list matches
putStrLn "\nI am looking for words...\n"
putStrLn "1. LESS THAN a certain number of letters"
putStrLn "2. GREATER THAN a certain number of letters"
putStrLn "3. EQUAL to a certain number of letters"
putStrLn "4. I don't care"
option <- getLine
if(option == "4")
then
putStrLn(unlines hits)
else
do
putStrLn "# of letters?"
strLength <- getLine
if(checkNumber strLength == True)
then do
let length = read strLength :: Int
if(option == "1")
then
putStrLn(unlines(lessThan hits length))
else if(option == "2")
then
putStrLn(unlines(greaterThan hits length))
else if(option == "3")
then
putStrLn(unlines(equalTo hits length))
else
putStrLn "Invalid Input \n"
else
putStrLn "Invalid Input \n"
main
else if(strChoice == "2")
then do
putStrLn "Give me a string"
putStrLn "Use '$' as a wildcard"
str <- getLine
let matches = map (startsWith str) list
let hits = contains list matches
putStrLn "\nI am looking for words...\n"
putStrLn "1. LESS THAN a certain number of letters"
putStrLn "2. GREATER THAN a certain number of letters"
putStrLn "3. EQUAL to a certain number of letters"
putStrLn "4. I don't care"
option <- getLine
if(option == "4")
then
putStrLn(unlines hits)
else
do
putStrLn "# of letters?"
strLength <- getLine
if(checkNumber strLength == True)
then do
let length = read strLength :: Int
if(option == "1")
then
putStrLn(unlines(lessThan hits length))
else if(option == "2")
then
putStrLn(unlines(greaterThan hits length))
else if(option == "3")
then
putStrLn(unlines(equalTo hits length))
else
putStrLn "Invalid Input \n"
else
putStrLn "Invalid Input \n"
main
else if(strChoice == "3")
then do
putStrLn "Give me a string"
putStrLn "Use '$' as a wildcard"
str <- getLine
let matches = map (endsWith str) list
let hits = contains list matches
putStrLn "\nI am looking for words...\n"
putStrLn "1. LESS THAN a certain number of letters"
putStrLn "2. GREATER THAN a certain number of letters"
putStrLn "3. EQUAL to a certain number of letters"
putStrLn "4. I don't care"
option <- getLine
if(option == "4")
then
putStrLn(unlines hits)
else
do
putStrLn "# of letters?"
strLength <- getLine
if(checkNumber strLength == True)
then do
let length = read strLength :: Int
if(option == "1")
then
putStrLn(unlines(lessThan hits length))
else if(option == "2")
then
putStrLn(unlines(greaterThan hits length))
else if(option == "3")
then
putStrLn(unlines(equalTo hits length))
else
putStrLn "Invalid Input \n"
else
putStrLn "Invalid Input \n"
main
else if(strChoice == "4")
then do
putStrLn "Give me a string"
str <- getLine
let hits = containsElem list str
putStrLn "\nI am looking for words...\n"
putStrLn "1. LESS THAN a certain number of letters"
putStrLn "2. GREATER THAN a certain number of letters"
putStrLn "3. EQUAL to a certain number of letters"
putStrLn "4. I don't care"
option <- getLine
if(option == "4")
then
putStrLn(unlines hits)
else
do
putStrLn "# of letters?"
strLength <- getLine
if(checkNumber strLength == True)
then do
let length = read strLength :: Int
if(option == "1")
then
putStrLn(unlines(lessThan hits length))
else if(option == "2")
then
putStrLn(unlines(greaterThan hits length))
else if(option == "3")
then
putStrLn(unlines(equalTo hits length))
else
putStrLn "Invalid Input \n"
else
putStrLn "Invalid Input \n"
main
else if(strChoice == "5")
then
putStrLn "Goodbye! \n"
else
do
putStrLn "Invalid Choice \n"
main
-- |Takes a list of words, and a list of Booleans
-- and outputs the words corresponding to the the True
-- values in the list of Booleans
--
-- To be used with 'startsWith', 'endsWith', and 'containsWildcard' functions
contains :: [String] -> [Bool] -> [String]
contains (x:xs) [] = []
contains [] (y:ys) = []
contains [] [] = []
contains (x:xs) (y:ys)
|(y) = [x] ++ contains xs ys
|otherwise = [] ++ contains xs ys
-- |Takes in a list of words and a list of characters, and outputs a subset of the list of words which contain all of the input characters
containsElem :: [String] -> [Char] -> [String]
containsElem [] y = []
containsElem x [] = x
containsElem x (y:ys) = containsElem (contains x (map (elem y) x)) ys
-- |Outputs a subset of strings which have lengths less than the input Int, from the input [String]
lessThan :: [String] -> Int -> [String]
lessThan [] y = []
lessThan (x:xs) y
|((length x) < y) = [x] ++ lessThan xs y
|otherwise = [] ++ lessThan xs y
-- |Outputs a subset of strings which have lengths greater than the input Int, from the input [String]
greaterThan :: [String] -> Int -> [String]
greaterThan [] y = []
greaterThan (x:xs) y
|((length x) > y) = [x] ++ greaterThan xs y
|otherwise = [] ++ greaterThan xs y
-- |Outputs a subset of strings which have lengths equal to the input Int, from the input [String]
equalTo :: [String] -> Int -> [String]
equalTo [] y = []
equalTo (x:xs) y
|((length x) == y) = [x] ++ equalTo xs y
|otherwise = [] ++ equalTo xs y
-- | Checks if input String is a Digit
--
-- Used for user input selection
checkNumber :: [Char] -> Bool
checkNumber (x:xs)
|(length xs) == 0 = isDigit x
|(length xs) > 0 = isDigit x && checkNumber xs
|otherwise = False
checkNumber [] = False
-- | Checks if a string starts with another string
--
-- Also utilizes wildcards denoted by \"$\" in the second argument
startsWith :: [Char]->[Char] -> Bool
startsWith [] _ = True
startsWith _ [] = False
startsWith (x:xs) (y:ys)
|x == '$' = startsWith xs ys
|otherwise = x == y && startsWith xs ys
-- | Checks if a string contains a list of characters
--
-- Also utilizes wildcards denoted by \"$\" in the second argument
containsWildcard :: [Char] -> [Char] -> Bool
containsWildcard x y = any (startsWith x) (tails y)
-- | Checks if a string ends with another string
--
-- Also utilizes wildcards denoted by \"$\" in the second argument
endsWith :: [Char] -> [Char] -> Bool
endsWith x y = reverse x `startsWith` reverse y
|
cdm1006/Words
|
src/Main.hs
|
gpl-3.0
| 7,501
| 152
| 26
| 2,206
| 2,240
| 1,102
| 1,138
| 178
| 26
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeOperators #-}
module Routes.Admin.Products
( ProductAPI
, productRoutes
) where
import Control.Monad (forM_, unless)
import Control.Monad.Reader (liftIO, lift)
import Data.Aeson ((.=), (.:), (.:?), ToJSON(..), FromJSON(..), Value(Object), object, withObject)
import Data.Maybe (mapMaybe, listToMaybe, fromMaybe)
import Data.Monoid ((<>))
import Data.Text.Encoding (encodeUtf8)
import Data.Time (UTCTime, getCurrentTime)
import Database.Persist
( (==.), (=.), Entity(..), SelectOpt(Asc), selectList, selectFirst
, insert, insertMany_, insert_, update, get, getBy, deleteWhere, delete
)
import Servant ((:<|>)(..), (:>), AuthProtect, ReqBody, Capture, Get, Post, JSON, err404)
import Auth (WrappedAuthToken, Cookied, withAdminCookie, validateAdminAndParameters)
import Models
( EntityField(..), Product(..), ProductId, ProductVariant(..), ProductVariantId
, SeedAttribute(..), Category(..), CategoryId, Unique(..), slugify
, ProductToCategory(..)
)
import Models.Fields (LotSize, Cents, Region)
import Routes.CommonData
( AdminCategorySelect, makeAdminCategorySelects, validateCategorySelect
, getAdditionalCategories
)
import Routes.Utils (activeVariantExists, makeImageFromBase64, sanitize)
import Server (App, AppSQL, runDB, serverError)
import Validation (Validation(validators))
import qualified Data.ByteString as BS
import qualified Data.Text as T
import qualified Data.List as L
import qualified Data.Map.Strict as M
import qualified Database.Esqueleto as E
import qualified Validation as V
type ProductAPI =
"list" :> ProductListRoute
:<|> "data" :> SharedProductDataRoute
:<|> "new" :> NewProductRoute
:<|> "edit" :> EditProductDataRoute
:<|> "edit" :> EditProductRoute
type ProductRoutes =
(WrappedAuthToken -> App (Cookied ProductListData))
:<|> (WrappedAuthToken -> App (Cookied SharedProductData))
:<|> (WrappedAuthToken -> ProductParameters -> App (Cookied ProductId))
:<|> (WrappedAuthToken -> ProductId -> App (Cookied EditProductData))
:<|> (WrappedAuthToken -> EditProductParameters -> App (Cookied ProductId))
productRoutes :: ProductRoutes
productRoutes =
productListRoute
:<|> sharedProductDataRoute
:<|> newProductRoute
:<|> editProductDataRoute
:<|> editProductRoute
-- LIST
type ProductListRoute =
AuthProtect "cookie-auth"
:> Get '[JSON] (Cookied ProductListData)
newtype ProductListData =
ProductListData
{ pldProducts :: [ListProduct]
} deriving (Show)
instance ToJSON ProductListData where
toJSON ProductListData {..} =
object
[ "products" .= pldProducts
]
data ListProduct =
ListProduct
{ lpId :: ProductId
, lpName :: T.Text
, lpBaseSku :: T.Text
, lpCategories :: [T.Text]
, lpIsActive :: Bool
} deriving (Show)
instance ToJSON ListProduct where
toJSON ListProduct {..} =
object
[ "id" .= lpId
, "name" .= lpName
, "baseSKU" .= lpBaseSku
, "categories" .= lpCategories
, "isActive" .= lpIsActive
]
productListRoute :: WrappedAuthToken -> App (Cookied ProductListData)
productListRoute t = withAdminCookie t $ \_ -> runDB $ do
categoryNameMap <- makeNameMap <$> selectList [] []
ProductListData . map (makeProduct categoryNameMap) <$> getProducts
where
makeNameMap :: [Entity Category] -> M.Map CategoryId T.Text
makeNameMap =
foldr (\(Entity cId c) m -> M.insert cId (categoryName c) m) M.empty
getProducts :: AppSQL [(Entity Product, E.Value Bool)]
getProducts =
E.select $ E.from $ \p -> do
E.orderBy [E.asc $ p E.^. ProductBaseSku]
return (p, activeVariantExists p )
makeProduct :: M.Map CategoryId T.Text -> (Entity Product, E.Value Bool) -> ListProduct
makeProduct nameMap (Entity pId prod, isActive) =
ListProduct
{ lpId = pId
, lpName = productName prod
, lpBaseSku = productBaseSku prod
, lpCategories = (: []) . fromMaybe "" $ productMainCategory prod `M.lookup` nameMap
, lpIsActive = E.unValue isActive
}
-- NEW / EDIT COMMON DATA
type SharedProductDataRoute =
AuthProtect "cookie-auth"
:> Get '[JSON] (Cookied SharedProductData)
newtype SharedProductData =
SharedProductData
{ spdCategories :: [AdminCategorySelect]
} deriving (Show)
instance ToJSON SharedProductData where
toJSON SharedProductData {..} =
object [ "categories" .= spdCategories ]
sharedProductDataRoute :: WrappedAuthToken -> App (Cookied SharedProductData)
sharedProductDataRoute t = withAdminCookie t $ \_ ->
SharedProductData <$> runDB makeAdminCategorySelects
data ProductParameters =
ProductParameters
{ ppName :: T.Text
, ppSlug :: T.Text
, ppCategories :: [CategoryId]
, ppBaseSku :: T.Text
, ppLongDescription :: T.Text
, ppImageData :: BS.ByteString
-- ^ Base64 Encoded
, ppImageName :: T.Text
, ppKeywords :: T.Text
, ppShippingRestrictions :: [Region]
, ppVariantData :: [VariantData]
, ppSeedAttribute :: Maybe SeedData
} deriving (Show)
instance FromJSON ProductParameters where
parseJSON = withObject "ProductParameters" $ \v -> do
ppName <- v .: "name"
ppSlug <- v .: "slug"
ppCategories <- v .: "categories"
ppBaseSku <- v .: "baseSku"
ppLongDescription <- v .: "longDescription"
ppImageData <- encodeUtf8 <$> v .: "imageData"
ppImageName <- v .: "imageName"
ppKeywords <- fromMaybe "" <$> (v .:? "keywords")
ppShippingRestrictions <- v .: "shippingRestrictions"
ppVariantData <- v .: "variants"
ppSeedAttribute <- v .: "seedAttributes"
return ProductParameters {..}
instance Validation ProductParameters where
validators ProductParameters {..} = do
slugDoesntExist <- V.doesntExist $ UniqueProductSlug ppSlug
skuDoesntExist <- V.doesntExist $ UniqueBaseSku ppBaseSku
categoryValidations <- validateCategorySelect True ppCategories
return $
[ ( ""
, [ ("At least one Variant is required.", null ppVariantData) ]
)
, ( "name"
, [ V.required ppName ]
)
, ( "slug"
, [ V.required ppSlug
, ( "A Product with this Slug already exists."
, slugDoesntExist
)
]
)
, ( "baseSku"
, [ V.required ppBaseSku
, ( "A Product with this SKU already exists."
, skuDoesntExist
)
]
)
]
++ getDuplicateSuffixErrors ppVariantData
++ categoryValidations
data VariantData =
VariantData
{ vdSkuSuffix :: T.Text
, vdPrice :: Cents
, vdQuantity :: Int
, vdLotSize :: Maybe LotSize
, vdIsActive :: Bool
, vdId :: Maybe ProductVariantId
-- ^ Only used in the EditProductRoute
} deriving (Show)
instance FromJSON VariantData where
parseJSON = withObject "VariantData" $ \v -> do
vdSkuSuffix <- v .: "skuSuffix"
vdPrice <- v .: "price"
vdQuantity <- v .: "quantity"
vdLotSize <- v .: "lotSize"
vdIsActive <- v .: "isActive"
vdId <- v .: "id"
return VariantData {..}
instance ToJSON VariantData where
toJSON VariantData {..} =
object
[ "id" .= vdId
, "skuSuffix" .= vdSkuSuffix
, "price" .= vdPrice
, "quantity" .= vdQuantity
, "lotSize" .= vdLotSize
, "isActive" .= vdIsActive
]
data SeedData =
SeedData
{ sdOrganic :: Bool
, sdHeirloom :: Bool
, sdSmallGrower :: Bool
, sdRegional :: Bool
} deriving (Show)
instance FromJSON SeedData where
parseJSON = withObject "SeedData" $ \v -> do
sdOrganic <- v .: "organic"
sdHeirloom <- v .: "heirloom"
sdSmallGrower <- v .: "smallGrower"
sdRegional <- v .: "regional"
return SeedData {..}
instance ToJSON SeedData where
toJSON SeedData {..} =
object
[ "organic" .= sdOrganic
, "heirloom" .= sdHeirloom
, "smallGrower" .= sdSmallGrower
, "regional" .= sdRegional
]
-- NEW
type NewProductRoute =
AuthProtect "cookie-auth"
:> ReqBody '[JSON] ProductParameters
:> Post '[JSON] (Cookied ProductId)
newProductRoute :: WrappedAuthToken -> ProductParameters -> App (Cookied ProductId)
newProductRoute = validateAdminAndParameters $ \_ p@ProductParameters {..} -> do
time <- liftIO getCurrentTime
imageFileName <- makeImageFromBase64 "products" ppImageName ppImageData
runDB $ do
(prod, extraCategories) <- makeProduct p imageFileName time
productId <- insert prod
insertMany_ $ map (ProductToCategory productId) extraCategories
insertMany_ $ map (makeVariant productId) ppVariantData
maybe (return ()) (insert_ . makeAttributes productId) ppSeedAttribute
return productId
where
makeProduct :: ProductParameters -> T.Text -> UTCTime -> AppSQL (Product, [CategoryId])
makeProduct ProductParameters {..} imageUrl time =
case ppCategories of
main : rest -> return
( Product
{ productName = sanitize ppName
, productSlug = slugify ppSlug
, productMainCategory = main
, productBaseSku = ppBaseSku
, productShortDescription = ""
, productLongDescription = sanitize ppLongDescription
, productImageUrl = imageUrl
, productKeywords = ppKeywords
, productShippingRestrictions = L.nub ppShippingRestrictions
, productCreatedAt = time
, productUpdatedAt = time
}
, rest
)
[] ->
lift $ V.singleError "At least one Category is required."
-- EDIT
type EditProductDataRoute =
AuthProtect "cookie-auth"
:> Capture "id" ProductId
:> Get '[JSON] (Cookied EditProductData)
data EditProductData =
EditProductData
{ epdId :: ProductId
, epdName :: T.Text
, epdSlug :: T.Text
, epdCategories :: [CategoryId]
, epdBaseSku :: T.Text
, epdLongDescription :: T.Text
, epdImageUrl :: T.Text
, epdKeywords :: T.Text
, epdShippingRestrictions :: [Region]
, epdVariantData :: [VariantData]
, epdSeedAttribute :: Maybe SeedData
} deriving (Show)
instance ToJSON EditProductData where
toJSON EditProductData {..} =
object
[ "id" .= epdId
, "name" .= epdName
, "slug" .= epdSlug
, "categories" .= epdCategories
, "baseSku" .= epdBaseSku
, "longDescription" .= epdLongDescription
, "imageUrl" .= epdImageUrl
, "keywords" .= epdKeywords
, "shippingRestrictions" .= epdShippingRestrictions
, "variants" .= epdVariantData
, "seedAttributes" .= epdSeedAttribute
]
editProductDataRoute :: WrappedAuthToken -> ProductId -> App (Cookied EditProductData)
editProductDataRoute t productId = withAdminCookie t $ \_ ->
runDB (get productId) >>= \case
Nothing ->
serverError err404
Just Product {..} -> runDB $ do
variants <- map makeVariantData
<$> selectList
[ProductVariantProductId ==. productId]
[Asc ProductVariantSkuSuffix]
seedAttr <- fmap makeAttributeData <$> getBy (UniqueAttribute productId)
categories <- getAdditionalCategories productId
return EditProductData
{ epdId = productId
, epdName = productName
, epdSlug = productSlug
, epdCategories = productMainCategory
: map (productToCategoryCategoryId . entityVal) categories
, epdBaseSku = productBaseSku
, epdLongDescription = productLongDescription
, epdImageUrl = productImageUrl
, epdKeywords = productKeywords
, epdShippingRestrictions = productShippingRestrictions
, epdVariantData = variants
, epdSeedAttribute = seedAttr
}
where
makeVariantData :: Entity ProductVariant -> VariantData
makeVariantData (Entity variantId ProductVariant {..}) =
VariantData
{ vdId = Just variantId
, vdSkuSuffix = productVariantSkuSuffix
, vdPrice = productVariantPrice
, vdQuantity = fromIntegral productVariantQuantity
, vdLotSize = productVariantLotSize
, vdIsActive = productVariantIsActive
}
makeAttributeData :: Entity SeedAttribute -> SeedData
makeAttributeData (Entity _ SeedAttribute {..}) =
SeedData
{ sdOrganic = seedAttributeIsOrganic
, sdHeirloom = seedAttributeIsHeirloom
, sdRegional = seedAttributeIsRegional
, sdSmallGrower = seedAttributeIsSmallGrower
}
type EditProductRoute =
AuthProtect "cookie-auth"
:> ReqBody '[JSON] EditProductParameters
:> Post '[JSON] (Cookied ProductId)
data EditProductParameters =
EditProductParameters
{ eppId :: ProductId
, eppProduct :: ProductParameters
}
instance FromJSON EditProductParameters where
parseJSON = withObject "EditProductParameters" $ \v -> do
eppId <- v .: "id"
eppProduct <- parseJSON $ Object v
return EditProductParameters {..}
instance Validation EditProductParameters where
validators EditProductParameters {..} = do
let ProductParameters {..} = eppProduct
productExists <- V.exists eppId
categoryValidations <- validateCategorySelect True ppCategories
return $
[ ( ""
, [ ("Could not find this product in the database.", productExists)
, ("At least one Variant is required.", null ppVariantData)
]
)
, ( "name", [ V.required ppName ] )
, ( "slug", [ V.required ppSlug ] )
, ( "baseSku", [ V.required ppBaseSku ])
]
++ getDuplicateSuffixErrors ppVariantData
++ categoryValidations
editProductRoute :: WrappedAuthToken -> EditProductParameters -> App (Cookied ProductId)
editProductRoute = validateAdminAndParameters $ \_ EditProductParameters {..} -> do
let ProductParameters {..} = eppProduct
imageUpdate <-
if not (BS.null ppImageData) && not (T.null ppImageName) then do
imageFileName <- makeImageFromBase64 "products" ppImageName ppImageData
return [ ProductImageUrl =. imageFileName ]
else
return []
time <- liftIO getCurrentTime
(mainCategory, extraCategories) <-
case ppCategories of
[] ->
V.singleError "At least one Category is required."
main : rest ->
return (main, rest)
runDB $ do
update eppId $
[ ProductName =. sanitize ppName
, ProductSlug =. slugify ppSlug
, ProductMainCategory =. mainCategory
, ProductBaseSku =. ppBaseSku
, ProductLongDescription =. sanitize ppLongDescription
, ProductKeywords =. ppKeywords
, ProductShippingRestrictions =. L.nub ppShippingRestrictions
, ProductUpdatedAt =. time
] ++ imageUpdate
deleteWhere [ProductToCategoryProductId ==. eppId]
insertMany_ $ map (ProductToCategory eppId) extraCategories
(ppSeedAttribute,) <$> selectFirst [SeedAttributeProductId ==. eppId] [] >>= \case
(Just seedData, Nothing) ->
insert_ $ makeAttributes eppId seedData
(Just SeedData {..}, Just (Entity attrId _)) ->
update attrId
[ SeedAttributeProductId =. eppId
, SeedAttributeIsOrganic =. sdOrganic
, SeedAttributeIsHeirloom =. sdHeirloom
, SeedAttributeIsRegional =. sdRegional
, SeedAttributeIsSmallGrower =. sdSmallGrower
]
(Nothing, Just (Entity attrId _)) ->
delete attrId
_ ->
return ()
forM_ ppVariantData $ \variant@VariantData {..} ->
case vdId of
Nothing ->
insert_ $ makeVariant eppId variant
Just variantId -> do
update variantId
[ ProductVariantProductId =. eppId
, ProductVariantSkuSuffix =. vdSkuSuffix
, ProductVariantPrice =. vdPrice
, ProductVariantQuantity =. fromIntegral vdQuantity
, ProductVariantLotSize =. vdLotSize
, ProductVariantIsActive =. vdIsActive
]
unless vdIsActive $
deleteWhere [CartItemProductVariantId ==. variantId]
return eppId
-- UTILS
makeVariant :: ProductId -> VariantData -> ProductVariant
makeVariant pId VariantData {..} =
ProductVariant
{ productVariantProductId = pId
, productVariantSkuSuffix = vdSkuSuffix
, productVariantPrice = vdPrice
, productVariantQuantity = fromIntegral vdQuantity
, productVariantLotSize = vdLotSize
, productVariantIsActive = vdIsActive
}
makeAttributes :: ProductId -> SeedData -> SeedAttribute
makeAttributes pId SeedData {..} =
SeedAttribute
{ seedAttributeProductId = pId
, seedAttributeIsOrganic = sdOrganic
, seedAttributeIsHeirloom = sdHeirloom
, seedAttributeIsSmallGrower = sdSmallGrower
, seedAttributeIsRegional = sdRegional
}
getDuplicateSuffixErrors :: [VariantData] -> [(T.Text, [(T.Text, Bool)])]
getDuplicateSuffixErrors variants =
let duplicateSuffixes =
mapMaybe (\l -> if length l > 1 then listToMaybe l else Nothing)
$ L.group
$ L.sort
$ map vdSkuSuffix variants
in checkDuplicateSuffix duplicateSuffixes
where
checkDuplicateSuffix dupes =
let duplicateIndexes =
L.findIndices ((`elem` dupes) . vdSkuSuffix) variants
in
map (\i ->
( "variant-" <> T.pack (show i) <> "-skuSuffix"
, [ ("SKU suffixes must be unique.", True) ]
)
)
duplicateIndexes
|
Southern-Exposure-Seed-Exchange/southernexposure.com
|
server/src/Routes/Admin/Products.hs
|
gpl-3.0
| 19,437
| 0
| 22
| 6,164
| 4,440
| 2,413
| 2,027
| 436
| 7
|
module Rebass.FileStatus where
import Rebass.Path
import System.IO
import System.Time(CalendarTime)
import System.Time(ClockTime, toCalendarTime)
import System.Directory(getDirectoryContents, doesDirectoryExist, getModificationTime)
import System.Posix.Files(getFileStatus, fileSize)
import Data.List(sort)
import Control.Monad(liftM2)
data File = RegularFile { path :: Path, status :: FileStatus }
| Directory { path :: Path, contents :: [File]}
deriving (Show, Read, Eq)
data FileStatus = FileStatus { timeStamp :: CalendarTime, size :: Integer }
deriving (Show, Read, Eq)
instance Pathy File where
pathOf (RegularFile path _) = path
pathOf (Directory path _) = path
emptyDir = Directory "" []
ignored = [".", "..", ".git", ".gitignore", ".rebass"]
readFileStatus :: Path -> IO File
readFileStatus root = read root
where
read path = handleFileOrDirectory path readFile readDirectory
readFile path = do
timestamp <- getModificationTime path >>= toCalendarTime
posixFileStatus <- getFileStatus path
return $ RegularFile (relativePath path) $ FileStatus timestamp (toInteger $ fileSize posixFileStatus)
readDirectory path = do
contents <- (getDirectoryContents path >>= (readDirectoryContents path))
return $ Directory (relativePath path) contents
readDirectoryContents parent paths = sequence $ map read $ map fullPath $ filter realFile $ sort $ paths
where
realFile path = path `notElem` ignored
fullPath path = parent ++ "/" ++ path
relativePath path = drop ((length root)+1) path
handleFileOrDirectory path fileHandler directoryHandler =
(doesDirectoryExist path) >>= (\dir -> if dir then (directoryHandler path) else (fileHandler path))
|
codeflows/rebass
|
src/Rebass/FileStatus.hs
|
gpl-3.0
| 2,093
| 0
| 13
| 663
| 556
| 296
| 260
| 35
| 2
|
{-# LANGUAGE FlexibleInstances
, FlexibleContexts #-}
module XMonad.Hooks.DynamicLog.Dzen2.StatusText where
import XMonad hiding (Status, Position, Color, Dimension, Font)
import XMonad.Hooks.DynamicLog.Dzen2.Font
import XMonad.Hooks.DynamicLog.Dzen2.Render
import XMonad.Hooks.DynamicLog.Dzen2.Content
import XMonad.Hooks.DynamicLog.Dzen2.Status
import XMonad.Util.Font
import XMonad.Util.Font.Width
import qualified Data.List as L
newtype StatusT fnt s = StatusT (Status s) deriving Eq
type StatusText fnt = StatusT fnt String
instance Content s => Content (StatusT fnt s) where
content (StatusT (SAtom x)) = content x
content (StatusT (SList xs)) = mconcat $ content <$> xs
content (StatusT (SP _ x)) = content x
content (StatusT (SPA _ x)) = content x
content (StatusT (SFG _ x)) = content x
content (StatusT (SBG _ x)) = content x
content (StatusT (SCA _ _ x)) = content x
content (StatusT (SStatic s)) = ""
instance Render s => Render (StatusT fnt s) where
render (StatusT x) = render x
instance Functor (StatusT fnt) where
fmap f (StatusT s) = StatusT $ fmap f s
instance Applicative (StatusT fnt) where
pure = StatusT . SAtom
(StatusT f) <*> (StatusT s) = StatusT $ f <*> s
instance Monad (StatusT fnt) where
return = pure
(StatusT x) >>= f = StatusT $ x >>= (\(StatusT x) -> x) . f
instance Monoid (StatusT fnt s) where
mempty = StatusT $ mempty
(StatusT x) `mappend` (StatusT y) = StatusT (x `mappend` y)
-- | Return the logical length of the StatusText, in number of
-- characters. That is, the length of its content.
length :: StatusText fnt -> Int
length = L.length . content
onto :: (Status s -> Status t) -> StatusT fnt s -> StatusT fnt t
onto f (StatusT s) = StatusT $ f s
pack :: Status s -> StatusT fnt s
pack s = StatusT s
unpack :: StatusT fnt s -> Status s
unpack (StatusT s) = s
|
Fizzixnerd/xmonad-config
|
site-haskell/src/XMonad/Hooks/DynamicLog/Dzen2/StatusText.hs
|
gpl-3.0
| 1,865
| 0
| 11
| 365
| 736
| 387
| 349
| 43
| 1
|
module Codewars.Exercise.Inversions where
import Data.List
countInversions :: Ord a => [a] -> Int
countInversions = length . inv
where inv xs = [(a,b) | (a:bs) <- tails xs, b <- bs, a > b]
--
|
ice1000/OI-codes
|
codewars/1-100/calculate-number-of-inversions-in-array.hs
|
agpl-3.0
| 196
| 0
| 11
| 39
| 94
| 52
| 42
| 5
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Erd.Config
( Config(..)
, configIO
, defaultConfig
, defaultConfigFile
, Notation(..)
)
where
import Control.Exception (tryJust)
import Control.Monad (guard)
import qualified Data.ByteString.Char8 as B
import Data.Char (isSpace)
import qualified Data.GraphViz.Attributes.Complete as A
import qualified Data.GraphViz.Commands as G
import Data.List (dropWhileEnd, intercalate)
import qualified Data.Map as M
import Data.Maybe (isNothing)
import Data.Version (showVersion)
import Data.Yaml (FromJSON (..), (.:?))
import qualified Data.Yaml as Y
import Development.GitRev (gitHash)
import Paths_erd (version)
import qualified System.Console.GetOpt as O
import System.Directory (getHomeDirectory)
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.FilePath ((</>))
import System.IO (Handle, IOMode (..),
openFile, stderr, stdin,
stdout)
import System.IO.Error (isDoesNotExistError)
import Text.Printf (HPrintfType, hPrintf,
printf)
import Text.RawString.QQ
-- | Notation style for relations.
data Notation = UML | IE
deriving Show
-- | Config represents all information from command line flags.
data Config = Config
{ cin :: (String, Handle)
, cout :: (String, Handle)
, outfmt :: Maybe G.GraphvizOutput
, edgeType :: Maybe A.EdgeType
, configFile :: Maybe FilePath
, dotentity :: Maybe Bool
, edgePattern :: Maybe A.StyleName
, notation :: Maybe Notation
}
-- | Represents fields that are stored in the configuration file.
data ConfigFile = ConfigFile
{ cFmtOut :: Maybe String
, cEdgeType :: Maybe String
, cDotEntity :: Maybe Bool
, cEdgePattern :: Maybe String
, cNotation :: Maybe String
}
deriving Show
-- | A ConfigFile with all fields initialized with Nothing.
emptyConfigFile :: ConfigFile
emptyConfigFile = ConfigFile Nothing Nothing Nothing Nothing Nothing
instance FromJSON ConfigFile where
parseJSON (Y.Object v) =
ConfigFile <$>
v .:? "output-format" <*>
v .:? "edge-style" <*>
v .:? "dot-entity" <*>
v .:? "edge-pattern" <*>
v .:? "notation"
parseJSON Y.Null = return emptyConfigFile
parseJSON _ = fail "Incorrect configuration file."
defaultConfig :: Config
defaultConfig =
Config { cin = ("<stdin>", stdin)
, cout = ("<stdout>", stdout)
, outfmt = Nothing
, edgeType = Just A.SplineEdges
, configFile = Nothing
, dotentity = Just False
, edgePattern = Just A.Dashed
, notation = Just UML
}
defaultConfigFile :: B.ByteString
defaultConfigFile = B.unlines
[[r|# Erd (~/.erd.yaml) default configuration file.|],
B.append [r|output-format: pdf # Supported formats: |] (defVals fmts),
B.append [r|edge-style: spline # Supported values : |] (defVals edges),
B.append [r|dot-entity: false # Supported values : |] (defVals valBool),
B.append [r|edge-pattern: dashed # Supported values : |] (defVals edgePatterns),
B.append [r|notation: uml # Supported values : |] (defVals notations)
]
where
defVals = B.pack . unwords . M.keys
-- | Creates a new Config value from command line options.
-- If an output path is given and `--fmt` is omitted, then a format
-- will be inferred from the output path extension.
-- Failing all of that, PDF is used by default.
configIO :: IO Config
configIO = do
args <- getArgs
case O.getOpt O.Permute opts args of
(flags, [], []) -> do
conf <- foldl (\c app -> app c) (return defaultConfig) flags
let outpath = fst (cout conf)
return $
if isNothing (outfmt conf) && outpath /= "<stdout>" then
conf { outfmt = toGraphFmt $ takeExtension outpath }
else
conf
(_, _, errs@(_:_)) -> do
ef "Error(s) parsing flags:\n\t%s\n" $
intercalate "\n\t" $ map strip errs
exitFailure
(_, _, []) -> do
ef "erd does not have any positional arguments.\n\n"
usageExit
-- | Order of processing command-line options is important to keep priority of
-- configuration sources, in terms of increasing precedence.
-- 1. Command-line options
-- 2. Configuration file of arbitrary path, e.g. '-c"/tmp/myconfig.yaml"'
-- 3. Configuration file: ~/.erd.yaml
opts :: [O.OptDescr (IO Config -> IO Config)]
opts =
[ O.Option "c" ["config"]
(O.OptArg (\mf cIO -> cIO >>= \c -> do
globConfFile <- readGlobalConfigFile
f <- readConfigFile mf
case (f, globConfFile) of
(Nothing, Nothing) -> -- Config-file is desired, but unavailable.
B.putStr defaultConfigFile >> return c
(Nothing, Just x) -> -- Use global config-file from ~/.erd.yaml .
return $ toConfig x
(Just x, _) -> -- Use user specified config-file.
return $ toConfig x
) "FILE")
"Configuration file."
, O.Option "i" ["input"]
(O.ReqArg (\fpath cIO -> do
c <- cIO
i <- openFile fpath ReadMode
return $ c {cin = (fpath, i)}
)
"FILE")
("When set, input will be read from the given file.\n"
++ "Otherwise, stdin will be used.")
, O.Option "o" ["output"]
(O.ReqArg (\fpath cIO -> do
c <- cIO
o <- openFile fpath WriteMode
return $ c {cout = (fpath, o)}
)
"FILE")
("When set, output will be written to the given file.\n"
++ "Otherwise, stdout will be used.\n"
++ "If given and if --fmt is omitted, then the format will be\n"
++ "guessed from the file extension.")
, O.Option "h" ["help"]
(O.NoArg $ const usageExit)
"Show this usage message."
, O.Option "f" ["fmt"]
(O.ReqArg (\fmt cIO -> do
c <- cIO
let mfmt = toGraphFmt fmt
case mfmt of
Nothing -> do
ef "'%s' is not a valid output format.\n" fmt
exitFailure
Just gfmt -> return c {outfmt = Just gfmt}
)
"FMT")
(descriptionWithValuesList "Force the output format to one of" fmts)
, O.Option "e" ["edge"]
(O.ReqArg (\edge cIO -> do
c <- cIO
let edgeG = toEdgeG edge
case edgeG of
Nothing -> do
ef "'%s' is not a valid type of edge.\n" edge
exitFailure
Just x -> return c {edgeType = Just x}
)
"EDGE")
(descriptionWithValuesList "Select one type of edge" edges)
, O.Option "p" ["edge-pattern"]
(O.ReqArg (\epat cIO -> do
c <- cIO
case toEdgePattern epat of
Nothing -> do
ef "'%s' is not a valid type of edge pattern.\n" epat
exitFailure
Just x -> return c {edgePattern = Just x}
)
"PATTERN")
(descriptionWithValuesList "Select one of the edge patterns" edgePatterns)
, O.Option "n" ["notation"]
(O.ReqArg (\nt cIO -> do
c <- cIO
case toNotation nt of
Nothing -> do
ef "'%s' is not a valid notation style.\n" nt
exitFailure
Just x -> return c {notation = Just x}
)
"NOTATION")
(descriptionWithValuesList "Select one of the notation styles" notations)
, O.Option "d" ["dot-entity"]
(O.NoArg (\cIO -> do
c <- cIO
return $ c { dotentity = Just True } ))
("When set, output will consist of regular dot tables instead of HTML tables.\n"
++ "Formatting will be disabled. Use only for further manual configuration.")
, O.Option "v" ["version"]
(O.NoArg $ const erdVersion) "Shows version of application and revision code."
]
where
descriptionWithValuesList :: String -> M.Map String a -> String
descriptionWithValuesList txt m = printf (txt <> ":\n%s.") (intercalate ", " $ M.keys m)
toConfig :: ConfigFile -> Config
toConfig c = defaultConfig {outfmt = cFmtOut c >>= toGraphFmt,
edgeType = cEdgeType c >>= toEdgeG,
dotentity = cDotEntity c,
edgePattern = cEdgePattern c >>= toEdgePattern,
notation = cNotation c >>= toNotation}
-- | Reads and parses configuration file at default location: ~/.erd.yaml
readGlobalConfigFile :: IO (Maybe ConfigFile)
readGlobalConfigFile = do
mHome <- tryJust (guard . isDoesNotExistError) getHomeDirectory
case mHome of
Left _ -> return Nothing
Right home -> readConfigFile $ Just (home </> ".erd.yaml")
-- | Reads and parses a configuration file, exceptions may come via
-- AesonException.
readConfigFile :: Maybe FilePath -> IO (Maybe ConfigFile)
readConfigFile Nothing = return Nothing
readConfigFile (Just f) = do
mHome <- tryJust (guard . isDoesNotExistError) $ B.readFile f
case mHome of
Left _ -> return Nothing
Right home -> Y.decodeThrow home
-- | A subset of formats supported from GraphViz.
fmts :: M.Map String G.GraphvizOutput
fmts = M.fromList
[ ("pdf", G.Pdf)
, ("svg", G.Svg)
, ("eps", G.Eps)
, ("bmp", G.Bmp)
, ("jpg", G.Jpeg)
, ("png", G.Png)
, ("gif", G.Gif)
, ("tiff", G.Tiff)
, ("dot", G.Canon)
, ("ps", G.Ps)
, ("ps2", G.Ps2)
, ("plain", G.Plain)
]
edges :: M.Map String A.EdgeType
edges = M.fromList
[ ("spline", A.SplineEdges)
, ("ortho", A.Ortho)
, ("noedge", A.NoEdges)
, ("poly", A.PolyLine)
, ("compound", A.CompoundEdge)
]
valBool :: M.Map String Bool
valBool = M.fromList
[ ("true", True)
, ("false", False) ]
edgePatterns :: M.Map String A.StyleName
edgePatterns = M.fromList
[ ("solid", A.Solid)
, ("dashed", A.Dashed)
, ("dotted", A.Dotted)
]
notations :: M.Map String Notation
notations = M.fromList
[ ("uml", UML)
, ("ie", IE)
]
-- | takeExtension returns the last extension from a file path, or the
-- empty string if no extension was found. e.g., the extension of
-- "wat.pdf" is "pdf".
takeExtension :: String -> String
takeExtension s = if null rest then "" else reverse ext
where (ext, rest) = span (/= '.') $ reverse s
toGraphFmt :: String -> Maybe G.GraphvizOutput
toGraphFmt = (`M.lookup` fmts)
toEdgeG :: String -> Maybe A.EdgeType
toEdgeG = (`M.lookup` edges)
toEdgePattern :: String -> Maybe A.StyleName
toEdgePattern = (`M.lookup` edgePatterns)
toNotation :: String -> Maybe Notation
toNotation = (`M.lookup` notations)
usageExit :: IO a
usageExit = usage >> exitFailure
usage :: IO ()
usage = hPrintf stderr "%s\n" $ O.usageInfo "Usage: erd [flags]" opts
erdVersion :: IO a
erdVersion = do
hPrintf stdout "erd-%s %s\n" (showVersion version) ($(gitHash) :: String)
exitSuccess
ef :: HPrintfType r => String -> r
ef = hPrintf stderr
strip :: String -> String
strip = dropWhile isSpace . dropWhileEnd isSpace
|
BurntSushi/erd
|
src/Erd/Config.hs
|
unlicense
| 12,273
| 0
| 20
| 4,227
| 2,952
| 1,612
| 1,340
| 266
| 7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.