code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE CPP #-}
module CorePrelude
( -- * Standard
-- ** Operators
(Prelude.$)
, (Prelude.$!)
, (Prelude.&&)
, (Prelude.||)
, (Control.Category..)
-- ** Functions
, Prelude.not
, Prelude.otherwise
, Prelude.fst
, Prelude.snd
, Control.Category.id
, Prelude.maybe
, Prelude.either
, Prelude.flip
, Prelude.const
, Prelude.error
, putStr
, putStrLn
, print
, getArgs
, terror
, Prelude.odd
, Prelude.even
, Prelude.uncurry
, Prelude.curry
, Data.Tuple.swap
, Prelude.until
, Prelude.asTypeOf
, Prelude.undefined
, Prelude.seq
-- ** Type classes
, Prelude.Ord (..)
, Prelude.Eq (..)
, Prelude.Bounded (..)
, Prelude.Enum (..)
, Prelude.Show
, Prelude.Read
, Prelude.Functor (..)
, Prelude.Monad (..)
, (Control.Monad.=<<)
, Data.String.IsString (..)
-- ** Numeric type classes
, Prelude.Num (..)
, Prelude.Real (..)
, Prelude.Integral (..)
, Prelude.Fractional (..)
, Prelude.Floating (..)
, Prelude.RealFrac (..)
, Prelude.RealFloat(..)
-- ** Data types
, Prelude.Maybe (..)
, Prelude.Ordering (..)
, Prelude.Bool (..)
, Prelude.Char
, Prelude.IO
, Prelude.Either (..)
-- * Re-exports
-- ** Packed reps
, ByteString
, LByteString
, Text
, LText
-- ** Containers
, Map
, HashMap
, IntMap
, Set
, HashSet
, IntSet
, Seq
, Vector
, UVector
, Unbox
, SVector
, Data.Vector.Storable.Storable
, Hashable
-- ** Numbers
, Word
, Word8
, Word32
, Word64
, Prelude.Int
, Int32
, Int64
, Prelude.Integer
, Prelude.Rational
, Prelude.Float
, Prelude.Double
-- ** Numeric functions
, (Prelude.^)
, (Prelude.^^)
, Prelude.subtract
, Prelude.fromIntegral
, Prelude.realToFrac
-- ** Monoids
, Monoid (..)
, (<>)
-- ** Folds and traversals
, Data.Foldable.Foldable
, Data.Foldable.asum
, Data.Traversable.Traversable
-- ** arrow
, Control.Arrow.first
, Control.Arrow.second
, (Control.Arrow.***)
, (Control.Arrow.&&&)
-- ** Bool
, bool
-- ** Maybe
, Data.Maybe.mapMaybe
, Data.Maybe.catMaybes
, Data.Maybe.fromMaybe
, Data.Maybe.isJust
, Data.Maybe.isNothing
, Data.Maybe.listToMaybe
, Data.Maybe.maybeToList
-- ** Either
, Data.Either.partitionEithers
, Data.Either.lefts
, Data.Either.rights
-- ** Ord
, Data.Function.on
, Data.Ord.comparing
, equating
, GHC.Exts.Down (..)
-- ** Applicative
, Control.Applicative.Applicative (..)
, (Control.Applicative.<$>)
, (Control.Applicative.<|>)
-- ** Monad
, (Control.Monad.>=>)
-- ** Transformers
, Control.Monad.Trans.Class.lift
, Control.Monad.IO.Class.MonadIO
, Control.Monad.IO.Class.liftIO
-- ** Exceptions
, Control.Exception.Exception (..)
, Data.Typeable.Typeable (..)
, Control.Exception.SomeException
, Control.Exception.IOException
, module System.IO.Error
-- ** Files
, Prelude.FilePath
, (F.</>)
, (F.<.>)
-- ** Strings
, Prelude.String
-- ** Hashing
, hash
, hashWithSalt
) where
import qualified Prelude
import Prelude (Char, (.), Eq, Bool)
import Data.Hashable (Hashable, hash, hashWithSalt)
import Data.Vector.Unboxed (Unbox)
import Data.Monoid (Monoid (..))
import qualified Control.Arrow
import Control.Applicative
import qualified Control.Category
import qualified Control.Monad
import qualified Control.Exception
import qualified Data.Typeable
import qualified Data.Foldable
import qualified Data.Traversable
import Data.Word (Word8, Word32, Word64, Word)
import Data.Int (Int32, Int64)
import qualified Data.Text.IO
import qualified Data.Maybe
import qualified Data.Either
import qualified Data.Ord
import qualified Data.Function
import qualified Data.Tuple
import qualified Data.String
import qualified Control.Monad.Trans.Class
import qualified Control.Monad.IO.Class
import Control.Monad.IO.Class (MonadIO (liftIO))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy
import Data.Text (Text)
import qualified Data.Text.Lazy
import Data.Vector (Vector)
import qualified Data.Vector.Unboxed
import qualified Data.Vector.Storable
import Data.Map (Map)
import Data.Set (Set)
import Data.IntMap (IntMap)
import Data.IntSet (IntSet)
import Data.Sequence (Seq)
import Data.HashMap.Strict (HashMap)
import Data.HashSet (HashSet)
import qualified System.FilePath as F
import qualified System.Environment
import qualified Data.Text
import qualified Data.List
import System.IO.Error hiding (catch, try)
import qualified GHC.Exts
#if MIN_VERSION_base(4,7,0)
import Data.Bool (bool)
#endif
#if MIN_VERSION_base(4,5,0)
import Data.Monoid ((<>))
#endif
#if MIN_VERSION_base(4,9,0)
import GHC.Stack (HasCallStack)
#endif
type LText = Data.Text.Lazy.Text
type LByteString = Data.ByteString.Lazy.ByteString
type UVector = Data.Vector.Unboxed.Vector
type SVector = Data.Vector.Storable.Vector
#if !MIN_VERSION_base(4,7,0)
bool :: a -> a -> Bool -> a
bool f t b = if b then t else f
#endif
#if !MIN_VERSION_base(4,5,0)
infixr 6 <>
(<>) :: Monoid w => w -> w -> w
(<>) = mappend
{-# INLINE (<>) #-}
#endif
equating :: Eq a => (b -> a) -> b -> b -> Bool
equating = Data.Function.on (Prelude.==)
getArgs :: MonadIO m => m [Text]
getArgs = liftIO (Data.List.map Data.Text.pack <$> System.Environment.getArgs)
putStr :: MonadIO m => Text -> m ()
putStr = liftIO . Data.Text.IO.putStr
putStrLn :: MonadIO m => Text -> m ()
putStrLn = liftIO . Data.Text.IO.putStrLn
print :: (MonadIO m, Prelude.Show a) => a -> m ()
print = liftIO . Prelude.print
-- | @error@ applied to @Text@
--
-- Since 0.4.1
#if MIN_VERSION_base(4,9,0)
terror :: HasCallStack => Text -> a
#else
terror :: Text -> a
#endif
terror = Prelude.error . Data.Text.unpack
|
snoyberg/basic-prelude
|
src/CorePrelude.hs
|
Haskell
|
mit
| 6,110
|
flip f = \a b -> f b a
|
scravy/nodash
|
doc/Function/flip.hs
|
Haskell
|
mit
| 23
|
module Tools.Mill.Table where
import Data.ByteString
import Text.Parsec.Prim
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.ByteString (GenParser)
import qualified Data.ByteString.Char8 as C
import Control.Applicative ((<$>), (<*>), (*>), (<*))
type Colname = ByteString
type DataLine = ByteString
type Header = [Colname]
parseHeader :: GenParser Char st Header
parseHeader = (char '#' *> many1 colname)
where colname = C.pack <$> (spaces *> many1 (noneOf " "))
|
lucasdicioccio/mill
|
Tools/Mill/Table.hs
|
Haskell
|
mit
| 518
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.CmdItemSpec (main, spec) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>), (<*>))
#endif
import Test.Hspec
import Test.Hspec.Laws
import Test.QuickCheck
import Test.QuickCheck.Instances ()
import Data.CmdItem
spec :: Spec
spec = describe "CmdItem" $ shouldSatisfyMonoidLaws (undefined :: CmdItem)
main :: IO ()
main = hspec spec
instance Arbitrary CmdItem where
arbitrary = CmdItem <$> arbitrary <*> arbitrary
|
geraud/cmd-item
|
test/Data/CmdItemSpec.hs
|
Haskell
|
mit
| 551
|
module Barycenter where
barTriang :: (Double, Double) -> (Double, Double) -> (Double, Double) -> (Double, Double)
barTriang (a, b) (c, d) (e, f) = (x, y)
where
x = (a + c + e) / 3
y = (b + d + f) / 3
|
cojoj/Codewars
|
Haskell/Codewars.hsproj/Barycenter.hs
|
Haskell
|
mit
| 225
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html
module Stratosphere.Resources.ApiGatewayV2Integration where
import Stratosphere.ResourceImports
-- | Full data type definition for ApiGatewayV2Integration. See
-- 'apiGatewayV2Integration' for a more convenient constructor.
data ApiGatewayV2Integration =
ApiGatewayV2Integration
{ _apiGatewayV2IntegrationApiId :: Val Text
, _apiGatewayV2IntegrationConnectionType :: Maybe (Val Text)
, _apiGatewayV2IntegrationContentHandlingStrategy :: Maybe (Val Text)
, _apiGatewayV2IntegrationCredentialsArn :: Maybe (Val Text)
, _apiGatewayV2IntegrationDescription :: Maybe (Val Text)
, _apiGatewayV2IntegrationIntegrationMethod :: Maybe (Val Text)
, _apiGatewayV2IntegrationIntegrationType :: Val Text
, _apiGatewayV2IntegrationIntegrationUri :: Maybe (Val Text)
, _apiGatewayV2IntegrationPassthroughBehavior :: Maybe (Val Text)
, _apiGatewayV2IntegrationRequestParameters :: Maybe Object
, _apiGatewayV2IntegrationRequestTemplates :: Maybe Object
, _apiGatewayV2IntegrationTemplateSelectionExpression :: Maybe (Val Text)
, _apiGatewayV2IntegrationTimeoutInMillis :: Maybe (Val Integer)
} deriving (Show, Eq)
instance ToResourceProperties ApiGatewayV2Integration where
toResourceProperties ApiGatewayV2Integration{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ApiGatewayV2::Integration"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("ApiId",) . toJSON) _apiGatewayV2IntegrationApiId
, fmap (("ConnectionType",) . toJSON) _apiGatewayV2IntegrationConnectionType
, fmap (("ContentHandlingStrategy",) . toJSON) _apiGatewayV2IntegrationContentHandlingStrategy
, fmap (("CredentialsArn",) . toJSON) _apiGatewayV2IntegrationCredentialsArn
, fmap (("Description",) . toJSON) _apiGatewayV2IntegrationDescription
, fmap (("IntegrationMethod",) . toJSON) _apiGatewayV2IntegrationIntegrationMethod
, (Just . ("IntegrationType",) . toJSON) _apiGatewayV2IntegrationIntegrationType
, fmap (("IntegrationUri",) . toJSON) _apiGatewayV2IntegrationIntegrationUri
, fmap (("PassthroughBehavior",) . toJSON) _apiGatewayV2IntegrationPassthroughBehavior
, fmap (("RequestParameters",) . toJSON) _apiGatewayV2IntegrationRequestParameters
, fmap (("RequestTemplates",) . toJSON) _apiGatewayV2IntegrationRequestTemplates
, fmap (("TemplateSelectionExpression",) . toJSON) _apiGatewayV2IntegrationTemplateSelectionExpression
, fmap (("TimeoutInMillis",) . toJSON) _apiGatewayV2IntegrationTimeoutInMillis
]
}
-- | Constructor for 'ApiGatewayV2Integration' containing required fields as
-- arguments.
apiGatewayV2Integration
:: Val Text -- ^ 'agviApiId'
-> Val Text -- ^ 'agviIntegrationType'
-> ApiGatewayV2Integration
apiGatewayV2Integration apiIdarg integrationTypearg =
ApiGatewayV2Integration
{ _apiGatewayV2IntegrationApiId = apiIdarg
, _apiGatewayV2IntegrationConnectionType = Nothing
, _apiGatewayV2IntegrationContentHandlingStrategy = Nothing
, _apiGatewayV2IntegrationCredentialsArn = Nothing
, _apiGatewayV2IntegrationDescription = Nothing
, _apiGatewayV2IntegrationIntegrationMethod = Nothing
, _apiGatewayV2IntegrationIntegrationType = integrationTypearg
, _apiGatewayV2IntegrationIntegrationUri = Nothing
, _apiGatewayV2IntegrationPassthroughBehavior = Nothing
, _apiGatewayV2IntegrationRequestParameters = Nothing
, _apiGatewayV2IntegrationRequestTemplates = Nothing
, _apiGatewayV2IntegrationTemplateSelectionExpression = Nothing
, _apiGatewayV2IntegrationTimeoutInMillis = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-apiid
agviApiId :: Lens' ApiGatewayV2Integration (Val Text)
agviApiId = lens _apiGatewayV2IntegrationApiId (\s a -> s { _apiGatewayV2IntegrationApiId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-connectiontype
agviConnectionType :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviConnectionType = lens _apiGatewayV2IntegrationConnectionType (\s a -> s { _apiGatewayV2IntegrationConnectionType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-contenthandlingstrategy
agviContentHandlingStrategy :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviContentHandlingStrategy = lens _apiGatewayV2IntegrationContentHandlingStrategy (\s a -> s { _apiGatewayV2IntegrationContentHandlingStrategy = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-credentialsarn
agviCredentialsArn :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviCredentialsArn = lens _apiGatewayV2IntegrationCredentialsArn (\s a -> s { _apiGatewayV2IntegrationCredentialsArn = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-description
agviDescription :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviDescription = lens _apiGatewayV2IntegrationDescription (\s a -> s { _apiGatewayV2IntegrationDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-integrationmethod
agviIntegrationMethod :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviIntegrationMethod = lens _apiGatewayV2IntegrationIntegrationMethod (\s a -> s { _apiGatewayV2IntegrationIntegrationMethod = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-integrationtype
agviIntegrationType :: Lens' ApiGatewayV2Integration (Val Text)
agviIntegrationType = lens _apiGatewayV2IntegrationIntegrationType (\s a -> s { _apiGatewayV2IntegrationIntegrationType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-integrationuri
agviIntegrationUri :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviIntegrationUri = lens _apiGatewayV2IntegrationIntegrationUri (\s a -> s { _apiGatewayV2IntegrationIntegrationUri = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-passthroughbehavior
agviPassthroughBehavior :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviPassthroughBehavior = lens _apiGatewayV2IntegrationPassthroughBehavior (\s a -> s { _apiGatewayV2IntegrationPassthroughBehavior = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-requestparameters
agviRequestParameters :: Lens' ApiGatewayV2Integration (Maybe Object)
agviRequestParameters = lens _apiGatewayV2IntegrationRequestParameters (\s a -> s { _apiGatewayV2IntegrationRequestParameters = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-requesttemplates
agviRequestTemplates :: Lens' ApiGatewayV2Integration (Maybe Object)
agviRequestTemplates = lens _apiGatewayV2IntegrationRequestTemplates (\s a -> s { _apiGatewayV2IntegrationRequestTemplates = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-templateselectionexpression
agviTemplateSelectionExpression :: Lens' ApiGatewayV2Integration (Maybe (Val Text))
agviTemplateSelectionExpression = lens _apiGatewayV2IntegrationTemplateSelectionExpression (\s a -> s { _apiGatewayV2IntegrationTemplateSelectionExpression = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html#cfn-apigatewayv2-integration-timeoutinmillis
agviTimeoutInMillis :: Lens' ApiGatewayV2Integration (Maybe (Val Integer))
agviTimeoutInMillis = lens _apiGatewayV2IntegrationTimeoutInMillis (\s a -> s { _apiGatewayV2IntegrationTimeoutInMillis = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/Resources/ApiGatewayV2Integration.hs
|
Haskell
|
mit
| 8,500
|
module Problem047 where
import Data.List
main =
print $ head $ dropWhile (not . c) [1..]
where c x = all (== 4) $ map (nods !!) $ map (+ x) [0..3]
nods = map (length . nub . divisors) [0..]
divisors 0 = []
divisors 1 = []
divisors x = divisors' primes [] x
where divisors' _ ds 1 = ds
divisors' (p:ps) ds x
| r == 0 = divisors' (p:ps) (p:ds) q
| otherwise = divisors' ps ds x
where (q, r) = x `quotRem` p
isPrime = primeF primes
primes = 2 : 3 : filter (primeF primes) [5, 7 ..]
primeF (p:ps) x = p * p > x || x `rem` p /= 0 && primeF ps x
|
vasily-kartashov/playground
|
euler/problem-047.hs
|
Haskell
|
apache-2.0
| 593
|
{-# LANGUAGE OverloadedStrings #-}
module Model.Service where
import Control.Applicative
import Control.Monad
import Data.Aeson
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as C
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.Text (Text)
import Data.Word (Word16)
import Database.CouchDB.Conduit (Revision)
import Network.HTTP.Types.Method (Method)
import Model.URI
import Model.UUID
type Params = Map ByteString [ByteString]
data Service = Service {
uuid :: UUID,
revision :: Revision,
description :: Text,
host :: ByteString,
port :: Word16,
path :: ByteString,
methods :: [Method],
params :: Params
} deriving (Eq, Show)
url :: Service -> URI
url s = fromJust . parseURI . C.unpack $ C.concat
["http://", host s, ":", C.pack . show $ port s, if C.null $ path s
then ""
else '/' `C.cons` path s]
instance FromJSON Service where
parseJSON (Object v) =
Service <$> v .: "_id"
<*> v .: "_rev"
<*> v .: "description"
<*> v .: "host"
<*> v .: "port"
<*> v .: "path"
<*> v .: "methods"
<*> v .: "params"
parseJSON _ = mzero
instance ToJSON Service where
toJSON (Service _ _ d h p pa m par) =
object [ "type" .= ("service" :: ByteString)
, "description" .= d
, "host" .= h
, "port" .= p
, "path" .= pa
, "methods" .= m
, "params" .= par
]
|
alexandrelucchesi/pfec
|
server-common/src/Model/Service.hs
|
Haskell
|
apache-2.0
| 2,064
|
{-# LANGUAGE TemplateHaskell #-}
import HMSTimeSpec
import FFMpegCommandSpec
main :: IO ()
main =
do runHMSTimeSpecTests
runFFMpegCommandTests
return ()
|
connrs/ffsplitgen
|
out/production/ffsplitgen/test/Spec.hs
|
Haskell
|
apache-2.0
| 167
|
import Data.Char
ans :: String -> String
ans [] = []
ans (c:cs)
| isUpper c = (toLower c):(ans cs)
| isLower c = (toUpper c):(ans cs)
| otherwise = c:(ans cs)
main = do
c <- getContents
let i = lines c
o = map ans i
mapM_ putStrLn o
|
a143753/AOJ
|
ITP1_8_A.hs
|
Haskell
|
apache-2.0
| 259
|
{-# LANGUAGE TupleSections, OverloadedStrings, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Handler.Asset where
import Import
import qualified Data.Text
import Database.Persist.GenericSql
import Handler.Utils
import Handler.Rent (assetRentFormWidgetM)
import Handler.Review (reviewForm)
import Handler.File (deleteFile)
-- assets
assetAForm :: (Maybe Asset) -> [(Text,AssetId)] -> AForm App App Asset
assetAForm proto otherAssets = Asset
<$> areq textField "Name" (fmap assetName proto)
<*> areq textareaField "Description" (fmap assetDescription proto)
<*> areq (selectFieldList kinds) "Kind" (fmap assetKind proto)
<*> aopt (selectFieldList otherAssets) "Next asset" (fmap assetNext proto)
where
kinds :: [(Text,AssetKind)]
kinds = [("music",AssetMusic),("book",AssetBook),("movie",AssetMovie)]
assetForm :: Maybe Asset -> [(Text,AssetId)] -> Html -> MForm App App (FormResult Asset, Widget)
assetForm proto other = renderTable $ assetAForm proto other
-----
assetRentedWidget :: AssetId -> Handler Widget
assetRentedWidget aid = do
-- rentals <- runDB $ selectList [RentWhat ==. aid] [Asc RentId]
role <- getThisUserRole
let getThisUserId = do
mu <- maybeAuth
case mu of
Nothing -> return (const False)
Just user -> return (\uid -> uid == entityKey user)
checkSelf <- getThisUserId
let isAdmin = role [AdminRole]
canAuthorize = role [AdminRole, ResidentRole]
canUserSee uid = checkSelf uid || role [AdminRole, ResidentRole]
-- isAdmin
let query = Data.Text.concat [
"SELECT DISTINCT ??, ??, ",
" CASE ",
" WHEN rent.authorized_by IS NULL THEN NULL ",
" ELSE u2.ident END ",
" FROM rent, ",
" public.user, ",
" public.user as u2 ",
" WHERE rent.what = ? ",
" AND rent.taken_by = public.user.id ",
" AND (rent.authorized_by = u2.id OR rent.authorized_by IS NULL) ",
" ORDER BY rent.id "]
query' = "SELECT DISTINCT ??,??,NULL FROM rent, public.user WHERE what = ?"
results' <- runDB (do
ret <- rawSql query [unKey aid]
return (ret :: [(Entity Rent, Entity User, Single (Maybe Text))]))
let results = map (\ (a,b,Single c) -> (a,b,c)) results'
return $(widgetFile "asset/rented-widget")
----
getAssetViewR :: AssetId -> Handler RepHtml
getAssetViewR aid = do
asset :: Asset <- runDB $ get404 aid
displayUserWidget <- mkDisplayUserWidget
grpElems :: [Entity AssetGroupElement] <- runDB $ selectList [AssetGroupElementAsset ==. aid] [Desc AssetGroupElementAsset]
let agrpIds = map (assetGroupElementGroup . entityVal) grpElems
assetGroupsAll :: [Entity AssetGroup] <- runDB $ selectList [] [Desc AssetGroupId]
reviews :: [Entity Review] <- runDB $ selectList [ReviewWhat ==. aid] [Desc ReviewId]
files :: [Entity File] <- runDB $ selectList [FileAsset ==. aid] [Desc FileId]
let assetGroupsNot = filter (\ ent -> not ((entityKey ent) `elem` agrpIds)) assetGroupsAll
assetGroupsIn = filter (\ ent -> ((entityKey ent) `elem` agrpIds)) assetGroupsAll
rentedWidget <- assetRentedWidget aid
rentWidget <- assetRentFormWidgetM aid
let mkRevForm (Just user) = fmap Just (generateFormPost (renderTable (reviewForm (entityKey user) aid)))
mkRevForm Nothing = return Nothing
m'form'review <- mkRevForm =<< maybeAuth
thisUserRole <- getThisUserRole
let canModifyGroups = thisUserRole [AdminRole, ResidentRole, FriendRole]
canPostReviews = thisUserRole [AdminRole, ResidentRole, FriendRole, GuestRole]
canDelReviews = thisUserRole [AdminRole]
canUploadFiles = thisUserRole [AdminRole, ResidentRole, FriendRole]
canDeleteFiles = thisUserRole [AdminRole]
canDeleteAsset = thisUserRole [AdminRole]
defaultLayout $ do
setTitle $ toHtml $ "Asset " ++ show (assetName asset)
$(widgetFile "asset/view")
prepareAssetsToList assets = map (\a -> (formatAsset a, entityKey a)) assets
formatAsset a = Data.Text.concat [assetName (entityVal a), "(id=", (Data.Text.pack . showPeristentKey . unKey . entityKey $ a) , ")"]
getAssetAllGeneric title filter'lst = do
assets :: [Entity Asset] <- runDB $ selectList filter'lst [Asc AssetId]
(fwidget, enctype) <- generateFormPost (assetForm Nothing $ prepareAssetsToList assets)
thisUserRole <- getThisUserRole
let auth = thisUserRole [AdminRole, ResidentRole]
defaultLayout $ do
setTitle title
$(widgetFile "asset/all-view")
getAssetAllMusicR :: Handler RepHtml
getAssetAllMusicR = getAssetAllGeneric "A list of all music assets." [AssetKind ==. AssetMusic]
getAssetAllMoviesR :: Handler RepHtml
getAssetAllMoviesR = getAssetAllGeneric "A list of all movie assets." [AssetKind ==. AssetMovie]
getAssetAllBooksR :: Handler RepHtml
getAssetAllBooksR = getAssetAllGeneric "A list of all book assets." [AssetKind ==. AssetBook]
getAssetAllR :: Handler RepHtml
getAssetAllR = getAssetAllGeneric "A list of all assets." []
getAssetNewR :: Handler RepHtml
getAssetNewR = do
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
(fwidget, enctype) <- generateFormPost (assetForm Nothing $ prepareAssetsToList assets)
defaultLayout $ do
setTitle "A new asset."
$(widgetFile "asset/new")
postAssetNewR :: Handler RepHtml
postAssetNewR = do
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
((result, fwidget), enctype) <- runFormPost (assetForm Nothing $ prepareAssetsToList assets)
case result of
FormSuccess asset -> do
aid <- runDB $ insert asset
redirect (AssetViewR aid)
_ -> defaultLayout $ do
setTitle "A new asset."
$(widgetFile "asset/new")
getAssetEditR :: AssetId -> Handler RepHtml
getAssetEditR aid = do
asset <- runDB $ get404 aid
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
(fwidget, enctype) <- generateFormPost (assetForm (Just asset) $ prepareAssetsToList assets)
defaultLayout $ do
setTitle "Edit existing asset."
$(widgetFile "asset/edit")
postAssetEditR ::AssetId -> Handler RepHtml
postAssetEditR aid = do
asset :: Asset <- runDB $ get404 aid
assets :: [Entity Asset] <- runDB $ selectList [] [Asc AssetId]
((result, fwidget), enctype) <- runFormPost (assetForm (Just asset) $ prepareAssetsToList assets)
case result of
FormSuccess asset'new -> do
runDB $ replace aid asset'new
redirect (AssetViewR aid)
_ -> defaultLayout $ do
setTitle "Edit existing asset."
$(widgetFile "asset/edit")
assetDeleteForm = renderTable (const <$> areq areYouSureField "Are you sure?" (Just False))
where areYouSureField = check isSure boolField
isSure False = Left ("You must be sure to delete an asset" :: Text)
isSure True = Right True
getAssetDeleteR ::AssetId -> Handler RepHtml
getAssetDeleteR aid = do
asset :: Asset <- runDB $ get404 aid
(fwidget, enctype) <- generateFormPost assetDeleteForm
defaultLayout $ do
setTitle "Deleting an asset."
$(widgetFile "asset/delete")
postAssetDeleteR ::AssetId -> Handler RepHtml
postAssetDeleteR aid = do
asset :: Asset <- runDB $ get404 aid
((result,fwidget), enctype) <- runFormPost assetDeleteForm
case result of
FormSuccess _ -> do
files <- runDB $ selectList [FileAsset ==. aid] []
mapM_ deleteFile files
runDB $ do
deleteWhere [AssetGroupElementAsset ==. aid]
deleteWhere [RentWhat ==. aid]
deleteWhere [ReviewWhat ==. aid]
delete aid
defaultLayout [whamlet|
<p> <strong>Asset deleted.</strong> |]
_ -> defaultLayout $ do
setTitle "Deleting an asset."
$(widgetFile "asset/delete")
|
Tener/personal-library-yesod
|
Handler/Asset.hs
|
Haskell
|
bsd-2-clause
| 8,574
|
{-# LANGUAGE CPP, DeriveDataTypeable, MagicHash, UnboxedTuples #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM.TMVar
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- TMVar: Transactional MVars, for use in the STM monad
-- (GHC only)
--
-----------------------------------------------------------------------------
module Control.Concurrent.STM.TMVar (
#ifdef __GLASGOW_HASKELL__
-- * TMVars
TMVar,
newTMVar,
newEmptyTMVar,
newTMVarIO,
newEmptyTMVarIO,
takeTMVar,
putTMVar,
readTMVar,
tryReadTMVar,
swapTMVar,
tryTakeTMVar,
tryPutTMVar,
isEmptyTMVar,
mkWeakTMVar
#endif
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Conc
import GHC.Weak
import Data.Typeable (Typeable)
newtype TMVar a = TMVar (TVar (Maybe a)) deriving (Eq, Typeable)
{- ^
A 'TMVar' is a synchronising variable, used
for communication between concurrent threads. It can be thought of
as a box, which may be empty or full.
-}
-- |Create a 'TMVar' which contains the supplied value.
newTMVar :: a -> STM (TMVar a)
newTMVar a = do
t <- newTVar (Just a)
return (TMVar t)
-- |@IO@ version of 'newTMVar'. This is useful for creating top-level
-- 'TMVar's using 'System.IO.Unsafe.unsafePerformIO', because using
-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
-- possible.
newTMVarIO :: a -> IO (TMVar a)
newTMVarIO a = do
t <- newTVarIO (Just a)
return (TMVar t)
-- |Create a 'TMVar' which is initially empty.
newEmptyTMVar :: STM (TMVar a)
newEmptyTMVar = do
t <- newTVar Nothing
return (TMVar t)
-- |@IO@ version of 'newEmptyTMVar'. This is useful for creating top-level
-- 'TMVar's using 'System.IO.Unsafe.unsafePerformIO', because using
-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
-- possible.
newEmptyTMVarIO :: IO (TMVar a)
newEmptyTMVarIO = do
t <- newTVarIO Nothing
return (TMVar t)
-- |Return the contents of the 'TMVar'. If the 'TMVar' is currently
-- empty, the transaction will 'retry'. After a 'takeTMVar',
-- the 'TMVar' is left empty.
takeTMVar :: TMVar a -> STM a
takeTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> retry
Just a -> do writeTVar t Nothing; return a
-- | A version of 'takeTMVar' that does not 'retry'. The 'tryTakeTMVar'
-- function returns 'Nothing' if the 'TMVar' was empty, or @'Just' a@ if
-- the 'TMVar' was full with contents @a@. After 'tryTakeTMVar', the
-- 'TMVar' is left empty.
tryTakeTMVar :: TMVar a -> STM (Maybe a)
tryTakeTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> return Nothing
Just a -> do writeTVar t Nothing; return (Just a)
-- |Put a value into a 'TMVar'. If the 'TMVar' is currently full,
-- 'putTMVar' will 'retry'.
putTMVar :: TMVar a -> a -> STM ()
putTMVar (TMVar t) a = do
m <- readTVar t
case m of
Nothing -> do writeTVar t (Just a); return ()
Just _ -> retry
-- | A version of 'putTMVar' that does not 'retry'. The 'tryPutTMVar'
-- function attempts to put the value @a@ into the 'TMVar', returning
-- 'True' if it was successful, or 'False' otherwise.
tryPutTMVar :: TMVar a -> a -> STM Bool
tryPutTMVar (TMVar t) a = do
m <- readTVar t
case m of
Nothing -> do writeTVar t (Just a); return True
Just _ -> return False
-- | This is a combination of 'takeTMVar' and 'putTMVar'; ie. it
-- takes the value from the 'TMVar', puts it back, and also returns
-- it.
readTMVar :: TMVar a -> STM a
readTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> retry
Just a -> return a
-- | A version of 'readTMVar' which does not retry. Instead it
-- returns @Nothing@ if no value is available.
tryReadTMVar :: TMVar a -> STM (Maybe a)
tryReadTMVar (TMVar t) = readTVar t
-- |Swap the contents of a 'TMVar' for a new value.
swapTMVar :: TMVar a -> a -> STM a
swapTMVar (TMVar t) new = do
m <- readTVar t
case m of
Nothing -> retry
Just old -> do writeTVar t (Just new); return old
-- |Check whether a given 'TMVar' is empty.
isEmptyTMVar :: TMVar a -> STM Bool
isEmptyTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> return True
Just _ -> return False
-- | Make a 'Weak' pointer to a 'TMVar', using the second argument as
-- a finalizer to run when the 'TMVar' is garbage-collected.
--
-- @since 2.4.4
mkWeakTMVar :: TMVar a -> IO () -> IO (Weak (TMVar a))
mkWeakTMVar tmv@(TMVar (TVar t#)) (IO finalizer) = IO $ \s ->
case mkWeak# t# tmv finalizer s of (# s1, w #) -> (# s1, Weak w #)
#endif
|
gridaphobe/packages-stm
|
Control/Concurrent/STM/TMVar.hs
|
Haskell
|
bsd-3-clause
| 4,893
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Chat.Internal.Types where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Data.Aeson
import qualified Data.Aeson.Types as A
import Data.ByteString (ByteString)
import Data.Data
import qualified Data.HashTable.IO as HT
import qualified Data.HashMap.Strict as Map
import Data.Monoid
import Data.Text (Text)
import System.Posix.Types
------------------------------------------------------------------------------
import System.TimeoutManager (TimeoutManager, TimeoutHandle)
------------------------------------------------------------------------------
type UserName = Text
------------------------------------------------------------------------------
data MessageContents = Talk { _messageText :: !Text }
| Action { _messageText :: !Text }
| Join
| Leave { _messageText :: !Text }
deriving (Show, Eq)
instance FromJSON MessageContents where
parseJSON (Object obj) = do
ty <- (obj .: "type") :: A.Parser Text
case ty of
"talk" -> Talk <$>
obj .: "text"
"action" -> Action <$>
obj .: "text"
"join" -> pure Join
"leave" -> Leave <$>
obj .: "text"
_ -> fail "bad type"
parseJSON _ = fail "MessageContents: JSON object of wrong type"
------------------------------------------------------------------------------
instance ToJSON MessageContents where
toJSON (Talk t) =
Object $ Map.fromList [ ("type", toJSON ("talk"::Text))
, ("text", toJSON t )
]
toJSON (Action t) =
Object $ Map.fromList [ ("type", toJSON ("action"::Text))
, ("text", toJSON t )
]
toJSON (Join) =
Object $ Map.fromList [ ("type", toJSON ("join"::Text))
]
toJSON (Leave t) =
Object $ Map.fromList [ ("type", toJSON ("leave"::Text))
, ("text", toJSON t )
]
------------------------------------------------------------------------------
data Message = Message {
_messageUser :: !UserName
, _messageTime :: !EpochTime
, _messageContents :: !MessageContents
}
deriving (Show, Eq)
------------------------------------------------------------------------------
getMessageUserName :: Message -> UserName
getMessageUserName = _messageUser
getMessageTime :: Message -> EpochTime
getMessageTime = _messageTime
getMessageContents :: Message -> MessageContents
getMessageContents = _messageContents
------------------------------------------------------------------------------
instance FromJSON Message where
parseJSON (Object obj) =
Message <$>
obj .: "user" <*>
(toEnum <$> obj .: "time") <*>
obj .: "contents"
parseJSON _ = fail "Message: JSON object of wrong type"
instance ToJSON Message where
toJSON (Message u t c) =
Object $ Map.fromList [ ("user" , toJSON u )
, ("time" , toJSON $ fromEnum t)
, ("contents", toJSON c ) ]
------------------------------------------------------------------------------
newtype UserToken = UserToken ByteString
deriving (Show, Eq, Data, Ord, Typeable, Monoid, FromJSON, ToJSON)
------------------------------------------------------------------------------
data User = User {
_userName :: !UserName
, _userMsgChan :: !(TChan Message)
, _userToken :: !UserToken
, _timeoutHandle :: !TimeoutHandle
}
------------------------------------------------------------------------------
getUserName :: User -> UserName
getUserName = _userName
------------------------------------------------------------------------------
getUserToken :: User -> UserToken
getUserToken = _userToken
------------------------------------------------------------------------------
type HashTable k v = HT.CuckooHashTable k v
------------------------------------------------------------------------------
data ChatRoom = ChatRoom {
_timeoutManager :: !TimeoutManager
, _userMap :: !(MVar (HashTable UserName User))
, _chatChannel :: !(TChan Message)
, _userTimeout :: !Int -- ^ how long users can remain
-- inactive
}
|
snapframework/cufp2011
|
sample-implementation/Snap/Chat/Internal/Types.hs
|
Haskell
|
bsd-3-clause
| 4,997
|
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -Wall -fno-warn-orphans -fno-warn-type-defaults #-}
-- | Orphan 'FromJSON' and 'ToJSON' instances for certain Cryptol
-- types. Since these are meant to be consumed over a wire, they are
-- mostly focused on base values and interfaces rather than a full
-- serialization of internal ASTs and such.
module Cryptol.Aeson where
import Control.Applicative
import Control.Exception
import Data.Aeson
import Data.Aeson.TH
import qualified Data.HashMap.Strict as HM
import Data.List
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Cryptol.Eval.Error as E
import qualified Cryptol.Eval.Value as E
import qualified Cryptol.ModuleSystem as M
import qualified Cryptol.ModuleSystem.Monad as M
import qualified Cryptol.ModuleSystem.Renamer as M
import Cryptol.ModuleSystem.Interface
import Cryptol.ModuleSystem.Name
import qualified Cryptol.Parser as P
import qualified Cryptol.Parser.AST as P
import qualified Cryptol.Parser.Lexer as P
import qualified Cryptol.Parser.NoInclude as P
import qualified Cryptol.Parser.NoPat as NoPat
import qualified Cryptol.Parser.Position as P
import Cryptol.REPL.Monad
import qualified Cryptol.TypeCheck.AST as T
import qualified Cryptol.TypeCheck.InferTypes as T
import Cryptol.Utils.PP hiding (empty)
instance FromJSON a => FromJSON (Map QName a) where
parseJSON = withObject "QName map" $ \o -> do
let (ks, vs) = unzip (HM.toList o)
ks' = map keyToQName ks
vs' <- mapM parseJSON vs
return (Map.fromList (zip ks' vs'))
instance ToJSON a => ToJSON (Map QName a) where
toJSON m = Object (HM.fromList (zip ks' vs'))
where (ks, vs) = unzip (Map.toList m)
ks' = map keyFromQName ks
vs' = map toJSON vs
-- | Assume that a 'QName' contains only an optional 'ModName' and a
-- 'Name', rather than a 'NewName'. This should be safe for the
-- purposes of this API where we're dealing with top-level names.
keyToQName :: Text -> QName
keyToQName str =
case map T.unpack (T.split (== '.') str) of
[] -> error "empty QName"
[""] -> error "empty QName"
[x] -> mkUnqual (Name x)
xs -> mkQual (ModName (init xs)) (Name (last xs))
keyFromQName :: QName -> Text
keyFromQName = \case
QName Nothing (Name x) -> T.pack x
QName (Just (ModName mn)) (Name x) ->
T.pack (intercalate "." (mn ++ [x]))
_ -> error "NewName unsupported in JSON"
instance ToJSON Doc where
toJSON = String . T.pack . render
instance ToJSON E.Value where
toJSON = \case
E.VRecord fs -> object
[ "record" .= fs ]
E.VTuple vs -> object
[ "tuple" .= vs ]
E.VBit b -> object
[ "bit" .= b ]
E.VSeq isWord xs -> object
[ "sequence" .= object [ "isWord" .= isWord, "elements" .= xs ] ]
E.VWord w -> object
[ "word" .= w ]
E.VStream _ -> object
[ "stream" .= object [ "@note" .= "streams not supported" ] ]
E.VFun _ -> object
[ "function" .= object [ "@note" .= "functions not supported" ] ]
E.VPoly _ -> object
[ "poly" .= object [ "@note" .= "polymorphic values not supported" ] ]
instance FromJSON E.Value where
parseJSON = withObject "Value" $ \o ->
E.VRecord <$> o .: "record"
<|> E.VTuple <$> o .: "tuple"
<|> E.VBit <$> o .: "bit"
<|> do s <- o .: "sequence"
E.VSeq <$> s .: "isWord" <*> s .: "elements"
<|> E.VWord <$> o .: "word"
<|> error ("unexpected JSON value: " ++ show o)
instance ToJSON P.Token where
toJSON = toJSON . pp
instance ToJSON IOException where
toJSON exn = object
[ "IOException" .= show exn ]
instance ToJSON M.RenamerError where
toJSON err = object
[ "renamerError" .= pp err ]
instance ToJSON T.Error where
toJSON err = object
[ "inferError" .= pp err ]
instance ToJSON E.BV where
toJSON = \case
E.BV w v -> object
[ "bitvector" .= object [ "width" .= w, "value" .= v ] ]
instance FromJSON E.BV where
parseJSON = withObject "BV" $ \o -> do
bv <- o .: "bitvector"
E.BV <$> bv .: "width" <*> bv .: "value"
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''REPLException)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''NameEnv)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''NameInfo)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''E.EvalError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.ParseError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Position)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Range)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Located)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.IncludeError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Schema)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Type)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.TParam)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Prop)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Named)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''P.Kind)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''NoPat.Error)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''M.ModuleError)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''M.ImportSource)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Import)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.ImportSpec)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Type)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TParam)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Kind)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TVar)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TCon)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.PC)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TC)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.UserTC)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Schema)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TFun)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Selector)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } { fieldLabelModifier = drop 1 } ''T.Fixity)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Pragma)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Assoc)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''QName)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''ModName)
$(deriveJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Name)
$(deriveJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Pass)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''IfaceDecl)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.Newtype)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''T.TySyn)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''IfaceDecls)
$(deriveToJSON defaultOptions { sumEncoding = ObjectWithSingleField } ''Iface)
|
ntc2/cryptol
|
cryptol-server/Cryptol/Aeson.hs
|
Haskell
|
bsd-3-clause
| 7,781
|
{-# LANGUAGE PackageImports ,FlexibleInstances ,MultiParamTypeClasses#-}
module PkgCereal(PkgCereal(..),Data.Serialize.Serialize,sd) where
import Control.Exception
import Types hiding (Serialize)
import qualified Types as T
import Test.Data
import Test.Data.Values
import qualified Data.ByteString.Lazy as L
import "cereal" Data.Serialize
import Data.ByteString as B
data PkgCereal a = PkgCereal a deriving (Eq,Show)
instance Arbitrary a => Arbitrary (PkgCereal a) where arbitrary = fmap PkgCereal arbitrary
sd = ("cereal","cereal",serializeF,deserializeF)
serializeF = L.fromStrict . encode
deserializeF = either (Left . error . show) Right . decode . L.toStrict
{-
instance Serialize a => T.Serialize (PkgCereal a) where
serialize (PkgCereal a) = encodeLazy a
-- deserialize = either (Left . error . show) (\(_,_,v) -> Right $ PkgCereal v) . Binary.decodeOrFail
deserialize = either (Left . error) (Right . PkgCereal) . decodeLazy
-}
instance Serialize a => T.Serialize PkgCereal a where
serialize (PkgCereal a) = encodeLazy a
deserialize = either (Left . error) (Right . PkgCereal) . decodeLazy
pkg = PkgCereal
unpkg (PkgCereal a) = a
-- Tests
t = ser $ PkgCereal tree1
-- x = Prelude.putStrLn $ derive (undefined :: Engine)
{-
benchmarking serialize/deserialise/tree1
mean: 5.103695 us, lb 4.868698 us, ub 5.414622 us, ci 0.950
std dev: 1.373780 us, lb 1.141381 us, ub 1.700686 us, ci 0.950
found 18 outliers among 100 samples (18.0%)
5 (5.0%) high mild
13 (13.0%) high severe
variance introduced by outliers: 96.797%
variance is severely inflated by outliers
benchmarking serialize/deserialise/tree2
mean: 1.136065 us, lb 1.120947 us, ub 1.159394 us, ci 0.950
std dev: 95.01065 ns, lb 68.06466 ns, ub 137.1691 ns, ci 0.950
found 7 outliers among 100 samples (7.0%)
3 (3.0%) high mild
4 (4.0%) high severe
variance introduced by outliers: 72.777%
variance is severely inflated by outliers
benchmarking serialize/deserialise/car1
mean: 15.31410 us, lb 15.21677 us, ub 15.52387 us, ci 0.950
std dev: 699.8115 ns, lb 403.9063 ns, ub 1.387295 us, ci 0.950
found 4 outliers among 100 samples (4.0%)
3 (3.0%) high mild
1 (1.0%) high severe
variance introduced by outliers: 43.485%
variance is moderately inflated by outliers
-}
instance Serialize Car
instance Serialize Acceleration
instance Serialize Consumption
instance Serialize CarModel
instance Serialize OptionalExtra
instance Serialize Engine
instance Serialize Various
instance Serialize N
instance {-# OVERLAPPABLE #-} Serialize a => Serialize (List a)
instance {-# OVERLAPPABLE #-} Serialize a => Serialize (Tree a)
instance {-# OVERLAPPING #-} Serialize (Tree N)
instance {-# OVERLAPPING #-} Serialize (Tree (N,N,N))
instance {-# OVERLAPPING #-} Serialize [N]
instance {-# OVERLAPPING #-} Serialize (N,N,N)
-- !! Apparently Generics based derivation is as fast as hand written one.
{-
benchmarking serialize/deserialise/tree1
mean: 4.551243 us, lb 4.484404 us, ub 4.680212 us, ci 0.950
std dev: 459.9530 ns, lb 260.7037 ns, ub 704.4624 ns, ci 0.950
found 9 outliers among 100 samples (9.0%)
5 (5.0%) high mild
4 (4.0%) high severe
variance introduced by outliers: 79.996%
variance is severely inflated by outliers
benchmarking serialize/deserialise/tree2
mean: 1.148759 us, lb 1.138991 us, ub 1.183448 us, ci 0.950
std dev: 83.66155 ns, lb 25.57640 ns, ub 190.4369 ns, ci 0.950
found 7 outliers among 100 samples (7.0%)
4 (4.0%) high mild
2 (2.0%) high severe
variance introduced by outliers: 66.638%
variance is severely inflated by outliers
benchmarking serialize/deserialise/car1
mean: 15.67617 us, lb 15.57603 us, ub 15.82105 us, ci 0.950
std dev: 611.6098 ns, lb 450.8581 ns, ub 853.6561 ns, ci 0.950
found 6 outliers among 100 samples (6.0%)
3 (3.0%) high mild
3 (3.0%) high severe
variance introduced by outliers: 35.595%
variance is moderately inflated by outliers
instance (Binary a) => Binary (Tree a) where
put (Node a b) = putWord8 0 >> put a >> put b
put (Leaf a) = putWord8 1 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (Node a b)
1 -> get >>= \a -> return (Leaf a)
_ -> fail "no decoding"
instance Binary Car where
put (Car a b c d e f g h i j k l) = put a >> put b >> put c >> put d >> put e >> put f >> put g >> put h >> put i >> put j >> put k >> put l
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> get >>= \f -> get >>= \g -> get >>= \h -> get >>= \i -> get >>= \j -> get >>= \k -> get >>= \l -> return (Car a b c d e f g h i j k l)
instance Binary Acceleration where
put (Acceleration a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (Acceleration a b)
instance Binary Consumption where
put (Consumption a b) = put a >> put b
get = get >>= \a -> get >>= \b -> return (Consumption a b)
instance Binary Model where
put A = putWord8 0
put B = putWord8 1
put C = putWord8 2
get = do
tag_ <- getWord8
case tag_ of
0 -> return A
1 -> return B
2 -> return C
_ -> fail "no decoding"
instance Binary OptionalExtra where
put SunRoof = putWord8 0
put SportsPack = putWord8 1
put CruiseControl = putWord8 2
get = do
tag_ <- getWord8
case tag_ of
0 -> return SunRoof
1 -> return SportsPack
2 -> return CruiseControl
_ -> fail "no decoding"
instance Binary Engine where
put (Engine a b c d e) = put a >> put b >> put c >> put d >> put e
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> get >>= \e -> return (Engine a b c d e)
-}
|
tittoassini/flat
|
benchmarks/PkgCereal.hs
|
Haskell
|
bsd-3-clause
| 5,593
|
{-# LANGUAGE ExistentialQuantification #-}
module Main where
import Scheme()
import Text.ParserCombinators.Parsec hiding (spaces)
import System.Environment
import Numeric
import GHC.Real
import Data.Char
import Data.Complex
import Data.IORef
import Data.Maybe
import Control.Monad.Except
import System.IO
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~,"
readExpr :: String -> ThrowsError LispVal
readExpr = readOrThrow parseExpr
readExprList = readOrThrow (endBy parseExpr spaces)
readOrThrow :: Parser a -> String -> ThrowsError a
readOrThrow parser input = case parse parser "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
spaces :: Parser ()
spaces = skipMany1 space
ioPrimitives :: [(String, [LispVal] -> IOThrowsError LispVal)]
ioPrimitives = [("apply", applyProc),
("open-input-file", makePort ReadMode),
("open-output-file", makePort WriteMode),
("close-input-port", closePort),
("close-output-port", closePort),
("read", readProc),
("write", writeProc),
("read-contents", readContents),
("read-all", readAll)
]
applyProc :: [LispVal] -> IOThrowsError LispVal
applyProc [func, List args] = apply func args
applyProc (func : args) = apply func args
makePort :: IOMode -> [LispVal] -> IOThrowsError LispVal
makePort mode [String filename] = fmap Port $ liftIO $ openFile filename mode
closePort :: [LispVal] -> IOThrowsError LispVal
closePort [Port port] = liftIO $ hClose port >> return (Bool True)
closePort _ = return $ Bool False
readProc :: [LispVal] -> IOThrowsError LispVal
readProc [] = readProc [Port stdin]
readProc [Port port] = liftIO (hGetLine port) >>= liftThrows . readExpr
writeProc :: [LispVal] -> IOThrowsError LispVal
writeProc [obj] = writeProc [obj, Port stdout]
writeProc [obj, Port port] = liftIO $ hPrint port obj >> return (Bool True)
readContents :: [LispVal] -> IOThrowsError LispVal
readContents [String filename] = fmap String $ liftIO $ readFile filename
load :: String -> IOThrowsError [LispVal]
load filename = liftIO (readFile filename) >>= liftThrows . readExprList
readAll :: [LispVal] -> IOThrowsError LispVal
readAll [String filename] = List <$> load filename
-- Type
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| Float Double
| String String
| Bool Bool
| Character Char
| Ratio Rational
| Complex (Complex Double)
| PrimitiveFunc ([LispVal] -> ThrowsError LispVal)
| Func {params :: [String], vararg :: Maybe String,
body :: [LispVal], closure :: Env}
| Macro {params :: [String], vararg :: Maybe String,
body :: [LispVal], closure :: Env}
| IOFunc ([LispVal] -> IOThrowsError LispVal)
| Port Handle
instance Eq LispVal where
Atom x == Atom x' = x == x'
Atom _ == _ = False
List xs == List xs' = xs == xs'
List _ == _ = False
DottedList xs x == DottedList xs' x' = xs == xs' && x == x'
DottedList _ _ == _ = False
Number n == Number n' = n == n'
Number _ == _ = False
Float x == Float x' = x == x'
Float _ == _ = False
Bool b == Bool b' = b == b'
String s == String s' = s == s'
String _ == _ = False
Bool _ == _ = False
Character c == Character c' = c == c'
Character _ == _ = False
Ratio r == Ratio r' = r == r'
Ratio _ == _ = False
Complex c == Complex c' = c == c'
Complex _ == _ = False
PrimitiveFunc _ == _ = False
Func params vararg body closure == Func params' vararg' body' closure' =
params == params' && vararg == vararg' && body == body' && closure == closure'
Func {} == _ = False
-- Parser
parseString :: Parser LispVal
parseString = do char '"'
x <- many (escapedChars <|> noneOf "\"")
char '"'
return $ String x
parseCharacter :: Parser LispVal
parseCharacter = do
try $ string "#\\"
value <- try (string "newline" <|> string "space")
<|> do { x <- anyChar; notFollowedBy alphaNum ; return [x] }
return $ Character $ case value of
"space" -> ' '
"newline" -> '\n'
_ -> head value
escapedChars :: Parser Char
escapedChars = do x <- char '\\' >> oneOf "\\\"nrt"
return $ case x of
'n' -> '\n'
'r' -> '\r'
't' -> '\t'
_ -> x
parseAtom :: Parser LispVal
parseAtom = do first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = first:rest
return $ Atom atom
parseBool :: Parser LispVal
parseBool = do string "#"
x <- oneOf "tf"
return $ case x of
't' -> Bool True
'f' -> Bool False
parseNumber :: Parser LispVal
parseNumber = parseDigital1 <|> parseDigital2 <|> parseHex <|> parseOct <|> parseBin
parseDigital1 :: Parser LispVal
parseDigital1 = do x <- many1 digit
(return . Number . read) x
parseDigital2 :: Parser LispVal
parseDigital2 = do try $ string "#d"
x <- many1 digit
(return . Number . read) x
parseHex :: Parser LispVal
parseHex = do try $ string "#x"
x <- many1 hexDigit
return $ Number (hex2dig x)
parseOct :: Parser LispVal
parseOct = do try $ string "#o"
x <- many1 octDigit
return $ Number (oct2dig x)
parseBin :: Parser LispVal
parseBin = do try $ string "#b"
x <- many1 $ oneOf "10"
return $ Number (bin2dig x)
oct2dig x = fst $ head $ readOct x
hex2dig x = fst $ head $ readHex x
bin2dig = bin2dig' 0
bin2dig' digint "" = digint
bin2dig' digint (x:xs) = let old = 2 * digint + (if x == '0' then 0 else 1) in
bin2dig' old xs
parseFloat :: Parser LispVal
parseFloat = do x <- many1 digit
char '.'
y <- many1 digit
return $ Float (fst . head $ readFloat (x++ "." ++y))
parseRatio :: Parser LispVal
parseRatio = do x <- many1 digit
char '/'
y <- many1 digit
return $ Ratio (read x % read y)
toDouble :: LispVal -> Double
toDouble (Float f) = f
toDouble (Number n) = fromIntegral n
parseComplex :: Parser LispVal
parseComplex = do x <- try parseFloat <|> parseNumber
char '+'
y <- try parseFloat <|> parseNumber
char 'i'
return $ Complex (toDouble x :+ toDouble y)
parseList :: Parser LispVal
parseList = List <$> sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList = do
head <- endBy parseExpr spaces
tail <- char '.' >> spaces >> parseExpr
return $ DottedList head tail
parseQuoted :: Parser LispVal
parseQuoted = do char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseQuasiQuoted :: Parser LispVal
parseQuasiQuoted = do char '`'
x <- parseInQuasiQuoted
return $ List [Atom "backQuote", x]
parseInQuasiQuoted :: Parser LispVal
parseInQuasiQuoted = try parseUnquoteSpliced
<|> try parseUnquoted
<|> try parseInQuasiQuotedList
<|> parseExpr
parseInQuasiQuotedList :: Parser LispVal
parseInQuasiQuotedList = do char '('
x <- List <$> sepBy parseInQuasiQuoted spaces
char ')'
return x
parseUnquoted :: Parser LispVal
parseUnquoted = do char ','
x <- parseExpr
return $ List [Atom "unquote", x]
parseUnquoteSpliced :: Parser LispVal
parseUnquoteSpliced = do string ",@"
x <- parseExpr
return $ List [Atom "unquote-spliced", x]
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> try parseQuasiQuoted
<|> try parseQuoted
<|> parseString
<|> try parseFloat
<|> try parseRatio
<|> try parseComplex
<|> try parseNumber
<|> try parseBool
<|> try parseCharacter
<|> do char '('
x <- try parseList <|> parseDottedList
char ')'
return x
-- Show
instance Show LispVal where show = showVal
showVal :: LispVal -> String
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Character contents) = "#\\" ++ show contents
showVal (Atom name) = name
showVal (Number contents) = show contents
showVal (Float contents) = show contents
showVal (Ratio (x :% y)) = show x ++ "/" ++ show y
showVal (Complex (r :+ i)) = show r ++ "+" ++ show i ++ "i"
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (List contents) = "(" ++ unwordsList contents ++ ")"
showVal (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ showVal tail ++ ")"
showVal (PrimitiveFunc _) = "<primitive>"
showVal Func {params = args, vararg = varargs, body = body, closure = env} =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
showVal Macro {params = args, vararg = varargs, body = body, closure = env} =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
showVal (Port _) = "<IO port>"
showVal (IOFunc _) = "<IO primitive>"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
eval :: Env -> LispVal -> IOThrowsError LispVal
eval _ val@(String _) = return val
eval _ val@(Character _) = return val
eval _ val@(Number _) = return val
eval _ val@(Float _) = return val
eval _ val@(Ratio _) = return val
eval _ val@(Complex _) = return val
eval _ val@(Bool _) = return val
eval env (Atom id) = getVar env id
eval _ (List [Atom "quote", val]) = return val
eval env (List [Atom "backQuote", val]) =
case val of
List [Atom "unquote", _] -> evalUnquote val
List vals -> List <$> mapM evalUnquote vals
_ -> evalUnquote val
where
evalUnquote (List [Atom "unquote", val]) = eval env val
evalUnquote val = return val
eval env (List [Atom "if", pred, conseq, alt]) =
do result <- eval env pred
case result of
Bool False -> eval env alt
_ -> eval env conseq
eval env (List (Atom "cond" : expr : rest)) = eval' expr rest
where eval' (List [cond, value]) (x : xs) = do
result <- eval env cond
case result of
Bool False -> eval' x xs
_ -> eval env value
eval' (List [Atom "else", value]) [] = eval env value
eval' (List [cond, value]) [] = do
result <- eval env cond
case result of
Bool False -> return $ Atom "#<undef>"
_ -> eval env value
eval env form@(List (Atom "case":key:clauses)) =
if null clauses
then throwError $ BadSpecialForm "no true clause in case expression: " form
else case head clauses of
List (Atom "else" : exprs) -> fmap last (mapM (eval env) exprs)
List (List datums : exprs) -> do
result <- eval env key
equality <- liftThrows $ mapM (\x -> eqv [result, x]) datums
if Bool True `elem` equality
then fmap last (mapM (eval env) exprs)
else eval env $ List (Atom "case" : key : tail clauses)
_ -> throwError $ BadSpecialForm "ill-formed case expression: " form
eval env (List [Atom "set!", Atom var, form]) =
eval env form >>= setVar env var
eval env (List [Atom "define", Atom var, form]) =
eval env form >>= defineVar env var
eval env (List (Atom "define" : List (Atom var:params) : body)) =
makeNormalFunc env params body >>= defineVar env var
eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) =
makeVarargs varargs env params body >>= defineVar env var
eval env (List (Atom "define-macro" : List (Atom var:params) : body)) =
makeNormalMacro env params body >>= defineVar env var
eval env (List (Atom "define-macro" : DottedList (Atom var : params) varargs : body)) =
makeVarArgsMacro varargs env params body >>= defineVar env var
eval env (List (Atom "lambda" : List params : body)) =
makeNormalFunc env params body
eval env (List (Atom "lambda" : DottedList params varargs : body)) =
makeVarargs varargs env params body
eval env (List (Atom "lambda" : varargs@(Atom _) : body)) =
makeVarargs varargs env [] body
eval env (List [Atom "load", String filename]) =
load filename >>= fmap last . mapM (eval env)
-- bindings = [List LispVal]
eval env (List (Atom "let" : List bindings : body)) =
eval env (List (List (Atom "lambda" : List (fmap fst' bindings) : body) : fmap snd' bindings))
where fst' :: LispVal -> LispVal
fst' (List (x:xs)) = x
snd' :: LispVal -> LispVal
snd' (List (x:y:xs)) = y
eval env (List (function : args)) = do
func <- eval env function
argVals <- mapM (eval env) args
apply func argVals
eval _ badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm
apply :: LispVal -> [LispVal] -> IOThrowsError LispVal
apply (PrimitiveFunc func) args = liftThrows $ func args
apply (Macro params varargs body closure) args =
if num params /= num args && isNothing varargs
then throwError $ NumArgs (num params) args
else liftIO (bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalMacro
where remainingArgs = drop (length params) args
num = toInteger . length
evalMacro env = do
evaled <- mapM (eval env) body
last <$> mapM (eval env) evaled
bindVarArgs arg env = case arg of
Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)]
Nothing -> return env
apply (Func params varargs body closure) args =
if num params /= num args && isNothing varargs
then throwError $ NumArgs (num params) args
else liftIO (bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody
where remainingArgs = drop (length params) args
num = toInteger . length
evalBody env = last <$> mapM (eval env) body
bindVarArgs arg env = case arg of
Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)]
Nothing -> return env
apply (IOFunc func) args = func args
primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
primitives = [("+", numericBinop (+)),
("-", numericBinop (-)),
("*", numericBinop (*)),
("/", numericBinop div),
("mod", numericBinop mod),
("quotient", numericBinop quot),
("remainder", numericBinop rem),
("symbol?", isSym),
("symbol->string", symbolToString),
("=", numBoolBinop (==)),
("<", numBoolBinop (<)),
(">", numBoolBinop (>)),
("/=", numBoolBinop (/=)),
(">=", numBoolBinop (>=)),
("&&", boolBoolBinop (&&)),
("||", boolBoolBinop (||)),
("string?", isString),
("make-string", makeString),
("string-length", stringLength),
("string-ref", stringLef),
("string->symbol", stringToSymbol),
("string=?", strBoolBinop (==)),
("string<?", strBoolBinop (<)),
("string>?", strBoolBinop (>)),
("string<=?", strBoolBinop (<=)),
("string>=?", strBoolBinop (>=)),
("string-ci=?", strCiBinop (==)),
("string-ci<?", strCiBinop (<)),
("string-ci>?", strCiBinop (>)),
("string-ci<=?", strCiBinop (<=)),
("string-ci>=?", strCiBinop (>=)),
("substring", subString),
("string-append", stringAppend),
("string->list", stringList),
("list->string", listString),
("string-copy", stringCopy),
("string-fill!", stringFill),
("car", car),
("cdr", cdr),
("cons", cons),
("eq?", eqv),
("eqv?", eqv),
("equal?", equal)
]
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
numericBinop _ singleVal@[args] = throwError $ NumArgs 2 singleVal
numericBinop op params = fmap (Number . foldl1 op) (mapM unpackNum params)
boolBinop :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal
boolBinop unpacker op args = if length args /= 2
then throwError $ NumArgs 2 args
else do left <- unpacker $ head args
right <- unpacker $ args !! 1
return $ Bool $ left `op` right
strCiBinop :: (String -> String -> Bool) -> [LispVal] -> ThrowsError LispVal
strCiBinop op [String x, String y] = return $ Bool $ map toLower x `op` map toLower y
strCiBinop _ [notStr, String y] = throwError $ TypeMismatch "string" notStr
strCiBinop _ [String x, notStr] = throwError $ TypeMismatch "string" notStr
strCiBinop _ argList = throwError $ NumArgs 2 argList
subString :: [LispVal] -> ThrowsError LispVal
subString [String str, Number start, Number end]
| start <= end = return $ String $ take (fromIntegral (end - start)) $ drop (fromIntegral start) str
| start > end = throwError $ Otherwise $ "end argument (" ++ show end ++ ") must be greater than or equal to the start argument (" ++ show start ++ ")"
subString [notStr, Number _, Number _] = throwError $ TypeMismatch "string" notStr
subString [String _, notNum, _] = throwError $ TypeMismatch "number" notNum
subString [_, _, notNum] = throwError $ TypeMismatch "number" notNum
subString argList = throwError $ NumArgs 3 argList
stringAppend :: [LispVal] -> ThrowsError LispVal
stringAppend [] = return $ String ""
stringAppend args = foldM stringAppend' (String "") args
stringAppend' :: LispVal -> LispVal -> ThrowsError LispVal
stringAppend' (String x) (String y) = return $ String $ x ++ y
stringAppend' (String _) notStr = throwError $ TypeMismatch "string" notStr
stringAppend' notStr _ = throwError $ TypeMismatch "string" notStr
stringList :: [LispVal] -> ThrowsError LispVal
stringList [String s] = return $ List $ fmap Character s
stringList [notStr] = throwError $ TypeMismatch "string" notStr
stringList argList = throwError $ NumArgs 1 argList
listString :: [LispVal] -> ThrowsError LispVal
listString [list@(List xs)] = if all isCharacter xs
then return $ String $ fmap (\(Character c) -> c) xs
else throwError $ TypeMismatch "character list" list
where isCharacter (Character _) = True
isCharacter _ = False
listString argList = throwError $ NumArgs 1 argList
stringCopy :: [LispVal] -> ThrowsError LispVal
stringCopy [String str] = return $ String $ foldr (:) [] str
stringCopy [notStr] = throwError $ TypeMismatch "string" notStr
stringCopy argList = throwError $ NumArgs 1 argList
stringFill :: [LispVal] -> ThrowsError LispVal
stringFill [String str, Character c] = return $ String $ stringFill' str c
where stringFill' [] c = []
stringFill' str c = c:stringFill' (tail str) c
stringFill [String _, notChar] = throwError $ TypeMismatch "character" notChar
stringFill [notStr, _] = throwError $ TypeMismatch "string" notStr
stringFill argList = throwError $ NumArgs 2 argList
numBoolBinop = boolBinop unpackNum
strBoolBinop = boolBinop unpackStr
boolBoolBinop = boolBinop unpackBool
unpackNum :: LispVal -> ThrowsError Integer
unpackNum (Number n) = return n
unpackNum (String n) = let parsed = reads n
in if null parsed
then throwError $ TypeMismatch "number" $ String n
else return $ fst $ head parsed
unpackNum (List [n]) = unpackNum n
unpackNum notNum = throwError $ TypeMismatch "number" notNum
unpackStr :: LispVal -> ThrowsError String
unpackStr (String s) = return s
unpackStr (Number s) = return $ show s
unpackStr (Bool s) = return $ show s
unpackStr notString = throwError $ TypeMismatch "string" notString
unpackBool :: LispVal -> ThrowsError Bool
unpackBool (Bool b) = return b
unpackBool notBool = throwError $ TypeMismatch "boolean" notBool
isSym :: [LispVal] -> ThrowsError LispVal
isSym [Atom _] = return $ Bool True
isSym xs = case length xs of
1 -> return $ Bool False
_ -> throwError $ NumArgs 1 xs
symbolToString :: [LispVal] -> ThrowsError LispVal
symbolToString [Atom x] = return $ String x
symbolToString [notSym] = throwError $ TypeMismatch "symbol" notSym
symbolToString xs = throwError $ NumArgs 1 xs
stringToSymbol :: [LispVal] -> ThrowsError LispVal
stringToSymbol [String x] = return $ Atom x
stringToSymbol [notString] = throwError $ TypeMismatch "string" notString
stringToSymbol xs = throwError $ NumArgs 1 xs
isString :: [LispVal] -> ThrowsError LispVal
isString [String _] = return $ Bool True
isString [_] = return $ Bool False
isString badArgList = throwError $ NumArgs 1 badArgList
makeString :: [LispVal] -> ThrowsError LispVal
makeString [Number n] = makeString [Number n, Character ' ']
makeString [notNumber] = throwError $ TypeMismatch "number" notNumber
makeString [Number n, Character c] = return $ String $ replicate (fromIntegral n) c
makeString [notNumber, Character _] = throwError $ TypeMismatch "number" notNumber
makeString [Number _, notChar] = throwError $ TypeMismatch "char" notChar
makeString [notNumber, _] = throwError $ TypeMismatch "number" notNumber
makeString badArgList = throwError $ NumArgs 2 badArgList
stringLength :: [LispVal] -> ThrowsError LispVal
stringLength [String s] = return $ Number $ fromIntegral . length $ s
stringLength [notString] = throwError $ TypeMismatch "string" notString
stringLength badArgList = throwError $ NumArgs 1 badArgList
stringLef :: [LispVal] -> ThrowsError LispVal
stringLef [String s, Number n] = return $ Character $ s !! fromIntegral n
stringLef [notString, Number _] = throwError $ TypeMismatch "string" notString
stringLef [String _, notNumber] = throwError $ TypeMismatch "number" notNumber
stringLef [notString, _] = throwError $ TypeMismatch "string" notString
stringLef badArgList = throwError $ NumArgs 2 badArgList
car :: [LispVal] -> ThrowsError LispVal
car [List (x:_)] = return x
car [DottedList (x:_) _] =return x
car [badArg] = throwError $ TypeMismatch "pair" badArg
car badArgList = throwError $ NumArgs 1 badArgList
cdr :: [LispVal] -> ThrowsError LispVal
cdr [List (_:xs)] = return $ List xs
cdr [DottedList [_] x] = return x
cdr [DottedList (_:xs) x] = return $ DottedList xs x
cdr [badArg] = throwError $ TypeMismatch "pair" badArg
cdr badArgList = throwError $ NumArgs 1 badArgList
cons :: [LispVal] -> ThrowsError LispVal
cons [x1, List []] = return $ List [x1]
cons [x, List xs] = return $ List $ x:xs
cons [x, DottedList xs xlast] = return $ DottedList (x:xs) xlast
cons [x1, x2] = return $ DottedList [x1] x2
cons badArgList = throwError $ NumArgs 2 badArgList
eqv :: [LispVal] -> ThrowsError LispVal
eqv [Bool arg1, Bool arg2] = return $ Bool $ arg1 == arg2
eqv [Number arg1, Number arg2] = return $ Bool $ arg1 == arg2
eqv [String arg1, String arg2] = return $ Bool $ arg1 == arg2
eqv [Atom arg1, Atom arg2] = return $ Bool $ arg1 == arg2
eqv [DottedList xs x, DottedList ys y] = eqv [List $ xs ++ [x], List $ ys ++ [y]]
eqv [List arg1, List arg2] = return $ Bool $ length arg1 == length arg2 && all eqvPair (zip arg1 arg2)
where eqvPair (x1, x2) = case eqv [x1, x2] of
Left _ -> False
Right (Bool val) -> val
eqv [_, _] = return $ Bool False
eqv badArgList = throwError $ NumArgs 2 badArgList
data Unpacker = forall a. Eq a => AnyUnpacker (LispVal -> ThrowsError a)
unpackEquals :: LispVal -> LispVal -> Unpacker -> ThrowsError Bool
unpackEquals arg1 arg2 (AnyUnpacker unpacker) =
do unpacked1 <- unpacker arg1
unpacked2 <- unpacker arg2
return $ unpacked1 == unpacked2
`catchError` const (return False)
equal :: [LispVal] -> ThrowsError LispVal
equal [l1@(List _), l2@(List _)] = eqvList equal [l1, l2]
equal [DottedList xs x, DottedList ys y] = equal [List $ xs ++ [x], List $ ys ++ [y]]
equal [arg1, arg2] = do
primitiveEquals <- or <$> mapM (unpackEquals arg1 arg2)
[AnyUnpacker unpackNum, AnyUnpacker unpackStr, AnyUnpacker unpackBool]
eqvEquals <- eqv [arg1, arg2]
return $ Bool (primitiveEquals || let (Bool x) = eqvEquals in x)
equal badArgList = throwError $ NumArgs 2 badArgList
eqvList :: ([LispVal] -> ThrowsError LispVal) -> [LispVal] -> ThrowsError LispVal
eqvList eqvFunc [List arg1, List arg2] = return $ Bool $ length arg1 == length arg2 && all eqvPair (zip arg1 arg2)
where eqvPair (x1, x2) = case eqvFunc [x1, x2] of
Left _ -> False
Right (Bool val) -> val
-- Error
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Otherwise String
showError :: LispError -> String
showError (UnboundVar message varname) = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func) = message ++ ": " ++ show func
showError (NumArgs expected found) = "Expected " ++ show expected
++ " args: found valued " ++ unwordsList found
showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found
showError (Parser parseErr) = "Parse error at " ++ show parseErr
showError (Otherwise message) = message
instance Show LispError where show = showError
type ThrowsError = Either LispError
trapError action = catchError action (return . show)
-- Env
type Env = IORef [(String, IORef LispVal)]
nullEnv :: IO Env
nullEnv = newIORef []
type IOThrowsError = ExceptT LispError IO
liftThrows :: ThrowsError a -> IOThrowsError a
liftThrows (Left err) = throwError err
liftThrows (Right val) = return val
runIOThrows :: IOThrowsError String -> IO String
runIOThrows action = fmap extractValue (runExceptT (trapError action))
isBound :: Env -> String -> IO Bool
isBound envRef var = fmap (isJust . lookup var) (readIORef envRef)
getVar :: Env -> String -> IOThrowsError LispVal
getVar envRef var = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Getting an unbound variable: " var)
(liftIO . readIORef)
(lookup var env)
setVar :: Env -> String -> LispVal -> IOThrowsError LispVal
setVar envRef var value = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Setting an unbound variable: " var)
(liftIO . flip writeIORef value)
(lookup var env)
return value
defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal
defineVar envRef var value = do
alreadyDefined <- liftIO $ isBound envRef var
if alreadyDefined
then setVar envRef var value >> return value
else liftIO $ do
valueRef <- newIORef value
env <- readIORef envRef
writeIORef envRef ((var, valueRef) : env)
return value
bindVars :: Env -> [(String, LispVal)] -> IO Env
bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef
where extendEnv bindings env = fmap (++ env) (mapM addBinding bindings)
addBinding (var, value) = do ref <- newIORef value
return (var, ref)
makeFunc varargs env params body = return $ Func (map showVal params) varargs body env
makeNormalFunc = makeFunc Nothing
makeVarargs = makeFunc . Just . showVal
makeMacro varargs env params body = return $ Macro (map showVal params) varargs body env
makeNormalMacro = makeMacro Nothing
makeVarArgsMacro = makeMacro . Just . showVal
primitiveBindings :: IO Env
primitiveBindings = nullEnv >>= flip bindVars (map (makeFunc IOFunc) ioPrimitives
++ map (makeFunc PrimitiveFunc) primitives)
where makeFunc constructor (var, func) = (var, constructor func)
extractValue :: ThrowsError a -> a
extractValue (Right val) = val
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: Env -> String -> IO String
evalString env expr = runIOThrows $ fmap show $ liftThrows (readExpr expr) >>= eval env
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env expr = evalString env expr >>= putStrLn
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ pred prompt action = do
result <- prompt
unless (pred result) $ action result >> until_ pred prompt action
runRepl :: IO ()
runRepl = primitiveBindings >>= until_ (== "quit") (readPrompt "Lisp>>> ") . evalAndPrint
runOne :: [String] -> IO ()
runOne args = do
env <- primitiveBindings >>= flip bindVars [("args", List $ map String $ drop 1 args)]
runIOThrows (show <$> eval env (List [Atom "load", String (head args)]))
>>= hPutStrLn stderr
main :: IO ()
main = do args <- getArgs
if null args
then runRepl
else runOne args
|
wat-aro/scheme
|
app/Main.hs
|
Haskell
|
bsd-3-clause
| 29,792
|
{-# LANGUAGE FlexibleContexts, RankNTypes #-}
module EC2Tests.AvailabilityZoneTests
( runAvailabilityZoneTests
)
where
import Data.Text (Text)
import Test.Hspec
import Cloud.AWS.EC2
import Util
import EC2Tests.Util
region :: Text
region = "ap-northeast-1"
runAvailabilityZoneTests :: IO ()
runAvailabilityZoneTests = do
hspec describeAvailabilityZonesTest
describeAvailabilityZonesTest :: Spec
describeAvailabilityZonesTest = do
describe "describeAvailabilityZones doesn't fail" $ do
it "describeAvailabilityZones doesn't throw any exception" $ do
testEC2 region (describeAvailabilityZones [] []) `miss` anyConnectionException
|
worksap-ate/aws-sdk
|
test/EC2Tests/AvailabilityZoneTests.hs
|
Haskell
|
bsd-3-clause
| 673
|
import Distribution.Simple
import Distribution.Simple.Setup
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program
import qualified Distribution.LV2 as LV2
main = defaultMainWithHooks simpleUserHooks { confHook = LV2.confHook simpleUserHooks }
|
mmartin/haskell-lv2
|
examples/amp-lv2/Setup.hs
|
Haskell
|
bsd-3-clause
| 268
|
-- | Description: Applicative order evaluation Krivine machine.
module Rossum.Krivine.Eager where
import Data.Maybe
import Rossum.Krivine.Term
data Sided a = L | V a | R
deriving (Show)
type Configuration = (Env, Maybe Term, Stack (Sided Closure))
-- | Step an applicative order Krivine machine.
--
-- Implements rules from Hankin (2004), pp 125-127.
step :: Configuration -> Maybe Configuration
step c = case c of
(p, Just (App m n), s) -> Just (p, Just m, L : (V (Closure n p)) : s)
(p, Just (Abs m), s) -> Just ([], Nothing, (V (Closure (Abs m) p)) : s)
(u:p, Just (Var n), s) | n > 1 -> Just (p, Just (Var (n - 1)), s)
(u:p, Just (Var 1), s) -> Just ([], Nothing, (V u) : s)
([], Nothing, (V u):L:(V (Closure n p)):s) -> Just (p, Just n, R : V u : s)
([], Nothing, (V u):R:(V (Closure (Abs m) p)):s) -> Just (u:p, Just m, s)
_ -> Nothing
run :: Configuration -> [Configuration]
run c = map fromJust . takeWhile isJust $ iterate (>>= step) (Just c)
-- | Execute a compiled 'Term' in applicative order.
execute :: Term -> Either [String] [String]
execute kt =
let cfg = ([], Just kt, [])
cfg' = last (run cfg)
in Right [ "K Term: " ++ format kt
, "Result: " ++ show cfg'
]
|
thsutton/rossum
|
src/Rossum/Krivine/Eager.hs
|
Haskell
|
bsd-3-clause
| 1,276
|
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
[lq| assume foo :: {v:Bool | (Prop v)} |]
foo = False
bar = liquidAssertB foo
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/Assume.hs
|
Haskell
|
bsd-3-clause
| 174
|
module MultiLinear.Class where
import Rotation.SO2
import Rotation.SO3
import Exponential.SO3
import qualified Linear.Matrix as M
import Data.Distributive
import Linear.V3
class MultiLinear f where
(!*!) :: Num a => f a -> f a -> f a
transpose :: Num a => f a -> f a
r0 = rotation (V3 0.1 0.1 0.1)
r1 = rotation (V3 0.1 0.1 0.1)
instance MultiLinear SH2 where
SH2 x !*! SH2 y = SH2 ( x M.!*! y )
transpose = SH2 . distribute . unSH2
instance MultiLinear SO2 where
SO2 x !*! SO2 y = SO2 ( x M.!*! y )
transpose = SO2 . distribute . unSO2
instance MultiLinear SO3 where
SO3 x !*! SO3 y = SO3 ( x M.!*! y )
transpose = SO3 . distribute . unSO3
|
massudaw/mtk
|
MultiLinear/Class.hs
|
Haskell
|
bsd-3-clause
| 682
|
module Genotype.Types where
import Data.Text (Text)
data BasePair = C | T | A | G deriving (Eq, Show)
data Name = Name Text Text (Maybe Char) deriving (Eq, Show)
data Datum
= Missing
| Estimated BasePair
| Certain BasePair
deriving (Eq, Show)
data Genotype = Genotype
{ geno_name :: Name
, geno_subpopLabel :: Int
, geno_datums :: [(Datum, Datum)]
} deriving (Eq, Show)
|
Jonplussed/genotype-parser
|
src/Genotype/Types.hs
|
Haskell
|
bsd-3-clause
| 391
|
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{- | Provides a representation for (top-level) integer term rewrite systems.
See <http://aprove.informatik.rwth-aachen.de/help_new/inttrs.html> for details.
Example:
@
outer(x, r) -> inner(1, 1, x, r) [ x >= 0 && r <= 100000 ]
inner(f, i, x, r) -> inner(f + i, i+1, x, r) [ i <= x ]
inner(f, i, x, r) -> outer(x - 1, r + f) [ i > x ]
g(cons(x, xs), y) -> g(xs, y + 1)
h(xs, y) -> h(cons(0, xs), y - 1) [ y > 0]
@
Remarks:
* no arithmetic expressions on the lhs of a rule
* no variable section in contrast to TRS (WST) format; non-arithmetic constants require parenthesis, ie, @c()@
Assumption:
* system is well-typed wrt. to @Univ@ and @Int@ type
* arithmetic are expressions not on root positions
* for the translation to ITS there is a unique start location, ie., exists ONE rule with unique function symbol on lhs
Changelog:
0.2.1.0
* add wellformed-ness predicate and processor
0.2.0.0 - successfully parses all examples of the TPDB
* identifier can contain `.`, `$` and `-
* ppKoat: FUNCTIONSYMBOLS instead of FUNCTIONSYMBOL
* for the ITS translation introduce an extra rule if the original one consists of a single rule; koat and tct-its do not allow start rules to have incoming edges
* parse and ignore TRUE in constraints
* parse && as well as /\ in constraints
* parse integer numbers
-}
module Tct.IntTrs
(
-- * Transformation
toTrs' , toIts' , infer
, parseRules, parse, parseIO
, prettyPrintRules
, putTrs, putIts
-- * Tct Integration
, IntTrs, IntTrsConfig
, isWellFormed
, rules
, runIntTrs, intTrsConfig
, toTrs, toIts, withTrs, withIts, withBoth, wellformed, intTrsDeclarations
) where
import Control.Applicative ((<|>))
import Control.Monad.Except
import Control.Monad.RWS.Strict
import qualified Data.Map.Strict as M
import Data.Maybe (fromJust, fromMaybe, catMaybes)
import qualified Data.Set as S
import System.IO (hPutStrLn, stderr)
import qualified Tct.Common.Polynomial as P
import qualified Tct.Common.Ring as R
import Tct.Core
import Tct.Core.Common.Pretty (Doc, Pretty, pretty)
import qualified Tct.Core.Common.Pretty as PP
import Tct.Core.Common.Xml (Xml, XmlContent, toXml)
import qualified Tct.Core.Common.Xml as Xml
import qualified Tct.Core.Data as T
import Tct.Core.Processor.Transform (transform)
import qualified Text.Parsec as PS
import qualified Text.Parsec.Expr as PE
import qualified Text.Parsec.Language as PL
import qualified Text.Parsec.Token as PT
import qualified Data.Rewriting.Problem as R
import qualified Data.Rewriting.Rule as R
import qualified Data.Rewriting.Rules as RS
import qualified Data.Rewriting.Term as T
-- TODO: MS: better export list for Its
import Tct.Its (Its)
import qualified Tct.Its.Data.Problem as Its (Its (..), initialise, domain)
import qualified Tct.Its.Data.Types as Its (AAtom (..), ARule (..), ATerm (..), rules)
import qualified Tct.Its.Strategies as Its (runtime)
import Tct.Trs (Trs)
import qualified Tct.Trs as Trs (runtime)
import qualified Tct.Trs.Data.Problem as Trs (fromRewriting)
-- TODO: MS: rename Nat
data IFun = Add | Mul | Sub | Nat Int deriving (Eq, Ord, Show)
type ITerm f v = T.Term IFun v
data CFun = Lte | Lt | Eq | Gt | Gte deriving (Eq, Ord, Show, Enum, Bounded)
data Constraint f v = Constraint (ITerm f v) CFun (ITerm f v) deriving (Eq, Ord, Show)
data Fun f = UFun f | IFun IFun deriving (Eq, Ord, Show)
type Term f v = T.Term (Fun f) v
data Rule f v = Rule
{ rule :: R.Rule (Fun f) v
, constraints :: [Constraint f v ] }
deriving (Eq, Ord, Show)
rename :: (v -> v') -> Rule f v -> Rule f v'
rename var (Rule rl cs) = Rule (R.rename var rl) (k `fmap` cs)
where k (Constraint t1 op t2) = Constraint (T.rename var t1) op (T.rename var t2)
-- vars :: Ord v => Rule f v -> [v]
-- vars (Rule (R.Rule lhs rhs) cs) = S.toList $ S.fromList $ (T.varsDL lhs <> T.varsDL rhs <> cvarsDL cs) []
-- where cvarsDL = foldr (mappend . k) id where k (Constraint t1 _ t2) = T.varsDL t1 <> T.varsDL t2
varsL :: Ord v => Rule f v -> [v]
varsL (Rule (R.Rule lhs rhs) cs) = (T.varsDL lhs <> T.varsDL rhs <> cvarsDL cs) []
where cvarsDL = foldr (mappend . k) id where k (Constraint t1 _ t2) = T.varsDL t1 <> T.varsDL t2
termToITerm :: ErrorM m => Term f v -> m (ITerm f v)
termToITerm (T.Fun (UFun _) _) = throwError "termToIterm: not an iterm"
termToITerm (T.Fun (IFun f) ts) = T.Fun f <$> traverse termToITerm ts
termToITerm (T.Var v) = pure (T.Var v)
type Rules f v = [Rule f v]
-- | Checks wether the system is wellformed.
-- A system is well-formed if for all rules following properties is fullfilled.
--
-- * no variables at root position
-- * no arithmetic expression at root position
-- * no univ function symbols below arithmetic expressions
--
-- This properties are sometimes used during translation; but actually never checked.
isWellFormed' :: (ErrorM m, Show f, Show v) => Rules f v -> m (Rules f v)
isWellFormed' rs = all' isWellFormedRule rs *> pure rs
where
isWellFormedRule (Rule (R.Rule lhs rhs) _) = isWellFormedRoot lhs *> isWellFormedRoot rhs
isWellFormedRoot (T.Fun (UFun _) ts) = all' isWellFormedTerm ts
isWellFormedRoot t@(T.Fun (IFun _) _) = throwError $ "iterm at root position: " ++ show t
isWellFormedRoot t@(T.Var _) = throwError $ "var at root position: " ++ show t
isWellFormedTerm (T.Fun (UFun _) ts) = all' isWellFormedTerm ts
isWellFormedTerm t@(T.Fun (IFun _) _) = isWellFormedITerm t
isWellFormedTerm (T.Var _ ) = pure True
isWellFormedITerm t@(T.Fun (UFun _) _) = throwError $ "uterm at iterm position" ++ show t
isWellFormedITerm (T.Fun (IFun Add) ts@[_,_]) = all' isWellFormedITerm ts
isWellFormedITerm (T.Fun (IFun Mul) ts@[_,_]) = all' isWellFormedITerm ts
isWellFormedITerm (T.Fun (IFun Sub) ts@[_,_]) = all' isWellFormedITerm ts
isWellFormedITerm (T.Fun (IFun (Nat _)) []) = pure True
isWellFormedITerm t@(T.Fun (IFun _) _) = throwError $ "iterm with wrong arity" ++ show t
isWellFormedITerm (T.Var _) = pure True
all' f as = and <$> traverse f as
iop :: f -> T.Term f v -> T.Term f v -> T.Term f v
iop f x y = T.Fun f [x,y]
add, mul, sub :: T.Term IFun v -> T.Term IFun v -> T.Term IFun v
add = iop Add
mul = iop Mul
sub = iop Sub
int :: Int -> ITerm f v
int i = T.Fun (Nat i) []
iRep :: IFun -> String
iRep Mul = "*"
iRep Add = "+"
iRep Sub = "-"
iRep (Nat i) = show i
cRep :: CFun -> String
cRep Lte = "<="
cRep Lt = "<"
cRep Eq = "="
cRep Gt = ">"
cRep Gte = ">="
type ErrorM = MonadError String
--- * parser ---------------------------------------------------------------------------------------------------------
tok :: PT.TokenParser st
tok = PT.makeTokenParser
PL.emptyDef
{ PT.commentStart = "(*)"
, PT.commentEnd = "*)"
, PT.nestedComments = False
, PT.identStart = PS.letter
, PT.identLetter = PS.alphaNum <|> PS.oneOf "_'.$-"
, PT.reservedOpNames = cRep `fmap` [(minBound :: CFun)..]
, PT.reservedNames = []
, PT.caseSensitive = True }
pIdentifier, pComma :: Parser String
pIdentifier = PT.identifier tok
pComma = PT.comma tok
pSymbol :: String -> Parser String
pSymbol = PT.symbol tok
pParens :: Parser a -> Parser a
pParens = PT.parens tok
pReservedOp :: String -> Parser ()
pReservedOp = PT.reservedOp tok
pInt :: Parser Int
pInt = fromIntegral <$> PT.integer tok
type Parser = PS.Parsec String ()
-- type Parser = PS.ParsecT Text () Identity
pVar :: Parser (T.Term f String)
pVar = T.Var `fmap` pIdentifier
pTerm :: Parser (T.Term (Fun String) String)
pTerm =
PS.try (T.Fun <$> (UFun <$> pIdentifier) <*> pParens (pTerm `PS.sepBy` pComma))
<|> T.map IFun id <$> pITerm
pITerm :: Parser (ITerm String String)
pITerm = PE.buildExpressionParser table (pParens pITerm <|> (int <$> pInt) <|> pVar)
where
table =
-- [ [ unary "-" neg ]
[ [ binaryL (iRep Mul) mul PE.AssocLeft]
, [ binaryL (iRep Add) add PE.AssocLeft, binaryL (iRep Sub) sub PE.AssocLeft] ]
-- unary f op = PE.Prefix (PS.reserved f *> return op)
binaryL f op = PE.Infix (pSymbol f *> return op)
pCFun :: Parser CFun
pCFun = PS.choice $ k `fmap` [(minBound :: CFun)..]
where k c = PS.try (pReservedOp $ cRep c) *> return c
pConstraint :: Parser (Maybe (Constraint String String))
pConstraint =
(PS.try (pSymbol "TRUE") *> return Nothing)
<|> (Just <$> (Constraint <$> pITerm <*> pCFun <*> pITerm))
pConstraints :: Parser [Constraint String String]
pConstraints = catMaybes <$> PS.option [] (brackets $ pConstraint `PS.sepBy1` pAnd)
where
brackets p = pSymbol "[" *> p <* pSymbol "]"
pAnd = pSymbol "&&" <|> pSymbol "/\\"
pRule :: Parser (Rule String String)
pRule = Rule <$> k <*> pConstraints
where k = R.Rule <$> (pTerm <* pSymbol "->") <*> pTerm
pRules :: Parser (Rules String String)
pRules = PS.many1 pRule
-- | Parser for intTrs rules
parseRules :: Parser (Rules String String)
parseRules = pRules
--- * type inference -------------------------------------------------------------------------------------------------
type Signature f = M.Map (Fun f) Int
signature :: Ord f => Rules f v -> Signature f
signature = M.fromList . RS.funs . fmap (rmap T.withArity . rule)
where rmap k (R.Rule lhs rhs) = R.Rule (k lhs) (k rhs)
fsignature :: Ord f => Rules f v -> Signature f
fsignature = M.filterWithKey (\k _ -> isUTerm k) . signature
where isUTerm f = case f of {(UFun _) -> True; _ -> False}
-- | @vars r = (univvars, numvars)@. Variables in constraints and arithmetic expressions are @numvars@, all other wars
-- are @univvars@.
tvars :: Ord v => Rule f v -> ([v],[v])
tvars (Rule (R.Rule lhs rhs) cs) = (S.toList $ tvarS `S.difference` nvarS, S.toList nvarS)
where
tvarS = S.fromList $ (T.varsDL lhs <> T.varsDL rhs) []
nvarS = S.fromList $ (nvars1 lhs <> nvars1 rhs <> nvars2 cs) []
nvars1 (T.Fun (UFun _) ts) = foldr (mappend . nvars1) id ts
nvars1 (T.Fun (IFun _) ts) = foldr (mappend . T.varsDL) id ts
nvars1 _ = id
nvars2 = foldr (mappend . k) id where k (Constraint t1 _ t2) = T.varsDL t1 <> T.varsDL t2
data Type = Univ | Num | Alpha Int
deriving (Eq, Ord, Show)
data TypeDecl = TypeDecl
{ inputTypes :: [Type]
, outputType :: Type }
deriving Show
type Typing f = M.Map (Fun f) TypeDecl
type Unify = [(Type, Type)]
data Environment f v = Environment
{ variables_ :: M.Map v Type
, declarations_ :: M.Map (Fun f) TypeDecl }
newtype InferM f v a = InferM { runInferM :: RWST (Environment f v) Unify Int (Except String) a }
deriving
(Functor, Applicative, Monad
, MonadWriter Unify
, MonadReader (Environment f v)
, MonadState Int
, MonadError String)
(=~) :: Type -> Type -> InferM f v ()
a =~ b = tell [(a,b)]
-- MS: (almost) standard type inference
-- we already know the type output type of function symbols, and the type of variables in arithmetic expressions
-- still we have to type the rest of the variables
infer :: (ErrorM m, Show v, Show f, Ord f, Ord v) => Rules f v -> m (Typing f)
infer rs = either throwError pure $ do
(decs,_,up) <- runExcept $ runRWST (runInferM inferM) (Environment M.empty M.empty) 0
subst <- unify up
return $ instDecl subst `fmap` decs
where
lookupEnv v = asks variables_ >>= maybe (throwError $ "undefined var: " ++ show v) return . M.lookup v
lookupDecl f = asks declarations_ >>= maybe (throwError $ "undefined fun: " ++ show f) return . M.lookup f
fresh = do { i <- get; put $! i + 1; return $ Alpha i}
inferM = do
tdecls <- M.traverseWithKey initDecl (signature rs)
local (\e -> e {declarations_ = tdecls}) $ do
forM_ rs typeRule
return tdecls
instDecl subst (TypeDecl its ot) = TypeDecl [apply subst t | t <- its] (apply subst ot)
initDecl (UFun _) i = TypeDecl <$> mapM (const fresh) [1..i] <*> pure Univ
initDecl (IFun _) i = TypeDecl <$> mapM (const fresh) [1..i] <*> pure Num
typeRule rl = do
let
(uvars,nvars) = tvars rl
env1 = foldr (`M.insert` Num) M.empty nvars
env2 <- foldM (\ e v -> flip (M.insert v) e `liftM` fresh) env1 uvars
local (\e -> e {variables_ = env2}) $ do
l <- typeTerm (R.lhs $ rule rl)
r <- typeTerm (R.rhs $ rule rl)
l =~ r
typeTerm (T.Var v) = lookupEnv v
typeTerm (T.Fun f ts) = do
TypeDecl its ot <- lookupDecl f
its' <- forM ts typeTerm
sequence_ [ t1 =~ t2 | (t1,t2) <- zip its' its ]
return ot
apply subst t = t `fromMaybe` M.lookup t subst
s1 `compose` s2 = (apply s2 `M.map` s1) `M.union` s2 -- left-biased
unify [] = pure M.empty
unify ((t1,t2):ts) = case (t1,t2) of
(Univ, Num) -> throwError "type inference error"
(Num, Univ) -> throwError "type inference error"
_ | t1 == t2 -> unify ts
_ -> compose s `fmap` unify [(s `apply` t3,s `apply` t4) | (t3,t4) <- ts]
-- TODO: make this more explicit
where s = if t1 > t2 then M.insert t1 t2 M.empty else M.insert t2 t1 M.empty -- MS: we want to replace alphas if possible
--- * transformations ------------------------------------------------------------------------------------------------
toTrs' :: Typing String -> Rules String String -> Either String Trs
toTrs' tys rs = Trs.fromRewriting =<< toRewriting' tys rs
-- | Transforms the inttrs rules to a Trs. If successfull the problem is rendered to the standard output, otherwise
-- the error is rendered to standard error.
putTrs :: Rules String String -> IO ()
putTrs rs = case infer rs >>= flip toRewriting' rs of
Left err -> hPutStrLn stderr err
Right trs -> putStrLn $ PP.display $ R.prettyWST pretty pretty trs
toRewriting' :: Ord f => Typing f -> Rules f v -> Either String (R.Problem f v)
toRewriting' tys rs = case filterUniv tys rs of
Left s -> Left s
Right trs -> Right R.Problem
{ R.startTerms = R.BasicTerms
, R.strategy = R.Innermost
, R.theory = Nothing
, R.rules = R.RulesPair
{ R.weakRules = []
, R.strictRules = trs }
, R.variables = RS.vars trs
, R.symbols = RS.funs trs
, R.comment = Just "intTrs2Trs"}
filterUniv :: Ord f => Typing f -> Rules f v -> Either String [R.Rule f v]
filterUniv tys = traverse (filterRule . rule)
where
filterRule (R.Rule lhs rhs) = R.Rule <$> filterTerm lhs <*> filterTerm rhs
filterTerm (T.Fun f@(UFun g) ts) = T.Fun g <$> (filterEach f ts >>= traverse filterTerm)
filterTerm (T.Fun _ _) = throwError "filterUniv: type inference error"
filterTerm (T.Var v) = pure (T.Var v)
filterEach f ts = maybe
(throwError "filterUniv: undefined function symbol")
(pure . fst . unzip . filter ((/= Num). snd) . zip ts . inputTypes)
(M.lookup f tys)
-- MS: assumes top-level rewriting; lhs and rhs is following form
-- f(aexp1,...,aexp2) -> g(aexp1,...,aexp2)
toIts' :: ErrorM m => Typing String -> Rules String String -> m Its
toIts' tys rs = do
let (tys1, rs1) = addStartRule (tys,rs)
l0 <- findStart rs1
rs2 <- filterNum tys1 rs1
asItsRules l0 . padRules . renameRules $ filter (not . rhsIsVar) rs2
where
rhsIsVar = T.isVar . R.rhs . rule
asItsRules l0 rls = toItsRules rls >>= \rls' -> return $ Its.initialise ([l0],[],rls')
-- | Transforms the inttrs rules to a Its. If successfull the problem is rendered to the standard output, otherwise
-- the error is rendered to standard error.
putIts :: Rules String String -> IO ()
putIts rs = case infer rs >>= flip toIts' rs of
Left err -> hPutStrLn stderr err
Right its -> putStrLn $ PP.display $ ppKoat its
-- TODO: MS: move to tct-its
ppKoat :: Its -> Doc
ppKoat its = PP.vcat
[ PP.text "(GOAL COMPLEXITY)"
, PP.text "(STARTTERM (FUNCTIONSYMBOLS "<> PP.text (Its.fun $ Its.startterm_ its) <> PP.text "))"
, PP.text "(VAR " <> PP.hsep (PP.text `fmap` Its.domain its) <> PP.text ")"
, PP.text "(RULES "
, PP.indent 2 $ PP.vcat (pp `fmap` Its.rules (Its.irules_ its))
, PP.text ")" ]
where
pp (Its.Rule lhs rhss cs) =
PP.pretty lhs
<> PP.text " -> "
<> PP.text "Com_" <> PP.int (length rhss) <> PP.tupled' rhss
<> if null cs then PP.empty else PP.encloseSep PP.lbracket PP.rbracket (PP.text " /\\ ") (PP.pretty `fmap` cs)
renameRules :: Rules f String -> Rules f String
renameRules = fmap renameRule
renameRule :: Rule f String -> Rule f String
renameRule r = rename mapping r
where
mapping v = fromJust . M.lookup v . fst $ foldl k (M.empty, freshvars) (varsL r)
k (m,i) v = if M.member v m then (m,i) else (M.insert v (head i) m, tail i)
freshvars :: [String]
freshvars = (mappend "x" . show) `fmap` [(0::Int)..]
padRules :: Ord f => Rules f String -> Rules f String
padRules rls = padRule (mx rls) `fmap` rls
where mx = maximum . M.elems . fsignature
padRule :: Int -> Rule f String -> Rule f String
padRule mx (Rule (R.Rule lhs rhs) cs) = Rule (R.Rule (padTerm mx lhs) (padTerm mx rhs)) cs
padTerm :: Int -> Term f String -> Term f String
padTerm mx (T.Fun (UFun f) ts) = T.Fun (UFun f) $ zip' ts (take mx freshvars)
where
zip' (s:ss) (_:rr) = s: zip' ss rr
zip' [] rr = T.Var `fmap` rr
zip' _ [] = error "a"
padTerm _ _ = error "a"
toItsRules :: (Ord v, ErrorM m) => Rules f v -> m [Its.ARule f v]
toItsRules = traverse toItsRule
toItsRule :: (Ord v, ErrorM m) => Rule f v -> m (Its.ARule f v)
toItsRule (Rule (R.Rule lhs rhs) cs) = Its.Rule <$> toItsTerm lhs <*> ((:[]) <$> toItsTerm rhs) <*> traverse toItsConstraint cs
toItsTerm :: (Ord v, ErrorM m) => Term f v -> m (Its.ATerm f v)
toItsTerm (T.Fun (UFun f) ts) = Its.Term f <$> traverse (termToITerm >=> itermToPoly) ts
toItsTerm _ = throwError "toItsTerm: not a valid term"
itermToPoly :: (Ord v, ErrorM m) => ITerm f v -> m (P.Polynomial Int v)
itermToPoly (T.Fun (Nat n) []) = pure $ P.constant n
itermToPoly (T.Fun f ts@(t1:t2:tss)) = case f of
Add -> R.bigAdd <$> traverse itermToPoly ts
Mul -> R.bigMul <$> traverse itermToPoly ts
Sub -> R.sub <$> itermToPoly t1 <*> (R.bigAdd `fmap` traverse itermToPoly (t2:tss))
_ -> throwError "itermToPoly: not a valid term"
itermToPoly (T.Var v) = pure $ P.variable v
itermToPoly _ = throwError "itermToPoly: not a valid term"
toItsConstraint :: (Ord v, ErrorM m) => Constraint f v -> m (Its.AAtom v)
toItsConstraint (Constraint t1 cop t2) = case cop of
Lte -> Its.Gte <$> itermToPoly t2 <*> itermToPoly t1
Lt -> Its.Gte <$> itermToPoly t2 <*> (R.add R.one <$> itermToPoly t1)
Eq -> Its.Eq <$> itermToPoly t1 <*> itermToPoly t2
Gt -> Its.Gte <$> itermToPoly t1 <*> (R.add R.one <$> itermToPoly t2)
Gte -> Its.Gte <$> itermToPoly t1 <*> itermToPoly t2
-- MS: just another hack to deduce the starting location
-- | If the system constists only of a single rule; introduce an extra rule with a unique start location.
addStartRule :: (Ord f, Monoid f) => (Typing f, Rules f v) -> (Typing f, Rules f v)
addStartRule (ty,rs@[Rule (R.Rule (T.Fun (UFun f) ts) (T.Fun (UFun g) _)) _]) = (M.insert lfun ldec ty, Rule r []:rs)
where
ldec = TypeDecl [] Univ
lfun = UFun (f <> g)
r = R.Rule (T.Fun lfun []) (T.Fun (UFun f) ts)
addStartRule rs = rs
-- | Look for a single unique function symbol on the rhs.
findStart :: (ErrorM m, Ord f) => Rules f v -> m f
findStart rs = case S.toList $ roots R.lhs `S.difference` roots R.rhs of
[fun] -> pure fun
_ -> throwError "Could not deduce a start symbol."
where
roots f = foldr (k f) S.empty rs
k f (Rule r _) acc = case f r of {T.Fun (UFun g) _ -> g `S.insert` acc; _ -> acc}
-- | Restricts to 'Num' type
-- If successfull, 'UFun' appears only at root positions, and 'IFun' appear only below root.
filterNum :: (ErrorM m, Ord f) => Typing f -> Rules f v -> m (Rules f v)
filterNum tys = traverse filterRule
where
filterRule (Rule (R.Rule lhs rhs) cs) = Rule <$> (R.Rule <$> filterRoot lhs <*> filterRoot rhs) <*> pure cs
filterRoot (T.Fun f@(UFun _) ts) = T.Fun f <$> (filterEach f ts >>= validate)
filterRoot (T.Fun _ _) = throwError "filterNum: arithmetic expression at root position"
filterRoot (T.Var v) = pure (T.Var v)
filterEach f ts = maybe
(throwError "filterUniv: undefined function symbol")
(pure . fst . unzip . filter ((== Num). snd) . zip ts . inputTypes)
(M.lookup f tys)
validate ts = if all p ts then pure ts else throwError "filterNum: type inference error"
where p t = case t of {(T.Fun (UFun _) _) -> False; _ -> True}
--- * TcT integration ------------------------------------------------------------------------------------------------
--- ** Problem -------------------------------------------------------------------------------------------------------
-- MS: integration with TcT
data Problem f v = Problem { rules :: Rules f v } deriving Show
ppRules :: (f -> Doc) -> (v -> Doc) -> Rules f v -> Doc
ppRules fun var rs = PP.vcat (ppRule fun var `fmap` rs)
-- | Pretty printer for a list of rules.
prettyPrintRules :: (f -> Doc) -> (v -> Doc) -> Rules f v -> Doc
prettyPrintRules = ppRules
ppRule :: (f -> Doc) -> (v -> Doc) -> Rule f v -> Doc
ppRule fun var (Rule (R.Rule lhs rhs) cs) =
PP.hang 2 $ ppTerm fun var lhs PP.<+> PP.string "->" PP.</> ppTerm fun var rhs PP.<+> ppConstraints var cs
ppTerm :: (f -> Doc) -> (v -> Doc) -> Term f v -> Doc
ppTerm fun var (T.Fun (UFun f) ts) = fun f <> PP.tupled (ppTerm fun var `fmap` ts)
ppTerm fun var (T.Fun (IFun f) ts) = case f of
Nat i -> PP.int i
op -> k op
where k op = PP.encloseSep PP.lparen PP.rparen (PP.space <> PP.text (iRep op) <> PP.space) (ppTerm fun var `fmap` ts)
ppTerm _ var (T.Var v) = var v
ppConstraints :: (v -> Doc) -> [Constraint f v] -> Doc
ppConstraints var cs = PP.encloseSep PP.lbracket PP.rbracket (PP.text " && ") (ppConstraint var `fmap` cs)
ppConstraint :: (v -> Doc) -> Constraint f v -> Doc
ppConstraint var (Constraint lhs eq rhs) = ppITerm lhs PP.<+> PP.text (cRep eq) PP.<+> ppITerm rhs
where
k op ts = PP.encloseSep PP.lparen PP.rparen (PP.space <> PP.text (iRep op) <> PP.space) (ppITerm `fmap` ts)
ppITerm (T.Fun f ts) = case f of
Nat i -> PP.int i
op -> k op ts
ppITerm (T.Var v) = var v
xmlRules :: (f -> XmlContent) -> (v -> XmlContent) -> Rules f v -> XmlContent
xmlRules _ _ _ = Xml.empty
instance (Pretty f, Pretty v) => Pretty (Problem f v) where
pretty (Problem rs) = PP.text "Rules" PP.<$$> PP.indent 2 (ppRules PP.pretty PP.pretty rs)
instance (Xml f, Xml v) => Xml (Problem f v) where
toXml (Problem rs) = Xml.elt "inttrs" [ Xml.elt "rules" [xmlRules toXml toXml rs] ]
instance {-# OVERLAPPING #-} Xml (Problem String String) where
toXml (Problem rs) = Xml.elt "inttrs" [ Xml.elt "rules" [xmlRules Xml.text Xml.text rs] ]
--- ** Config --------------------------------------------------------------------------------------------------------
type IntTrs = Problem String String
type IntTrsConfig = TctConfig IntTrs
parse :: String -> Either String IntTrs
parse s = case PS.parse pRules "" s of
Left e -> Left (show e)
Right p -> Right (Problem p)
parseIO :: FilePath -> IO (Either String IntTrs)
parseIO fn = parse <$> readFile fn
isWellFormed :: (ErrorM m, Ord f, Ord v, Show f, Show v) => Rules f v -> m (Rules f v)
isWellFormed rs = isWellFormed' rs *> infer rs *> pure rs
intTrsConfig :: IntTrsConfig
intTrsConfig = (defaultTctConfig parseIO)
{ defaultStrategy = withBoth Trs.runtime Its.runtime }
runIntTrs :: Declared IntTrs IntTrs => IntTrsConfig -> IO ()
runIntTrs = runTct
-- | Checks wether the problem 'isWellFormed'.
wellformed :: Strategy IntTrs IntTrs
wellformed = withProblem $ \p -> case isWellFormed (rules p) of
Left err -> failing err
Right _ -> identity
toTrs :: Strategy IntTrs Trs
toTrs = transform "We extract a TRS fragment from the current int-TRS problem:"
(\p -> infer (rules p) >>= \tp -> toTrs' tp (rules p))
withTrs :: Strategy Trs Trs -> Strategy IntTrs Trs
withTrs st = toTrs .>>> st
toIts :: Strategy IntTrs Its
toIts = transform "We extract a Its fragment from the current int-TRS problem:"
(\p -> infer (rules p) >>= \tp -> toIts' tp (rules p))
-- (\p -> infer (rules p) >>= \tp -> toIts' tp (rules p) >>= \its' -> trace (PP.display $ PP.pretty p) (trace (PP.display $ PP.pretty its') (return its')))
withIts :: Strategy Its Its -> Strategy IntTrs Its
withIts st = toIts .>>> st
withBoth :: Strategy Trs Trs -> Strategy Its Its -> Strategy IntTrs IntTrs
withBoth st1 st2 = withProblem $ \p -> let tpM = infer (rules p) in fastest
[ transform "a" (const $ tpM >>= \tp -> toTrs' tp (rules p)) .>>> st1 .>>> close
, transform "a" (const $ tpM >>= \tp -> toIts' tp (rules p)) .>>> st2 .>>> close]
-- TODO: MS: move to tct-trs
trsArg :: Declared Trs Trs => T.Argument 'T.Required (Strategy Trs Trs)
trsArg = T.strat "trs" ["This argument specifies the trs strategy to apply."]
-- TODO: MS: move to tct-its
itsArg :: Declared Its Its => T.Argument 'T.Required (Strategy Its Its)
itsArg = T.strat "its" ["This argument specifies the trs strategy to apply."]
intTrsDeclarations :: (Declared Trs Trs, Declared Its Its) => [StrategyDeclaration IntTrs IntTrs]
intTrsDeclarations =
[ T.SD $ T.declare "withTrs" ["Solve with TRS."]
(OneTuple $ trsArg `optional` Trs.runtime)
(\st -> withTrs st .>>> close)
, T.SD $ T.declare "withIts" ["Solve with ITS."]
(OneTuple $ itsArg `optional` Its.runtime)
(\st -> withIts st .>>> close)
, T.SD $ T.declare "withBoth" ["Solve with TRS and ITS."]
(trsArg `optional` Trs.runtime, itsArg `optional` Its.runtime)
(\st1 st2 -> withBoth st1 st2 .>>> close)
, T.SD $ T.declare "wellformed" ["checks wether the system is wellformed"]
()
wellformed ]
|
ComputationWithBoundedResources/tct-inttrs
|
src/Tct/IntTrs.hs
|
Haskell
|
bsd-3-clause
| 26,631
|
{-# LANGUAGE FlexibleContexts #-}
import Plots
import Plots.Axis
import Plots.Types hiding (B)
import Data.List
import Diagrams.Prelude
import Diagrams.Backend.Rasterific
mydata1 = [(1,3), (2,5.5), (3.2, 6), (3.5, 6.1)]
mydata2 = mydata1 & each . _1 *~ 0.5
mydata3 = [V2 1.2 2.7, V2 2 5.1, V2 3.2 2.6, V2 3.5 5]
-- Could add helper functions in plots to make this easier
fillOpacity = barStyle . mapped . _opacity
myaxis :: Axis B V2 Double
myaxis = r2Axis &~ do
ribbonPlot' ((fst foo1) ++ reverse (zeroy (fst foo1))) $ do
addLegendEntry (snd foo1)
plotColor .= white
fillOpacity .= 0.7
strokeEdge .= False
ribbonPlot' ((fst foo2) ++ reverse (zeroy (fst foo2))) $ do
addLegendEntry (snd foo1)
fillOpacity .= 0.5
ribbonPlot' ((fst foo3) ++ reverse (zeroy (fst foo3))) $ do
addLegendEntry (snd foo1)
fillOpacity .= 0.5
strokeEdge .= False
make :: Diagram B -> IO ()
make = renderRasterific "test.png" (mkWidth 600) . frame 20
main :: IO ()
main = make $ renderAxis myaxis
foo1 = ([(111.0,0.1),(140.0,1.2),(150.0,2.3)],"typeA")
foo2 = ([(155.0,3.5),(167.0,5.1),(200.0,6.4),(211.0,7.5)],"typeB")
foo3 = ([(191.0,5.8),(233.0,8.5),(250.0,9.1),(270.0,9.6)],"typeC")
|
bergey/plots
|
examples/ribbonopacity.hs
|
Haskell
|
bsd-3-clause
| 1,247
|
{-# LANGUAGE FlexibleContexts #-}
module Database.Redis.Internal where
import Control.Monad.Trans ( MonadIO, liftIO )
import Control.Failure ( MonadFailure, failure )
import Data.Convertible.Base ( convertUnsafe )
import Data.Convertible.Instances ( )
import Database.Redis.Core
import System.IO ( hGetChar )
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
-- ---------------------------------------------------------------------------
-- Command
--
command :: (MonadIO m, MonadFailure RedisError m) => Server -> m a -> m RedisValue
command r f = f >> getReply r
multiBulk :: (MonadIO m, MonadFailure RedisError m)
=> Server -> T.Text -> [T.Text] -> m ()
multiBulk (Server h) command' vs = do
let vs' = concatMap (\a -> ["$" ~~ (toParam $ T.length a), a]) $ [command'] ++ vs
liftIO $ TIO.hPutStrLn h $ "*" ~~ (toParam $ 1 + length vs)
mapM_ (liftIO . TIO.hPutStrLn h) vs'
multiBulkT2 :: (MonadIO m, MonadFailure RedisError m)
=> Server -> T.Text -> [(T.Text, T.Text)] -> m ()
multiBulkT2 r command' kvs = do
multiBulk r command' $ concatMap (\kv -> [fst kv] ++ [snd kv]) kvs
-- ---------------------------------------------------------------------------
-- Reply
--
getReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
getReply r@(Server h) = do
prefix <- liftIO $ hGetChar h
getReplyType r prefix
getReplyType :: (MonadIO m, MonadFailure RedisError m)
=> Server -> Char -> m RedisValue
getReplyType r prefix =
case prefix of
'$' -> bulkReply r
':' -> integerReply r
'+' -> singleLineReply r
'-' -> singleLineReply r >>= \(RedisString m) -> failure $ ServerError m
'*' -> multiBulkReply r
_ -> singleLineReply r
bulkReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
bulkReply r@(Server h) = do
l <- liftIO $ TIO.hGetLine h
let bytes = convertUnsafe l::Int
if bytes == -1
then return $ RedisNil
else do
v <- takeChar bytes r
_ <- liftIO $ TIO.hGetLine h -- cleans up
return $ RedisString v
integerReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
integerReply (Server h) = do
l <- liftIO $ TIO.hGetLine h
return $ RedisInteger (convertUnsafe l::Int)
singleLineReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
singleLineReply (Server h) = do
l <- liftIO $ TIO.hGetLine h
return $ RedisString l
multiBulkReply :: (MonadIO m, MonadFailure RedisError m) => Server -> m RedisValue
multiBulkReply r@(Server h) = do
l <- liftIO $ TIO.hGetLine h
let items = convertUnsafe l::Int
multiBulkReply' r items []
multiBulkReply' :: (MonadIO m, MonadFailure RedisError m)
=> Server -> Int -> [RedisValue] -> m RedisValue
multiBulkReply' _ 0 values = return $ RedisMulti values
multiBulkReply' r@(Server h) n values = do
_ <- liftIO $ hGetChar h -- discard the type data since we know it's a bulk string
v <- bulkReply r
multiBulkReply' r (n - 1) (values ++ [v])
takeChar :: (MonadIO m, MonadFailure RedisError m)
=> Int -> Server -> m (T.Text)
takeChar n r = takeChar' n r ""
takeChar' :: (MonadIO m, MonadFailure RedisError m)
=> Int -> Server -> T.Text -> m (T.Text)
takeChar' 0 _ s = return s
takeChar' n r@(Server h) s = do
c <- liftIO $ hGetChar h
(takeChar' (n - 1) r (s ~~ (T.singleton c)))
-- ---------------------------------------------------------------------------
-- Helpers
--
(~~) :: T.Text -> T.Text -> T.Text
(~~) = T.append
boolify :: (Monad m) => m RedisValue -> m (Bool)
boolify v' = do
v <- v'
return $ case v of RedisString "OK" -> True
RedisInteger 1 -> True
_ -> False
discard :: (Monad a) => a b -> a ()
discard f = f >> return ()
|
brandur/redis-haskell
|
src/Database/Redis/Internal.hs
|
Haskell
|
bsd-3-clause
| 3,957
|
{-# OPTIONS -fglasgow-exts #-}
module LogicExample where
import Language.GroteTrap
import Data.Generics hiding (Prefix)
import Data.Set hiding (map)
-- Logic data structure.
data Logic
= Var String
| Or [Logic]
| And [Logic]
| Impl Logic Logic
| Not Logic
deriving (Show, Eq, Typeable, Data)
type LogicAlg a =
( String -> a
, [a] -> a
, [a] -> a
, a -> a -> a
, a -> a
)
foldLogic :: LogicAlg a -> Logic -> a
foldLogic (f1, f2, f3, f4, f5) = f where
f (Var a1 ) = f1 a1
f (Or a1) = f2 (map f a1)
f (And a1) = f3 (map f a1)
f (Impl a1 a2) = f4 (f a1) (f a2)
f (Not a1 ) = f5 (f a1)
-- Language definition.
logicLanguage :: Language Logic
logicLanguage = language
{ variable = Just Var
, operators =
[ Unary Not Prefix 0 "!"
, Assoc And 1 "&&"
, Assoc Or 2 "||"
, Binary Impl InfixR 3 "->"
]
}
-- Evaluation.
type Environment = Set String
evalLogic :: Environment -> Logic -> Bool
evalLogic env = foldLogic ((`member` env), or, and, (||) . not, not)
readLogic :: Environment -> String -> Bool
readLogic env = evalLogic env . readExpression logicLanguage
-- Examples
appie :: ParseTree
appie = readParseTree logicLanguage "piet && klaas && maartje -> supermarkt"
demo1 = appie
demo2 = unparse $ appie
demo9 = evaluate logicLanguage appie
demo3 = printTree $ appie
demo4 = fromError $ follow appie root
demo5 = fromError $ follow appie [0]
demo6 = range $ fromError $ follow appie [0]
demo7 = lshow logicLanguage (And [Var "p", Var "q"])
|
MedeaMelana/GroteTrap
|
LogicExample.hs
|
Haskell
|
bsd-3-clause
| 1,566
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternSynonyms #-}
module Syntax.Internal where
import Control.Lens.Prism
import Data.Map (Map)
import Data.Text (Text)
import Data.Vector (Vector)
import Syntax.Common
-- Would like to merge this with NType, but difficult to give a unifying type for Mon
-- Adding an extra type argument breaks a lot of stuff, and we then need to rethink Subst
data Kind
= KFun PType Kind
| KForall NTBinder Kind
| KVar NTVariable
| KObject KObject
| KUniverse
deriving (Show, Eq)
type Object = Map Projection
type KObject = Object Kind
type NObject = Object NType
_Fun :: Prism' NType (PType, NType)
_Fun = prism' (uncurry Fun) $ \case
Fun p n -> Just (p, n)
_ -> Nothing
_Forall :: Prism' NType (NTBinder, NType)
_Forall = prism' (uncurry Forall) $ \case
Forall p n -> Just (p, n)
_ -> Nothing
_NObject :: Prism' NType NObject
_NObject = prism' NObject $ \case
NObject n -> Just n
_ -> Nothing
_NCon :: Prism' NType (TConstructor, Args)
_NCon = prism' (uncurry NCon) $ \case
NCon d a -> Just (d, a)
_ -> Nothing
_Mon :: Prism' NType PType
_Mon = prism' Mon $ \case
Mon d -> Just d
_ -> Nothing
data NType
= Fun PType NType
-- ^ Functions, so far not dependent
| Forall NTBinder NType
| NVar NTVariable
| NCon TConstructor Args
| NObject NObject
| Mon PType
deriving (Show, Eq, Ord)
data TLit = TInt | TString
deriving (Show, Eq, Ord)
type PCoProduct = Map Constructor PType
type PStruct = Vector PType
_PCon :: Prism' PType (TConstructor, Args)
_PCon = prism' (uncurry PCon) $ \case
PCon d a -> Just (d,a)
_ -> Nothing
_PCoProduct :: Prism' PType PCoProduct
_PCoProduct = prism' PCoProduct $ \case
PCoProduct d -> Just d
_ -> Nothing
_PStruct :: Prism' PType PStruct
_PStruct = prism' PStruct $ \case
PStruct d -> Just d
_ -> Nothing
_Ptr :: Prism' PType NType
_Ptr = prism' Ptr $ \case
Ptr d -> Just d
_ -> Nothing
data PType
= PCon TConstructor Args
| PCoProduct PCoProduct
| PStruct PStruct
| PVar PTVariable
| Ptr NType
| PLit TLit
deriving (Show, Eq, Ord)
data CallFun = CDef Definition | CVar Variable deriving (Show, Eq, Ord)
data Call = Apply CallFun Args deriving (Show, Eq, Ord)
type TailCall = Call -- further checks should be done
-- can infer
data Act
= PutStrLn Val
| ReadLn
| Malloc PType Val
deriving (Show, Eq, Ord)
-- must check
data CMonad
= Act Act
| TCall TailCall
| Return Val
| CLeftTerm (LeftTerm CMonad)
| Bind Act Binder CMonad
| With Call Binder CMonad -- This allocates on the stack
deriving (Show)
-- must check
data Term mon
= Do mon
| RightTerm (RightTerm (Term mon))
| LeftTerm (LeftTerm (Term mon))
-- Explicit substitution, not sure yet I want this
-- | Let (ValSimple (ActSimple (CallSimple defs (Args nty defs free) free) free) free, PType defs pf nb nf bound free) bound
-- (Term mon defs pf nb nf bound free) -- This allocates on the stack
deriving (Show)
-- introduction for negatives,
-- (maybe it should have the CDef cut here)
data RightTerm cont
= Lam Binder cont
| TLam NTBinder cont
| New (Vector (CoBranch cont))
deriving (Show)
pattern Lam' :: Binder -> Term mon -> Term mon
pattern Lam' b t = RightTerm (Lam b t)
pattern TLam' :: NTBinder -> Term mon -> Term mon
pattern TLam' b t = RightTerm (TLam b t)
pattern New' :: Vector (CoBranch (Term mon)) -> Term mon
pattern New' bs = RightTerm (New bs)
-- elimination for positives + Cuts
--(maybe it should just have CVar -calls)
data LeftTerm cont
= Case Variable (Vector (Branch cont))
| Split Variable (Vector Binder) cont
| Derefence Variable cont
deriving (Show)
pattern Case' :: Variable -> (Vector (Branch (Term mon))) -> Term mon
pattern Case' v bs = LeftTerm (Case v bs)
pattern Split' :: Variable -> Vector Binder -> Term mon -> Term mon
pattern Split' v bs t = LeftTerm (Split v bs t)
pattern Derefence' :: Variable -> Term mon -> Term mon
pattern Derefence' v t = LeftTerm (Derefence v t)
data Branch cont = Branch Constructor cont
deriving (Show)
data CoBranch cont = CoBranch Projection cont
deriving (Show)
-- can infer
data Arg
= Push Val -- maybe we want (CMonad) and auto-lift computations to closest Do-block
-- Could have a run CMonad if it is guaranteed to be side-effect free (including free from non-termination aka it terminates)
| Proj Projection
| Type NType
deriving (Show, Eq, Ord)
-- type Arg defs pf nb nf bound free = ArgSimple
type Args = Vector Arg
data Literal = LInt Int | LStr Text
deriving (Show, Eq, Ord)
-- must check
data Val
= Var Variable
| Lit Literal
| Con Constructor Val
| Struct (Vector Val)
| Thunk Call -- or be monadic code?
| ThunkVal Val
deriving (Show, Eq, Ord)
|
Danten/lejf
|
src/Syntax/Internal.hs
|
Haskell
|
bsd-3-clause
| 4,829
|
import Distribution.PackageDescription
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.UserHooks
import System.Directory
import System.Exit
import System.FilePath
import System.Process
testSuiteExe = "b1-tests"
main :: IO ()
main = defaultMainWithHooks hooks
hooks :: UserHooks
hooks = simpleUserHooks { runTests = runTestSuite }
runTestSuite :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO ()
runTestSuite _ _ _ localBuildInfo = do
let testDir = buildDir localBuildInfo </> testSuiteExe
setCurrentDirectory testDir
exitCode <- system testSuiteExe
exitWith exitCode
|
btmura/b1
|
Setup.hs
|
Haskell
|
bsd-3-clause
| 642
|
module Data.MediaBus.Media.SyncStreamSpec
( spec,
)
where
import Control.Lens
import Control.Monad.State
import Data.Function
import Data.MediaBus
import Debug.Trace
import Test.Hspec
import Test.QuickCheck
import FakePayload
spec :: Spec
spec =
describe "setSequenceNumberAndTimestamp" $ do
it "increases the sequence number by one (only) for each frame" $
let prop :: (NonEmptyList (SyncStream () () FakePayload)) -> Bool
prop (NonEmpty inStr) =
let expectedLastSeqNum =
let isNext (MkStream (Next _)) = True
isNext _ = False
in max 0 (fromIntegral (length (filter isNext inStr)) - 1)
actualLastSeqNum =
let outStr =
let z :: (SeqNum16, Ticks64At8000)
z = (0, 0)
in evalState
( mapM
(state . setSequenceNumberAndTimestamp)
inStr
)
z
in case last outStr of
MkStream (Next f) -> f ^. seqNum
MkStream (Start f) -> max 0 (f ^. seqNum - 1)
in expectedLastSeqNum == actualLastSeqNum
in property prop
it "increases the sequence number monotonic" $
let prop :: (NonEmptyList (SyncStream () () FakePayload)) -> Bool
prop (NonEmpty inStr) =
let seqNumDiffs =
let outFrames =
let isNext (MkStream (Next _)) = True
isNext _ = False
outStr =
let z :: (SeqNum16, Ticks64At8000)
z = (0, 0)
in evalState
( mapM
(state . setSequenceNumberAndTimestamp)
inStr
)
z
in filter isNext outStr
in zipWith ((-) `on` (view seqNum)) (drop 1 outFrames) outFrames
in all (== 1) seqNumDiffs
in property prop
it "increases the timestamps by the duration of each frame" $
let prop :: (NonEmptyList (SyncStream () () FakePayload)) -> Bool
prop (NonEmpty inStr) =
let isNext (MkStream (Next _)) = True
isNext _ = False
outFrames :: [Stream () SeqNum16 Ticks64At8000 () FakePayload]
outFrames =
let outStr =
let z :: (SeqNum16, Ticks64At8000)
z = (0, MkTicks 0)
in evalState
( mapM
(state . setSequenceNumberAndTimestamp)
inStr
)
z
in filter isNext outStr
timestamps = map (view timestamp) outFrames
expectedTimestamps :: [Ticks64At8000]
expectedTimestamps =
let inFramesWithoutLast =
(filter isNext inStr)
inDurations =
map
(view (from nominalDiffTime) . getDuration)
inFramesWithoutLast
in scanl (+) 0 inDurations
in if and (zipWith (==) timestamps expectedTimestamps)
then True
else
traceShow
( timestamps,
expectedTimestamps,
outFrames
)
False
in property prop
|
lindenbaum/mediabus
|
specs/Data/MediaBus/Media/SyncStreamSpec.hs
|
Haskell
|
bsd-3-clause
| 3,912
|
{-|
Module : Graphics.Mosaico.Ventana
Description : Ventanas interactivas con distribuciones de rectángulos
Copyright : ⓒ Manuel Gómez, 2015
License : BSD3
Maintainer : targen@gmail.com
Stability : experimental
Portability : portable
Representación orientada a objetos de una ventana interactiva donde se puede
mostrar un 'Diagrama' con una parte enfocada, y obtener eventos de teclas
pulsadas en la ventana.
-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE UnicodeSyntax #-}
module Graphics.Mosaico.Ventana
( Ventana
, cerrar
, crearVentana
, leerTecla
, mostrar
)
where
import Control.Applicative (pure)
import Control.Concurrent (forkIO)
import Control.Concurrent.STM.TMChan (newTMChanIO, closeTMChan, readTMChan, writeTMChan)
import Control.Concurrent.STM.TVar (newTVarIO, readTVarIO, writeTVar)
import Control.Monad (void)
import Control.Monad.STM (atomically)
import Control.Monad.Unicode ((=≪))
import Control.Monad.IO.Class (liftIO)
import Data.Bool (Bool(True))
import Data.Colour.Names (blue, green, red, yellow)
import Data.Colour.SRGB (Colour, sRGB24)
import Data.Function (($), flip)
import Data.Function.Unicode ((∘))
import Data.Functor ((<$>))
import Data.List (reverse)
import Data.Maybe (Maybe(Nothing, Just))
import Data.Monoid (mappend, mempty)
import Data.String (String)
import Diagrams.Attributes (opacity)
import Diagrams.Backend.Cairo (Cairo)
import Diagrams.Backend.Gtk (renderToGtk, toGtkCoords)
import Diagrams.BoundingBox (boundingBox, boxExtents)
import Diagrams.Core.Types (Diagram)
import Diagrams.TwoD.Align (centerXY)
import Diagrams.TwoD.Attributes (fillColor, lineColor, lineWidth, ultraThick)
import Diagrams.TwoD.Combinators ((===), (|||))
import Diagrams.TwoD.Shapes (rect, unitSquare)
import Diagrams.TwoD.Size (SizeSpec2D(Dims), sized)
import Diagrams.TwoD.Transform (scaleX, scaleY)
import Diagrams.TwoD.Types (R2(R2))
import Diagrams.Util (( # ))
import Graphics.Mosaico.Imagen (Imagen(Imagen, altura, anchura), Color(Color, rojo, verde, azul))
import Graphics.Mosaico.Diagrama (Diagrama((:-:), (:|:), Hoja), Paso(Primero, Segundo), Rectángulo(Rectángulo, color, imagen))
import Graphics.UI.Gtk.Abstract.Container (containerChild)
import Graphics.UI.Gtk.Abstract.Widget (EventMask(KeyPressMask), Requisition(Requisition), exposeEvent, keyPressEvent, onDestroy, sizeRequest, widgetAddEvents, widgetDestroy, widgetQueueDraw, widgetShowAll)
import Graphics.UI.Gtk.Gdk.EventM (eventKeyName, eventWindow)
import Graphics.UI.Gtk.General.General (initGUI, mainGUI, mainQuit, postGUIAsync, postGUISync)
import Graphics.UI.Gtk.Misc.DrawingArea (drawingAreaNew)
import Graphics.UI.Gtk.Windows.Window (windowNew)
import Prelude (Double, Integer, fromInteger, fromIntegral)
import System.Glib.Attributes (AttrOp((:=)), set)
import System.Glib.Signals (on)
import System.Glib.UTFString (glibToString)
import System.IO (IO)
-- | Un valor del tipo 'Ventana' es un objeto que representa a una ventana
-- interactiva donde puede dibujarse un 'Diagrama'. Es posible, además,
-- obtener información de qué teclas son pulsadas sobre la ventana.
data Ventana
= Ventana
{ mostrar ∷ [Paso] → Diagrama → IO ()
-- ^ Dada una 'Ventana', un 'Diagrama', y una lista de 'Paso's,
-- representar gráficamente el 'Diagrama' dado sobre el lienzo de la
-- 'Ventana', haciendo resaltar visualmente el nodo del árbol alcanzado
-- si se realizan los movimientos correspondientes a la lista de
-- 'Paso's desde la raíz del árbol.
--
-- Los nodos se resaltan con un cuadro verde, y se colorean según el
-- tipo de nodo. En el caso de nodos intermedios, se colorea en azul
-- la región correspondiente al primer subárbol del nodo binario, y en
-- rojo la región correspondiente al segundo subárbol. En el caso de
-- nodos terminales (hojas), el rectángulo se colorea en amarillo.
, leerTecla ∷ IO (Maybe String)
-- ^ Dada una 'Ventana', esperar por un evento de teclado.
--
-- Cuando sobre la ventana se haya pulsado alguna tecla que no haya sido
-- reportada a través de este cómputo, se producirá como resultado
-- @'Just' tecla@, donde @tecla@ será el nombre de la tecla.
--
-- Si la ventana ya ha sido cerrada, se producirá como resultado
-- 'Nothing'.
--
-- El texto correspondiente a cada tecla es aproximadamente igual al
-- nombre del símbolo en la biblioteca GDK sin el prefijo @GDK_KEY_@.
-- La lista completa está disponible en
-- <https://git.gnome.org/browse/gtk+/plain/gdk/gdkkeysyms.h el código fuente de la biblioteca GDK>.
-- Sin embargo, la mejor manera de descubrir cuál simbolo corresponde
-- a cada tecla es crear una 'Ventana' y hacer que se imprima el texto
-- correspondiente a cada tecla pulsada sobre ella.
, cerrar ∷ IO ()
-- ^ Dada una 'Ventana', hacer que se cierre y que no pueda producir
-- más eventos de teclado.
}
-- | Construye un objeto del tipo 'Ventana' dadas sus dimensiones en número
-- de píxeles.
crearVentana
∷ Integer -- ^ Número de píxeles de anchura de la 'Ventana' a crear.
→ Integer -- ^ Número de píxeles de altura de la 'Ventana' a crear.
→ IO Ventana -- ^ La 'Ventana' nueva, ya visible, con el lienzo en blanco.
crearVentana anchura' altura'
= do
chan ← newTMChanIO
diagramaV ← newTVarIO mempty
void initGUI
window ← windowNew
drawingArea ← drawingAreaNew
set window [containerChild := drawingArea]
void
$ drawingArea `on` sizeRequest
$ pure (Requisition (fromInteger anchura') (fromInteger altura'))
void
$ window `on` keyPressEvent
$ do
key ← glibToString <$> eventKeyName
liftIO
∘ void
∘ atomically
$ writeTMChan chan key
pure True
void
$ drawingArea `on` exposeEvent
$ do
w ← eventWindow
liftIO
$ do
renderToGtk w
∘ toGtkCoords
∘ sized (Dims (fromIntegral anchura') (fromIntegral altura'))
=≪ readTVarIO diagramaV
pure True
void
$ onDestroy window
$ do
mainQuit
atomically $ closeTMChan chan
widgetAddEvents window [KeyPressMask]
widgetShowAll window
void $ forkIO mainGUI
let
ventana
= Ventana {..}
cerrar
= postGUISync
$ widgetDestroy window
leerTecla
= atomically
$ readTMChan chan
mostrar pasos diagrama
= postGUIAsync
$ do
atomically
∘ writeTVar diagramaV
$ renderDiagrama pasos diagrama
widgetQueueDraw drawingArea
pure ventana
renderDiagrama ∷ [Paso] → Diagrama → Diagram Cairo R2
renderDiagrama
= go ∘ pure
where
go pasos
= centerXY
∘ \ case
d1 :-: d2 → foco blue (go pasosPrimero d1) === foco red (go pasosSegundo d2)
d1 :|: d2 → foco blue (go pasosPrimero d1) ||| foco red (go pasosSegundo d2)
Hoja
Rectángulo { color = Color {..}, imagen = Imagen {..} }
→ foco yellow
$ unitSquare
# fillColor (sRGB24 rojo verde azul ∷ Colour Double)
# scaleX (fromInteger anchura)
# scaleY (fromInteger altura )
where
pasosPrimero
= case pasos of
Just (Primero:xs) → Just xs
_ → Nothing
pasosSegundo
= case pasos of
Just (Segundo:xs) → Just xs
_ → Nothing
foco color diagrama
= case pasos of
Just []
→ flip mappend (diagrama # centerXY)
∘ toRect
∘ boxExtents
$ boundingBox diagrama
_ → diagrama
where
toRect (R2 w h)
= rect w h
# fillColor (color ∷ Colour Double)
# lineColor (green ∷ Colour Double)
# lineWidth ultraThick
# opacity 0.25
|
mgomezch/mosaico-lib
|
src/Graphics/Mosaico/Ventana.hs
|
Haskell
|
bsd-3-clause
| 8,806
|
{-| Implementation of the Ganeti confd utilities.
This holds a few utility functions that could be useful in both
clients and servers.
-}
{-
Copyright (C) 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Confd.Utils
( getClusterHmac
, parseSignedMessage
, parseRequest
, parseReply
, signMessage
, getCurrentTime
, extractJSONPath
) where
import qualified Data.Attoparsec.Text as P
import qualified Data.ByteString as B
import Data.Text (pack)
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Confd.Types
import Ganeti.Hash
import qualified Ganeti.Constants as C
import qualified Ganeti.Path as Path
import Ganeti.JSON (fromJResult)
import Ganeti.Utils
-- | Type-adjusted max clock skew constant.
maxClockSkew :: Integer
maxClockSkew = fromIntegral C.confdMaxClockSkew
-- | Returns the HMAC key.
getClusterHmac :: IO HashKey
getClusterHmac = Path.confdHmacKey >>= fmap B.unpack . B.readFile
-- | Parses a signed message.
parseSignedMessage :: (J.JSON a) => HashKey -> String
-> Result (String, String, a)
parseSignedMessage key str = do
(SignedMessage hmac msg salt) <- fromJResult "parsing signed message"
$ J.decode str
parsedMsg <- if verifyMac key (Just salt) msg hmac
then fromJResult "parsing message" $ J.decode msg
else Bad "HMAC verification failed"
return (salt, msg, parsedMsg)
-- | Message parsing. This can either result in a good, valid request
-- message, or fail in the Result monad.
parseRequest :: HashKey -> String -> Integer
-> Result (String, ConfdRequest)
parseRequest hmac msg curtime = do
(salt, origmsg, request) <- parseSignedMessage hmac msg
ts <- tryRead "Parsing timestamp" salt::Result Integer
if abs (ts - curtime) > maxClockSkew
then fail "Too old/too new timestamp or clock skew"
else return (origmsg, request)
-- | Message parsing. This can either result in a good, valid reply
-- message, or fail in the Result monad.
-- It also checks that the salt in the message corresponds to the one
-- that is expected
parseReply :: HashKey -> String -> String -> Result (String, ConfdReply)
parseReply hmac msg expSalt = do
(salt, origmsg, reply) <- parseSignedMessage hmac msg
if salt /= expSalt
then fail "The received salt differs from the expected salt"
else return (origmsg, reply)
-- | Signs a message with a given key and salt.
signMessage :: HashKey -> String -> String -> SignedMessage
signMessage key salt msg =
SignedMessage { signedMsgMsg = msg
, signedMsgSalt = salt
, signedMsgHmac = hmac
}
where hmac = computeMac key (Just salt) msg
data Pointer = Pointer [String]
deriving (Show, Eq)
-- | Parse a fixed size Int.
readInteger :: String -> J.Result Int
readInteger = either J.Error J.Ok . P.parseOnly P.decimal . pack
-- | Parse a path for a JSON structure.
pointerFromString :: String -> J.Result Pointer
pointerFromString s =
either J.Error J.Ok . P.parseOnly parser $ pack s
where
parser = do
_ <- P.char '/'
tokens <- token `P.sepBy1` P.char '/'
return $ Pointer tokens
token =
P.choice [P.many1 (P.choice [ escaped
, P.satisfy $ P.notInClass "~/"])
, P.endOfInput *> return ""]
escaped = P.choice [escapedSlash, escapedTilde]
escapedSlash = P.string (pack "~1") *> return '/'
escapedTilde = P.string (pack "~0") *> return '~'
-- | Use a Pointer to access any value nested in a JSON object.
extractValue :: J.JSON a => Pointer -> a -> J.Result J.JSValue
extractValue (Pointer l) json =
getJSValue l $ J.showJSON json
where
indexWithString x (J.JSObject object) = J.valFromObj x object
indexWithString x (J.JSArray list) = do
i <- readInteger x
if 0 <= i && i < length list
then return $ list !! i
else J.Error ("list index " ++ show i ++ " out of bounds")
indexWithString _ _ = J.Error "Atomic value was indexed"
getJSValue :: [String] -> J.JSValue -> J.Result J.JSValue
getJSValue [] js = J.Ok js
getJSValue (x:xs) js = do
value <- indexWithString x js
getJSValue xs value
-- | Extract a 'JSValue' from an object at the position defined by the path.
--
-- The path syntax follows RCF6901. Error is returned if the path doesn't
-- exist, Ok if the path leads to an valid value.
--
-- JSON pointer syntax according to RFC6901:
--
-- > "/path/0/x" => Pointer ["path", "0", "x"]
--
-- This accesses 1 in the following JSON:
--
-- > { "path": { "0": { "x": 1 } } }
--
-- or the following:
--
-- > { "path": [{"x": 1}] }
extractJSONPath :: J.JSON a => String -> a -> J.Result J.JSValue
extractJSONPath path obj = do
pointer <- pointerFromString path
extractValue pointer obj
|
mbakke/ganeti
|
src/Ganeti/Confd/Utils.hs
|
Haskell
|
bsd-2-clause
| 6,028
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
-- | Main stack tool entry point.
module Main where
import Control.Exception
import qualified Control.Exception.Lifted as EL
import Control.Monad hiding (mapM, forM)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (ask, asks, runReaderT)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Attoparsec.Args (withInterpreterArgs, parseArgs, EscapingMode (Escaping))
import qualified Data.ByteString.Lazy as L
import Data.IORef
import Data.List
import qualified Data.Map as Map
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Traversable
import Data.Typeable (Typeable)
import Data.Version (showVersion)
import Distribution.System (buildArch)
import Distribution.Text (display)
import Development.GitRev (gitCommitCount)
import GHC.IO.Encoding (mkTextEncoding, textEncodingName)
import Network.HTTP.Client
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Options.Applicative.Simple
import Options.Applicative.Types (readerAsk)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import qualified Paths_stack as Meta
import Prelude hiding (pi, mapM)
import Stack.Build
import Stack.Types.Build
import Stack.Config
import Stack.Constants
import qualified Stack.Docker as Docker
import Stack.Dot
import Stack.Exec
import Stack.Fetch
import Stack.FileWatch
import Stack.Ide
import qualified Stack.Image as Image
import Stack.Init
import Stack.New
import Stack.Options
import Stack.Package (getCabalFileName)
import qualified Stack.PackageIndex
import Stack.Ghci
import Stack.GhcPkg (getGlobalDB, mkGhcPackagePath)
import Stack.SDist (getSDistTarball)
import Stack.Setup
import Stack.Solver (solveExtraDeps)
import Stack.Types
import Stack.Types.Internal
import Stack.Types.StackT
import Stack.Upgrade
import qualified Stack.Upload as Upload
import System.Directory (canonicalizePath, doesFileExist, doesDirectoryExist, createDirectoryIfMissing)
import System.Environment (getEnvironment, getProgName)
import System.Exit
import System.FileLock (lockFile, tryLockFile, unlockFile, SharedExclusive(Exclusive), FileLock)
import System.FilePath (searchPathSeparator)
import System.IO (hIsTerminalDevice, stderr, stdin, stdout, hSetBuffering, BufferMode(..), hPutStrLn, Handle, hGetEncoding, hSetEncoding)
import System.Process.Read
-- | Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit h = do
menc <- hGetEncoding h
case fmap textEncodingName menc of
Just name
| '/' `notElem` name -> do
enc' <- mkTextEncoding $ name ++ "//TRANSLIT"
hSetEncoding h enc'
_ -> return ()
-- | Commandline dispatcher.
main :: IO ()
main = withInterpreterArgs stackProgName $ \args isInterpreter -> do
-- Line buffer the output by default, particularly for non-terminal runs.
-- See https://github.com/commercialhaskell/stack/pull/360
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
hSetBuffering stderr LineBuffering
hSetTranslit stdout
hSetTranslit stderr
progName <- getProgName
isTerminal <- hIsTerminalDevice stdout
execExtraHelp args
dockerHelpOptName
(dockerOptsParser True)
("Only showing --" ++ Docker.dockerCmdName ++ "* options.")
let versionString' = concat $ concat
[ [$(simpleVersion Meta.version)]
-- Leave out number of commits for --depth=1 clone
-- See https://github.com/commercialhaskell/stack/issues/792
, [" (" ++ $gitCommitCount ++ " commits)" | $gitCommitCount /= ("1"::String) &&
$gitCommitCount /= ("UNKNOWN" :: String)]
, [" ", display buildArch]
]
let numericVersion :: Parser (a -> a)
numericVersion =
infoOption
(showVersion Meta.version)
(long "numeric-version" <>
help "Show only version number")
eGlobalRun <- try $
simpleOptions
versionString'
"stack - The Haskell Tool Stack"
""
(numericVersion <*> extraHelpOption progName (Docker.dockerCmdName ++ "*") dockerHelpOptName <*>
globalOptsParser isTerminal)
(do addCommand "build"
"Build the project(s) in this directory/configuration"
buildCmd
(buildOptsParser Build)
addCommand "install"
"Shortcut for 'build --copy-bins'"
buildCmd
(buildOptsParser Install)
addCommand "uninstall"
"DEPRECATED: This command performs no actions, and is present for documentation only"
uninstallCmd
(many $ strArgument $ metavar "IGNORED")
addCommand "test"
"Shortcut for 'build --test'"
buildCmd
(buildOptsParser Test)
addCommand "bench"
"Shortcut for 'build --bench'"
buildCmd
(buildOptsParser Bench)
addCommand "haddock"
"Shortcut for 'build --haddock'"
buildCmd
(buildOptsParser Haddock)
addCommand "new"
"Create a new project from a template. Run `stack templates' to see available templates."
newCmd
newOptsParser
addCommand "templates"
"List the templates available for `stack new'."
templatesCmd
(pure ())
addCommand "init"
"Initialize a stack project based on one or more cabal packages"
initCmd
initOptsParser
addCommand "solver"
"Use a dependency solver to try and determine missing extra-deps"
solverCmd
solverOptsParser
addCommand "setup"
"Get the appropriate GHC for your project"
setupCmd
setupParser
addCommand "path"
"Print out handy path information"
pathCmd
(fmap
catMaybes
(sequenceA
(map
(\(desc,name,_) ->
flag Nothing
(Just name)
(long (T.unpack name) <>
help desc))
paths)))
addCommand "unpack"
"Unpack one or more packages locally"
unpackCmd
(some $ strArgument $ metavar "PACKAGE")
addCommand "update"
"Update the package index"
updateCmd
(pure ())
addCommand "upgrade"
"Upgrade to the latest stack (experimental)"
upgradeCmd
((,) <$> (switch
( long "git"
<> help "Clone from Git instead of downloading from Hackage (more dangerous)"
))
<*> (strOption
( long "git-repo"
<> help "Clone from specified git repository"
<> value "https://github.com/commercialhaskell/stack"
<> showDefault
)))
addCommand "upload"
"Upload a package to Hackage"
uploadCmd
((,)
<$> (many $ strArgument $ metavar "TARBALL/DIR")
<*> optional pvpBoundsOption)
addCommand "sdist"
"Create source distribution tarballs"
sdistCmd
((,)
<$> (many $ strArgument $ metavar "DIR")
<*> optional pvpBoundsOption)
addCommand "dot"
"Visualize your project's dependency graph using Graphviz dot"
dotCmd
dotOptsParser
addCommand "exec"
"Execute a command"
execCmd
(execOptsParser Nothing)
addCommand "ghc"
"Run ghc"
execCmd
(execOptsParser $ Just "ghc")
addCommand "ghci"
"Run ghci in the context of project(s) (experimental)"
ghciCmd
ghciOptsParser
addCommand "runghc"
"Run runghc"
execCmd
(execOptsParser $ Just "runghc")
addCommand "eval"
"Evaluate some haskell code inline. Shortcut for 'stack exec ghc -- -e CODE'"
evalCmd
(evalOptsParser $ Just "CODE") -- metavar = "CODE"
addCommand "clean"
"Clean the local packages"
cleanCmd
(pure ())
addCommand "list-dependencies"
"List the dependencies"
listDependenciesCmd
(textOption (long "separator" <>
metavar "SEP" <>
help ("Separator between package name " <>
"and package version.") <>
value " " <>
showDefault))
addCommand "query"
"Query general build information (experimental)"
queryCmd
(many $ strArgument $ metavar "SELECTOR...")
addSubCommands
"ide"
"IDE-specific commands"
(do addCommand
"start"
"Start the ide-backend service"
ideCmd
((,) <$> many (textArgument
(metavar "TARGET" <>
help ("If none specified, use all " <>
"packages defined in current directory")))
<*> argsOption (long "ghc-options" <>
metavar "OPTION" <>
help "Additional options passed to GHCi" <>
value []))
addCommand
"packages"
"List all available local loadable packages"
packagesCmd
(pure ())
addCommand
"load-targets"
"List all load targets for a package target"
targetsCmd
(textArgument
(metavar "TARGET")))
addSubCommands
Docker.dockerCmdName
"Subcommands specific to Docker use"
(do addCommand Docker.dockerPullCmdName
"Pull latest version of Docker image from registry"
dockerPullCmd
(pure ())
addCommand "reset"
"Reset the Docker sandbox"
dockerResetCmd
(switch (long "keep-home" <>
help "Do not delete sandbox's home directory"))
addCommand Docker.dockerCleanupCmdName
"Clean up Docker images and containers"
dockerCleanupCmd
dockerCleanupOptsParser)
addSubCommands
Image.imgCmdName
"Subcommands specific to imaging (EXPERIMENTAL)"
(addCommand Image.imgDockerCmdName
"Build a Docker image for the project"
imgDockerCmd
(pure ())))
case eGlobalRun of
Left (exitCode :: ExitCode) -> do
when isInterpreter $
hPutStrLn stderr $ concat
[ "\nIf you are trying to use "
, stackProgName
, " as a script interpreter, a\n'-- "
, stackProgName
, " [options] runghc [options]' comment is required."
, "\nSee https://github.com/commercialhaskell/stack/blob/release/doc/GUIDE.md#ghcrunghc" ]
throwIO exitCode
Right (global,run) -> do
when (globalLogLevel global == LevelDebug) $ hPutStrLn stderr versionString'
case globalReExecVersion global of
Just expectVersion
| expectVersion /= showVersion Meta.version ->
throwIO $ InvalidReExecVersion expectVersion (showVersion Meta.version)
_ -> return ()
run global `catch` \e -> do
-- This special handler stops "stack: " from being printed before the
-- exception
case fromException e of
Just ec -> exitWith ec
Nothing -> do
printExceptionStderr e
exitFailure
where
dockerHelpOptName = Docker.dockerCmdName ++ "-help"
-- | Print out useful path information in a human-readable format (and
-- support others later).
pathCmd :: [Text] -> GlobalOpts -> IO ()
pathCmd keys go =
withBuildConfig
go
(do env <- ask
let cfg = envConfig env
bc = envConfigBuildConfig cfg
menv <- getMinimalEnvOverride
snap <- packageDatabaseDeps
local <- packageDatabaseLocal
global <- getGlobalDB menv =<< getWhichCompiler
snaproot <- installationRootDeps
localroot <- installationRootLocal
distDir <- distRelativeDir
forM_
(filter
(\(_,key,_) ->
null keys || elem key keys)
paths)
(\(_,key,path) ->
liftIO $ T.putStrLn
((if length keys == 1
then ""
else key <> ": ") <>
path
(PathInfo
bc
menv
snap
local
global
snaproot
localroot
distDir))))
-- | Passed to all the path printers as a source of info.
data PathInfo = PathInfo
{piBuildConfig :: BuildConfig
,piEnvOverride :: EnvOverride
,piSnapDb :: Path Abs Dir
,piLocalDb :: Path Abs Dir
,piGlobalDb :: Path Abs Dir
,piSnapRoot :: Path Abs Dir
,piLocalRoot :: Path Abs Dir
,piDistDir :: Path Rel Dir
}
-- | The paths of interest to a user. The first tuple string is used
-- for a description that the optparse flag uses, and the second
-- string as a machine-readable key and also for @--foo@ flags. The user
-- can choose a specific path to list like @--global-stack-root@. But
-- really it's mainly for the documentation aspect.
--
-- When printing output we generate @PathInfo@ and pass it to the
-- function to generate an appropriate string. Trailing slashes are
-- removed, see #506
paths :: [(String, Text, PathInfo -> Text)]
paths =
[ ( "Global stack root directory"
, "global-stack-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (configStackRoot (bcConfig (piBuildConfig pi)))))
, ( "Project root (derived from stack.yaml file)"
, "project-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (bcRoot (piBuildConfig pi))))
, ( "Configuration location (where the stack.yaml file is)"
, "config-location"
, \pi ->
T.pack (toFilePath (bcStackYaml (piBuildConfig pi))))
, ( "PATH environment variable"
, "bin-path"
, \pi ->
T.pack (intercalate [searchPathSeparator] (eoPath (piEnvOverride pi))))
, ( "Installed GHCs (unpacked and archives)"
, "ghc-paths"
, \pi ->
T.pack (toFilePathNoTrailingSep (configLocalPrograms (bcConfig (piBuildConfig pi)))))
, ( "Local bin path where stack installs executables"
, "local-bin-path"
, \pi ->
T.pack (toFilePathNoTrailingSep (configLocalBin (bcConfig (piBuildConfig pi)))))
, ( "Extra include directories"
, "extra-include-dirs"
, \pi ->
T.intercalate
", "
(Set.elems (configExtraIncludeDirs (bcConfig (piBuildConfig pi)))))
, ( "Extra library directories"
, "extra-library-dirs"
, \pi ->
T.intercalate ", " (Set.elems (configExtraLibDirs (bcConfig (piBuildConfig pi)))))
, ( "Snapshot package database"
, "snapshot-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailingSep (piSnapDb pi)))
, ( "Local project package database"
, "local-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailingSep (piLocalDb pi)))
, ( "Global package database"
, "global-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailingSep (piGlobalDb pi)))
, ( "GHC_PACKAGE_PATH environment variable"
, "ghc-package-path"
, \pi -> mkGhcPackagePath True (piLocalDb pi) (piSnapDb pi) (piGlobalDb pi))
, ( "Snapshot installation root"
, "snapshot-install-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piSnapRoot pi)))
, ( "Local project installation root"
, "local-install-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piLocalRoot pi)))
, ( "Snapshot documentation root"
, "snapshot-doc-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piSnapRoot pi </> docDirSuffix)))
, ( "Local project documentation root"
, "local-doc-root"
, \pi ->
T.pack (toFilePathNoTrailingSep (piLocalRoot pi </> docDirSuffix)))
, ( "Dist work directory"
, "dist-dir"
, \pi ->
T.pack (toFilePathNoTrailingSep (piDistDir pi)))]
data SetupCmdOpts = SetupCmdOpts
{ scoCompilerVersion :: !(Maybe CompilerVersion)
, scoForceReinstall :: !Bool
, scoUpgradeCabal :: !Bool
, scoStackSetupYaml :: !String
, scoGHCBindistURL :: !(Maybe String)
}
setupParser :: Parser SetupCmdOpts
setupParser = SetupCmdOpts
<$> (optional $ argument readVersion
(metavar "GHC_VERSION" <>
help ("Version of GHC to install, e.g. 7.10.2. " ++
"The default is to install the version implied by the resolver.")))
<*> boolFlags False
"reinstall"
"reinstalling GHC, even if available (implies no-system-ghc)"
idm
<*> boolFlags False
"upgrade-cabal"
"installing the newest version of the Cabal library globally"
idm
<*> strOption
( long "stack-setup-yaml"
<> help "Location of the main stack-setup.yaml file"
<> value defaultStackSetupYaml
<> showDefault
)
<*> (optional $ strOption
(long "ghc-bindist"
<> metavar "URL"
<> help "Alternate GHC binary distribution (requires custom --ghc-variant)"
))
where
readVersion = do
s <- readerAsk
case parseCompilerVersion ("ghc-" <> T.pack s) of
Nothing ->
case parseCompilerVersion (T.pack s) of
Nothing -> readerError $ "Invalid version: " ++ s
Just x -> return x
Just x -> return x
setupCmd :: SetupCmdOpts -> GlobalOpts -> IO ()
setupCmd SetupCmdOpts{..} go@GlobalOpts{..} = do
(manager,lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer
(lcProjectRoot lc)
Nothing
(runStackLoggingTGlobal manager go $ do
(wantedCompiler, compilerCheck, mstack) <-
case scoCompilerVersion of
Just v -> return (v, MatchMinor, Nothing)
Nothing -> do
bc <- lcLoadBuildConfig lc globalResolver
return ( bcWantedCompiler bc
, configCompilerCheck (lcConfig lc)
, Just $ bcStackYaml bc
)
miniConfig <- loadMiniConfig (lcConfig lc)
mpaths <- runStackTGlobal manager miniConfig go $
ensureCompiler SetupOpts
{ soptsInstallIfMissing = True
, soptsUseSystem =
(configSystemGHC $ lcConfig lc)
&& not scoForceReinstall
, soptsWantedCompiler = wantedCompiler
, soptsCompilerCheck = compilerCheck
, soptsStackYaml = mstack
, soptsForceReinstall = scoForceReinstall
, soptsSanityCheck = True
, soptsSkipGhcCheck = False
, soptsSkipMsys = configSkipMsys $ lcConfig lc
, soptsUpgradeCabal = scoUpgradeCabal
, soptsResolveMissingGHC = Nothing
, soptsStackSetupYaml = scoStackSetupYaml
, soptsGHCBindistURL = scoGHCBindistURL
}
let compiler = case wantedCompiler of
GhcVersion _ -> "GHC"
GhcjsVersion {} -> "GHCJS"
case mpaths of
Nothing -> $logInfo $ "stack will use the " <> compiler <> " on your PATH"
Just _ -> $logInfo $ "stack will use a locally installed " <> compiler
$logInfo "For more information on paths, see 'stack path' and 'stack exec env'"
$logInfo $ "To use this " <> compiler <> " and packages outside of a project, consider using:"
$logInfo "stack ghc, stack ghci, stack runghc, or stack exec"
)
Nothing
(Just $ munlockFile lk)
-- | Unlock a lock file, if the value is Just
munlockFile :: MonadIO m => Maybe FileLock -> m ()
munlockFile Nothing = return ()
munlockFile (Just lk) = liftIO $ unlockFile lk
-- | Enforce mutual exclusion of every action running via this
-- function, on this path, on this users account.
--
-- A lock file is created inside the given directory. Currently,
-- stack uses locks per-snapshot. In the future, stack may refine
-- this to an even more fine-grain locking approach.
--
withUserFileLock :: (MonadBaseControl IO m, MonadIO m)
=> GlobalOpts
-> Path Abs Dir
-> (Maybe FileLock -> m a)
-> m a
withUserFileLock go@GlobalOpts{} dir act = do
env <- liftIO getEnvironment
let toLock = lookup "STACK_LOCK" env == Just "true"
if toLock
then do
let lockfile = $(mkRelFile "lockfile")
let pth = dir </> lockfile
liftIO $ createDirectoryIfMissing True (toFilePath dir)
-- Just in case of asynchronous exceptions, we need to be careful
-- when using tryLockFile here:
EL.bracket (liftIO $ tryLockFile (toFilePath pth) Exclusive)
(\fstTry -> maybe (return ()) (liftIO . unlockFile) fstTry)
(\fstTry ->
case fstTry of
Just lk -> EL.finally (act $ Just lk) (liftIO $ unlockFile lk)
Nothing ->
do let chatter = globalLogLevel go /= LevelOther "silent"
when chatter $
liftIO $ hPutStrLn stderr $ "Failed to grab lock ("++show pth++
"); other stack instance running. Waiting..."
EL.bracket (liftIO $ lockFile (toFilePath pth) Exclusive)
(liftIO . unlockFile)
(\lk -> do
when chatter $
liftIO $ hPutStrLn stderr "Lock acquired, proceeding."
act $ Just lk))
else act Nothing
withConfigAndLock :: GlobalOpts
-> StackT Config IO ()
-> IO ()
withConfigAndLock go@GlobalOpts{..} inner = do
(manager, lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer (lcProjectRoot lc)
Nothing
(runStackTGlobal manager (lcConfig lc) go inner)
Nothing
(Just $ munlockFile lk)
-- For now the non-locking version just unlocks immediately.
-- That is, there's still a serialization point.
withBuildConfig :: GlobalOpts
-> (StackT EnvConfig IO ())
-> IO ()
withBuildConfig go inner =
withBuildConfigAndLock go (\lk -> do munlockFile lk
inner)
withBuildConfigAndLock :: GlobalOpts
-> (Maybe FileLock -> StackT EnvConfig IO ())
-> IO ()
withBuildConfigAndLock go inner =
withBuildConfigExt go Nothing inner Nothing
withBuildConfigExt
:: GlobalOpts
-> Maybe (StackT Config IO ())
-- ^ Action to perform after before build. This will be run on the host
-- OS even if Docker is enabled for builds. The build config is not
-- available in this action, since that would require build tools to be
-- installed on the host OS.
-> (Maybe FileLock -> StackT EnvConfig IO ())
-- ^ Action that uses the build config. If Docker is enabled for builds,
-- this will be run in a Docker container.
-> Maybe (StackT Config IO ())
-- ^ Action to perform after the build. This will be run on the host
-- OS even if Docker is enabled for builds. The build config is not
-- available in this action, since that would require build tools to be
-- installed on the host OS.
-> IO ()
withBuildConfigExt go@GlobalOpts{..} mbefore inner mafter = do
(manager, lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk0 -> do
-- A local bit of state for communication between callbacks:
curLk <- newIORef lk0
let inner' lk =
-- Locking policy: This is only used for build commands, which
-- only need to lock the snapshot, not the global lock. We
-- trade in the lock here.
do dir <- installationRootDeps
-- Hand-over-hand locking:
withUserFileLock go dir $ \lk2 -> do
liftIO $ writeIORef curLk lk2
liftIO $ munlockFile lk
inner lk2
let inner'' lk = do
bconfig <- runStackLoggingTGlobal manager go $
lcLoadBuildConfig lc globalResolver
envConfig <-
runStackTGlobal
manager bconfig go
(setupEnv Nothing)
runStackTGlobal
manager
envConfig
go
(inner' lk)
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer (lcProjectRoot lc) mbefore (inner'' lk0) mafter
(Just $ liftIO $
do lk' <- readIORef curLk
munlockFile lk')
cleanCmd :: () -> GlobalOpts -> IO ()
cleanCmd () go = withBuildConfigAndLock go (\_ -> clean)
-- | Helper for build and install commands
buildCmd :: BuildOpts -> GlobalOpts -> IO ()
buildCmd opts go = do
when (any (("-prof" `elem`) . either (const []) id . parseArgs Escaping) (boptsGhcOptions opts)) $ do
hPutStrLn stderr "When building with stack, you should not use the -prof GHC option"
hPutStrLn stderr "Instead, please use --enable-library-profiling and --enable-executable-profiling"
hPutStrLn stderr "See: https://github.com/commercialhaskell/stack/issues/1015"
error "-prof GHC option submitted"
case boptsFileWatch opts of
FileWatchPoll -> fileWatchPoll inner
FileWatch -> fileWatch inner
NoFileWatch -> inner $ const $ return ()
where
inner setLocalFiles = withBuildConfigAndLock go $ \lk ->
Stack.Build.build setLocalFiles lk opts
uninstallCmd :: [String] -> GlobalOpts -> IO ()
uninstallCmd _ go = withConfigAndLock go $ do
$logError "stack does not manage installations in global locations"
$logError "The only global mutation stack performs is executable copying"
$logError "For the default executable destination, please run 'stack path --local-bin-path'"
-- | Unpack packages to the filesystem
unpackCmd :: [String] -> GlobalOpts -> IO ()
unpackCmd names go = withConfigAndLock go $ do
menv <- getMinimalEnvOverride
Stack.Fetch.unpackPackages menv "." names
-- | Update the package index
updateCmd :: () -> GlobalOpts -> IO ()
updateCmd () go = withConfigAndLock go $
getMinimalEnvOverride >>= Stack.PackageIndex.updateAllIndices
upgradeCmd :: (Bool, String) -> GlobalOpts -> IO ()
upgradeCmd (fromGit, repo) go = withConfigAndLock go $
upgrade (if fromGit then Just repo else Nothing) (globalResolver go)
-- | Upload to Hackage
uploadCmd :: ([String], Maybe PvpBounds) -> GlobalOpts -> IO ()
uploadCmd ([], _) _ = error "To upload the current package, please run 'stack upload .'"
uploadCmd (args, mpvpBounds) go = do
let partitionM _ [] = return ([], [])
partitionM f (x:xs) = do
r <- f x
(as, bs) <- partitionM f xs
return $ if r then (x:as, bs) else (as, x:bs)
(files, nonFiles) <- partitionM doesFileExist args
(dirs, invalid) <- partitionM doesDirectoryExist nonFiles
when (not (null invalid)) $ error $
"stack upload expects a list sdist tarballs or cabal directories. Can't find " ++
show invalid
let getUploader :: (HasStackRoot config, HasPlatform config, HasConfig config) => StackT config IO Upload.Uploader
getUploader = do
config <- asks getConfig
manager <- asks envManager
let uploadSettings =
Upload.setGetManager (return manager) $
Upload.defaultUploadSettings
liftIO $ Upload.mkUploader config uploadSettings
if null dirs
then withConfigAndLock go $ do
uploader <- getUploader
liftIO $ forM_ files (canonicalizePath >=> Upload.upload uploader)
else withBuildConfigAndLock go $ \_ -> do
uploader <- getUploader
liftIO $ forM_ files (canonicalizePath >=> Upload.upload uploader)
forM_ dirs $ \dir -> do
pkgDir <- parseAbsDir =<< liftIO (canonicalizePath dir)
(tarName, tarBytes) <- getSDistTarball mpvpBounds pkgDir
liftIO $ Upload.uploadBytes uploader tarName tarBytes
sdistCmd :: ([String], Maybe PvpBounds) -> GlobalOpts -> IO ()
sdistCmd (dirs, mpvpBounds) go =
withBuildConfig go $ do -- No locking needed.
-- If no directories are specified, build all sdist tarballs.
dirs' <- if null dirs
then asks (Map.keys . envConfigPackages . getEnvConfig)
else mapM (parseAbsDir <=< liftIO . canonicalizePath) dirs
forM_ dirs' $ \dir -> do
(tarName, tarBytes) <- getSDistTarball mpvpBounds dir
distDir <- distDirFromDir dir
tarPath <- fmap (distDir </>) $ parseRelFile tarName
liftIO $ createTree $ parent tarPath
liftIO $ L.writeFile (toFilePath tarPath) tarBytes
$logInfo $ "Wrote sdist tarball to " <> T.pack (toFilePath tarPath)
-- | Execute a command.
execCmd :: ExecOpts -> GlobalOpts -> IO ()
execCmd ExecOpts {..} go@GlobalOpts{..} = do
(cmd, args) <-
case (eoCmd, eoArgs) of
(Just cmd, args) -> return (cmd, args)
(Nothing, cmd:args) -> return (cmd, args)
(Nothing, []) -> error "You must provide a command to exec, e.g. 'stack exec echo Hello World'"
case eoExtra of
ExecOptsPlain -> do
(manager,lc) <- liftIO $ loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.execWithOptionalContainer
(lcProjectRoot lc)
(\_ _ -> return (cmd, args, [], []))
-- Unlock before transferring control away, whether using docker or not:
(Just $ munlockFile lk)
(runStackTGlobal manager (lcConfig lc) go $ do
exec plainEnvSettings cmd args)
Nothing
Nothing -- Unlocked already above.
ExecOptsEmbellished {..} ->
withBuildConfigAndLock go $ \lk -> do
let targets = concatMap words eoPackages
unless (null targets) $
Stack.Build.build (const $ return ()) lk defaultBuildOpts
{ boptsTargets = map T.pack targets
}
munlockFile lk -- Unlock before transferring control away.
exec eoEnvSettings cmd args
-- | Evaluate some haskell code inline.
evalCmd :: EvalOpts -> GlobalOpts -> IO ()
evalCmd EvalOpts {..} go@GlobalOpts {..} = execCmd execOpts go
where
execOpts =
ExecOpts { eoCmd = Just "ghc"
, eoArgs = ["-e", evalArg]
, eoExtra = evalExtra
}
-- | Run GHCi in the context of a project.
ghciCmd :: GhciOpts -> GlobalOpts -> IO ()
ghciCmd ghciOpts go@GlobalOpts{..} =
withBuildConfigAndLock go $ \lk -> do
let packageTargets = concatMap words (ghciAdditionalPackages ghciOpts)
unless (null packageTargets) $
Stack.Build.build (const $ return ()) lk defaultBuildOpts
{ boptsTargets = map T.pack packageTargets
}
munlockFile lk -- Don't hold the lock while in the GHCI.
ghci ghciOpts
-- | Run ide-backend in the context of a project.
ideCmd :: ([Text], [String]) -> GlobalOpts -> IO ()
ideCmd (targets,args) go@GlobalOpts{..} =
withBuildConfig go $ -- No locking needed.
ide targets args
-- | List packages in the project.
packagesCmd :: () -> GlobalOpts -> IO ()
packagesCmd () go@GlobalOpts{..} =
withBuildConfig go $
do econfig <- asks getEnvConfig
locals <-
forM (M.toList (envConfigPackages econfig)) $
\(dir,_) ->
do cabalfp <- getCabalFileName dir
parsePackageNameFromFilePath cabalfp
forM_ locals (liftIO . putStrLn . packageNameString)
-- | List load targets for a package target.
targetsCmd :: Text -> GlobalOpts -> IO ()
targetsCmd target go@GlobalOpts{..} =
withBuildConfig go $
do (_realTargets,_,pkgs) <- ghciSetup Nothing [target]
pwd <- getWorkingDir
targets <-
fmap
(concat . snd . unzip)
(mapM (getPackageOptsAndTargetFiles pwd) pkgs)
forM_ targets (liftIO . putStrLn)
-- | Pull the current Docker image.
dockerPullCmd :: () -> GlobalOpts -> IO ()
dockerPullCmd _ go@GlobalOpts{..} = do
(manager,lc) <- liftIO $ loadConfigWithOpts go
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackTGlobal manager (lcConfig lc) go $
Docker.preventInContainer Docker.pull
-- | Reset the Docker sandbox.
dockerResetCmd :: Bool -> GlobalOpts -> IO ()
dockerResetCmd keepHome go@GlobalOpts{..} = do
(manager,lc) <- liftIO (loadConfigWithOpts go)
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackLoggingTGlobal manager go $
Docker.preventInContainer $ Docker.reset (lcProjectRoot lc) keepHome
-- | Cleanup Docker images and containers.
dockerCleanupCmd :: Docker.CleanupOpts -> GlobalOpts -> IO ()
dockerCleanupCmd cleanupOpts go@GlobalOpts{..} = do
(manager,lc) <- liftIO $ loadConfigWithOpts go
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackTGlobal manager (lcConfig lc) go $
Docker.preventInContainer $
Docker.cleanup cleanupOpts
imgDockerCmd :: () -> GlobalOpts -> IO ()
imgDockerCmd () go@GlobalOpts{..} = do
withBuildConfigExt
go
Nothing
(\lk ->
do Stack.Build.build
(const (return ()))
lk
defaultBuildOpts
Image.stageContainerImageArtifacts)
(Just Image.createContainerImageFromStage)
-- | Load the configuration with a manager. Convenience function used
-- throughout this module.
loadConfigWithOpts :: GlobalOpts -> IO (Manager,LoadConfig (StackLoggingT IO))
loadConfigWithOpts go@GlobalOpts{..} = do
manager <- newTLSManager
mstackYaml <-
case globalStackYaml of
Nothing -> return Nothing
Just fp -> do
path <- canonicalizePath fp >>= parseAbsFile
return $ Just path
lc <- runStackLoggingTGlobal
manager
go
(loadConfig globalConfigMonoid mstackYaml)
return (manager,lc)
-- | Project initialization
initCmd :: InitOpts -> GlobalOpts -> IO ()
initCmd initOpts go =
withConfigAndLock go $
do pwd <- getWorkingDir
config <- asks getConfig
miniConfig <- loadMiniConfig config
runReaderT (initProject pwd initOpts) miniConfig
-- | Create a project directory structure and initialize the stack config.
newCmd :: (NewOpts,InitOpts) -> GlobalOpts -> IO ()
newCmd (newOpts,initOpts) go@GlobalOpts{..} =
withConfigAndLock go $
do dir <- new newOpts
config <- asks getConfig
miniConfig <- loadMiniConfig config
runReaderT (initProject dir initOpts) miniConfig
-- | List the available templates.
templatesCmd :: () -> GlobalOpts -> IO ()
templatesCmd _ go@GlobalOpts{..} = withConfigAndLock go listTemplates
-- | Fix up extra-deps for a project
solverCmd :: Bool -- ^ modify stack.yaml automatically?
-> GlobalOpts
-> IO ()
solverCmd fixStackYaml go =
withBuildConfigAndLock go (\_ -> solveExtraDeps fixStackYaml)
-- | Visualize dependencies
dotCmd :: DotOpts -> GlobalOpts -> IO ()
dotCmd dotOpts go = withBuildConfigAndLock go (\_ -> dot dotOpts)
-- | List the dependencies
listDependenciesCmd :: Text -> GlobalOpts -> IO ()
listDependenciesCmd sep go = withBuildConfig go (listDependencies sep')
where sep' = T.replace "\\t" "\t" (T.replace "\\n" "\n" sep)
-- | Query build information
queryCmd :: [String] -> GlobalOpts -> IO ()
queryCmd selectors go = withBuildConfig go $ queryBuildInfo $ map T.pack selectors
data MainException = InvalidReExecVersion String String
deriving (Typeable)
instance Exception MainException
instance Show MainException where
show (InvalidReExecVersion expected actual) = concat
[ "When re-executing '"
, stackProgName
, "' in a container, the incorrect version was found\nExpected: "
, expected
, "; found: "
, actual]
|
lukexi/stack
|
src/main/Main.hs
|
Haskell
|
bsd-3-clause
| 41,959
|
foo x y =
do c <- getChar
return c
|
mpickering/ghc-exactprint
|
tests/examples/transform/Rename1.hs
|
Haskell
|
bsd-3-clause
| 47
|
module Dotnet.System.Xml.XmlNodeList where
import Dotnet
import qualified Dotnet.System.Object
import Dotnet.System.Collections.IEnumerator
import Dotnet.System.Xml.XmlNodeTy
data XmlNodeList_ a
type XmlNodeList a = Dotnet.System.Object.Object (XmlNodeList_ a)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.GetEnumerator"
getEnumerator :: XmlNodeList obj -> IO (Dotnet.System.Collections.IEnumerator.IEnumerator a0)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.get_ItemOf"
get_ItemOf :: Int -> XmlNodeList obj -> IO (Dotnet.System.Xml.XmlNodeTy.XmlNode a1)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.get_Count"
get_Count :: XmlNodeList obj -> IO (Int)
foreign import dotnet
"method Dotnet.System.Xml.XmlNodeList.Item"
item :: Int -> XmlNodeList obj -> IO (Dotnet.System.Xml.XmlNodeTy.XmlNode a1)
|
FranklinChen/Hugs
|
dotnet/lib/Dotnet/System/Xml/XmlNodeList.hs
|
Haskell
|
bsd-3-clause
| 866
|
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
{-# LANGUAGE CPP #-}
-- |
-- Module : Crypto.PasswordStore
-- Copyright : (c) Peter Scott, 2011
-- License : BSD-style
--
-- Maintainer : pjscott@iastate.edu
-- Stability : experimental
-- Portability : portable
--
-- Securely store hashed, salted passwords. If you need to store and verify
-- passwords, there are many wrong ways to do it, most of them all too
-- common. Some people store users' passwords in plain text. Then, when an
-- attacker manages to get their hands on this file, they have the passwords for
-- every user's account. One step up, but still wrong, is to simply hash all
-- passwords with SHA1 or something. This is vulnerable to rainbow table and
-- dictionary attacks. One step up from that is to hash the password along with
-- a unique salt value. This is vulnerable to dictionary attacks, since guessing
-- a password is very fast. The right thing to do is to use a slow hash
-- function, to add some small but significant delay, that will be negligible
-- for legitimate users but prohibitively expensive for someone trying to guess
-- passwords by brute force. That is what this library does. It iterates a
-- SHA256 hash, with a random salt, a few thousand times. This scheme is known
-- as PBKDF1, and is generally considered secure; there is nothing innovative
-- happening here.
--
-- The API here is very simple. What you store are called /password hashes/.
-- They are strings (technically, ByteStrings) that look like this:
--
-- > "sha256|14|jEWU94phx4QzNyH94Qp4CQ==|5GEw+jxP/4WLgzt9VS3Ee3nhqBlDsrKiB+rq7JfMckU="
--
-- Each password hash shows the algorithm, the strength (more on that later),
-- the salt, and the hashed-and-salted password. You store these on your server,
-- in a database, for when you need to verify a password. You make a password
-- hash with the 'makePassword' function. Here's an example:
--
-- > >>> makePassword "hunter2" 14
-- > "sha256|14|Zo4LdZGrv/HYNAUG3q8WcA==|zKjbHZoTpuPLp1lh6ATolWGIKjhXvY4TysuKvqtNFyk="
--
-- This will hash the password @\"hunter2\"@, with strength 14, which is a good
-- default value. The strength here determines how long the hashing will
-- take. When doing the hashing, we iterate the SHA256 hash function
-- @2^strength@ times, so increasing the strength by 1 makes the hashing take
-- twice as long. When computers get faster, you can bump up the strength a
-- little bit to compensate. You can strengthen existing password hashes with
-- the 'strengthenPassword' function. Note that 'makePassword' needs to generate
-- random numbers, so its return type is 'IO' 'ByteString'. If you want to avoid
-- the 'IO' monad, you can generate your own salt and pass it to
-- 'makePasswordSalt'.
--
-- Your strength value should not be less than 12, and 14 is a good default
-- value at the time of this writing, in 2013.
--
-- Once you've got your password hashes, the second big thing you need to do
-- with them is verify passwords against them. When a user gives you a password,
-- you compare it with a password hash using the 'verifyPassword' function:
--
-- > >>> verifyPassword "wrong guess" passwordHash
-- > False
-- > >>> verifyPassword "hunter2" passwordHash
-- > True
--
-- These two functions are really all you need. If you want to make existing
-- password hashes stronger, you can use 'strengthenPassword'. Just pass it an
-- existing password hash and a new strength value, and it will return a new
-- password hash with that strength value, which will match the same password as
-- the old password hash.
--
-- Note that, as of version 2.4, you can also use PBKDF2, and specify the exact
-- iteration count. This does not have a significant effect on security, but can
-- be handy for compatibility with other code.
module Yesod.PasswordStore (
-- * Algorithms
pbkdf1, -- :: ByteString -> Salt -> Int -> ByteString
pbkdf2, -- :: ByteString -> Salt -> Int -> ByteString
-- * Registering and verifying passwords
makePassword, -- :: ByteString -> Int -> IO ByteString
makePasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Int -> IO ByteString
makePasswordSalt, -- :: ByteString -> ByteString -> Int -> ByteString
makePasswordSaltWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Salt -> Int -> ByteString
verifyPassword, -- :: ByteString -> ByteString -> Bool
verifyPasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- (Int -> Int) -> ByteString -> ByteString -> Bool
-- * Updating password hash strength
strengthenPassword, -- :: ByteString -> Int -> ByteString
passwordStrength, -- :: ByteString -> Int
-- * Utilities
Salt,
isPasswordFormatValid, -- :: ByteString -> Bool
genSaltIO, -- :: IO Salt
genSaltRandom, -- :: (RandomGen b) => b -> (Salt, b)
makeSalt, -- :: ByteString -> Salt
exportSalt, -- :: Salt -> ByteString
importSalt -- :: ByteString -> Salt
) where
import qualified Crypto.Hash as CH
import qualified Crypto.Hash.SHA256 as H
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary as Binary
import Control.Monad
import Control.Monad.ST
import Data.Byteable (toBytes)
import Data.STRef
import Data.Bits
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Base64 (encode, decodeLenient)
import System.IO
import System.Random
import Data.Maybe
import qualified Control.Exception
---------------------
-- Cryptographic base
---------------------
-- | PBKDF1 key-derivation function. Takes a password, a 'Salt', and a number of
-- iterations. The number of iterations should be at least 1000, and probably
-- more. 5000 is a reasonable number, computing almost instantaneously. This
-- will give a 32-byte 'ByteString' as output. Both the salt and this 32-byte
-- key should be stored in the password file. When a user wishes to authenticate
-- a password, just pass it and the salt to this function, and see if the output
-- matches.
pbkdf1 :: ByteString -> Salt -> Int -> ByteString
pbkdf1 password (SaltBS salt) iter = hashRounds first_hash (iter + 1)
where first_hash = H.finalize $ H.init `H.update` password `H.update` salt
-- | Hash a 'ByteString' for a given number of rounds. The number of rounds is 0
-- or more. If the number of rounds specified is 0, the ByteString will be
-- returned unmodified.
hashRounds :: ByteString -> Int -> ByteString
hashRounds (!bs) 0 = bs
hashRounds bs rounds = hashRounds (H.hash bs) (rounds - 1)
-- | Computes the hmacSHA256 of the given message, with the given 'Salt'.
hmacSHA256 :: ByteString
-- ^ The secret (the salt)
-> ByteString
-- ^ The clear-text message
-> ByteString
-- ^ The encoded message
hmacSHA256 secret msg =
toBytes (CH.hmacGetDigest (CH.hmac secret msg) :: CH.Digest CH.SHA256)
-- | PBKDF2 key-derivation function.
-- For details see @http://tools.ietf.org/html/rfc2898@.
-- @32@ is the most common digest size for @SHA256@, and is
-- what the algorithm internally uses.
-- @HMAC+SHA256@ is used as @PRF@, because @HMAC+SHA1@ is considered too weak.
pbkdf2 :: ByteString -> Salt -> Int -> ByteString
pbkdf2 password (SaltBS salt) c =
let hLen = 32
dkLen = hLen in go hLen dkLen
where
go hLen dkLen | dkLen > (2^32 - 1) * hLen = error "Derived key too long."
| otherwise =
let !l = ceiling ((fromIntegral dkLen / fromIntegral hLen) :: Double)
!r = dkLen - (l - 1) * hLen
chunks = [f i | i <- [1 .. l]]
in (B.concat . init $ chunks) `B.append` B.take r (last chunks)
-- The @f@ function, as defined in the spec.
-- It calls 'u' under the hood.
f :: Int -> ByteString
f i = let !u1 = hmacSHA256 password (salt `B.append` int i)
-- Using the ST Monad, for maximum performance.
in runST $ do
u <- newSTRef u1
accum <- newSTRef u1
forM_ [2 .. c] $ \_ -> do
modifySTRef' u (hmacSHA256 password)
currentU <- readSTRef u
modifySTRef' accum (`xor'` currentU)
readSTRef accum
-- int(i), as defined in the spec.
int :: Int -> ByteString
int i = let str = BL.unpack . Binary.encode $ i
in BS.pack $ drop (length str - 4) str
-- | A convenience function to XOR two 'ByteString' together.
xor' :: ByteString -> ByteString -> ByteString
xor' !b1 !b2 = BS.pack $ BS.zipWith xor b1 b2
-- | Generate a 'Salt' from 128 bits of data from @\/dev\/urandom@, with the
-- system RNG as a fallback. This is the function used to generate salts by
-- 'makePassword'.
genSaltIO :: IO Salt
genSaltIO =
Control.Exception.catch genSaltDevURandom def
where
def :: IOError -> IO Salt
def _ = genSaltSysRandom
-- | Generate a 'Salt' from @\/dev\/urandom@.
genSaltDevURandom :: IO Salt
genSaltDevURandom = withFile "/dev/urandom" ReadMode $ \h -> do
rawSalt <- B.hGet h 16
return $ makeSalt rawSalt
-- | Generate a 'Salt' from 'System.Random'.
genSaltSysRandom :: IO Salt
genSaltSysRandom = randomChars >>= return . makeSalt . B.pack
where randomChars = sequence $ replicate 16 $ randomRIO ('\NUL', '\255')
-----------------------
-- Password hash format
-----------------------
-- Format: "sha256|strength|salt|hash", where strength is an unsigned int, salt
-- is a base64-encoded 16-byte random number, and hash is a base64-encoded hash
-- value.
-- | Try to parse a password hash.
readPwHash :: ByteString -> Maybe (Int, Salt, ByteString)
readPwHash pw | length broken /= 4
|| algorithm /= "sha256"
|| B.length hash /= 44 = Nothing
| otherwise = case B.readInt strBS of
Just (strength, _) -> Just (strength, SaltBS salt, hash)
Nothing -> Nothing
where broken = B.split '|' pw
[algorithm, strBS, salt, hash] = broken
-- | Encode a password hash, from a @(strength, salt, hash)@ tuple, where
-- strength is an 'Int', and both @salt@ and @hash@ are base64-encoded
-- 'ByteString's.
writePwHash :: (Int, Salt, ByteString) -> ByteString
writePwHash (strength, SaltBS salt, hash) =
B.intercalate "|" ["sha256", B.pack (show strength), salt, hash]
-----------------
-- High level API
-----------------
-- | Hash a password with a given strength (14 is a good default). The output of
-- this function can be written directly to a password file or
-- database. Generates a salt using high-quality randomness from
-- @\/dev\/urandom@ or (if that is not available, for example on Windows)
-- 'System.Random', which is included in the hashed output.
makePassword :: ByteString -> Int -> IO ByteString
makePassword = makePasswordWith pbkdf1
-- | A generic version of 'makePassword', which allow the user
-- to choose the algorithm to use.
--
-- >>> makePasswordWith pbkdf1 "password" 14
--
makePasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ The algorithm to use (e.g. pbkdf1)
-> ByteString
-- ^ The password to encrypt
-> Int
-- ^ log2 of the number of iterations
-> IO ByteString
makePasswordWith algorithm password strength = do
salt <- genSaltIO
return $ makePasswordSaltWith algorithm (2^) password salt strength
-- | A generic version of 'makePasswordSalt', meant to give the user
-- the maximum control over the generation parameters.
-- Note that, unlike 'makePasswordWith', this function takes the @raw@
-- number of iterations. This means the user will need to specify a
-- sensible value, typically @10000@ or @20000@.
makePasswordSaltWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. 'pbkdf1')
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ A password, given as clear text
-> Salt
-- ^ A hash 'Salt'
-> Int
-- ^ The password strength (e.g. @10000, 20000, etc.@)
-> ByteString
makePasswordSaltWith algorithm strengthModifier pwd salt strength = writePwHash (strength, salt, hash)
where hash = encode $ algorithm pwd salt (strengthModifier strength)
-- | Hash a password with a given strength (14 is a good default), using a given
-- salt. The output of this function can be written directly to a password file
-- or database. Example:
--
-- > >>> makePasswordSalt "hunter2" (makeSalt "72cd18b5ebfe6e96") 14
-- > "sha256|14|NzJjZDE4YjVlYmZlNmU5Ng==|yuiNrZW3KHX+pd0sWy9NTTsy5Yopmtx4UYscItSsoxc="
makePasswordSalt :: ByteString -> Salt -> Int -> ByteString
makePasswordSalt = makePasswordSaltWith pbkdf1 (2^)
-- | 'verifyPasswordWith' @algorithm userInput pwHash@ verifies
-- the password @userInput@ given by the user against the stored password
-- hash @pwHash@, with the hashing algorithm @algorithm@. Returns 'True' if the
-- given password is correct, and 'False' if it is not.
-- This function allows the programmer to specify the algorithm to use,
-- e.g. 'pbkdf1' or 'pbkdf2'.
-- Note: If you want to verify a password previously generated with
-- 'makePasswordSaltWith', but without modifying the number of iterations,
-- you can do:
--
-- > >>> verifyPasswordWith pbkdf2 id "hunter2" "sha256..."
-- > True
--
verifyPasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. pbkdf1)
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ User password
-> ByteString
-- ^ The generated hash (e.g. sha256|14...)
-> Bool
verifyPasswordWith algorithm strengthModifier userInput pwHash =
case readPwHash pwHash of
Nothing -> False
Just (strength, salt, goodHash) ->
encode (algorithm userInput salt (strengthModifier strength)) == goodHash
-- | Like 'verifyPasswordWith', but uses 'pbkdf1' as algorithm.
verifyPassword :: ByteString -> ByteString -> Bool
verifyPassword = verifyPasswordWith pbkdf1 (2^)
-- | Try to strengthen a password hash, by hashing it some more
-- times. @'strengthenPassword' pwHash new_strength@ will return a new password
-- hash with strength at least @new_strength@. If the password hash already has
-- strength greater than or equal to @new_strength@, then it is returned
-- unmodified. If the password hash is invalid and does not parse, it will be
-- returned without comment.
--
-- This function can be used to periodically update your password database when
-- computers get faster, in order to keep up with Moore's law. This isn't hugely
-- important, but it's a good idea.
strengthenPassword :: ByteString -> Int -> ByteString
strengthenPassword pwHash newstr =
case readPwHash pwHash of
Nothing -> pwHash
Just (oldstr, salt, hashB64) ->
if oldstr < newstr then
writePwHash (newstr, salt, newHash)
else
pwHash
where newHash = encode $ hashRounds hash extraRounds
extraRounds = (2^newstr) - (2^oldstr)
hash = decodeLenient hashB64
-- | Return the strength of a password hash.
passwordStrength :: ByteString -> Int
passwordStrength pwHash = case readPwHash pwHash of
Nothing -> 0
Just (strength, _, _) -> strength
------------
-- Utilities
------------
-- | A salt is a unique random value which is stored as part of the password
-- hash. You can generate a salt with 'genSaltIO' or 'genSaltRandom', or if you
-- really know what you're doing, you can create them from your own ByteString
-- values with 'makeSalt'.
newtype Salt = SaltBS ByteString
deriving (Show, Eq, Ord)
-- | Create a 'Salt' from a 'ByteString'. The input must be at least 8
-- characters, and can contain arbitrary bytes. Most users will not need to use
-- this function.
makeSalt :: ByteString -> Salt
makeSalt = SaltBS . encode . check_length
where check_length salt | B.length salt < 8 =
error "Salt too short. Minimum length is 8 characters."
| otherwise = salt
-- | Convert a 'Salt' into a 'ByteString'. The resulting 'ByteString' will be
-- base64-encoded. Most users will not need to use this function.
exportSalt :: Salt -> ByteString
exportSalt (SaltBS bs) = bs
-- | Convert a raw 'ByteString' into a 'Salt'.
-- Use this function with caution, since using a weak salt will result in a
-- weak password.
importSalt :: ByteString -> Salt
importSalt = SaltBS
-- | Is the format of a password hash valid? Attempts to parse a given password
-- hash. Returns 'True' if it parses correctly, and 'False' otherwise.
isPasswordFormatValid :: ByteString -> Bool
isPasswordFormatValid = isJust . readPwHash
-- | Generate a 'Salt' with 128 bits of data taken from a given random number
-- generator. Returns the salt and the updated random number generator. This is
-- meant to be used with 'makePasswordSalt' by people who would prefer to either
-- use their own random number generator or avoid the 'IO' monad.
genSaltRandom :: (RandomGen b) => b -> (Salt, b)
genSaltRandom gen = (salt, newgen)
where rands _ 0 = []
rands g n = (a, g') : rands g' (n-1 :: Int)
where (a, g') = randomR ('\NUL', '\255') g
salt = makeSalt $ B.pack $ map fst (rands gen 16)
newgen = snd $ last (rands gen 16)
#if !MIN_VERSION_base(4, 6, 0)
-- | Strict version of 'modifySTRef'
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' ref f = do
x <- readSTRef ref
let x' = f x
x' `seq` writeSTRef ref x'
#endif
#if MIN_VERSION_bytestring(0, 10, 0)
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BL.toStrict
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromStrict
#else
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BS.concat . BL.toChunks
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromChunks . return
#endif
|
MaxGabriel/yesod
|
yesod-auth/Yesod/PasswordStore.hs
|
Haskell
|
mit
| 18,769
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Rules.Selftest (selftestRules) where
import Hadrian.Haskell.Cabal
import Test.QuickCheck
import Base
import Context
import Oracles.ModuleFiles
import Oracles.Setting
import Packages
import Settings
import Target
import Utilities
instance Arbitrary Way where
arbitrary = wayFromUnits <$> arbitrary
instance Arbitrary WayUnit where
arbitrary = arbitraryBoundedEnum
test :: Testable a => a -> Action ()
test = liftIO . quickCheck
selftestRules :: Rules ()
selftestRules =
"selftest" ~> do
testBuilder
testChunksOfSize
testDependencies
testLookupAll
testModuleName
testPackages
testWay
testBuilder :: Action ()
testBuilder = do
putBuild "==== trackArgument"
let make = target undefined (Make undefined) undefined undefined
test $ forAll (elements ["-j", "MAKEFLAGS=-j", "THREADS="])
$ \prefix (NonNegative n) ->
not (trackArgument make prefix) &&
not (trackArgument make ("-j" ++ show (n :: Int)))
testChunksOfSize :: Action ()
testChunksOfSize = do
putBuild "==== chunksOfSize"
test $ chunksOfSize 3 [ "a", "b", "c" , "defg" , "hi" , "jk" ]
== [ ["a", "b", "c"], ["defg"], ["hi"], ["jk"] ]
test $ \n xs ->
let res = chunksOfSize n xs
in concat res == xs && all (\r -> length r == 1 || length (concat r) <= n) res
testDependencies :: Action ()
testDependencies = do
putBuild "==== pkgDependencies"
let pkgs = ghcPackages \\ [libffi] -- @libffi@ does not have a Cabal file.
depLists <- mapM pkgDependencies pkgs
test $ and [ deps == sort deps | deps <- depLists ]
putBuild "==== Dependencies of the 'ghc-bin' binary"
ghcDeps <- pkgDependencies ghc
test $ pkgName compiler `elem` ghcDeps
stage0Deps <- contextDependencies (vanillaContext Stage0 ghc)
stage1Deps <- contextDependencies (vanillaContext Stage1 ghc)
stage2Deps <- contextDependencies (vanillaContext Stage2 ghc)
test $ vanillaContext Stage0 compiler `notElem` stage1Deps
test $ vanillaContext Stage1 compiler `elem` stage1Deps
test $ vanillaContext Stage2 compiler `notElem` stage1Deps
test $ stage1Deps /= stage0Deps
test $ stage1Deps == stage2Deps
testLookupAll :: Action ()
testLookupAll = do
putBuild "==== lookupAll"
test $ lookupAll ["b" , "c" ] [("a", 1), ("c", 3), ("d", 4)]
== [Nothing, Just (3 :: Int)]
test $ forAll dicts $ \dict -> forAll extras $ \extra ->
let items = sort $ map fst dict ++ extra
in lookupAll items (sort dict) == map (`lookup` dict) items
where
dicts :: Gen [(Int, Int)]
dicts = nubBy (\x y -> fst x == fst y) <$> vector 20
extras :: Gen [Int]
extras = vector 20
testModuleName :: Action ()
testModuleName = do
putBuild "==== Encode/decode module name"
test $ encodeModule "Data/Functor" "Identity.hs" == "Data.Functor.Identity"
test $ encodeModule "" "Prelude" == "Prelude"
test $ decodeModule "Data.Functor.Identity" == ("Data/Functor", "Identity")
test $ decodeModule "Prelude" == ("", "Prelude")
test $ forAll names $ \n -> uncurry encodeModule (decodeModule n) == n
where
names = intercalate "." <$> listOf1 (listOf1 $ elements "abcABC123_'")
testPackages :: Action ()
testPackages = do
putBuild "==== Check system configuration"
win <- windowsHost -- This depends on the @boot@ and @configure@ scripts.
putBuild "==== Packages, interpretInContext, configuration flags"
forM_ [Stage0 ..] $ \stage -> do
pkgs <- stagePackages stage
when (win32 `elem` pkgs) . test $ win
when (unix `elem` pkgs) . test $ not win
test $ pkgs == nubOrd pkgs
testWay :: Action ()
testWay = do
putBuild "==== Read Way, Show Way"
test $ \(x :: Way) -> read (show x) == x
|
snowleopard/shaking-up-ghc
|
src/Rules/Selftest.hs
|
Haskell
|
bsd-3-clause
| 3,927
|
module DoIn1 where
io s
= do s <- getLine
let q = (s ++ s)
putStr q
putStr "foo"
|
kmate/HaRe
|
old/testing/removeDef/DoIn1AST.hs
|
Haskell
|
bsd-3-clause
| 121
|
module Lit where
{-@ test :: {v:Int | v == 3} @-}
test = length "cat"
|
abakst/liquidhaskell
|
tests/pos/lit.hs
|
Haskell
|
bsd-3-clause
| 71
|
module Foo
( foo
) where
foo :: IO ()
foo = putStrLn "foo2"
|
juhp/stack
|
test/integration/tests/2781-shadow-bug/files/foo/v2/Foo.hs
|
Haskell
|
bsd-3-clause
| 69
|
-- (c) The GHC Team
--
-- Functions to evaluate whether or not a string is a valid identifier.
-- There is considerable overlap between the logic here and the logic
-- in Lexer.x, but sadly there seems to be way to merge them.
module Lexeme (
-- * Lexical characteristics of Haskell names
-- | Use these functions to figure what kind of name a 'FastString'
-- represents; these functions do /not/ check that the identifier
-- is valid.
isLexCon, isLexVar, isLexId, isLexSym,
isLexConId, isLexConSym, isLexVarId, isLexVarSym,
startsVarSym, startsVarId, startsConSym, startsConId,
-- * Validating identifiers
-- | These functions (working over plain old 'String's) check
-- to make sure that the identifier is valid.
okVarOcc, okConOcc, okTcOcc,
okVarIdOcc, okVarSymOcc, okConIdOcc, okConSymOcc
-- Some of the exports above are not used within GHC, but may
-- be of value to GHC API users.
) where
import FastString
import Data.Char
import qualified Data.Set as Set
{-
************************************************************************
* *
Lexical categories
* *
************************************************************************
These functions test strings to see if they fit the lexical categories
defined in the Haskell report.
Note [Classification of generated names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some names generated for internal use can show up in debugging output,
e.g. when using -ddump-simpl. These generated names start with a $
but should still be pretty-printed using prefix notation. We make sure
this is the case in isLexVarSym by only classifying a name as a symbol
if all its characters are symbols, not just its first one.
-}
isLexCon, isLexVar, isLexId, isLexSym :: FastString -> Bool
isLexConId, isLexConSym, isLexVarId, isLexVarSym :: FastString -> Bool
isLexCon cs = isLexConId cs || isLexConSym cs
isLexVar cs = isLexVarId cs || isLexVarSym cs
isLexId cs = isLexConId cs || isLexVarId cs
isLexSym cs = isLexConSym cs || isLexVarSym cs
-------------
isLexConId cs -- Prefix type or data constructors
| nullFS cs = False -- e.g. "Foo", "[]", "(,)"
| cs == (fsLit "[]") = True
| otherwise = startsConId (headFS cs)
isLexVarId cs -- Ordinary prefix identifiers
| nullFS cs = False -- e.g. "x", "_x"
| otherwise = startsVarId (headFS cs)
isLexConSym cs -- Infix type or data constructors
| nullFS cs = False -- e.g. ":-:", ":", "->"
| cs == (fsLit "->") = True
| otherwise = startsConSym (headFS cs)
isLexVarSym fs -- Infix identifiers e.g. "+"
| fs == (fsLit "~R#") = True
| otherwise
= case (if nullFS fs then [] else unpackFS fs) of
[] -> False
(c:cs) -> startsVarSym c && all isVarSymChar cs
-- See Note [Classification of generated names]
-------------
startsVarSym, startsVarId, startsConSym, startsConId :: Char -> Bool
startsVarSym c = startsVarSymASCII c || (ord c > 0x7f && isSymbol c) -- Infix Ids
startsConSym c = c == ':' -- Infix data constructors
startsVarId c = c == '_' || case generalCategory c of -- Ordinary Ids
LowercaseLetter -> True
OtherLetter -> True -- See #1103
_ -> False
startsConId c = isUpper c || c == '(' -- Ordinary type constructors and data constructors
startsVarSymASCII :: Char -> Bool
startsVarSymASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
isVarSymChar :: Char -> Bool
isVarSymChar c = c == ':' || startsVarSym c
{-
************************************************************************
* *
Detecting valid names for Template Haskell
* *
************************************************************************
-}
----------------------
-- External interface
----------------------
-- | Is this an acceptable variable name?
okVarOcc :: String -> Bool
okVarOcc str@(c:_)
| startsVarId c
= okVarIdOcc str
| startsVarSym c
= okVarSymOcc str
okVarOcc _ = False
-- | Is this an acceptable constructor name?
okConOcc :: String -> Bool
okConOcc str@(c:_)
| startsConId c
= okConIdOcc str
| startsConSym c
= okConSymOcc str
| str == "[]"
= True
okConOcc _ = False
-- | Is this an acceptable type name?
okTcOcc :: String -> Bool
okTcOcc "[]" = True
okTcOcc "->" = True
okTcOcc "~" = True
okTcOcc str@(c:_)
| startsConId c
= okConIdOcc str
| startsConSym c
= okConSymOcc str
| startsVarSym c
= okVarSymOcc str
okTcOcc _ = False
-- | Is this an acceptable alphanumeric variable name, assuming it starts
-- with an acceptable letter?
okVarIdOcc :: String -> Bool
okVarIdOcc str = okIdOcc str &&
not (str `Set.member` reservedIds)
-- | Is this an acceptable symbolic variable name, assuming it starts
-- with an acceptable character?
okVarSymOcc :: String -> Bool
okVarSymOcc str = all okSymChar str &&
not (str `Set.member` reservedOps) &&
not (isDashes str)
-- | Is this an acceptable alphanumeric constructor name, assuming it
-- starts with an acceptable letter?
okConIdOcc :: String -> Bool
okConIdOcc str = okIdOcc str ||
is_tuple_name1 str
where
-- check for tuple name, starting at the beginning
is_tuple_name1 ('(' : rest) = is_tuple_name2 rest
is_tuple_name1 _ = False
-- check for tuple tail
is_tuple_name2 ")" = True
is_tuple_name2 (',' : rest) = is_tuple_name2 rest
is_tuple_name2 (ws : rest)
| isSpace ws = is_tuple_name2 rest
is_tuple_name2 _ = False
-- | Is this an acceptable symbolic constructor name, assuming it
-- starts with an acceptable character?
okConSymOcc :: String -> Bool
okConSymOcc ":" = True
okConSymOcc str = all okSymChar str &&
not (str `Set.member` reservedOps)
----------------------
-- Internal functions
----------------------
-- | Is this string an acceptable id, possibly with a suffix of hashes,
-- but not worrying about case or clashing with reserved words?
okIdOcc :: String -> Bool
okIdOcc str
= let hashes = dropWhile okIdChar str in
all (== '#') hashes -- -XMagicHash allows a suffix of hashes
-- of course, `all` says "True" to an empty list
-- | Is this character acceptable in an identifier (after the first letter)?
-- See alexGetByte in Lexer.x
okIdChar :: Char -> Bool
okIdChar c = case generalCategory c of
UppercaseLetter -> True
LowercaseLetter -> True
OtherLetter -> True
TitlecaseLetter -> True
DecimalNumber -> True
OtherNumber -> True
_ -> c == '\'' || c == '_'
-- | Is this character acceptable in a symbol (after the first char)?
-- See alexGetByte in Lexer.x
okSymChar :: Char -> Bool
okSymChar c
| c `elem` specialSymbols
= False
| c `elem` "_\"'"
= False
| otherwise
= case generalCategory c of
ConnectorPunctuation -> True
DashPunctuation -> True
OtherPunctuation -> True
MathSymbol -> True
CurrencySymbol -> True
ModifierSymbol -> True
OtherSymbol -> True
_ -> False
-- | All reserved identifiers. Taken from section 2.4 of the 2010 Report.
reservedIds :: Set.Set String
reservedIds = Set.fromList [ "case", "class", "data", "default", "deriving"
, "do", "else", "foreign", "if", "import", "in"
, "infix", "infixl", "infixr", "instance", "let"
, "module", "newtype", "of", "then", "type", "where"
, "_" ]
-- | All punctuation that cannot appear in symbols. See $special in Lexer.x.
specialSymbols :: [Char]
specialSymbols = "(),;[]`{}"
-- | All reserved operators. Taken from section 2.4 of the 2010 Report.
reservedOps :: Set.Set String
reservedOps = Set.fromList [ "..", ":", "::", "=", "\\", "|", "<-", "->"
, "@", "~", "=>" ]
-- | Does this string contain only dashes and has at least 2 of them?
isDashes :: String -> Bool
isDashes ('-' : '-' : rest) = all (== '-') rest
isDashes _ = False
|
green-haskell/ghc
|
compiler/basicTypes/Lexeme.hs
|
Haskell
|
bsd-3-clause
| 8,645
|
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
{-# LANGUAGE CPP #-}
-- |
-- Module : Crypto.PasswordStore
-- Copyright : (c) Peter Scott, 2011
-- License : BSD-style
--
-- Maintainer : pjscott@iastate.edu
-- Stability : experimental
-- Portability : portable
--
-- Securely store hashed, salted passwords. If you need to store and verify
-- passwords, there are many wrong ways to do it, most of them all too
-- common. Some people store users' passwords in plain text. Then, when an
-- attacker manages to get their hands on this file, they have the passwords for
-- every user's account. One step up, but still wrong, is to simply hash all
-- passwords with SHA1 or something. This is vulnerable to rainbow table and
-- dictionary attacks. One step up from that is to hash the password along with
-- a unique salt value. This is vulnerable to dictionary attacks, since guessing
-- a password is very fast. The right thing to do is to use a slow hash
-- function, to add some small but significant delay, that will be negligible
-- for legitimate users but prohibitively expensive for someone trying to guess
-- passwords by brute force. That is what this library does. It iterates a
-- SHA256 hash, with a random salt, a few thousand times. This scheme is known
-- as PBKDF1, and is generally considered secure; there is nothing innovative
-- happening here.
--
-- The API here is very simple. What you store are called /password hashes/.
-- They are strings (technically, ByteStrings) that look like this:
--
-- > "sha256|14|jEWU94phx4QzNyH94Qp4CQ==|5GEw+jxP/4WLgzt9VS3Ee3nhqBlDsrKiB+rq7JfMckU="
--
-- Each password hash shows the algorithm, the strength (more on that later),
-- the salt, and the hashed-and-salted password. You store these on your server,
-- in a database, for when you need to verify a password. You make a password
-- hash with the 'makePassword' function. Here's an example:
--
-- > >>> makePassword "hunter2" 14
-- > "sha256|14|Zo4LdZGrv/HYNAUG3q8WcA==|zKjbHZoTpuPLp1lh6ATolWGIKjhXvY4TysuKvqtNFyk="
--
-- This will hash the password @\"hunter2\"@, with strength 12, which is a good
-- default value. The strength here determines how long the hashing will
-- take. When doing the hashing, we iterate the SHA256 hash function
-- @2^strength@ times, so increasing the strength by 1 makes the hashing take
-- twice as long. When computers get faster, you can bump up the strength a
-- little bit to compensate. You can strengthen existing password hashes with
-- the 'strengthenPassword' function. Note that 'makePassword' needs to generate
-- random numbers, so its return type is 'IO' 'ByteString'. If you want to avoid
-- the 'IO' monad, you can generate your own salt and pass it to
-- 'makePasswordSalt'.
--
-- Your strength value should not be less than 12, and 14 is a good default
-- value at the time of this writing, in 2013.
--
-- Once you've got your password hashes, the second big thing you need to do
-- with them is verify passwords against them. When a user gives you a password,
-- you compare it with a password hash using the 'verifyPassword' function:
--
-- > >>> verifyPassword "wrong guess" passwordHash
-- > False
-- > >>> verifyPassword "hunter2" passwordHash
-- > True
--
-- These two functions are really all you need. If you want to make existing
-- password hashes stronger, you can use 'strengthenPassword'. Just pass it an
-- existing password hash and a new strength value, and it will return a new
-- password hash with that strength value, which will match the same password as
-- the old password hash.
--
-- Note that, as of version 2.4, you can also use PBKDF2, and specify the exact
-- iteration count. This does not have a significant effect on security, but can
-- be handy for compatibility with other code.
module Yesod.PasswordStore (
-- * Algorithms
pbkdf1, -- :: ByteString -> Salt -> Int -> ByteString
pbkdf2, -- :: ByteString -> Salt -> Int -> ByteString
-- * Registering and verifying passwords
makePassword, -- :: ByteString -> Int -> IO ByteString
makePasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Int -> IO ByteString
makePasswordSalt, -- :: ByteString -> ByteString -> Int -> ByteString
makePasswordSaltWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- ByteString -> Salt -> Int -> ByteString
verifyPassword, -- :: ByteString -> ByteString -> Bool
verifyPasswordWith, -- :: (ByteString -> Salt -> Int -> ByteString) ->
-- (Int -> Int) -> ByteString -> ByteString -> Bool
-- * Updating password hash strength
strengthenPassword, -- :: ByteString -> Int -> ByteString
passwordStrength, -- :: ByteString -> Int
-- * Utilities
Salt,
isPasswordFormatValid, -- :: ByteString -> Bool
genSaltIO, -- :: IO Salt
genSaltRandom, -- :: (RandomGen b) => b -> (Salt, b)
makeSalt, -- :: ByteString -> Salt
exportSalt, -- :: Salt -> ByteString
importSalt -- :: ByteString -> Salt
) where
import qualified Crypto.Hash as CH
import qualified Crypto.Hash.SHA256 as H
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary as Binary
import Control.Monad
import Control.Monad.ST
import Data.Byteable (toBytes)
import Data.STRef
import Data.Bits
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Base64 (encode, decodeLenient)
import System.IO
import System.Random
import Data.Maybe
import qualified Control.Exception
---------------------
-- Cryptographic base
---------------------
-- | PBKDF1 key-derivation function. Takes a password, a 'Salt', and a number of
-- iterations. The number of iterations should be at least 1000, and probably
-- more. 5000 is a reasonable number, computing almost instantaneously. This
-- will give a 32-byte 'ByteString' as output. Both the salt and this 32-byte
-- key should be stored in the password file. When a user wishes to authenticate
-- a password, just pass it and the salt to this function, and see if the output
-- matches.
pbkdf1 :: ByteString -> Salt -> Int -> ByteString
pbkdf1 password (SaltBS salt) iter = hashRounds first_hash (iter + 1)
where first_hash = H.finalize $ H.init `H.update` password `H.update` salt
-- | Hash a 'ByteString' for a given number of rounds. The number of rounds is 0
-- or more. If the number of rounds specified is 0, the ByteString will be
-- returned unmodified.
hashRounds :: ByteString -> Int -> ByteString
hashRounds (!bs) 0 = bs
hashRounds bs rounds = hashRounds (H.hash bs) (rounds - 1)
-- | Computes the hmacSHA256 of the given message, with the given 'Salt'.
hmacSHA256 :: ByteString
-- ^ The secret (the salt)
-> ByteString
-- ^ The clear-text message
-> ByteString
-- ^ The encoded message
hmacSHA256 secret msg =
toBytes (CH.hmacGetDigest (CH.hmac secret msg) :: CH.Digest CH.SHA256)
-- | PBKDF2 key-derivation function.
-- For details see @http://tools.ietf.org/html/rfc2898@.
-- @32@ is the most common digest size for @SHA256@, and is
-- what the algorithm internally uses.
-- @HMAC+SHA256@ is used as @PRF@, because @HMAC+SHA1@ is considered too weak.
pbkdf2 :: ByteString -> Salt -> Int -> ByteString
pbkdf2 password (SaltBS salt) c =
let hLen = 32
dkLen = hLen in go hLen dkLen
where
go hLen dkLen | dkLen > (2^32 - 1) * hLen = error "Derived key too long."
| otherwise =
let !l = ceiling ((fromIntegral dkLen / fromIntegral hLen) :: Double)
!r = dkLen - (l - 1) * hLen
chunks = [f i | i <- [1 .. l]]
in (B.concat . init $ chunks) `B.append` B.take r (last chunks)
-- The @f@ function, as defined in the spec.
-- It calls 'u' under the hood.
f :: Int -> ByteString
f i = let !u1 = hmacSHA256 password (salt `B.append` int i)
-- Using the ST Monad, for maximum performance.
in runST $ do
u <- newSTRef u1
accum <- newSTRef u1
forM_ [2 .. c] $ \_ -> do
modifySTRef' u (hmacSHA256 password)
currentU <- readSTRef u
modifySTRef' accum (`xor'` currentU)
readSTRef accum
-- int(i), as defined in the spec.
int :: Int -> ByteString
int i = let str = BL.unpack . Binary.encode $ i
in BS.pack $ drop (length str - 4) str
-- | A convenience function to XOR two 'ByteString' together.
xor' :: ByteString -> ByteString -> ByteString
xor' !b1 !b2 = BS.pack $ BS.zipWith xor b1 b2
-- | Generate a 'Salt' from 128 bits of data from @\/dev\/urandom@, with the
-- system RNG as a fallback. This is the function used to generate salts by
-- 'makePassword'.
genSaltIO :: IO Salt
genSaltIO =
Control.Exception.catch genSaltDevURandom def
where
def :: IOError -> IO Salt
def _ = genSaltSysRandom
-- | Generate a 'Salt' from @\/dev\/urandom@.
genSaltDevURandom :: IO Salt
genSaltDevURandom = withFile "/dev/urandom" ReadMode $ \h -> do
rawSalt <- B.hGet h 16
return $ makeSalt rawSalt
-- | Generate a 'Salt' from 'System.Random'.
genSaltSysRandom :: IO Salt
genSaltSysRandom = randomChars >>= return . makeSalt . B.pack
where randomChars = sequence $ replicate 16 $ randomRIO ('\NUL', '\255')
-----------------------
-- Password hash format
-----------------------
-- Format: "sha256|strength|salt|hash", where strength is an unsigned int, salt
-- is a base64-encoded 16-byte random number, and hash is a base64-encoded hash
-- value.
-- | Try to parse a password hash.
readPwHash :: ByteString -> Maybe (Int, Salt, ByteString)
readPwHash pw | length broken /= 4
|| algorithm /= "sha256"
|| B.length hash /= 44 = Nothing
| otherwise = case B.readInt strBS of
Just (strength, _) -> Just (strength, SaltBS salt, hash)
Nothing -> Nothing
where broken = B.split '|' pw
[algorithm, strBS, salt, hash] = broken
-- | Encode a password hash, from a @(strength, salt, hash)@ tuple, where
-- strength is an 'Int', and both @salt@ and @hash@ are base64-encoded
-- 'ByteString's.
writePwHash :: (Int, Salt, ByteString) -> ByteString
writePwHash (strength, SaltBS salt, hash) =
B.intercalate "|" ["sha256", B.pack (show strength), salt, hash]
-----------------
-- High level API
-----------------
-- | Hash a password with a given strength (14 is a good default). The output of
-- this function can be written directly to a password file or
-- database. Generates a salt using high-quality randomness from
-- @\/dev\/urandom@ or (if that is not available, for example on Windows)
-- 'System.Random', which is included in the hashed output.
makePassword :: ByteString -> Int -> IO ByteString
makePassword = makePasswordWith pbkdf1
-- | A generic version of 'makePassword', which allow the user
-- to choose the algorithm to use.
--
-- >>> makePasswordWith pbkdf1 "password" 14
--
makePasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ The algorithm to use (e.g. pbkdf1)
-> ByteString
-- ^ The password to encrypt
-> Int
-- ^ log2 of the number of iterations
-> IO ByteString
makePasswordWith algorithm password strength = do
salt <- genSaltIO
return $ makePasswordSaltWith algorithm (2^) password salt strength
-- | A generic version of 'makePasswordSalt', meant to give the user
-- the maximum control over the generation parameters.
-- Note that, unlike 'makePasswordWith', this function takes the @raw@
-- number of iterations. This means the user will need to specify a
-- sensible value, typically @10000@ or @20000@.
makePasswordSaltWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. 'pbkdf1')
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ A password, given as clear text
-> Salt
-- ^ A hash 'Salt'
-> Int
-- ^ The password strength (e.g. @10000, 20000, etc.@)
-> ByteString
makePasswordSaltWith algorithm strengthModifier pwd salt strength = writePwHash (strength, salt, hash)
where hash = encode $ algorithm pwd salt (strengthModifier strength)
-- | Hash a password with a given strength (14 is a good default), using a given
-- salt. The output of this function can be written directly to a password file
-- or database. Example:
--
-- > >>> makePasswordSalt "hunter2" (makeSalt "72cd18b5ebfe6e96") 14
-- > "sha256|14|NzJjZDE4YjVlYmZlNmU5Ng==|yuiNrZW3KHX+pd0sWy9NTTsy5Yopmtx4UYscItSsoxc="
makePasswordSalt :: ByteString -> Salt -> Int -> ByteString
makePasswordSalt = makePasswordSaltWith pbkdf1 (2^)
-- | 'verifyPasswordWith' @algorithm userInput pwHash@ verifies
-- the password @userInput@ given by the user against the stored password
-- hash @pwHash@, with the hashing algorithm @algorithm@. Returns 'True' if the
-- given password is correct, and 'False' if it is not.
-- This function allows the programmer to specify the algorithm to use,
-- e.g. 'pbkdf1' or 'pbkdf2'.
-- Note: If you want to verify a password previously generated with
-- 'makePasswordSaltWith', but without modifying the number of iterations,
-- you can do:
--
-- > >>> verifyPasswordWith pbkdf2 id "hunter2" "sha256..."
-- > True
--
verifyPasswordWith :: (ByteString -> Salt -> Int -> ByteString)
-- ^ A function modeling an algorithm (e.g. pbkdf1)
-> (Int -> Int)
-- ^ A function to modify the strength
-> ByteString
-- ^ User password
-> ByteString
-- ^ The generated hash (e.g. sha256|14...)
-> Bool
verifyPasswordWith algorithm strengthModifier userInput pwHash =
case readPwHash pwHash of
Nothing -> False
Just (strength, salt, goodHash) ->
encode (algorithm userInput salt (strengthModifier strength)) == goodHash
-- | Like 'verifyPasswordWith', but uses 'pbkdf1' as algorithm.
verifyPassword :: ByteString -> ByteString -> Bool
verifyPassword = verifyPasswordWith pbkdf1 (2^)
-- | Try to strengthen a password hash, by hashing it some more
-- times. @'strengthenPassword' pwHash new_strength@ will return a new password
-- hash with strength at least @new_strength@. If the password hash already has
-- strength greater than or equal to @new_strength@, then it is returned
-- unmodified. If the password hash is invalid and does not parse, it will be
-- returned without comment.
--
-- This function can be used to periodically update your password database when
-- computers get faster, in order to keep up with Moore's law. This isn't hugely
-- important, but it's a good idea.
strengthenPassword :: ByteString -> Int -> ByteString
strengthenPassword pwHash newstr =
case readPwHash pwHash of
Nothing -> pwHash
Just (oldstr, salt, hashB64) ->
if oldstr < newstr then
writePwHash (newstr, salt, newHash)
else
pwHash
where newHash = encode $ hashRounds hash extraRounds
extraRounds = (2^newstr) - (2^oldstr)
hash = decodeLenient hashB64
-- | Return the strength of a password hash.
passwordStrength :: ByteString -> Int
passwordStrength pwHash = case readPwHash pwHash of
Nothing -> 0
Just (strength, _, _) -> strength
------------
-- Utilities
------------
-- | A salt is a unique random value which is stored as part of the password
-- hash. You can generate a salt with 'genSaltIO' or 'genSaltRandom', or if you
-- really know what you're doing, you can create them from your own ByteString
-- values with 'makeSalt'.
newtype Salt = SaltBS ByteString
deriving (Show, Eq, Ord)
-- | Create a 'Salt' from a 'ByteString'. The input must be at least 8
-- characters, and can contain arbitrary bytes. Most users will not need to use
-- this function.
makeSalt :: ByteString -> Salt
makeSalt = SaltBS . encode . check_length
where check_length salt | B.length salt < 8 =
error "Salt too short. Minimum length is 8 characters."
| otherwise = salt
-- | Convert a 'Salt' into a 'ByteString'. The resulting 'ByteString' will be
-- base64-encoded. Most users will not need to use this function.
exportSalt :: Salt -> ByteString
exportSalt (SaltBS bs) = bs
-- | Convert a raw 'ByteString' into a 'Salt'.
-- Use this function with caution, since using a weak salt will result in a
-- weak password.
importSalt :: ByteString -> Salt
importSalt = SaltBS
-- | Is the format of a password hash valid? Attempts to parse a given password
-- hash. Returns 'True' if it parses correctly, and 'False' otherwise.
isPasswordFormatValid :: ByteString -> Bool
isPasswordFormatValid = isJust . readPwHash
-- | Generate a 'Salt' with 128 bits of data taken from a given random number
-- generator. Returns the salt and the updated random number generator. This is
-- meant to be used with 'makePasswordSalt' by people who would prefer to either
-- use their own random number generator or avoid the 'IO' monad.
genSaltRandom :: (RandomGen b) => b -> (Salt, b)
genSaltRandom gen = (salt, newgen)
where rands _ 0 = []
rands g n = (a, g') : rands g' (n-1 :: Int)
where (a, g') = randomR ('\NUL', '\255') g
salt = makeSalt $ B.pack $ map fst (rands gen 16)
newgen = snd $ last (rands gen 16)
#if !MIN_VERSION_base(4, 6, 0)
-- | Strict version of 'modifySTRef'
modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
modifySTRef' ref f = do
x <- readSTRef ref
let x' = f x
x' `seq` writeSTRef ref x'
#endif
#if MIN_VERSION_bytestring(0, 10, 0)
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BL.toStrict
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromStrict
#else
toStrict :: BL.ByteString -> BS.ByteString
toStrict = BS.concat . BL.toChunks
fromStrict :: BS.ByteString -> BL.ByteString
fromStrict = BL.fromChunks . return
#endif
|
ygale/yesod
|
yesod-auth/Yesod/PasswordStore.hs
|
Haskell
|
mit
| 18,769
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
module T6137 where
data Sum a b = L a | R b
data Sum1 (a :: k1 -> *) (b :: k2 -> *) :: Sum k1 k2 -> * where
LL :: a i -> Sum1 a b (L i)
RR :: b i -> Sum1 a b (R i)
data Code i o = F (Code (Sum i o) o)
-- An interpretation for `Code` using a data family works:
data family In (f :: Code i o) :: (i -> *) -> (o -> *)
data instance In (F f) r o where
MkIn :: In f (Sum1 r (In (F f) r)) o -> In (F f) r o
-- Requires polymorphic recursion
data In' (f :: Code i o) :: (i -> *) -> o -> * where
MkIn' :: In' g (Sum1 r (In' (F g) r)) t -> In' (F g) r t
|
urbanslug/ghc
|
testsuite/tests/polykinds/T6137.hs
|
Haskell
|
bsd-3-clause
| 699
|
{-# LANGUAGE UndecidableInstances #-}
module Tc173b where
import Tc173a
is :: ()
is = isFormValue (Just "")
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/Tc173b.hs
|
Haskell
|
bsd-3-clause
| 109
|
-- | Defines readers for reading tags of BACnet values
module BACnet.Tag.Reader
(
readNullAPTag,
readNullCSTag,
readBoolAPTag,
readBoolCSTag,
readUnsignedAPTag,
readUnsignedCSTag,
readSignedAPTag,
readSignedCSTag,
readRealAPTag,
readRealCSTag,
readDoubleAPTag,
readDoubleCSTag,
readOctetStringAPTag,
readOctetStringCSTag,
readStringAPTag,
readStringCSTag,
readBitStringAPTag,
readBitStringCSTag,
readEnumeratedAPTag,
readEnumeratedCSTag,
readDateAPTag,
readDateCSTag,
readTimeAPTag,
readTimeCSTag,
readObjectIdentifierAPTag,
readObjectIdentifierCSTag,
readAnyAPTag,
readOpenTag,
readCloseTag
) where
import BACnet.Tag.Core
import BACnet.Reader.Core
import Data.Word
import Control.Monad (guard)
import Control.Applicative ((<|>))
-- | Like 'const' but applied twice. It takes three arguments
-- and returns the first.
const2 :: a -> b -> c -> a
const2 = const . const
readNullAPTag :: Reader Tag
readNullAPTag = sat (== 0x00) >> return NullAP
readNullCSTag :: TagNumber -> Reader Tag
readNullCSTag t = readCS t (==0) (flip $ const NullCS)
readBoolAPTag :: Reader Tag
readBoolAPTag = (sat (== 0x10) >> return (BoolAP False)) <|>
(sat (== 0x11) >> return (BoolAP True))
readBoolCSTag :: TagNumber -> Reader Tag
readBoolCSTag t = readCS t (==1) (flip $ const BoolCS)
readUnsignedAPTag :: Reader Tag
readUnsignedAPTag = readAP 2 UnsignedAP
readUnsignedCSTag :: TagNumber -> Reader Tag
readUnsignedCSTag t = readCS t (/=0) UnsignedCS
readSignedAPTag :: Reader Tag
readSignedAPTag = readAP 3 SignedAP
readSignedCSTag :: TagNumber -> Reader Tag
readSignedCSTag t = readCS t (/=0) SignedCS
readRealAPTag :: Reader Tag
readRealAPTag = sat (== 0x44) >> return RealAP
readRealCSTag :: TagNumber -> Reader Tag
readRealCSTag t = readCS t (==4) (const2 $ RealCS t)
readDoubleAPTag :: Reader Tag
readDoubleAPTag = sat (== 0x55) >> sat (== 0x08) >> return DoubleAP
readDoubleCSTag :: TagNumber -> Reader Tag
readDoubleCSTag t = readCS t (==8) (const2 $ DoubleCS t)
readOctetStringAPTag :: Reader Tag
readOctetStringAPTag = readAP 6 OctetStringAP
readOctetStringCSTag :: TagNumber -> Reader Tag
readOctetStringCSTag t = readCS t (const True) OctetStringCS
readStringAPTag :: Reader Tag
readStringAPTag = readAP 7 CharacterStringAP
readStringCSTag :: TagNumber -> Reader Tag
readStringCSTag t = readCS t (const True) CharacterStringCS
readBitStringAPTag :: Reader Tag
readBitStringAPTag = readAP 8 BitStringAP
readBitStringCSTag :: TagNumber -> Reader Tag
readBitStringCSTag t = readCS t (const True) BitStringCS
readEnumeratedAPTag :: Reader Tag
readEnumeratedAPTag = readAP 9 EnumeratedAP
readEnumeratedCSTag :: TagNumber -> Reader Tag
readEnumeratedCSTag tn = readCS tn (/=0) EnumeratedCS
readDateAPTag :: Reader Tag
readDateAPTag = sat (== 0xa4) >> return DateAP
readDateCSTag :: TagNumber -> Reader Tag
readDateCSTag tn = readCS tn (==4) (flip $ const DateCS)
readTimeAPTag :: Reader Tag
readTimeAPTag = sat (== 0xb4) >> return TimeAP
readTimeCSTag :: TagNumber -> Reader Tag
readTimeCSTag tn = readCS tn (==4) (flip $ const TimeCS)
readObjectIdentifierAPTag :: Reader Tag
readObjectIdentifierAPTag = sat (== 0xc4) >> return ObjectIdentifierAP
readObjectIdentifierCSTag :: TagNumber -> Reader Tag
readObjectIdentifierCSTag tn = readCS tn (==4) (flip $ const ObjectIdentifierCS)
readOpenTag :: TagNumber -> Reader Tag
readOpenTag tn = readTag (==tn) (==classCS) (const True) (==6) (flip $ const Open)
readCloseTag :: TagNumber -> Reader Tag
readCloseTag tn = readTag (==tn) (==classCS) (const True) (==7) (flip $ const Close)
peeksat :: (Word8 -> Bool) -> Reader Word8
peeksat p = peek >>= \b -> if p b then return b else fail "predicate failed"
readAnyAPTag :: Reader Tag
readAnyAPTag =
do
t <- peeksat isAP
case tagNumber t of
0 -> readNullAPTag
1 -> readBoolAPTag
2 -> readUnsignedAPTag
3 -> readSignedAPTag
4 -> readRealAPTag
5 -> readDoubleAPTag
6 -> readOctetStringAPTag
7 -> readStringAPTag
8 -> readBitStringAPTag
9 -> readEnumeratedAPTag
10 -> readDateAPTag
11 -> readTimeAPTag
12 -> readObjectIdentifierAPTag
_ -> fail "Invalid tag number for AP Tag"
type LengthPredicate = Length -> Bool
type APTagConstructor = Length -> Tag
type CSTagConstructor = TagConstructor
readAP :: TagNumber -> APTagConstructor -> Reader Tag
readAP tn co = readTag (==tn) (==classAP) (const True) (const True) (const co)
-- | @readCS tn pred co@ succeeds if tn matches the tag number that is read,
-- and the tag is CS encoded, and the length checking predicate returns true.
-- It constructs a Tag by using the given constructor @co@.
readCS :: TagNumber -> LengthPredicate -> CSTagConstructor -> Reader Tag
readCS tn p = readTag (==tn) (==classCS) p (const True)
type TagNumberPredicate = TagNumber -> Bool
type ClassPredicate = Class -> Bool
type TagConstructor = TagNumber -> Length -> Tag
type TypePredicate = Word8 -> Bool
readTag :: TagNumberPredicate -> ClassPredicate -> LengthPredicate ->
TypePredicate -> TagConstructor -> Reader Tag
readTag tagNumberP classP lengthP typeP co
= byte >>= \b ->
readClass b >>= \c ->
readExtendedTag b c >>= \tn ->
readExtendedLength b >>= \len ->
guard (tagNumberP tn && classP c && lengthP len && typeP b) >>
return (co tn len)
where readClass b = return $ if isCS b then classCS else classAP
readExtendedTag b c | c == classAP = readTagNumber b
| c == classCS =
(guard (tagNumber b == 15) >> byte) <|>
readTagNumber b
readTagNumber = return . tagNumber
readExtendedLength = lengthOfContent
type TagInitialOctet = Word8
-- | Given an initial octet of a tag, reads the length of the content
lengthOfContent :: TagInitialOctet -> Reader Word32
lengthOfContent b | lvt b < 5 = return . fromIntegral $ lvt b
| lvt b == 5 = lengthOfContent'
| otherwise = fail "Invalid length encoding"
-- | Reads the next byte. If it is < 254 it returns that value
-- If it is 254, then reads the next 2 bytes as a Word32
-- If it is 255, then reads the next 4 bytes as a Word32
lengthOfContent' :: Reader Word32
lengthOfContent' = byte >>= \b ->
if b < 254
then return $ fromIntegral b
else fmap foldbytes (bytes (if b == 254 then 2 else 4))
foldbytes :: [Word8] -> Word32
foldbytes = foldl (\acc w -> acc * 256 + fromIntegral w) 0
|
michaelgwelch/bacnet
|
src/BACnet/Tag/Reader.hs
|
Haskell
|
mit
| 6,726
|
import Test.Hspec
import Language.Paradocs.Renderer
import Language.Paradocs.RendererState
import Language.Paradocs.MonadStorage
import qualified Data.HashMap.Strict as HashMap
main :: IO ()
main = hspec $ do
describe "%read" $ do
let storage = HashMap.fromList [
("a.pd", "content")
]
let rendered = runHashMapStorage (renderString "%read a.pd") storage
it "reads the content of a.pd" $ do
renderedToString rendered `shouldBe` "content"
|
pasberth/paradocs
|
test/ReadInstructionSpec.hs
|
Haskell
|
mit
| 549
|
{-# LANGUAGE CPP #-}
module Language.Haskell.Source.Enumerator
( enumeratePath
) where
import Conduit
import Control.Applicative
import Control.Monad
import Data.List
import Distribution.PackageDescription
import qualified Distribution.Verbosity as Verbosity
import System.Directory
import System.FilePath
#if MIN_VERSION_Cabal(2,2,0)
import Distribution.PackageDescription.Parsec (readGenericPackageDescription)
#elif MIN_VERSION_Cabal(2,0,0)
import Distribution.PackageDescription.Parse (readGenericPackageDescription)
#else
import Distribution.PackageDescription.Parse (readPackageDescription)
readGenericPackageDescription ::
Verbosity.Verbosity -> FilePath -> IO GenericPackageDescription
readGenericPackageDescription = readPackageDescription
#endif
enumeratePath :: FilePath -> ConduitT () FilePath IO ()
enumeratePath path = enumPath path .| mapC normalise
enumPath :: FilePath -> ConduitT () FilePath IO ()
enumPath path = do
isDirectory <- lift $ doesDirectoryExist path
case isDirectory of
True -> enumDirectory path
False
| hasCabalExtension path -> enumPackage path
False
| hasHaskellExtension path -> yield path
False -> return ()
enumPackage :: FilePath -> ConduitT () FilePath IO ()
enumPackage cabalFile = readPackage cabalFile >>= expandPaths
where
readPackage = lift . readGenericPackageDescription Verbosity.silent
expandPaths = mapM_ (enumPath . mkFull) . sourcePaths
packageDir = dropFileName cabalFile
mkFull = (packageDir </>)
enumDirectory :: FilePath -> ConduitT () FilePath IO ()
enumDirectory path = do
contents <- lift $ getDirectoryContentFullPaths path
cabalFiles <- lift $ filterM isCabalFile contents
if null cabalFiles
then mapM_ enumPath contents
else mapM_ enumPackage cabalFiles
getDirectoryContentFullPaths :: FilePath -> IO [FilePath]
getDirectoryContentFullPaths path =
mkFull . notHidden . notMeta <$> getDirectoryContents path
where
mkFull = map (path </>)
notHidden = filter (not . isPrefixOf ".")
notMeta = (\\ [".", ".."])
isCabalFile :: FilePath -> IO Bool
isCabalFile path = return (hasCabalExtension path) <&&> doesFileExist path
hasCabalExtension :: FilePath -> Bool
hasCabalExtension path = ".cabal" `isSuffixOf` path
hasHaskellExtension :: FilePath -> Bool
hasHaskellExtension path = ".hs" `isSuffixOf` path || ".lhs" `isSuffixOf` path
sourcePaths :: GenericPackageDescription -> [FilePath]
sourcePaths pkg = nub $ concatMap ($ pkg) pathExtractors
where
pathExtractors =
[ maybe [] (hsSourceDirs . libBuildInfo . condTreeData) . condLibrary
, concatMap (hsSourceDirs . buildInfo . condTreeData . snd) .
condExecutables
, concatMap (hsSourceDirs . testBuildInfo . condTreeData . snd) .
condTestSuites
, concatMap (hsSourceDirs . benchmarkBuildInfo . condTreeData . snd) .
condBenchmarks
]
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 3 <&&> -- same as (&&)
|
danstiner/hfmt
|
src/Language/Haskell/Source/Enumerator.hs
|
Haskell
|
mit
| 3,124
|
module BinaryTreesSpec (main, spec) where
import Test.Hspec
import BinaryTrees
import Control.Exception (evaluate)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Preparering" $ do
it "returns (Branch 1 Empty Empty) when x = 1" $ do
leaf (1 :: Int) `shouldBe` Branch 1 Empty Empty
describe "Problem 55" $ do
it "returns Empty when n = 0" $ do
cbalTree 0 `shouldBe` [Empty]
it "returns (B 'x' E E) when n = 1" $ do
cbalTree 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [(B 'x' (B 'x' E E) E), (B 'x' E (B 'x' E E))] when n = 2" $ do
cbalTree 2 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) Empty, Branch 'x' Empty (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' E E) (B 'x' E (B 'x' E E))), (B 'x' (B 'x' E E) (B 'x' (B 'x' E E) E)), ...] when n = 4" $ do
let expected = [
Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty),
Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))
] in
cbalTree 4 `shouldBe` expected
describe "Problem 56" $ do
describe "mirror" $ do
it "returns True when (t1 t2) = (E, E)" $ do
mirror Empty Empty `shouldBe` True
it "returns False when (t1 t2) = (E, (B 'x' E E))" $ do
mirror Empty (Branch 'x' Empty Empty) `shouldBe` False
it "returns True when (t1, t2) = ((B 'x' E E), (B 'x' E E))" $ do
mirror (Branch 'x' Empty Empty) (Branch 'x' Empty Empty) `shouldBe` True
it "returns False when (t1, t2) = ((B 'x' (B 'x' E E) E), (B 'x' E E))" $ do
mirror (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty) `shouldBe` False
it "returns False when (t1, t2) = ((B 'x' (B 'x' E E) E), (B 'x' (B 'x' E E) E))" $ do
mirror (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` False
it "returns True when (t1, t2) = ((B 'x' E (B 'x' E E)), (B 'x' (B 'x' E E) E))" $ do
mirror (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` True
describe "symmetric" $ do
it "returns False when t = (B 'x' (B 'x' E E) E)" $ do
symmetric (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` False
it "returns True when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
symmetric (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` True
it "returns False when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E (B 'x' E E)))" $ do
symmetric (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` False
it "returns True when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E (B 'x' E E)))" $ do
symmetric (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` True
describe "Problem 57" $ do
it "returns Empty when ns = []" $ do
construct [] `shouldBe` Empty
it "returns (B 1 E E) when ns = [1]" $ do
construct [1] `shouldBe` (Branch 1 Empty Empty)
it "returns (B 3 (B 2 (B 1 E E) E) (B 5 E (B 7 E E))) when ls = [3, 2, 5, 7, 1]" $ do
construct [3, 2, 5, 7, 1] `shouldBe` (Branch 3 (Branch 2 (Branch 1 Empty Empty) Empty) (Branch 5 Empty (Branch 7 Empty Empty)))
describe "symmetric test" $ do
it "returns True when ns = [5, 3, 18, 1, 4, 12, 21]" $ do
symmetric . construct $ [5, 3, 18, 1, 4, 12, 21]
it "returns True when ns = [3, 2, 5, 7, 1]" $ do
symmetric . construct $ [3, 2, 5, 7, 1]
describe "Problem 58" $ do
it "returns [E] when n = 0" $ do
symCbalTrees 0 `shouldBe` [Empty]
it "returns [(B 'x' E E)] when n = 1" $ do
symCbalTrees 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [] when n = 2" $ do
symCbalTrees 2 `shouldBe` []
it "returns [(B 'x' (B 'x' E E) (B 'x' E E))] when n = 3" $ do
symCbalTrees 3 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' E (B 'x' E E)) (B 'x' (B 'x' E E) E)), ...] when n = 5" $ do
let expected = [
Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty (Branch 'x' Empty Empty)),
Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) Empty)
] in
symCbalTrees 5 `shouldBe` expected
describe "Problem 59" $ do
it "returns [E] when (v, n) = ('x', 0)" $ do
hbalTree 'x' 0 `shouldBe` [Empty]
it "returns [(B 'x' E E)] when (v, n) = ('x', 1)" $ do
hbalTree 'x' 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [(B 'x' (B 'x' E E) E), (B 'x' E (B 'x' E E)), (B 'x' (B 'x' E E) (B 'x' E E))] when (v, n) = ('x', 2)" $ do
hbalTree 'x' 2 `shouldBe` [(Branch 'x' (Branch 'x' Empty Empty) Empty), (Branch 'x' Empty (Branch 'x' Empty Empty)), (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty))]
it "returns 315 patterns when (v, n) = ('x', 3)" $ do
(length $ hbalTree 'x' 4) `shouldBe` 315
describe "Problem 60" $ do
describe "minHbalNodes" $ do
it "returns 0 when h = 0" $ do
minHbalNodes 0 `shouldBe` 0
it "returns 1 when h = 1" $ do
minHbalNodes 1 `shouldBe` 1
it "returns 2 when h = 2" $ do
minHbalNodes 2 `shouldBe` 2
it "returns 4 when h = 3" $ do
minHbalNodes 3 `shouldBe` 4
it "returns 7 when h = 4" $ do
minHbalNodes 4 `shouldBe` 7
it "returns 12 when h = 5" $ do
minHbalNodes 5 `shouldBe` 12
describe "maxHbalHeight" $ do
it "returns 0 when h = 0" $ do
maxHbalHeight 0 `shouldBe` 0
it "returns 1 when h = 1" $ do
maxHbalHeight 1 `shouldBe` 1
it "returns 2 when h = 2" $ do
maxHbalHeight 2 `shouldBe` 2
it "returns 2 when h = 3" $ do
maxHbalHeight 3 `shouldBe` 2
it "returns 3 when h = 4" $ do
maxHbalHeight 4 `shouldBe` 3
it "returns 3 when h = 5" $ do
maxHbalHeight 5 `shouldBe` 3
it "returns 4 when h = 7" $ do
maxHbalHeight 7 `shouldBe` 4
it "returns 4 when h = 8" $ do
maxHbalHeight 8 `shouldBe` 4
describe "minHbalHeight" $ do
it "returns 0 when h = 0" $ do
minHbalHeight 0 `shouldBe` 0
it "returns 1 when h = 1" $ do
minHbalHeight 1 `shouldBe` 1
it "returns 2 when h = 2" $ do
minHbalHeight 2 `shouldBe` 2
it "returns 2 when h = 3" $ do
minHbalHeight 3 `shouldBe` 2
it "returns 3 when h = 4" $ do
minHbalHeight 4 `shouldBe` 3
it "returns 3 when h = 5" $ do
minHbalHeight 5 `shouldBe` 3
it "returns 4 when h = 7" $ do
minHbalHeight 7 `shouldBe` 3
it "returns 4 when h = 8" $ do
minHbalHeight 8 `shouldBe` 4
describe "nodeCount" $ do
it "returns 0 when t = E" $ do
nodeCount Empty `shouldBe` 0
it "returns 1 when t = (B 'x' E E)" $ do
nodeCount (Branch 'x' Empty Empty) `shouldBe` 1
it "returns 2 when t = (B 'x' (B 'x' E E) E)" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` 2
it "returns 2 when t = (B 'x' E (B 'x' E E))" $ do
nodeCount (Branch 'x' Empty (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 3 when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` 3
it "returns 4 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)) `shouldBe` 4
it "returns 4 when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 4
it "returns 4 when t = (B 'x' (B 'x' E E) (B 'x' (B 'x' E E) E))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 4
it "returns 4 when t = (B 'x' (B 'x' E E) (B 'x' E (B 'x' E E)))" $ do
nodeCount (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` 4
it "returns 5 when t = (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' E E))" $ do
nodeCount (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 5
it "returns 5 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' (B 'x' E E) E))" $ do
nodeCount (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 5
describe "hbalTreeNodes" $ do
it "returns [E] when (v, n) = ('x', 0)" $ do
hbalTreeNodes 'x' 0 `shouldBe` [Empty]
it "returns [(B 'x' E E)] when (v, n) = ('x', 1)" $ do
hbalTreeNodes 'x' 1 `shouldBe` [Branch 'x' Empty Empty]
it "returns [(B 'x' (B 'x' E E) E), (B 'x' E (B 'x' E E))] when (v, n) = ('x', 2)" $ do
hbalTreeNodes 'x' 2 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) Empty, Branch 'x' Empty (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' E E) (B 'x' E E))] when (v, n) = ('x', 3)" $ do
hbalTreeNodes 'x' 3 `shouldBe` [Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)]
it "returns [(B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E)), ...] when (v, n) = ('x', 4)" $ do
let expected = [
Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty),
Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty),
Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))
] in
hbalTreeNodes 'x' 4 `shouldBe` expected
-- FIXME ちょっと時間かかるので少し消しておく
-- it "returns 1553 patterns when (v, n) = ('x', 15)" $ do
-- length (hbalTreeNodes 'x' 15) `shouldBe` 1553
describe "Problem 61" $ do
it "returns 0 when t = E" $ do
countLeaves Empty `shouldBe` 0
it "returns 1 when t = (B 'x' E E)" $ do
countLeaves (Branch 'x' Empty Empty) `shouldBe` 1
it "returns 1 when t = (B 'x' (B 'x' E E) E)" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` 1
it "returns 1 when t = (B 'x' E (B 'x' E E))" $ do
countLeaves (Branch 'x' Empty (Branch 'x' Empty Empty)) `shouldBe` 1
it "returns 2 when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' E E) (B 'x' (B 'x' E E) E))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 2
it "returns 2 when t = (B 'x' (B 'x' E E) (B 'x' E (B 'x' E E)))" $ do
countLeaves (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty (Branch 'x' Empty Empty))) `shouldBe` 2
it "returns 2 when t = (B 1 (B 2 E (B 4 E E)) (B 2 E E))" $ do
countLeaves (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) `shouldBe` 2
it "returns 3 when t = (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' E E))" $ do
countLeaves (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` 3
it "returns 2 when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' (B 'x' E E) E))" $ do
countLeaves (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' (Branch 'x' Empty Empty) Empty)) `shouldBe` 2
describe "Problem 61A" $ do
it "returns [] when t = E" $ do
leaves Empty `shouldBe` ([] :: [Int])
it "returns [1] when t = (B 1 E E)" $ do
leaves (Branch (1 :: Int) Empty Empty) `shouldBe` [1]
it "returns [2] when t = (B 1 (B 2 E E) E)" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [2]
it "returns [3] when t = (B 1 E (B 3 E E))" $ do
leaves (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [3]
it "returns [2, 3] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [2, 3]
it "returns [3, 4] when t = (B 1 (B 2 (B 3 E E) E) (B 4 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 Empty Empty)) `shouldBe` [3, 4]
it "returns [3, 4] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [3, 4]
it "returns [2, 4] when t = (B 1 (B 2 E E) (B 3 (B 4 E E) E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 (Branch 4 Empty Empty) Empty)) `shouldBe` [2, 4]
it "returns [2, 4] when t = (B 1 (B 2 E E) (B 3 E (B 4 E E)))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty (Branch 4 Empty Empty))) `shouldBe` [2, 4]
it "returns [4, 2] when t = (B 1 (B 2 E (B 4 E E)) (B 2 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) `shouldBe` [4, 2]
it "returns [3, 4, 5] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E E))" $ do
leaves (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) (Branch 4 Empty Empty)) (Branch 5 Empty Empty)) `shouldBe` [3, 4, 5]
it "returns [3, 5] when t = (B 1 (B 2 (B 3 E E) E) (B 4 (B 5 E E) E))" $ do
leaves (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 (Branch 5 Empty Empty) Empty)) `shouldBe` [3, 5]
describe "Problem 62" $ do
it "returns [] when t = E" $ do
internals Empty `shouldBe` ([] :: [Int])
it "returns [] when t = (B 1 E E)" $ do
internals (Branch (1 :: Int) Empty Empty) `shouldBe` []
it "returns [1] when t = (B 1 (B 2 E E) E)" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [1]
it "returns [1] when t = (B 1 E (B 3 E E))" $ do
internals (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [1]
it "returns [1] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [1]
it "returns [1, 2] when t = (B 1 (B 2 (B 3 E E) E) (B 4 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 2] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 3] when t = (B 1 (B 2 E E) (B 3 (B 4 E E) E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 (Branch 4 Empty Empty) Empty)) `shouldBe` [1, 3]
it "returns [1, 3] when t = (B 1 (B 2 E E) (B 3 E (B 4 E E)))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty (Branch 4 Empty Empty))) `shouldBe` [1, 3]
it "returns [1, 2] when t = (B 1 (B 2 E (B 4 E E)) (B 2 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 2] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E E))" $ do
internals (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) (Branch 4 Empty Empty)) (Branch 5 Empty Empty)) `shouldBe` [1, 2]
it "returns [1, 2, 4] when t = (B 1 (B 2 (B 3 E E) E) (B 4 (B 5 E E) E))" $ do
internals (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) (Branch 4 (Branch 5 Empty Empty) Empty)) `shouldBe` [1, 2, 4]
describe "Problem 62B" $ do
it "returns [] when (t, n) = (E, 1)" $ do
atLevel Empty 1 `shouldBe` ([] :: [Int])
it "returns [1] when (t, n) = ((B 1 E E), 1)" $ do
atLevel (Branch (1 :: Int) Empty Empty) 1 `shouldBe` [1]
it "returns [] when (t, n) = ((B 1 E E), 2)" $ do
atLevel (Branch (1 :: Int) Empty Empty) 2 `shouldBe` []
it "returns [] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 0)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 0 `shouldBe` []
it "returns [1] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 1)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 1 `shouldBe` [1]
it "returns [2, 2] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 2)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 2 `shouldBe` [2, 2]
it "returns [4] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 3)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 3 `shouldBe` [4]
it "returns [] when (t, n) = ((B 1 (B 2 E (B 4 E E)) (B 2 E E)), 4)" $ do
atLevel (Branch (1 :: Int) (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)) 4 `shouldBe` []
describe "Problem 63" $ do
describe "completeBinaryTree" $ do
it "returns Empty when n = 0" $ do
completeBinaryTree 0 `shouldBe` Empty
it "returns (B 'x' E E) when n = 1" $ do
completeBinaryTree 1 `shouldBe` Branch 'x' Empty Empty
it "returns (B 'x' (B 'x' E E) E) when n = 2" $ do
completeBinaryTree 2 `shouldBe` Branch 'x' (Branch 'x' Empty Empty) Empty
it "returns (B 'x' (B 'x' E E) (B 'x' E E)) when n = 3" $ do
completeBinaryTree 3 `shouldBe` Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E)) when n = 4" $ do
completeBinaryTree 4 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' E E)) when n = 5" $ do
completeBinaryTree 5 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' (B 'x' E E) E)) when n = 6" $ do
completeBinaryTree 6 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) Empty)
it "returns (B 'x' (B 'x' (B 'x' E E) (B 'x' E E)) (B 'x' (B 'x' E E) (B 'x' E E))) when n = 7" $ do
completeBinaryTree 7 `shouldBe` Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty))
describe "isCompleteBinaryTree" $ do
it "returns True when t = Empty" $ do
isCompleteBinaryTree Empty `shouldBe` True
it "returns True when t = (B 'x' E E)" $ do
isCompleteBinaryTree (Branch 'x' Empty Empty) `shouldBe` True
it "returns True when t = (B 'x' (B 'x' E E) E)" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' Empty Empty) Empty) `shouldBe` True
it "returns False when t = (B 'x' E (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' Empty (Branch 'x' Empty Empty)) `shouldBe` False
it "returns True when t = (B 'x' (B 'x' E E) (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty)) `shouldBe` True
it "returns True when t = (B 'x' (B 'x' (B 'x' E E) E) (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' (Branch 'x' Empty Empty) Empty) (Branch 'x' Empty Empty)) `shouldBe` True
it "returns False when t = (B 'x' (B 'x' E (B 'x' E E)) (B 'x' E E))" $ do
isCompleteBinaryTree (Branch 'x' (Branch 'x' Empty (Branch 'x' Empty Empty)) (Branch 'x' Empty Empty)) `shouldBe` False
describe "isCompleteBinaryTree + completeBinaryTree" $ do
it "returns True" $ do
isCompleteBinaryTree (completeBinaryTree 4) `shouldBe` True
describe "Problem 64" $ do
it "returns Empty when t = E" $ do
layout (Empty :: Tree Char) `shouldBe` Empty
it "returns (B ('n', (1, 1)) Empty Empty) when t = (B 'n' E E)" $ do
layout (Branch 'n' Empty Empty) `shouldBe` (Branch ('n', (1, 1)) Empty Empty)
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) E) when t = (B 'n' (B 'k' E E) E)" $ do
layout (Branch 'n' (Branch 'k' Empty Empty) Empty) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) Empty)
it "returns (B ('n', (1, 1)) E (B ('k', (2, 2)) E E)) when t = (B 'n' E (B 'k' E E))" $ do
layout (Branch 'n' Empty (Branch 'k' Empty Empty)) `shouldBe` (Branch ('n', (1, 1)) Empty (Branch ('k', (2, 2)) Empty Empty))
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) (B ('u', (3, 2)) E E)) when t = (B 'n' (B 'k' E E) (B 'u' E E))" $ do
layout (Branch 'n' (Branch 'k' Empty Empty) (Branch 'u' Empty Empty)) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) (Branch ('u', (3, 2)) Empty Empty))
it "returns (B ('n', (3, 1)) (B ('k', (2, 2)) E E) (B ('u', (1, 3)) E E)) when t = (B 'n' (B 'k' (B 'u' E E) E) E)" $ do
layout (Branch 'n' (Branch 'k' (Branch 'u' Empty Empty) Empty) Empty) `shouldBe` (Branch ('n', (3, 1)) (Branch ('k', (2, 2)) (Branch ('u', (1, 3)) Empty Empty) Empty) Empty)
it "returns (B ('a', (1, 1)) E (B ('b', (2, 2)) E (B ('c', (3, 3)) E E))) when t = (B 'a' E (B 'b' E (B 'c' E E)))" $ do
layout (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty))) `shouldBe` (Branch ('a', (1, 1)) Empty (Branch ('b', (2, 2)) Empty (Branch ('c', (3, 3)) Empty Empty)))
it "returns (B ('a', (3, 1)) (B ('b', (1, 2)) E (B ('c', (2, 3)) E E)) (B ('d', (4, 2) E E))) when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
layout (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` ((Branch ('a', (3, 1)) (Branch ('b', (1, 2)) Empty (Branch ('c', (2, 3)) Empty Empty)) (Branch ('d', (4, 2)) Empty Empty)))
it "returns layout when t = tree64(in problem)" $ do
let tree64 = Branch 'n'
(Branch 'k'
(Branch 'c'
(Branch 'a' Empty Empty)
(Branch 'h'
(Branch 'g'
(Branch 'e' Empty Empty)
Empty
)
Empty
)
)
(Branch 'm' Empty Empty)
)
(Branch 'u'
(Branch 'p'
Empty
(Branch 's'
(Branch 'q' Empty Empty)
Empty
)
)
Empty
)
expected = Branch ('n', (8, 1))
(Branch ('k', (6, 2))
(Branch ('c', (2, 3))
(Branch ('a', (1, 4)) Empty Empty)
(Branch ('h', (5, 4))
(Branch ('g', (4, 5))
(Branch ('e', (3, 6)) Empty Empty)
Empty
)
Empty
)
)
(Branch ('m', (7, 3)) Empty Empty)
)
(Branch ('u', (12, 2))
(Branch ('p', (9, 3))
Empty
(Branch ('s', (11, 4))
(Branch ('q', (10, 5)) Empty Empty)
Empty
)
)
Empty
)
in layout tree64 `shouldBe` expected
describe "Problem 65" $ do
it "returns Empty when t = E" $ do
layout2 (Empty :: Tree Int) `shouldBe` Empty
it "returns (B ('n', (1, 1)) Empty Empty) when t = (B 'n' E E)" $ do
layout2 (Branch 'n' Empty Empty) `shouldBe` (Branch ('n', (1, 1)) Empty Empty)
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) E) when t = (B 'n' (B 'k' E E) E)" $ do
layout2 (Branch 'n' (Branch 'k' Empty Empty) Empty) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) Empty)
it "returns (B ('n', (1, 1)) E (B ('k', (2, 2)) E E)) when t = (B 'n' E (B 'k' E E))" $ do
layout2 (Branch 'n' Empty (Branch 'k' Empty Empty)) `shouldBe` (Branch ('n', (1, 1)) Empty (Branch ('k', (2, 2)) Empty Empty))
it "returns (B ('n', (2, 1)) (B ('k', (1, 2)) E E) (B ('u', (3, 2)) E E)) when t = (B 'n' (B 'k' E E) (B 'u' E E))" $ do
layout2 (Branch 'n' (Branch 'k' Empty Empty) (Branch 'u' Empty Empty)) `shouldBe` (Branch ('n', (2, 1)) (Branch ('k', (1, 2)) Empty Empty) (Branch ('u', (3, 2)) Empty Empty))
it "returns (B ('n', (4, 1)) (B ('k', (2, 2)) E E) (B ('u', (1, 3)) E E)) when t = (B 'n' (B 'k' (B 'u' E E) E) E)" $ do
layout2 (Branch 'n' (Branch 'k' (Branch 'u' Empty Empty) Empty) Empty) `shouldBe` (Branch ('n', (4, 1)) (Branch ('k', (2, 2)) (Branch ('u', (1, 3)) Empty Empty) Empty) Empty)
it "returns (B ('a', (1, 1)) E (B ('b', (3, 2)) E (B ('c', (4, 3)) E E))) when t = (B 'a' E (B 'b' E (B 'c' E E)))" $ do
layout2 (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty))) `shouldBe` (Branch ('a', (1, 1)) Empty (Branch ('b', (3, 2)) Empty (Branch ('c', (4, 3)) Empty Empty)))
it "returns (B ('a', (3, 1)) (B ('b', (1, 2)) E (B ('c', (2, 3)) E E)) (B ('d', (5, 2) E E))) when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
layout2 (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` ((Branch ('a', (3, 1)) (Branch ('b', (1, 2)) Empty (Branch ('c', (2, 3)) Empty Empty)) (Branch ('d', (5, 2)) Empty Empty)))
it "returns layout when t = tree65(in problem)" $ do
let tree65 = Branch 'n'
(Branch 'k'
(Branch 'c'
(Branch 'a' Empty Empty)
(Branch 'e'
(Branch 'd' Empty Empty)
(Branch 'g' Empty Empty)
)
)
(Branch 'm' Empty Empty)
)
(Branch 'u'
(Branch 'p'
Empty
(Branch 'q' Empty Empty)
)
Empty
)
expected = Branch ('n', (15, 1))
(Branch ('k', (7, 2))
(Branch ('c', (3, 3))
(Branch ('a', (1, 4)) Empty Empty)
(Branch ('e', (5, 4))
(Branch ('d', (4, 5)) Empty Empty)
(Branch ('g', (6, 5)) Empty Empty)
)
)
(Branch ('m', (11, 3)) Empty Empty)
)
(Branch ('u', (23, 2))
(Branch ('p', (19, 3))
Empty
(Branch ('q', (21, 4)) Empty Empty)
)
Empty
)
in layout2 tree65 `shouldBe` expected
describe "Problem 66" $ do
it "pass" $ do
True `shouldBe` True
describe "Problem 67A" $ do
describe "treeToString" $ do
it "returns \"\" when t = E" $ do
treeToString Empty `shouldBe` ""
it "returns \"a\" when t = (B 'a' E E)" $ do
treeToString (Branch 'a' Empty Empty) `shouldBe` "a"
it "returns \"a(b,)\" when t = (B 'a' (B 'b' E E) E)" $ do
treeToString (Branch 'a' (Branch 'b' Empty Empty) Empty) `shouldBe` "a(b,)"
it "returns \"a(,c)\" when t = (B 'a' E (B 'c' E E))" $ do
treeToString (Branch 'a' Empty (Branch 'c' Empty Empty)) `shouldBe` "a(,c)"
it "returns \"a(b,c)\" when t = (B 'a' (B 'b' E E) (B 'c' E E))" $ do
treeToString (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty)) `shouldBe` "a(b,c)"
it "returns \"a(b(,c),d)\" when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
treeToString (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` "a(b(,c),d)"
it "returns \"a(b(d,e),c(,f(g,)))\" when t = (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E)))" $ do
treeToString (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty))) `shouldBe` "a(b(d,e),c(,f(g,)))"
describe "stringToTree" $ do
it "returns E when s = \"\"" $ do
stringToTree "" `shouldBe` Empty
it "returns (B 'a' E E) when s = \"a\"" $ do
stringToTree "a" `shouldBe` (Branch 'a' Empty Empty)
it "returns (B 'a' (B 'b' E E) E) when s = \"a(b,)\"" $ do
stringToTree "a(b,)" `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) Empty)
it "returns (B 'a' E (B 'c' E E)) when s = \"a(,c)\"" $ do
stringToTree "a(,c)" `shouldBe` (Branch 'a' Empty (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' E E) (B 'c' E E)) when s = \"a(b,c)\"" $ do
stringToTree "a(b,c)" `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E)) when s = \"a(b(,c),d)\"" $ do
stringToTree "a(b(,c),d)" `shouldBe` (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty))
it "returns (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E))) when s = \"a(b(d,e),c(,f(g,)))\"" $ do
stringToTree "a(b(d,e),c(,f(g,)))" `shouldBe` (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty)))
it "returns (B 'x' (B 'y' E E) (B 'a' E (B 'b' E E))) when s = \"x(y,a(,b))\"" $ do
stringToTree "x(y,a(,b))" `shouldBe` (Branch 'x' (Branch 'y' Empty Empty) (Branch 'a' Empty (Branch 'b' Empty Empty)))
it "throws exception when s = \"xy,a(,b))\" (illegal format)" $ do
evaluate (stringToTree "xy,a(,b))" ) `shouldThrow` errorCall "illegal format"
describe "treeToString + stringToTree" $ do
it "returns same tree" $ do
let t = Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' (Branch 'e' (Branch 'f' Empty Empty) (Branch 'g' Empty Empty)) (Branch 'h' Empty Empty))
in (stringToTree . treeToString) t `shouldBe` t
describe "Problem 68" $ do
describe "treeToPreorder" $ do
it "returns [] when t = E" $ do
treeToPreorder (Empty :: Tree Int) `shouldBe` []
it "returns [1] when t = (B 1 E E)" $ do
treeToPreorder (Branch (1 :: Int) Empty Empty) `shouldBe` [1]
it "returns [1, 2] when t = (B 1 (B 2 E E) E)" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [1, 2]
it "returns [1, 3] when t = (B 1 E (B 3 E E))" $ do
treeToPreorder (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [1, 3]
it "returns [1, 2, 3] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [1, 2, 3]
it "returns [1, 2, 3] when t = (B 1 (B 2 (B 3 E E) E) E)" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) Empty) `shouldBe` [1, 2, 3]
it "returns [1, 2, 3] when t = (B 1 E (B 2 E (B 3 E E)))" $ do
treeToPreorder (Branch (1 :: Int) Empty (Branch 2 Empty (Branch 3 Empty Empty))) `shouldBe` [1, 2, 3]
it "returns [1, 2, 3, 4] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [1, 2, 3, 4]
it "returns [1, 2, 4, 5, 3, 6, 7] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E (B 6 (B 7 E E) E)))" $ do
treeToPreorder (Branch (1 :: Int) (Branch 2 (Branch 4 Empty Empty) (Branch 5 Empty Empty)) (Branch 3 Empty (Branch 6 (Branch 7 Empty Empty) Empty))) `shouldBe` [1, 2, 4, 5, 3, 6, 7]
describe "treeToInorder" $ do
it "returns [] when t = E" $ do
treeToInorder (Empty :: Tree Int) `shouldBe` []
it "returns [1] when t = (B 1 E E)" $ do
treeToInorder (Branch (1 :: Int) Empty Empty) `shouldBe` [1]
it "returns [2, 1] when t = (B 1 (B 2 E E) E)" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 Empty Empty) Empty) `shouldBe` [2, 1]
it "returns [1, 3] when t = (B 1 E (B 3 E E))" $ do
treeToInorder (Branch (1 :: Int) Empty (Branch 3 Empty Empty)) `shouldBe` [1, 3]
it "returns [2, 1, 3] when t = (B 1 (B 2 E E) (B 3 E E))" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 Empty Empty) (Branch 3 Empty Empty)) `shouldBe` [2, 1, 3]
it "returns [3, 2, 1] when t = (B 1 (B 2 (B 3 E E) E) E)" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 (Branch 3 Empty Empty) Empty) Empty) `shouldBe` [3, 2, 1]
it "returns [1, 2, 3] when t = (B 1 E (B 2 E (B 3 E E)))" $ do
treeToInorder (Branch (1 :: Int) Empty (Branch 2 Empty (Branch 3 Empty Empty))) `shouldBe` [1, 2, 3]
it "returns [2, 3, 1, 4] when t = (B 1 (B 2 E (B 3 E E)) (B 4 E E))" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty)) `shouldBe` [2, 3, 1, 4]
it "returns [4, 2, 5, 1, 3, 7, 6] when t = (B 1 (B 2 (B 3 E E) (B 4 E E)) (B 5 E (B 6 (B 7 E E) E)))" $ do
treeToInorder (Branch (1 :: Int) (Branch 2 (Branch 4 Empty Empty) (Branch 5 Empty Empty)) (Branch 3 Empty (Branch 6 (Branch 7 Empty Empty) Empty))) `shouldBe` [4, 2, 5, 1, 3, 7, 6]
describe "preInTree" $ do
it "returns E when (po, io) = ([], [])" $ do
preInTree ([] :: [Char]) [] `shouldBe` Empty
it "returns E when (po, io) = ([1], [])" $ do
preInTree [1 :: Int] [] `shouldBe` Empty
it "returns E when (po, io) = ([], [1])" $ do
preInTree [] [1 :: Int] `shouldBe` Empty
it "returns E when (po, io) = ([1, 2], [1])" $ do
preInTree [1 :: Int, 2] [1] `shouldBe` Empty
it "returns E when (po, io) = ([1], [1, 2])" $ do
preInTree [1 :: Int] [1, 2] `shouldBe` Empty
it "returns (B 1 E E) when (po, io) = ([1], [1])" $ do
preInTree [1 :: Int] [1] `shouldBe` (Branch 1 Empty Empty)
it "returns (B 1 (B 2 E E) E) when (po, io) = ([1, 2], [2, 1])" $ do
preInTree [1 :: Int, 2] [2, 1] `shouldBe` (Branch 1 (Branch 2 Empty Empty) Empty)
it "returns (B 1 E (B 3 E E)) when (po, io) = ([1, 3], [1, 3])" $ do
preInTree [1 :: Int, 3] [1, 3] `shouldBe` (Branch 1 Empty (Branch 3 Empty Empty))
it "returns (B 1 (B 2 E E) (B 3 E E)) when (po, io) = ([1, 2, 3], [2, 1, 3])" $ do
preInTree [1 :: Int, 2, 3] [2, 1, 3] `shouldBe` (Branch 1 (Branch 2 Empty Empty) (Branch 3 Empty Empty))
it "returns (B 1 (B 2 (B 3 E E) E) E) when (po, io) = ([1, 2, 3], [3, 2, 1])" $ do
preInTree [1 :: Int, 2, 3] [3, 2, 1] `shouldBe` (Branch 1 (Branch 2 (Branch 3 Empty Empty) Empty) Empty)
it "returns (B 1 (B 2 (B 3 E E) E) E) when (po, io) = ([1, 2, 3], [1, 2, 3])" $ do
preInTree [1 :: Int, 2, 3] [1, 2, 3] `shouldBe` (Branch 1 Empty (Branch 2 Empty (Branch 3 Empty Empty)))
it "returns (B 1 (B 2 E (B 3 E E)) (B 4 E E)) when (po, io) = ([1, 2, 3, 4], [2, 3, 1, 4])" $ do
preInTree [1 :: Int, 2, 3, 4] [2, 3, 1, 4] `shouldBe` (Branch 1 (Branch 2 Empty (Branch 3 Empty Empty)) (Branch 4 Empty Empty))
it "returns (B 1 (B 2 E (B 3 E E)) (B 4 E E)) when (po, io) = ([1, 2, 3, 4, 5, 6, 7], [4, 2, 5, 1, 3, 7, 6])" $ do
preInTree [1 :: Int, 2, 4, 5, 3, 6, 7] [4, 2, 5, 1, 3, 7, 6] `shouldBe` (Branch 1 (Branch 2 (Branch 4 Empty Empty) (Branch 5 Empty Empty)) (Branch 3 Empty (Branch 6 (Branch 7 Empty Empty) Empty)))
describe "treeToPreorder + treeToInorder + preInTree" $ do
it "returns (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E)))" $ do
let t = Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty))
po = treeToPreorder t
io = treeToInorder t
in preInTree po io `shouldBe` t
describe "Problem 69" $ do
describe "ds2tree" $ do
it "returns E when s = \".\"" $ do
ds2tree "." `shouldBe` Empty
it "returns (B 'a' E E) when s = \"a..\"" $ do
ds2tree "a.." `shouldBe` (Branch 'a' Empty Empty)
it "returns (B 'a' E E) when s = \"a...\"" $ do
ds2tree "a..." `shouldBe` (Branch 'a' Empty Empty)
it "returns (B 'a' (B 'b' E E) E) when s = \"ab...\"" $ do
ds2tree "ab..." `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) Empty)
it "returns (B 'a' E (B 'c' E E)) when s = \"a.c..\"" $ do
ds2tree "a.c.." `shouldBe` (Branch 'a' Empty (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' E E) (B 'c' E E)) when s = \"ab..c..\"" $ do
ds2tree "ab..c.." `shouldBe` (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty))
it "returns (B 'a' (B 'b' (B 'c' E E) E) E) when s = \"abc....\"" $ do
ds2tree "abc...." `shouldBe` (Branch 'a' (Branch 'b' (Branch 'c' Empty Empty) Empty) Empty)
it "returns (B 'a' E (B 'b' E (B 'c' E E))) when s = \"a.b.c..\"" $ do
ds2tree "a.b.c.." `shouldBe` (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty)))
it "returns (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E)) when s = \"ab.c..d..\"" $ do
ds2tree "ab.c..d.." `shouldBe` (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty))
it "returns (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E))) when s = \"abd..e..c.fg...\"" $ do
ds2tree "abd..e..c.fg..." `shouldBe` (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty)))
it "throws exception when s = \"a.\" (1)" $ do
evaluate (ds2tree "a.") `shouldThrow` anyException
describe "tree2ds" $ do
it "returns \".\" when t = E" $ do
tree2ds (Empty :: Tree Char) `shouldBe` "."
it "returns \"a..\" when t = (B 'a' E E)" $ do
tree2ds (Branch 'a' Empty Empty) `shouldBe` "a.."
it "returns \"ab...\" when t = (B 'a' (B 'b' E E) E)" $ do
tree2ds (Branch 'a' (Branch 'b' Empty Empty) Empty) `shouldBe` "ab..."
it "returns \"a.c..\" when t = (B 'a' E (B 'c' E E))" $ do
tree2ds (Branch 'a' Empty (Branch 'c' Empty Empty)) `shouldBe` "a.c.."
it "returns \"ab..c..\" when t = (B 'a' (B 'b' E E) (B 'c' E E))" $ do
tree2ds (Branch 'a' (Branch 'b' Empty Empty) (Branch 'c' Empty Empty)) `shouldBe` "ab..c.."
it "returns \"abc....\" when t = (B 'a' (B 'b' (B 'c' E E) E) E)" $ do
tree2ds (Branch 'a' (Branch 'b' (Branch 'c' Empty Empty) Empty) Empty) `shouldBe` "abc...."
it "returns \"a.b.c..\" when t = (B 'a' E (B 'b' E (B 'c' E E)))" $ do
tree2ds (Branch 'a' Empty (Branch 'b' Empty (Branch 'c' Empty Empty))) `shouldBe` "a.b.c.."
it "returns \"ab.c..d..\" when t = (B 'a' (B 'b' E (B 'c' E E)) (B 'd' E E))" $ do
tree2ds (Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' Empty Empty)) `shouldBe` "ab.c..d.."
it "returns \"abd..e..c.fg...\" when t = (B 'a' (B 'b' (B 'd' E E) (B 'e' E E)) (B 'c' E (B 'f' (B 'g' E E) E)))" $ do
tree2ds (Branch 'a' (Branch 'b' (Branch 'd' Empty Empty) (Branch 'e' Empty Empty)) (Branch 'c' Empty (Branch 'f' (Branch 'g' Empty Empty) Empty))) `shouldBe` "abd..e..c.fg..."
describe "tree2ds + ds2tree" $ do
it "returns same tree" $ do
let t = Branch 'a' (Branch 'b' Empty (Branch 'c' Empty Empty)) (Branch 'd' (Branch 'e' (Branch 'f' Empty Empty) (Branch 'g' Empty Empty)) (Branch 'h' Empty Empty))
in (ds2tree . tree2ds) t `shouldBe` t
|
yyotti/99Haskell
|
src/test/BinaryTreesSpec.hs
|
Haskell
|
mit
| 41,856
|
-----------------------------------------------------------------------------
--
-- Module : Main
-- Copyright : (c) 2013-15 Phil Freeman, (c) 2014-15 Gary Burgess
-- License : MIT (http://opensource.org/licenses/MIT)
--
-- Maintainer : Phil Freeman <paf31@cantab.net>
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Monad.Error.Class (MonadError(..))
import Control.Monad.Writer.Strict
import Data.List (isSuffixOf, partition)
import Data.Version (showVersion)
import qualified Data.Map as M
import Options.Applicative as Opts
import System.Exit (exitSuccess, exitFailure)
import System.IO (hPutStrLn, stderr)
import System.IO.UTF8
import System.FilePath.Glob (glob)
import qualified Language.PureScript as P
import qualified Paths_purescript as Paths
import Language.PureScript.Make
data PSCMakeOptions = PSCMakeOptions
{ pscmInput :: [FilePath]
, pscmForeignInput :: [FilePath]
, pscmOutputDir :: FilePath
, pscmOpts :: P.Options
, pscmUsePrefix :: Bool
}
data InputOptions = InputOptions
{ ioInputFiles :: [FilePath]
}
compile :: PSCMakeOptions -> IO ()
compile (PSCMakeOptions inputGlob inputForeignGlob outputDir opts usePrefix) = do
input <- globWarningOnMisses warnFileTypeNotFound inputGlob
when (null input) $ do
hPutStrLn stderr "psc: No input files."
exitFailure
let (jsFiles, pursFiles) = partition (isSuffixOf ".js") input
moduleFiles <- readInput (InputOptions pursFiles)
inputForeign <- globWarningOnMisses warnFileTypeNotFound inputForeignGlob
foreignFiles <- forM (inputForeign ++ jsFiles) (\inFile -> (inFile,) <$> readUTF8File inFile)
case runWriterT (parseInputs moduleFiles foreignFiles) of
Left errs -> do
hPutStrLn stderr (P.prettyPrintMultipleErrors (P.optionsVerboseErrors opts) errs)
exitFailure
Right ((ms, foreigns), warnings) -> do
when (P.nonEmpty warnings) $
hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings)
let filePathMap = M.fromList $ map (\(fp, P.Module _ _ mn _ _) -> (mn, fp)) ms
makeActions = buildMakeActions outputDir filePathMap foreigns usePrefix
(e, warnings') <- runMake opts $ P.make makeActions (map snd ms)
when (P.nonEmpty warnings') $
hPutStrLn stderr (P.prettyPrintMultipleWarnings (P.optionsVerboseErrors opts) warnings')
case e of
Left errs -> do
hPutStrLn stderr (P.prettyPrintMultipleErrors (P.optionsVerboseErrors opts) errs)
exitFailure
Right _ -> exitSuccess
warnFileTypeNotFound :: String -> IO ()
warnFileTypeNotFound = hPutStrLn stderr . ("psc: No files found using pattern: " ++)
globWarningOnMisses :: (String -> IO ()) -> [FilePath] -> IO [FilePath]
globWarningOnMisses warn = concatMapM globWithWarning
where
globWithWarning pattern = do
paths <- glob pattern
when (null paths) $ warn pattern
return paths
concatMapM f = liftM concat . mapM f
readInput :: InputOptions -> IO [(Either P.RebuildPolicy FilePath, String)]
readInput InputOptions{..} = forM ioInputFiles $ \inFile -> (Right inFile, ) <$> readUTF8File inFile
parseInputs :: (Functor m, Applicative m, MonadError P.MultipleErrors m, MonadWriter P.MultipleErrors m)
=> [(Either P.RebuildPolicy FilePath, String)]
-> [(FilePath, P.ForeignJS)]
-> m ([(Either P.RebuildPolicy FilePath, P.Module)], M.Map P.ModuleName FilePath)
parseInputs modules foreigns =
(,) <$> P.parseModulesFromFiles (either (const "") id) modules
<*> P.parseForeignModulesFromFiles foreigns
inputFile :: Parser FilePath
inputFile = strArgument $
metavar "FILE"
<> help "The input .purs file(s)"
inputForeignFile :: Parser FilePath
inputForeignFile = strOption $
short 'f'
<> long "ffi"
<> help "The input .js file(s) providing foreign import implementations"
outputDirectory :: Parser FilePath
outputDirectory = strOption $
short 'o'
<> long "output"
<> Opts.value "output"
<> showDefault
<> help "The output directory"
requirePath :: Parser (Maybe FilePath)
requirePath = optional $ strOption $
short 'r'
<> long "require-path"
<> help "The path prefix to use for require() calls in the generated JavaScript"
noTco :: Parser Bool
noTco = switch $
long "no-tco"
<> help "Disable tail call optimizations"
noMagicDo :: Parser Bool
noMagicDo = switch $
long "no-magic-do"
<> help "Disable the optimization that overloads the do keyword to generate efficient code specifically for the Eff monad"
noOpts :: Parser Bool
noOpts = switch $
long "no-opts"
<> help "Skip the optimization phase"
comments :: Parser Bool
comments = switch $
short 'c'
<> long "comments"
<> help "Include comments in the generated code"
verboseErrors :: Parser Bool
verboseErrors = switch $
short 'v'
<> long "verbose-errors"
<> help "Display verbose error messages"
noPrefix :: Parser Bool
noPrefix = switch $
short 'p'
<> long "no-prefix"
<> help "Do not include comment header"
options :: Parser P.Options
options = P.Options <$> noTco
<*> noMagicDo
<*> pure Nothing
<*> noOpts
<*> verboseErrors
<*> (not <$> comments)
<*> requirePath
pscMakeOptions :: Parser PSCMakeOptions
pscMakeOptions = PSCMakeOptions <$> many inputFile
<*> many inputForeignFile
<*> outputDirectory
<*> options
<*> (not <$> noPrefix)
main :: IO ()
main = execParser opts >>= compile
where
opts = info (version <*> helper <*> pscMakeOptions) infoModList
infoModList = fullDesc <> headerInfo <> footerInfo
headerInfo = header "psc - Compiles PureScript to Javascript"
footerInfo = footer $ "psc " ++ showVersion Paths.version
version :: Parser (a -> a)
version = abortOption (InfoMsg (showVersion Paths.version)) $ long "version" <> help "Show the version number" <> hidden
|
michaelficarra/purescript
|
psc/Main.hs
|
Haskell
|
mit
| 6,388
|
module Text.Docvim.Visitor.Options (extractOptions) where
import Control.Applicative
import Text.Docvim.AST
import Text.Docvim.Visitor
-- | Extracts a list of nodes (if any exist) from the `@options` section(s) of
-- the source code.
--
-- It is not recommended to have multiple `@options` sections in a project. If
-- multiple such sections (potentially across multiple translation units) exist,
-- there are no guarantees about order; they just get concatenated in the order
-- we see them.
extractOptions :: Alternative f => [Node] -> (f [Node], [Node])
extractOptions = extractBlocks f
where
f x = if x == OptionsAnnotation
then Just endSection
else Nothing
|
wincent/docvim
|
lib/Text/Docvim/Visitor/Options.hs
|
Haskell
|
mit
| 690
|
module Main where
import System.Environment
main :: IO ()
main = do
-- args <- getArgs
-- (arg0:arg1:restArgs) <- getArgs
-- putStrLn $ "sum: " ++ show (read arg0 + read arg1)
name <- getLine
putStrLn $ "Your name is: " ++ name
|
dreame4/scheme-in-haskell
|
hello.hs
|
Haskell
|
mit
| 236
|
module Network.Skype.Protocol.User where
import Data.Typeable (Typeable)
import Network.Skype.Protocol.Types
data UserProperty = UserHandle UserID
| UserFullName UserFullName
| UserBirthday (Maybe UserBirthday)
| UserSex UserSex
| UserLanguage (Maybe (UserLanguageISOCode, UserLanguage))
| UserCountry (Maybe (UserCountryISOCode, UserCountry))
| UserProvince UserProvince
| UserCity UserCity
| UserHomePhone UserPhone
| UserOfficePhone UserPhone
| UserMobilePhone UserPhone
| UserHomepage UserHomepage
| UserAbout UserAbout
| UserHasCallEquipment Bool
| UserIsVideoCapable Bool
| UserIsVoicemailCapable Bool
| UserBuddyStatus UserBuddyStatus
| UserIsAuthorized Bool
| UserIsBlocked Bool
| UserOnlineStatus UserOnlineStatus
| UserLastOnlineTimestamp Timestamp
| UserCanLeaveVoicemail Bool
| UserSpeedDial UserSpeedDial
| UserReceiveAuthRequest UserAuthRequestMessage
| UserMoodText UserMoodText
| UserRichMoodText UserRichMoodText
| UserTimezone UserTimezoneOffset
| UserIsCallForwardingActive Bool
| UserNumberOfAuthedBuddies Int
| UserDisplayName UserDisplayName
deriving (Eq, Show, Typeable)
data UserSex = UserSexUnknown
| UserSexMale
| UserSexFemale
deriving (Eq, Show, Typeable)
data UserStatus = UserStatusUnknown -- ^ no status information for current user.
| UserStatusOnline -- ^ current user is online.
| UserStatusOffline -- ^ current user is offline.
| UserStatusSkypeMe -- ^ current user is in "Skype Me" mode (Protocol 2).
| UserStatusAway -- ^ current user is away.
| UserStatusNotAvailable -- ^ current user is not available.
| UserStatusDoNotDisturb -- ^ current user is in "Do not disturb" mode.
| UserStatusInvisible -- ^ current user is invisible to others.
| UserStatusLoggedOut -- ^ current user is logged out. Clients are detached.
deriving (Eq, Show, Typeable)
data UserBuddyStatus = UserBuddyStatusNeverBeen
| UserBuddyStatusDeleted
| UserBuddyStatusPending
| UserBuddyStatusAdded
deriving (Eq, Show, Typeable)
data UserOnlineStatus = UserOnlineStatusUnknown
| UserOnlineStatusOffline
| UserOnlineStatusOnline
| UserOnlineStatusAway
| UserOnlineStatusNotAvailable
| UserOnlineStatusDoNotDisturb
deriving (Eq, Show, Typeable)
|
emonkak/skype4hs
|
src/Network/Skype/Protocol/User.hs
|
Haskell
|
mit
| 3,059
|
{-# LANGUAGE CPP #-}
module TCDExtra where
import TCD
import Data.Functor ((<$>))
import Data.List
import System.Directory
import System.FilePath
import Text.Printf
-- This is designed to match libtcd's dump_tide_record as closely as possible
formatTideRecord :: TideRecord -> IO String
formatTideRecord r =
unlines . (++ concatMap showConstituent constituents) <$> mapM formatField fields
where
formatField :: (String, TideRecord -> IO String) -> IO String
formatField (n, f) = printf "%s = %s" n <$> f r
fields =
[ ("Record number" , return . show . tshNumber . trHeader)
, ("Record size" , return . show . tshSize . trHeader)
, ("Record type" , return . show . tshType . trHeader)
, ("Latitude" , return . showF . tshLatitude . trHeader)
, ("Longitude" , return . showF . tshLongitude . trHeader)
, ("Reference station" , return . show . tshReferenceStation . trHeader)
, ("Tzfile" , getTZFile . tshTZFile . trHeader)
, ("Name" , return . tshName . trHeader)
, ("Country" , getCountry . trCountry )
, ("Source" , return . trSource )
, ("Restriction" , getRestriction . trRestriction )
, ("Comments" , return . trComments )
, ("Notes" , return . trNotes )
, ("Legalese" , getLegalese . trLegalese )
, ("Station ID context" , return . trStationIdContext )
, ("Station ID" , return . trStationId )
, ("Date imported" , return . show . trDateImported )
, ("Xfields" , return . trXfields )
, ("Direction units" , getDirUnits . trDirectionUnits )
, ("Min direction" , return . show . trMinDirection )
, ("Max direction" , return . show . trMaxDirection )
, ("Level units" , getLevelUnits . trLevelUnits )
, ("Datum offset" , return . showF . trDatumOffset )
, ("Datum" , getDatum . trDatum )
, ("Zone offset" , return . show . trZoneOffset )
, ("Expiration date" , return . show . trExpirationDate )
, ("Months on station" , return . show . trMonthsOnStation )
, ("Last date on station" , return . show . trLastDateOnStation )
, ("Confidence" , return . show . trConfidence )
]
showConstituent :: (Int, Double, Double) -> [String]
showConstituent (i, amp, epoch) =
if amp /= 0.0
then [ printf "Amplitude[%d] = %.6f" i amp
, printf "Epoch[%d] = %.6f" i epoch]
else []
constituents = zip3 [0..] (trAmplitudes r) (trEpochs r)
showF x = printf "%.6f" x :: String
#ifndef DEFAULT_TIDE_DB_PATH
#define DEFAULT_TIDE_DB_PATH "/usr/share/xtide"
#endif
defaultTideDbPath :: String
defaultTideDbPath = DEFAULT_TIDE_DB_PATH
openDefaultTideDb :: IO Bool
openDefaultTideDb = do
filenames <- getDirectoryContents defaultTideDbPath
let tcds = filter (".tcd" `isSuffixOf`) filenames
if null tcds
then return False
else openTideDb $ defaultTideDbPath </> head tcds
|
neilmayhew/Tides
|
TCDExtra.hs
|
Haskell
|
mit
| 3,769
|
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, DoAndIfThenElse #-}
-- | This module provides a way in which the Haskell standard input may be forwarded to the IPython
-- frontend and thus allows the notebook to use the standard input.
--
-- This relies on the implementation of file handles in GHC, and is generally unsafe and terrible.
-- However, it is difficult to find another way to do it, as file handles are generally meant to
-- point to streams and files, and not networked communication protocols.
--
-- In order to use this module, it must first be initialized with two things. First of all, in order
-- to know how to communicate with the IPython frontend, it must know the kernel profile used for
-- communication. For this, use @recordKernelProfile@ once the profile is known. Both this and
-- @recordParentHeader@ take a directory name where they can store this data.
--
--
-- Finally, the module must know what @execute_request@ message is currently being replied to (which
-- will request the input). Thus, every time the language kernel receives an @execute_request@
-- message, it should inform this module via @recordParentHeader@, so that the module may generate
-- messages with an appropriate parent header set. If this is not done, the IPython frontends will
-- not recognize the target of the communication.
--
-- Finally, in order to activate this module, @fixStdin@ must be called once. It must be passed the
-- same directory name as @recordParentHeader@ and @recordKernelProfile@. Note that if this is being
-- used from within the GHC API, @fixStdin@ /must/ be called from within the GHC session not from
-- the host code.
module IHaskell.IPython.Stdin (fixStdin, recordParentHeader, recordKernelProfile) where
import IHaskellPrelude
import Control.Concurrent
import Control.Applicative ((<$>))
import GHC.IO.Handle
import GHC.IO.Handle.Types
import System.FilePath ((</>))
import System.Posix.IO
import System.IO.Unsafe
import IHaskell.IPython.Types
import IHaskell.IPython.ZeroMQ
import IHaskell.IPython.Message.UUID as UUID
stdinInterface :: MVar ZeroMQStdin
{-# NOINLINE stdinInterface #-}
stdinInterface = unsafePerformIO newEmptyMVar
-- | Manipulate standard input so that it is sourced from the IPython frontend. This function is
-- build on layers of deep magical hackery, so be careful modifying it.
fixStdin :: String -> IO ()
fixStdin dir = do
-- Initialize the stdin interface.
let fpath = dir </> ".kernel-profile"
profile <- fromMaybe (error $ "fixStdin: Failed reading " ++ fpath)
. readMay <$> readFile fpath
interface <- serveStdin profile
putMVar stdinInterface interface
void $ forkIO $ stdinOnce dir
stdinOnce :: String -> IO ()
stdinOnce dir = do
-- Create a pipe using and turn it into handles.
(readEnd, writeEnd) <- createPipe
newStdin <- fdToHandle readEnd
stdinInput <- fdToHandle writeEnd
hSetBuffering newStdin NoBuffering
hSetBuffering stdinInput NoBuffering
-- Store old stdin and swap in new stdin.
oldStdin <- hDuplicate stdin
hDuplicateTo newStdin stdin
loop stdinInput oldStdin newStdin
where
loop stdinInput oldStdin newStdin = do
let FileHandle _ mvar = stdin
threadDelay $ 150 * 1000
e <- isEmptyMVar mvar
if not e
then loop stdinInput oldStdin newStdin
else do
line <- getInputLine dir
hPutStr stdinInput $ line ++ "\n"
loop stdinInput oldStdin newStdin
-- | Get a line of input from the IPython frontend.
getInputLine :: String -> IO String
getInputLine dir = do
StdinChannel req rep <- readMVar stdinInterface
-- Send a request for input.
uuid <- UUID.random
let fpath = dir </> ".last-req-header"
parentHdr <- fromMaybe (error $ "getInputLine: Failed reading " ++ fpath)
. readMay <$> readFile fpath
let hdr = MessageHeader (mhIdentifiers parentHdr) (Just parentHdr) mempty
uuid (mhSessionId parentHdr) (mhUsername parentHdr) InputRequestMessage
[]
let msg = RequestInput hdr ""
writeChan req msg
-- Get the reply.
InputReply _ value <- readChan rep
return value
recordParentHeader :: String -> MessageHeader -> IO ()
recordParentHeader dir hdr =
writeFile (dir ++ "/.last-req-header") $ show hdr
recordKernelProfile :: String -> Profile -> IO ()
recordKernelProfile dir profile =
writeFile (dir ++ "/.kernel-profile") $ show profile
|
gibiansky/IHaskell
|
src/IHaskell/IPython/Stdin.hs
|
Haskell
|
mit
| 4,526
|
{-# LANGUAGE UnicodeSyntax #-}
module Data.BEncode.Parser
( string
, value
)
where
import Control.Applicative ((<|>))
import qualified Data.Attoparsec.ByteString.Char8 as AP
(Parser, char, decimal, take)
import qualified Data.Attoparsec.Combinator as AP (manyTill)
import Data.BEncode.Types
import Data.ByteString (ByteString)
import qualified Data.Map as Map (fromList)
--------------------------------------------------------------------------------
string ∷ AP.Parser ByteString
string = AP.decimal <* AP.char ':' >>= AP.take
value ∷ AP.Parser Value
value = Integer <$> (AP.char 'i' *> AP.decimal <* AP.char 'e')
<|> List <$> (AP.char 'l' *> AP.manyTill value (AP.char 'e'))
<|> Dict . Map.fromList
<$> (AP.char 'd' *> AP.manyTill ((,) <$> string <*> value) (AP.char 'e'))
<|> String <$> string
|
drdo/swarm-bencode
|
Data/BEncode/Parser.hs
|
Haskell
|
mit
| 839
|
module Code where
type BlockName = String
type BlockId = Int
type BlockCode = String
|
christiaanb/SoOSiM
|
examples/Twente/Code.hs
|
Haskell
|
mit
| 88
|
{-# LANGUAGE OverloadedStrings #-}
-- You need to `cabal install css`
import Language.CSS hiding (borderRadius, boxShadow, textShadow)
import Data.Text.Lazy (Text,append,intercalate,pack)
import qualified Data.Text.Lazy.IO as LIO
import System (getArgs)
main = do
[path] <- getArgs
LIO.writeFile path style
style = renderCSS $ runCSS $ do
reset
layout
cards
game
players
hand
drawOrNextButton
eineButton
games
message
-- Rules
-- =====
reset = rule "*" $ margin "0" >> padding "0"
layout = do
rule "html, body, .game" $ do
width "100%" >> height "100%"
overflow "hidden"
rule "body" $ do
font "16px Ubuntu, Helvetica, sans-serif"
background "#0d3502 url(\"background.png\")"
color white
cardRule = rule . (".card" `append`)
bigCard = do
width "100px" >> height "150px"
borderWidth "10px"
fontSize "67px" >> lineHeight "150px"
smallCard = do
width "60px" >> height "90px"
borderWidth "6px"
fontSize "40px" >> lineHeight "90px"
cards = do
cardRule "" $ do
borderStyle "solid" >> borderColor white >> borderRadius "10px"
boxShadow "2px 2px 10px #0a2d00"
background white
position "relative"
cursor "pointer"
rule "span" $ do
absolute "0" "0" "0" "0"
textAlign "center"
pointerEvents "none"
zIndex "42"
let colorCard colorStr = borderColor colorStr >> color colorStr
cardRule ".yellow" $ colorCard yellow
cardRule ".green" $ colorCard green
cardRule ".blue" $ colorCard blue
cardRule ".red" $ colorCard red
cardRule ".closed" $ colorCard "#888" >> background black
cardRule ".closed:hover" $ colorCard "#aaa"
rule ".card.special" $ color white
rule ".card.black .color" $ outlineOffset "-5px"
rule ".card.black .color:hover" $ outline "5px solid rgba(0,0,0,0.25)"
rule ".card .red" $ absolute "0%" "50%" "50%" "0%" >> background red
rule ".card .green" $ absolute "0%" "0%" "50%" "50%" >> background green
rule ".card .blue" $ absolute "50%" "50%" "0%" "0%" >> background blue
rule ".card .yellow" $ absolute "50%" "0%" "0%" "50%" >> background yellow
rule ".card.open" $ cursor "default"
game = do
rule ".win-message" $ do
position "absolute" >> top "80px" >> left "0" >> right "0"
fontSize "64px"
textAlign "center"
rule ".open, .closed" $ do
bigCard
position "absolute" >> left "50%" >> top "50%"
marginTop "-85px"
rule ".open" $ marginLeft "-130px"
rule ".closed" $ marginLeft "10px"
players = do
rule ".player" $ do
minWidth "150px"
textAlign "center"
position "absolute"
fontSize "18px" >> lineHeight "30px"
padding "0 10px"
background "#375b2d"
transition "background 0.3s linear"
rule ".number-of-cards" $ do
fontWeight "bold"
color "#ff9"
marginLeft "5px"
rule ".player.winner .number-of-cards" $ color black
rule ".player.current" $ background "#609352"
rule ".player.winner" $ background white >> color black
rule ".player.left, .player.right" $ top "50%"
rule ".player.left" $ left "0" >> transform "rotate(90deg) translate(-15px, 70px)" >> margin "0 0 -70px"
rule ".player.right" $ right "0" >> transform "rotate(-90deg) translate(15px, 70px)" >> margin "0 0 -70px"
rule ".player.top" $ left "50%" >> top "0" >> marginLeft "-85px"
rule ".player.bottom" $ do
bottom "0" >> left "50px" >> right "50px"
padding "15px"
height "100px" >> lineHeight "100px"
textAlign "right"
hand :: CSS Rule
hand = rule ".hand" $ do
listStyle "none"
rule "li" (float "left")
rule "li .card" (smallCard >> margin "0 2px" >> transform "rotate(2deg)" >> transition "all 0.3s ease")
rule "li:nth-child(2n) .card" (transform "rotate(-4deg)")
rule "li:nth-child(3n) .card" (transform "rotate(12deg)")
rule "li .card:hover" (transform "rotate(0) translate(0, -10px)")
rules ["li.fade-out .card", "li.fade-in .card"] $ do
margin "0 -36px"
transform "translate(0, 150px)"
rule ".card:not(.matching)" $ do
transform "translate(0, 50px) !important"
cursor "default"
drawOrNextButton = do
rule ".draw-or-next-button" $ do
fontSize "18px"
margin "0 30px 0 0"
color "inherit"
textDecoration "none"
rule ".draw-or-next-button:hover" $ do
fontWeight "bold"
-- http://css3button.net/5232
eineButton = do
let purple = "#570071"
let lightGrey = "#bbb"
rule ".eine-button" $ do
--position "absolute" >> top "30px" >> right "30px"
color purple >> fontSize "32px" >> textDecoration "none"
padding "20px" >> margin "0 15px"
border ("3px solid " `append` purple) >> borderRadius "10px"
boxShadow "0px 1px 3px rgba(000,000,000,0.5), inset 0px 0px 3px rgba(255,255,255,1)"
verticalGradient white [(0.5,white)] lightGrey
rule ".eine-button:hover" $ do
verticalGradient lightGrey [(0.5,white)] white
rule ".eine-button:active" $ do
verticalGradient "#000" [(0.5,"#333")] "#333"
color white
textShadow "none"
rules [".eine-button:active", ".eine-button:focus"] $ outline "none"
rule ".eine-button.active" $ do
color white
borderColor white
background purple
games = do
rule "#games" $ do
background "#042600"
width "400px" >> minHeight "400px"
margin "64px auto" >> padding "32px"
boxShadow "inset 0 0 16px #020"
lineHeight "32px"
rule "input" $ marginLeft "5px"
rule "h1" $ do
textAlign "center"
fontSize "48px"
margin "0 0 26px"
rule "p" $ margin "2px"
rule "#name" $ do
padding "2px"
rule "ul#open-games" $ do
minHeight "300px"
listStyle "none"
rule "li" $ do
borderTop "1px solid #fff"
padding "2px 8px"
rule "li:hover" $ do
cursor "pointer"
background "rgba(255,255,255,0.25)"
rule "#new-game" $ do
padding "4px"
message = rule ".message" $ do
position "absolute" >> bottom "150px" >> left "0" >> right "0"
textAlign "center"
fontSize "14px"
-- Colors
-- ======
white = "#fff"
black = "#000"
yellow = "#ffa200"
green = "#089720"
blue = "#0747ff"
red = "#d50b00"
-- Helpers
-- =======
absolute t r b l = position "absolute" >> top t >> right r >> bottom b >> left l
vendor name value = do
prop ("-moz-" `append` name) value
prop ("-webkit-" `append` name) value
prop name value
-- Properties
-- ==========
-- CSS3
-- ----
borderRadius = vendor "border-radius"
transform = vendor "transform"
transition = vendor "transition"
boxShadow = vendor "box-shadow"
textShadow = vendor "text-shadow"
pointerEvents = prop "pointer-events"
outlineOffset = prop "outline-offset"
verticalGradient :: Text -> [(Float, Text)] -> Text -> CSS (Either Property Rule)
verticalGradient top stops bottom = do
let (++) = append
let stopToGecko (percentage, color) = color ++ " " ++ (pack $ show (percentage*100)) ++ "%"
let stopsToGecko = intercalate "," . map stopToGecko
background $ "-moz-linear-gradient(top, " ++ top ++ " 0%, " ++ stopsToGecko stops ++ "," ++ bottom ++ ")"
let stopToWebkit (percentage, color) = "color-stop(" ++ (pack $ show percentage) ++ ", " ++ color ++ ")"
let stopsToWebkit = intercalate "," . map stopToWebkit
background $ "-webkit-gradient(linear, left top, left bottom, from(" ++ top ++ "), " ++ stopsToWebkit stops ++ ", to(" ++ bottom ++ "))"
|
timjb/eine
|
public/style.hs
|
Haskell
|
mit
| 7,314
|
{-# LANGUAGE OverloadedStrings #-}
module EDDA.Schema.ShipyardV2Test where
import Test.HUnit
import Data.Maybe (fromJust,isJust)
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString.Char8 as C
import qualified Data.HashSet as HS
import Control.Monad.Trans.Reader
import EDDA.Config
import EDDA.Schema.OutfittingV1 (parseOutfitting)
import EDDA.Schema.Util
import EDDA.Schema.Parser
import EDDA.Types
import EDDA.Test.Util
test1 :: Test
test1 = TestCase $ do conf <- readConf
val <- readJsonTestFile "test/EDDA/Schema/shipyard2.json"
maybeHeader <- runReaderT (parseHeader val) conf
assertBool "header couldn't be parsed" (isJust maybeHeader)
let header = fromJust maybeHeader
assertEqual "uploader id" "Dovacube" (headerUploaderId header)
assertEqual "software name" "E:D Market Connector [Windows]" (headerSoftwareName header)
assertEqual "software version" "2.1.7.0" (headerSoftwareVersion header)
maybeMessage <- runReaderT (parseMessage val) conf
assertBool "message couldn't be parsed" (isJust maybeMessage)
let shipyardInfo = fromJust maybeMessage
assertEqual "system name" "Gateway" (shipyardInfoSystemName shipyardInfo)
assertEqual "station name" "Dublin Citadel" (shipyardInfoStationName shipyardInfo)
assertEqual "ships" 3 (HS.size (shipyardInfoShips shipyardInfo))
shipyardV2Tests = [TestLabel "shipyard2 test" test1]
|
troydm/edda
|
test/EDDA/Schema/ShipyardV2Test.hs
|
Haskell
|
mit
| 1,666
|
-- generate code for combinators
import List (intersperse)
import Char (toUpper)
import IO
type Var = Char
data Expr = EVar Var
| EApp Expr Expr
isVar, isApp :: Expr -> Bool
isVar (EVar _) = True
isVar _ = False
isApp (EApp _ _) = True
isApp _ = False
eVar :: Expr -> Var
eVar (EVar x) = x
instance Show Expr where
showsPrec _ e = se False e
where
se _ (EVar x) = showChar x
se False (EApp f x) = se False f . showChar ' ' . se True x
se True (EApp f x) = showChar '(' . se False f . showChar ' ' . se True x . showChar ')'
type Instr = String
-- projection combinators
combGen :: (String, [Var], Expr) -> Bool -> CodeGen ()
combGen (c, args, expr@(EVar v)) True =
do bindArgs args expr
emitSet (arity - 1) ("a_" ++ show expr)
emitPop (arity - 1)
emit "c.get1().overwriteHole()"
emit "c.eval()"
emit "Node result = c.getTos()"
emit "c.get1().overwriteInd(result)"
emitSet 1 "result"
emitPop 1
emitUnwind
where
arity = length args
combGen (c, args, expr@(EVar v)) False =
do bindArgs args expr
emitPop arity
emit ("c.getTos().overwriteInd(" ++ result ++ ")")
emit ("c.setTos(" ++ result ++ ")")
emitUnwind
where
arity = length args
result = "a_" ++ show expr
-- combinators resulting in an application
combGen (c, args, expr@(EApp f a)) _ =
do bindArgs args expr
emit ("Node redex = " ++ getSpine arity)
f' <- buildNode f
a' <- buildNode a
emit ("redex.overwriteApp(" ++ f' ++ ", " ++ a' ++ ")")
emitSet (arity - 1) f'
emitPop (arity - 1)
emitUnwind
where
arity = length args
buildNode :: Expr -> CodeGen String
buildNode (EVar x) = return ("a_" ++ [x])
buildNode (EApp f a) = do f' <- buildNode f
a' <- buildNode a
r <- newVar "g"
emit ("Node " ++ r ++ " = c.mkApp(" ++ f' ++ ", " ++ a' ++ ")")
return r
bindArgs :: [Var] -> Expr -> CodeGen ()
bindArgs args expr = loop args 1
where loop [] _ = return ()
loop (v:vs) n = do bindArg v n; loop vs (n+1)
bindArg v n | occurs v expr = emit ("Node a_" ++ [v] ++ " = " ++ getArg n)
| otherwise = return ()
-- variable occurs in expression?
occurs :: Var -> Expr -> Bool
occurs v (EVar x) = v == x
occurs v (EApp f a) = occurs v f || occurs v a
combDefns = [
("S", "fgx", EApp (EApp (EVar 'f') (EVar 'x')) (EApp (EVar 'g') (EVar 'x'))),
("K", "cx", EVar 'c'),
("K'", "xc", EVar 'c'),
("I", "x", EVar 'x'),
("J", "fgx", EApp (EVar 'f') (EVar 'g')),
("J'", "kfgx", EApp (EApp (EVar 'k') (EVar 'f')) (EVar 'g')),
("C", "fxy", EApp (EApp (EVar 'f') (EVar 'y')) (EVar 'x')),
("B", "fgx", EApp (EVar 'f') (EApp (EVar 'g') (EVar 'x'))),
("B*", "cfgx", EApp (EVar 'c') (EApp (EVar 'f') (EApp (EVar 'g') (EVar 'x')))),
("B'", "cfgx", EApp (EApp (EVar 'c') (EVar 'f')) (EApp (EVar 'g') (EVar 'x'))),
("C'", "cfgx", EApp (EApp (EVar 'c') (EApp (EVar 'f') (EVar 'x'))) (EVar 'g')),
-- S' c f g x = c (f x) (g x)
("S'", "cfgx", EApp (EApp (EVar 'c') (EApp (EVar 'f') (EVar 'x'))) (EApp (EVar 'g') (EVar 'x'))),
("W", "fx", EApp (EApp (EVar 'f') (EVar 'x')) (EVar 'x'))
]
intOps = [("add", "+"), ("sub", "-"), ("mul", "*"),
("div", "/"), ("rem", "%"),
("Rsub", "-"), ("Rdiv", "/"), ("Rrem", "%")]
relOps = [("less", "PrimLess", "<"),
("greater", "PrimGreater", ">"),
("less_eq", "PrimLessEq", "<="),
("gr_eq", "PrimGreaterEq", ">="),
("eq", "PrimEq", "=="),
("neq", "PrimNeq", "!=")]
main = do mapM_ showDef combDefns
mapM_ (\(name, op) -> genBinOpInt name op (isRevOp name)) intOps
mapM_ (\(name, cname, op) -> genRelOp name cname op) relOps
where
isRevOp ('R':name) = True
isRevOp _ = False
showDef (c,a,e) = do putStr c
putStr " "
putStr (intersperse ' ' a)
putStr " = "
putStrLn (show e)
genCombs (c,a,e)
genCombs :: (String, [Var], Expr) -> IO ()
genCombs s@(c, a, e@(EVar _)) = do genComb s False
genComb s True
genCombs s = genComb s False
putCode :: Handle -> [Instr] -> IO ()
putCode h = mapM_ (\i -> if null i then return () else do hPutStr h " "; hPutStr h i; hPutStrLn h ";")
genComb :: (String, [Var], Expr) -> Bool -> IO ()
genComb (c,a,e) eval =
do h <- openFile fileName WriteMode
hPutStrLn h "package de.bokeh.skred.red;\n"
hPutStrLn h "/**"
hPutStrLn h (" * The " ++ c ++ " combinator.")
hPutStrLn h " * <p>"
hPutStrLn h " * Reduction rule:"
hPutStrLn h (" * " ++ c ++ " " ++ intersperse ' ' a ++ " ==> " ++ show e)
hPutStrLn h " */"
hPutStrLn h ("class " ++ className ++ " extends Function {\n")
hPutStrLn h (" public " ++ className ++ "() {")
hPutStrLn h (" super(\"" ++ c ++ "\", " ++ show arity ++ ");")
hPutStrLn h " }\n"
hPutStrLn h " @Override"
hPutStrLn h " Node exec(RedContext c) {"
let code = runCG (combGen (c,a,e) eval)
putCode h code
hPutStrLn h " }\n"
hPutStrLn h "}"
hClose h
where
arity = length a
className = "Comb" ++ map toJava c ++ if eval then "_Eval" else ""
fileName = className ++ ".java"
toJava :: Char -> Char
toJava '\'' = '1'
toJava '*' = 's'
toJava c = c
initCap :: String -> String
initCap "" = ""
initCap (c:cs) = Char.toUpper c : cs
genBinOpInt :: String -> String -> Bool -> IO ()
genBinOpInt name op rev =
do h <- openFile fileName WriteMode
hPutStrLn h "package de.bokeh.skred.red;\n"
hPutStrLn h "/**"
hPutStrLn h (" * Int " ++ name)
hPutStrLn h " */"
hPutStrLn h ("class " ++ className ++ " extends Function {\n")
hPutStrLn h (" public " ++ className ++ "() {")
hPutStrLn h (" super(\"" ++ name ++ "\", 2);")
hPutStrLn h " }\n\n\
\ @Override\n\
\ Node exec(RedContext c) {\n\
\ c.rearrange2();\n\
\ c.eval();\n\
\ c.swap();\n\
\ c.eval();\n\
\ Node a2 = c.getTos();\n\
\ Node a1 = c.get1();\n\
\ int n1 = a1.intValue();\n\
\ int n2 = a2.intValue();"
hPutStrLn h (if rev then " int r = n2 " ++ op ++ " n1;"
else " int r = n1 " ++ op ++ " n2;")
hPutStrLn h " Node result = Int.valueOf(r);\n\
\ c.pop2();\n\
\ c.getTos().overwriteInd(result);\n\
\ c.setTos(result);\n\
\ return result;\n\
\ }\n\n\
\}"
hClose h
where
className = "Prim" ++ initCap name ++ "Int"
fileName = className ++ ".java"
genRelOp :: String -> String -> String -> IO ()
genRelOp name className op =
do h <- openFile fileName WriteMode
hPutStrLn h "package de.bokeh.skred.red;\n"
hPutStrLn h "/**"
hPutStrLn h (" * Relop " ++ name)
hPutStrLn h " */"
hPutStrLn h ("class " ++ className ++ " extends Function {\n")
hPutStrLn h (" public " ++ className ++ "() {")
hPutStrLn h (" super(\"" ++ name ++ "\", 2);")
hPutStrLn h " }\n\n\
\ @Override\n\
\ Node exec(RedContext c) {\n\
\ c.rearrange2();\n\
\ c.eval();\n\
\ c.swap();\n\
\ c.eval();\n\
\ Node a2 = c.getTos();\n\
\ Node a1 = c.get1();\n\
\ int n1 = a1.intValue();\n\
\ int n2 = a2.intValue();"
hPutStrLn h (" boolean r = n1 " ++ op ++ " n2;")
hPutStrLn h " Node result = Data.valueOf(r?1:0);\n\
\ c.pop2();\n\
\ c.getTos().overwriteInd(result);\n\
\ c.setTos(result);\n\
\ return result;\n\
\ }\n\n\
\}"
hClose h
where
fileName = className ++ ".java"
data CGState = CG Int [Instr]
newtype CodeGen a = CGM (CGState -> (CGState, a))
runCG :: CodeGen a -> [Instr]
runCG (CGM m) = let (CG _ is, _) = m (CG 1 []) in reverse is
instance Monad CodeGen where
return x = CGM (\st -> (st, x))
(CGM m) >>= f = CGM (\s -> let (s',x) = m s; CGM f' = f x in f' s')
emit :: Instr -> CodeGen ()
emit i = CGM (\(CG ns is) -> (CG ns (i:is), ()))
newVar :: String -> CodeGen String
newVar prefix = CGM (\(CG ns is) -> (CG (ns+1) is, prefix ++ show ns))
getCode :: CodeGen [Instr]
getCode = CGM (\st@(CG _ is) -> (st, reverse is))
mAX_SPECIALIZED_OFFSET :: Int
mAX_SPECIALIZED_OFFSET = 3
-- instruction helpers
emitPop :: Int -> CodeGen ()
emitPop 0 = return ()
emitPop n | n <= mAX_SPECIALIZED_OFFSET = emit ("c.pop" ++ shows n "()")
| otherwise = emit ("c.pop(" ++ shows n ")")
emitSet :: Int -> String -> CodeGen ()
emitSet 0 x = emit ("c.setTos(" ++ x ++ ")")
emitSet n x | n <= mAX_SPECIALIZED_OFFSET = emit ("c.set" ++ show n ++ "(" ++ x ++ ")")
| otherwise = emit ("c.set(" ++ show n ++ ", " ++ x ++ ")")
emitUnwind :: CodeGen ()
emitUnwind = emit "return null"
getSpine, getArg :: Int -> String
getSpine 0 = "c.getTos()"
getSpine n | n <= mAX_SPECIALIZED_OFFSET = "c.get" ++ show n ++ "()"
| otherwise = "c.get(" ++ show n ++ ")"
getArg n | n <= mAX_SPECIALIZED_OFFSET = "c.getArg" ++ show n ++ "()"
| otherwise = "c.getArg(" ++ show n ++ ")"
|
bokesan/skred
|
tools/CombGen.hs
|
Haskell
|
mit
| 11,196
|
module Tuura.Fantasi.Main (main) where
import Tuura.Fantasi.Options
import qualified Pangraph.GraphML.Parser as P
import qualified Tuura.Fantasi.VHDL.Writer as VHDL
import Data.ByteString (readFile, writeFile)
import Prelude hiding (readFile, writeFile)
import Data.Maybe (maybe)
main :: IO ()
main = do
-- get arguments
options <- getOptions
let graphMLPath = optGraphML options
graphVHDLPath = optGraphName options
simulationEnvVhdlPath = optSimName options
-- parse graph
pangraph <- ((maybe (error "file or graph is malformed") id) . P.parse) <$> readFile graphMLPath
let graphVHDL = VHDL.writeGraph pangraph
let simEnvVHDL = VHDL.writeEnvironment pangraph
-- output vhdl graph
writeFile graphVHDLPath graphVHDL
-- output vhdl simulation environment
writeFile simulationEnvVhdlPath simEnvVHDL
|
tuura/fantasi
|
src/fantasi/Tuura/Fantasi/Main.hs
|
Haskell
|
mit
| 896
|
{-# LANGUAGE CPP #-}
module Test.Hspec.Core.FailureReport (
FailureReport (..)
, writeFailureReport
, readFailureReport
) where
import Prelude ()
import Test.Hspec.Core.Compat
#ifndef __GHCJS__
import System.SetEnv (setEnv)
import Test.Hspec.Core.Util (safeTry)
#endif
import System.IO
import System.Directory
import Test.Hspec.Core.Util (Path)
import Test.Hspec.Core.Config.Definition (Config(..))
data FailureReport = FailureReport {
failureReportSeed :: Integer
, failureReportMaxSuccess :: Int
, failureReportMaxSize :: Int
, failureReportMaxDiscardRatio :: Int
, failureReportPaths :: [Path]
} deriving (Eq, Show, Read)
writeFailureReport :: Config -> FailureReport -> IO ()
writeFailureReport config report = case configFailureReport config of
Just file -> writeFile file (show report)
Nothing -> do
#ifdef __GHCJS__
-- ghcjs currently does not support setting environment variables
-- (https://github.com/ghcjs/ghcjs/issues/263). Since writing a failure report
-- into the environment is a non-essential feature we just disable this to be
-- able to run hspec test-suites with ghcjs at all. Should be reverted once
-- the issue is fixed.
return ()
#else
-- on Windows this can throw an exception when the input is too large, hence
-- we use `safeTry` here
safeTry (setEnv "HSPEC_FAILURES" $ show report) >>= either onError return
where
onError err = do
hPutStrLn stderr ("WARNING: Could not write environment variable HSPEC_FAILURES (" ++ show err ++ ")")
#endif
readFailureReport :: Config -> IO (Maybe FailureReport)
readFailureReport config = case configFailureReport config of
Just file -> do
exists <- doesFileExist file
if exists
then do
r <- readFile file
let report = readMaybe r
when (report == Nothing) $ do
hPutStrLn stderr ("WARNING: Could not read failure report from file " ++ show file ++ "!")
return report
else return Nothing
Nothing -> do
mx <- lookupEnv "HSPEC_FAILURES"
case mx >>= readMaybe of
Nothing -> do
hPutStrLn stderr "WARNING: Could not read environment variable HSPEC_FAILURES; `--rerun' is ignored!"
return Nothing
report -> return report
|
hspec/hspec
|
hspec-core/src/Test/Hspec/Core/FailureReport.hs
|
Haskell
|
mit
| 2,326
|
-- | Query and update documents
{-# LANGUAGE OverloadedStrings, RecordWildCards, NamedFieldPuns, TupleSections, FlexibleContexts, FlexibleInstances, UndecidableInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, StandaloneDeriving, TypeSynonymInstances, TypeFamilies, CPP, DeriveDataTypeable, ScopedTypeVariables, BangPatterns #-}
module Database.MongoDB.Query (
-- * Monad
Action, access, Failure(..), ErrorCode,
AccessMode(..), GetLastError, master, slaveOk, accessMode,
liftDB,
MongoContext(..), HasMongoContext(..),
-- * Database
Database, allDatabases, useDb, thisDatabase,
-- ** Authentication
Username, Password, auth, authMongoCR, authSCRAMSHA1,
-- * Collection
Collection, allCollections,
-- ** Selection
Selection(..), Selector, whereJS,
Select(select),
-- * Write
-- ** Insert
insert, insert_, insertMany, insertMany_, insertAll, insertAll_,
-- ** Update
save, replace, repsert, upsert, Modifier, modify, updateMany, updateAll,
WriteResult(..), UpdateOption(..), Upserted(..),
-- ** Delete
delete, deleteOne, deleteMany, deleteAll, DeleteOption(..),
-- * Read
-- ** Query
Query(..), QueryOption(NoCursorTimeout, TailableCursor, AwaitData, Partial),
Projector, Limit, Order, BatchSize,
explain, find, findOne, fetch,
findAndModify, findAndModifyOpts, FindAndModifyOpts(..), defFamUpdateOpts,
count, distinct,
-- *** Cursor
Cursor, nextBatch, next, nextN, rest, closeCursor, isCursorClosed,
-- ** Aggregate
Pipeline, AggregateConfig(..), aggregate, aggregateCursor,
-- ** Group
Group(..), GroupKey(..), group,
-- ** MapReduce
MapReduce(..), MapFun, ReduceFun, FinalizeFun, MROut(..), MRMerge(..),
MRResult, mapReduce, runMR, runMR',
-- * Command
Command, runCommand, runCommand1,
eval, retrieveServerData, ServerData(..)
) where
import Prelude hiding (lookup)
import Control.Exception (Exception, throwIO)
import Control.Monad (unless, replicateM, liftM, liftM2)
import Data.Default.Class (Default(..))
import Data.Int (Int32, Int64)
import Data.Either (lefts, rights)
import Data.List (foldl1')
import Data.Maybe (listToMaybe, catMaybes, isNothing)
import Data.Word (Word32)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (mappend)
#endif
import Data.Typeable (Typeable)
import System.Mem.Weak (Weak)
import qualified Control.Concurrent.MVar as MV
#if MIN_VERSION_base(4,6,0)
import Control.Concurrent.MVar.Lifted (MVar,
readMVar)
#else
import Control.Concurrent.MVar.Lifted (MVar, addMVarFinalizer,
readMVar)
#endif
import Control.Applicative ((<$>))
import Control.Exception (catch)
import Control.Monad (when, void)
import Control.Monad.Error (Error(..))
import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask, asks, local)
import Control.Monad.Trans (MonadIO, liftIO)
import Data.Binary.Put (runPut)
import Data.Bson (Document, Field(..), Label, Val, Value(String, Doc, Bool),
Javascript, at, valueAt, lookup, look, genObjectId, (=:),
(=?), (!?), Val(..), ObjectId, Value(..))
import Data.Bson.Binary (putDocument)
import Data.Text (Text)
import qualified Data.Text as T
import Database.MongoDB.Internal.Protocol (Reply(..), QueryOption(..),
ResponseFlag(..), InsertOption(..),
UpdateOption(..), DeleteOption(..),
CursorId, FullCollection, Username,
Password, Pipe, Notice(..),
Request(GetMore, qOptions, qSkip,
qFullCollection, qBatchSize,
qSelector, qProjector),
pwKey, ServerData(..))
import Database.MongoDB.Internal.Util (loop, liftIOE, true1, (<.>))
import qualified Database.MongoDB.Internal.Protocol as P
import qualified Crypto.Nonce as Nonce
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as B
import qualified Data.Either as E
import qualified Crypto.Hash.MD5 as MD5
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Crypto.MAC.HMAC as HMAC
import Data.Bits (xor)
import qualified Data.Map as Map
import Text.Read (readMaybe)
import Data.Maybe (fromMaybe)
-- * Monad
type Action = ReaderT MongoContext
-- ^ A monad on top of m (which must be a MonadIO) that may access the database and may fail with a DB 'Failure'
access :: (MonadIO m) => Pipe -> AccessMode -> Database -> Action m a -> m a
-- ^ Run action against database on server at other end of pipe. Use access mode for any reads and writes.
-- Throw 'Failure' in case of any error.
access mongoPipe mongoAccessMode mongoDatabase action = runReaderT action MongoContext{..}
-- | A connection failure, or a read or write exception like cursor expired or inserting a duplicate key.
-- Note, unexpected data from the server is not a Failure, rather it is a programming error (you should call 'error' in this case) because the client and server are incompatible and requires a programming change.
data Failure =
ConnectionFailure IOError -- ^ TCP connection ('Pipeline') failed. May work if you try again on the same Mongo 'Connection' which will create a new Pipe.
| CursorNotFoundFailure CursorId -- ^ Cursor expired because it wasn't accessed for over 10 minutes, or this cursor came from a different server that the one you are currently connected to (perhaps a fail over happen between servers in a replica set)
| QueryFailure ErrorCode String -- ^ Query failed for some reason as described in the string
| WriteFailure Int ErrorCode String -- ^ Error observed by getLastError after a write, error description is in string, index of failed document is the first argument
| WriteConcernFailure Int String -- ^ Write concern error. It's reported only by insert, update, delete commands. Not by wire protocol.
| DocNotFound Selection -- ^ 'fetch' found no document matching selection
| AggregateFailure String -- ^ 'aggregate' returned an error
| CompoundFailure [Failure] -- ^ When we need to aggregate several failures and report them.
| ProtocolFailure Int String -- ^ The structure of the returned documents doesn't match what we expected
deriving (Show, Eq, Typeable)
instance Exception Failure
type ErrorCode = Int
-- ^ Error code from getLastError or query failure
instance Error Failure where strMsg = error
-- ^ 'fail' is treated the same as a programming 'error'. In other words, don't use it.
-- | Type of reads and writes to perform
data AccessMode =
ReadStaleOk -- ^ Read-only action, reading stale data from a slave is OK.
| UnconfirmedWrites -- ^ Read-write action, slave not OK, every write is fire & forget.
| ConfirmWrites GetLastError -- ^ Read-write action, slave not OK, every write is confirmed with getLastError.
deriving Show
type GetLastError = Document
-- ^ Parameters for getLastError command. For example @[\"w\" =: 2]@ tells the server to wait for the write to reach at least two servers in replica set before acknowledging. See <http://www.mongodb.org/display/DOCS/Last+Error+Commands> for more options.
class Result a where
isFailed :: a -> Bool
data WriteResult = WriteResult
{ failed :: Bool
, nMatched :: Int
, nModified :: Maybe Int
, nRemoved :: Int
-- ^ Mongodb server before 2.6 doesn't allow to calculate this value.
-- This field is meaningless if we can't calculate the number of modified documents.
, upserted :: [Upserted]
, writeErrors :: [Failure]
, writeConcernErrors :: [Failure]
} deriving Show
instance Result WriteResult where
isFailed = failed
instance Result (Either a b) where
isFailed (Left _) = True
isFailed _ = False
data Upserted = Upserted
{ upsertedIndex :: Int
, upsertedId :: ObjectId
} deriving Show
master :: AccessMode
-- ^ Same as 'ConfirmWrites' []
master = ConfirmWrites []
slaveOk :: AccessMode
-- ^ Same as 'ReadStaleOk'
slaveOk = ReadStaleOk
accessMode :: (Monad m) => AccessMode -> Action m a -> Action m a
-- ^ Run action with given 'AccessMode'
accessMode mode act = local (\ctx -> ctx {mongoAccessMode = mode}) act
readMode :: AccessMode -> ReadMode
readMode ReadStaleOk = StaleOk
readMode _ = Fresh
writeMode :: AccessMode -> WriteMode
writeMode ReadStaleOk = Confirm []
writeMode UnconfirmedWrites = NoConfirm
writeMode (ConfirmWrites z) = Confirm z
-- | Values needed when executing a db operation
data MongoContext = MongoContext {
mongoPipe :: Pipe, -- ^ operations read/write to this pipelined TCP connection to a MongoDB server
mongoAccessMode :: AccessMode, -- ^ read/write operation will use this access mode
mongoDatabase :: Database } -- ^ operations query/update this database
mongoReadMode :: MongoContext -> ReadMode
mongoReadMode = readMode . mongoAccessMode
mongoWriteMode :: MongoContext -> WriteMode
mongoWriteMode = writeMode . mongoAccessMode
class HasMongoContext env where
mongoContext :: env -> MongoContext
instance HasMongoContext MongoContext where
mongoContext = id
liftDB :: (MonadReader env m, HasMongoContext env, MonadIO m)
=> Action IO a
-> m a
liftDB m = do
env <- ask
liftIO $ runReaderT m (mongoContext env)
-- * Database
type Database = Text
allDatabases :: (MonadIO m) => Action m [Database]
-- ^ List all databases residing on server
allDatabases = (map (at "name") . at "databases") `liftM` useDb "admin" (runCommand1 "listDatabases")
thisDatabase :: (Monad m) => Action m Database
-- ^ Current database in use
thisDatabase = asks mongoDatabase
useDb :: (Monad m) => Database -> Action m a -> Action m a
-- ^ Run action against given database
useDb db act = local (\ctx -> ctx {mongoDatabase = db}) act
-- * Authentication
auth :: MonadIO m => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new pipe. SCRAM-SHA-1 will be used for server versions 3.0+, MONGO-CR for lower versions.
auth un pw = do
let serverVersion = liftM (at "version") $ useDb "admin" $ runCommand ["buildinfo" =: (1 :: Int)]
mmv <- liftM (readMaybe . T.unpack . head . T.splitOn ".") $ serverVersion
maybe (return False) performAuth mmv
where
performAuth majorVersion =
case (majorVersion >= (3 :: Int)) of
True -> authSCRAMSHA1 un pw
False -> authMongoCR un pw
authMongoCR :: (MonadIO m) => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database, using the MongoDB-CR authentication mechanism (default in MongoDB server < 3.0)
authMongoCR usr pss = do
n <- at "nonce" `liftM` runCommand ["getnonce" =: (1 :: Int)]
true1 "ok" `liftM` runCommand ["authenticate" =: (1 :: Int), "user" =: usr, "nonce" =: n, "key" =: pwKey n usr pss]
authSCRAMSHA1 :: MonadIO m => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database, using the SCRAM-SHA-1 authentication mechanism (default in MongoDB server >= 3.0)
authSCRAMSHA1 un pw = do
let hmac = HMAC.hmac SHA1.hash 64
nonce <- liftIO (Nonce.withGenerator Nonce.nonce128 >>= return . B64.encode)
let firstBare = B.concat [B.pack $ "n=" ++ (T.unpack un) ++ ",r=", nonce]
let client1 = ["saslStart" =: (1 :: Int), "mechanism" =: ("SCRAM-SHA-1" :: String), "payload" =: (B.unpack . B64.encode $ B.concat [B.pack "n,,", firstBare]), "autoAuthorize" =: (1 :: Int)]
server1 <- runCommand client1
shortcircuit (true1 "ok" server1) $ do
let serverPayload1 = B64.decodeLenient . B.pack . at "payload" $ server1
let serverData1 = parseSCRAM serverPayload1
let iterations = read . B.unpack $ Map.findWithDefault "1" "i" serverData1
let salt = B64.decodeLenient $ Map.findWithDefault "" "s" serverData1
let snonce = Map.findWithDefault "" "r" serverData1
shortcircuit (B.isInfixOf nonce snonce) $ do
let withoutProof = B.concat [B.pack "c=biws,r=", snonce]
let digestS = B.pack $ T.unpack un ++ ":mongo:" ++ T.unpack pw
let digest = B16.encode $ MD5.hash digestS
let saltedPass = scramHI digest salt iterations
let clientKey = hmac saltedPass (B.pack "Client Key")
let storedKey = SHA1.hash clientKey
let authMsg = B.concat [firstBare, B.pack ",", serverPayload1, B.pack ",", withoutProof]
let clientSig = hmac storedKey authMsg
let pval = B64.encode . BS.pack $ BS.zipWith xor clientKey clientSig
let clientFinal = B.concat [withoutProof, B.pack ",p=", pval]
let serverKey = hmac saltedPass (B.pack "Server Key")
let serverSig = B64.encode $ hmac serverKey authMsg
let client2 = ["saslContinue" =: (1 :: Int), "conversationId" =: (at "conversationId" server1 :: Int), "payload" =: (B.unpack $ B64.encode clientFinal)]
server2 <- runCommand client2
shortcircuit (true1 "ok" server2) $ do
let serverPayload2 = B64.decodeLenient . B.pack $ at "payload" server2
let serverData2 = parseSCRAM serverPayload2
let serverSigComp = Map.findWithDefault "" "v" serverData2
shortcircuit (serverSig == serverSigComp) $ do
let done = true1 "done" server2
if done
then return True
else do
let client2Step2 = [ "saslContinue" =: (1 :: Int)
, "conversationId" =: (at "conversationId" server1 :: Int)
, "payload" =: String ""]
server3 <- runCommand client2Step2
shortcircuit (true1 "ok" server3) $ do
return True
where
shortcircuit True f = f
shortcircuit False _ = return False
scramHI :: B.ByteString -> B.ByteString -> Int -> B.ByteString
scramHI digest salt iters = snd $ foldl com (u1, u1) [1..(iters-1)]
where
hmacd = HMAC.hmac SHA1.hash 64 digest
u1 = hmacd (B.concat [salt, BS.pack [0, 0, 0, 1]])
com (u,uc) _ = let u' = hmacd u in (u', BS.pack $ BS.zipWith xor uc u')
parseSCRAM :: B.ByteString -> Map.Map B.ByteString B.ByteString
parseSCRAM = Map.fromList . fmap cleanup . (fmap $ T.breakOn "=") . T.splitOn "," . T.pack . B.unpack
where cleanup (t1, t2) = (B.pack $ T.unpack t1, B.pack . T.unpack $ T.drop 1 t2)
retrieveServerData :: (MonadIO m) => Action m ServerData
retrieveServerData = do
d <- runCommand1 "isMaster"
let newSd = ServerData
{ isMaster = (fromMaybe False $ lookup "ismaster" d)
, minWireVersion = (fromMaybe 0 $ lookup "minWireVersion" d)
, maxWireVersion = (fromMaybe 0 $ lookup "maxWireVersion" d)
, maxMessageSizeBytes = (fromMaybe 48000000 $ lookup "maxMessageSizeBytes" d)
, maxBsonObjectSize = (fromMaybe (16 * 1024 * 1024) $ lookup "maxBsonObjectSize" d)
, maxWriteBatchSize = (fromMaybe 1000 $ lookup "maxWriteBatchSize" d)
}
return newSd
-- * Collection
type Collection = Text
-- ^ Collection name (not prefixed with database)
allCollections :: MonadIO m => Action m [Collection]
-- ^ List all collections in this database
allCollections = do
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd <= 2)
then do
db <- thisDatabase
docs <- rest =<< find (query [] "system.namespaces") {sort = ["name" =: (1 :: Int)]}
return . filter (not . isSpecial db) . map dropDbPrefix $ map (at "name") docs
else do
r <- runCommand1 "listCollections"
let curData = do
(Doc curDoc) <- r !? "cursor"
(curId :: Int64) <- curDoc !? "id"
(curNs :: Text) <- curDoc !? "ns"
(firstBatch :: [Value]) <- curDoc !? "firstBatch"
return $ (curId, curNs, ((catMaybes (map cast' firstBatch)) :: [Document]))
case curData of
Nothing -> return []
Just (curId, curNs, firstBatch) -> do
db <- thisDatabase
nc <- newCursor db curNs 0 $ return $ Batch Nothing curId firstBatch
docs <- rest nc
return $ catMaybes $ map (\d -> (d !? "name")) docs
where
dropDbPrefix = T.tail . T.dropWhile (/= '.')
isSpecial db col = T.any (== '$') col && db <.> col /= "local.oplog.$main"
-- * Selection
data Selection = Select {selector :: Selector, coll :: Collection} deriving (Show, Eq)
-- ^ Selects documents in collection that match selector
type Selector = Document
-- ^ Filter for a query, analogous to the where clause in SQL. @[]@ matches all documents in collection. @[\"x\" =: a, \"y\" =: b]@ is analogous to @where x = a and y = b@ in SQL. See <http://www.mongodb.org/display/DOCS/Querying> for full selector syntax.
whereJS :: Selector -> Javascript -> Selector
-- ^ Add Javascript predicate to selector, in which case a document must match both selector and predicate
whereJS sel js = ("$where" =: js) : sel
class Select aQueryOrSelection where
select :: Selector -> Collection -> aQueryOrSelection
-- ^ 'Query' or 'Selection' that selects documents in collection that match selector. The choice of type depends on use, for example, in @'find' (select sel col)@ it is a Query, and in @'delete' (select sel col)@ it is a Selection.
instance Select Selection where
select = Select
instance Select Query where
select = query
-- * Write
data WriteMode =
NoConfirm -- ^ Submit writes without receiving acknowledgments. Fast. Assumes writes succeed even though they may not.
| Confirm GetLastError -- ^ Receive an acknowledgment after every write, and raise exception if one says the write failed. This is acomplished by sending the getLastError command, with given 'GetLastError' parameters, after every write.
deriving (Show, Eq)
write :: Notice -> Action IO (Maybe Document)
-- ^ Send write to server, and if write-mode is 'Safe' then include getLastError request and raise 'WriteFailure' if it reports an error.
write notice = asks mongoWriteMode >>= \mode -> case mode of
NoConfirm -> do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [notice]
return Nothing
Confirm params -> do
let q = query (("getlasterror" =: (1 :: Int)) : params) "$cmd"
pipe <- asks mongoPipe
Batch _ _ [doc] <- do
r <- queryRequest False q {limit = 1}
rr <- liftIO $ request pipe [notice] r
fulfill rr
return $ Just doc
-- ** Insert
insert :: (MonadIO m) => Collection -> Document -> Action m Value
-- ^ Insert document into collection and return its \"_id\" value, which is created automatically if not supplied
insert col doc = do
doc' <- liftIO $ assignId doc
res <- insertBlock [] col (0, [doc'])
case res of
Left failure -> liftIO $ throwIO failure
Right r -> return $ head r
insert_ :: (MonadIO m) => Collection -> Document -> Action m ()
-- ^ Same as 'insert' except don't return _id
insert_ col doc = insert col doc >> return ()
insertMany :: (MonadIO m) => Collection -> [Document] -> Action m [Value]
-- ^ Insert documents into collection and return their \"_id\" values,
-- which are created automatically if not supplied.
-- If a document fails to be inserted (eg. due to duplicate key)
-- then remaining docs are aborted, and LastError is set.
-- An exception will be throw if any error occurs.
insertMany = insert' []
insertMany_ :: (MonadIO m) => Collection -> [Document] -> Action m ()
-- ^ Same as 'insertMany' except don't return _ids
insertMany_ col docs = insertMany col docs >> return ()
insertAll :: (MonadIO m) => Collection -> [Document] -> Action m [Value]
-- ^ Insert documents into collection and return their \"_id\" values,
-- which are created automatically if not supplied. If a document fails
-- to be inserted (eg. due to duplicate key) then remaining docs
-- are still inserted.
insertAll = insert' [KeepGoing]
insertAll_ :: (MonadIO m) => Collection -> [Document] -> Action m ()
-- ^ Same as 'insertAll' except don't return _ids
insertAll_ col docs = insertAll col docs >> return ()
insertCommandDocument :: [InsertOption] -> Collection -> [Document] -> Document -> Document
insertCommandDocument opts col docs writeConcern =
[ "insert" =: col
, "ordered" =: (KeepGoing `notElem` opts)
, "documents" =: docs
, "writeConcern" =: writeConcern
]
takeRightsUpToLeft :: [Either a b] -> [b]
takeRightsUpToLeft l = E.rights $ takeWhile E.isRight l
insert' :: (MonadIO m)
=> [InsertOption] -> Collection -> [Document] -> Action m [Value]
-- ^ Insert documents into collection and return their \"_id\" values, which are created automatically if not supplied
insert' opts col docs = do
p <- asks mongoPipe
let sd = P.serverData p
docs' <- liftIO $ mapM assignId docs
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
let docSize = sizeOfDocument $ insertCommandDocument opts col [] writeConcern
let ordered = (not (KeepGoing `elem` opts))
let preChunks = splitAtLimit
(maxBsonObjectSize sd - docSize)
-- size of auxiliary part of insert
-- document should be subtracted from
-- the overall size
(maxWriteBatchSize sd)
docs'
let chunks =
if ordered
then takeRightsUpToLeft preChunks
else rights preChunks
let lens = map length chunks
let lSums = 0 : (zipWith (+) lSums lens)
chunkResults <- interruptibleFor ordered (zip lSums chunks) $ insertBlock opts col
let lchunks = lefts preChunks
when (not $ null lchunks) $ do
liftIO $ throwIO $ head lchunks
let lresults = lefts chunkResults
when (not $ null lresults) $ liftIO $ throwIO $ head lresults
return $ concat $ rights chunkResults
insertBlock :: (MonadIO m)
=> [InsertOption] -> Collection -> (Int, [Document]) -> Action m (Either Failure [Value])
-- ^ This will fail if the list of documents is bigger than restrictions
insertBlock _ _ (_, []) = return $ Right []
insertBlock opts col (prevCount, docs) = do
db <- thisDatabase
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd < 2)
then do
res <- liftDB $ write (Insert (db <.> col) opts docs)
let errorMessage = do
jRes <- res
em <- lookup "err" jRes
return $ WriteFailure prevCount (maybe 0 id $ lookup "code" jRes) em
-- In older versions of ^^ the protocol we can't really say which document failed.
-- So we just report the accumulated number of documents in the previous blocks.
case errorMessage of
Just failure -> return $ Left failure
Nothing -> return $ Right $ map (valueAt "_id") docs
else do
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
doc <- runCommand $ insertCommandDocument opts col docs writeConcern
case (look "writeErrors" doc, look "writeConcernError" doc) of
(Nothing, Nothing) -> return $ Right $ map (valueAt "_id") docs
(Just (Array errs), Nothing) -> do
let writeErrors = map (anyToWriteError prevCount) $ errs
let errorsWithFailureIndex = map (addFailureIndex prevCount) writeErrors
return $ Left $ CompoundFailure errorsWithFailureIndex
(Nothing, Just err) -> do
return $ Left $ WriteFailure
prevCount
(maybe 0 id $ lookup "ok" doc)
(show err)
(Just (Array errs), Just writeConcernErr) -> do
let writeErrors = map (anyToWriteError prevCount) $ errs
let errorsWithFailureIndex = map (addFailureIndex prevCount) writeErrors
return $ Left $ CompoundFailure $ (WriteFailure
prevCount
(maybe 0 id $ lookup "ok" doc)
(show writeConcernErr)) : errorsWithFailureIndex
(Just unknownValue, Nothing) -> do
return $ Left $ ProtocolFailure prevCount $ "Expected array of errors. Received: " ++ show unknownValue
(Just unknownValue, Just writeConcernErr) -> do
return $ Left $ CompoundFailure $ [ ProtocolFailure prevCount $ "Expected array of errors. Received: " ++ show unknownValue
, WriteFailure prevCount (maybe 0 id $ lookup "ok" doc) $ show writeConcernErr]
splitAtLimit :: Int -> Int -> [Document] -> [Either Failure [Document]]
splitAtLimit maxSize maxCount list = chop (go 0 0 []) list
where
go :: Int -> Int -> [Document] -> [Document] -> ((Either Failure [Document]), [Document])
go _ _ res [] = (Right $ reverse res, [])
go curSize curCount [] (x:xs) |
((curSize + (sizeOfDocument x) + 2 + curCount) > maxSize) =
(Left $ WriteFailure 0 0 "One document is too big for the message", xs)
go curSize curCount res (x:xs) =
if ( ((curSize + (sizeOfDocument x) + 2 + curCount) > maxSize)
-- we have ^ 2 brackets and curCount commas in
-- the document that we need to take into
-- account
|| ((curCount + 1) > maxCount))
then
(Right $ reverse res, x:xs)
else
go (curSize + (sizeOfDocument x)) (curCount + 1) (x:res) xs
chop :: ([a] -> (b, [a])) -> [a] -> [b]
chop _ [] = []
chop f as = let (b, as') = f as in b : chop f as'
sizeOfDocument :: Document -> Int
sizeOfDocument d = fromIntegral $ LBS.length $ runPut $ putDocument d
assignId :: Document -> IO Document
-- ^ Assign a unique value to _id field if missing
assignId doc = if any (("_id" ==) . label) doc
then return doc
else (\oid -> ("_id" =: oid) : doc) `liftM` genObjectId
-- ** Update
save :: (MonadIO m)
=> Collection -> Document -> Action m ()
-- ^ Save document to collection, meaning insert it if its new (has no \"_id\" field) or upsert it if its not new (has \"_id\" field)
save col doc = case look "_id" doc of
Nothing -> insert_ col doc
Just i -> upsert (Select ["_id" := i] col) doc
replace :: (MonadIO m)
=> Selection -> Document -> Action m ()
-- ^ Replace first document in selection with given document
replace = update []
repsert :: (MonadIO m)
=> Selection -> Document -> Action m ()
-- ^ Replace first document in selection with given document, or insert document if selection is empty
repsert = update [Upsert]
{-# DEPRECATED repsert "use upsert instead" #-}
upsert :: (MonadIO m)
=> Selection -> Document -> Action m ()
-- ^ Update first document in selection with given document, or insert document if selection is empty
upsert = update [Upsert]
type Modifier = Document
-- ^ Update operations on fields in a document. See <http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations>
modify :: (MonadIO m)
=> Selection -> Modifier -> Action m ()
-- ^ Update all documents in selection using given modifier
modify = update [MultiUpdate]
update :: (MonadIO m)
=> [UpdateOption] -> Selection -> Document -> Action m ()
-- ^ Update first document in selection using updater document, unless 'MultiUpdate' option is supplied then update all documents in selection. If 'Upsert' option is supplied then treat updater as document and insert it if selection is empty.
update opts (Select sel col) up = do
db <- thisDatabase
ctx <- ask
liftIO $ runReaderT (void $ write (Update (db <.> col) opts sel up)) ctx
updateCommandDocument :: Collection -> Bool -> [Document] -> Document -> Document
updateCommandDocument col ordered updates writeConcern =
[ "update" =: col
, "ordered" =: ordered
, "updates" =: updates
, "writeConcern" =: writeConcern
]
{-| Bulk update operation. If one update fails it will not update the remaining
- documents. Current returned value is only a place holder. With mongodb server
- before 2.6 it will send update requests one by one. In order to receive
- error messages in versions under 2.6 you need to user confirmed writes.
- Otherwise even if the errors had place the list of errors will be empty and
- the result will be success. After 2.6 it will use bulk update feature in
- mongodb.
-}
updateMany :: (MonadIO m)
=> Collection
-> [(Selector, Document, [UpdateOption])]
-> Action m WriteResult
updateMany = update' True
{-| Bulk update operation. If one update fails it will proceed with the
- remaining documents. With mongodb server before 2.6 it will send update
- requests one by one. In order to receive error messages in versions under
- 2.6 you need to use confirmed writes. Otherwise even if the errors had
- place the list of errors will be empty and the result will be success.
- After 2.6 it will use bulk update feature in mongodb.
-}
updateAll :: (MonadIO m)
=> Collection
-> [(Selector, Document, [UpdateOption])]
-> Action m WriteResult
updateAll = update' False
update' :: (MonadIO m)
=> Bool
-> Collection
-> [(Selector, Document, [UpdateOption])]
-> Action m WriteResult
update' ordered col updateDocs = do
p <- asks mongoPipe
let sd = P.serverData p
let updates = map (\(s, d, os) -> [ "q" =: s
, "u" =: d
, "upsert" =: (Upsert `elem` os)
, "multi" =: (MultiUpdate `elem` os)])
updateDocs
mode <- asks mongoWriteMode
ctx <- ask
liftIO $ do
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
let docSize = sizeOfDocument $ updateCommandDocument
col
ordered
[]
writeConcern
let preChunks = splitAtLimit
(maxBsonObjectSize sd - docSize)
-- size of auxiliary part of update
-- document should be subtracted from
-- the overall size
(maxWriteBatchSize sd)
updates
let chunks =
if ordered
then takeRightsUpToLeft preChunks
else rights preChunks
let lens = map length chunks
let lSums = 0 : (zipWith (+) lSums lens)
blocks <- interruptibleFor ordered (zip lSums chunks) $ \b -> do
ur <- runReaderT (updateBlock ordered col b) ctx
return ur
`catch` \(e :: Failure) -> do
return $ WriteResult True 0 Nothing 0 [] [e] []
let failedTotal = or $ map failed blocks
let updatedTotal = sum $ map nMatched blocks
let modifiedTotal =
if all isNothing $ map nModified blocks
then Nothing
else Just $ sum $ catMaybes $ map nModified blocks
let totalWriteErrors = concat $ map writeErrors blocks
let totalWriteConcernErrors = concat $ map writeConcernErrors blocks
let upsertedTotal = concat $ map upserted blocks
return $ WriteResult
failedTotal
updatedTotal
modifiedTotal
0 -- nRemoved
upsertedTotal
totalWriteErrors
totalWriteConcernErrors
`catch` \(e :: Failure) -> return $ WriteResult True 0 Nothing 0 [] [e] []
updateBlock :: (MonadIO m)
=> Bool -> Collection -> (Int, [Document]) -> Action m WriteResult
updateBlock ordered col (prevCount, docs) = do
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd < 2)
then liftIO $ ioError $ userError "updateMany doesn't support mongodb older than 2.6"
else do
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
doc <- runCommand $ updateCommandDocument col ordered docs writeConcern
let n = fromMaybe 0 $ doc !? "n"
let writeErrorsResults =
case look "writeErrors" doc of
Nothing -> WriteResult False 0 (Just 0) 0 [] [] []
Just (Array err) -> WriteResult True 0 (Just 0) 0 [] (map (anyToWriteError prevCount) err) []
Just unknownErr -> WriteResult
True
0
(Just 0)
0
[]
[ ProtocolFailure
prevCount
$ "Expected array of error docs, but received: "
++ (show unknownErr)]
[]
let writeConcernResults =
case look "writeConcernError" doc of
Nothing -> WriteResult False 0 (Just 0) 0 [] [] []
Just (Doc err) -> WriteResult
True
0
(Just 0)
0
[]
[]
[ WriteConcernFailure
(fromMaybe (-1) $ err !? "code")
(fromMaybe "" $ err !? "errmsg")
]
Just unknownErr -> WriteResult
True
0
(Just 0)
0
[]
[]
[ ProtocolFailure
prevCount
$ "Expected doc in writeConcernError, but received: "
++ (show unknownErr)]
let upsertedList = map docToUpserted $ fromMaybe [] (doc !? "upserted")
let successResults = WriteResult False n (doc !? "nModified") 0 upsertedList [] []
return $ foldl1' mergeWriteResults [writeErrorsResults, writeConcernResults, successResults]
interruptibleFor :: (Monad m, Result b) => Bool -> [a] -> (a -> m b) -> m [b]
interruptibleFor ordered = go []
where
go !res [] _ = return $ reverse res
go !res (x:xs) f = do
y <- f x
if isFailed y && ordered
then return $ reverse (y:res)
else go (y:res) xs f
mergeWriteResults :: WriteResult -> WriteResult -> WriteResult
mergeWriteResults
(WriteResult failed1 nMatched1 nModified1 nDeleted1 upserted1 writeErrors1 writeConcernErrors1)
(WriteResult failed2 nMatched2 nModified2 nDeleted2 upserted2 writeErrors2 writeConcernErrors2) =
(WriteResult
(failed1 || failed2)
(nMatched1 + nMatched2)
((liftM2 (+)) nModified1 nModified2)
(nDeleted1 + nDeleted2)
-- This function is used in foldl1' function. The first argument is the accumulator.
-- The list in the accumulator is usually longer than the subsequent value which goes in the second argument.
-- So, changing the order of list concatenation allows us to keep linear complexity of the
-- whole list accumulation process.
(upserted2 ++ upserted1)
(writeErrors2 ++ writeErrors1)
(writeConcernErrors2 ++ writeConcernErrors1)
)
docToUpserted :: Document -> Upserted
docToUpserted doc = Upserted ind uid
where
ind = at "index" doc
uid = at "_id" doc
docToWriteError :: Document -> Failure
docToWriteError doc = WriteFailure ind code msg
where
ind = at "index" doc
code = at "code" doc
msg = at "errmsg" doc
-- ** Delete
delete :: (MonadIO m)
=> Selection -> Action m ()
-- ^ Delete all documents in selection
delete = deleteHelper []
deleteOne :: (MonadIO m)
=> Selection -> Action m ()
-- ^ Delete first document in selection
deleteOne = deleteHelper [SingleRemove]
deleteHelper :: (MonadIO m)
=> [DeleteOption] -> Selection -> Action m ()
deleteHelper opts (Select sel col) = do
db <- thisDatabase
ctx <- ask
liftIO $ runReaderT (void $ write (Delete (db <.> col) opts sel)) ctx
{-| Bulk delete operation. If one delete fails it will not delete the remaining
- documents. Current returned value is only a place holder. With mongodb server
- before 2.6 it will send delete requests one by one. After 2.6 it will use
- bulk delete feature in mongodb.
-}
deleteMany :: (MonadIO m)
=> Collection
-> [(Selector, [DeleteOption])]
-> Action m WriteResult
deleteMany = delete' True
{-| Bulk delete operation. If one delete fails it will proceed with the
- remaining documents. Current returned value is only a place holder. With
- mongodb server before 2.6 it will send delete requests one by one. After 2.6
- it will use bulk delete feature in mongodb.
-}
deleteAll :: (MonadIO m)
=> Collection
-> [(Selector, [DeleteOption])]
-> Action m WriteResult
deleteAll = delete' False
deleteCommandDocument :: Collection -> Bool -> [Document] -> Document -> Document
deleteCommandDocument col ordered deletes writeConcern =
[ "delete" =: col
, "ordered" =: ordered
, "deletes" =: deletes
, "writeConcern" =: writeConcern
]
delete' :: (MonadIO m)
=> Bool
-> Collection
-> [(Selector, [DeleteOption])]
-> Action m WriteResult
delete' ordered col deleteDocs = do
p <- asks mongoPipe
let sd = P.serverData p
let deletes = map (\(s, os) -> [ "q" =: s
, "limit" =: if SingleRemove `elem` os
then (1 :: Int) -- Remove only one matching
else (0 :: Int) -- Remove all matching
])
deleteDocs
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
let docSize = sizeOfDocument $ deleteCommandDocument col ordered [] writeConcern
let preChunks = splitAtLimit
(maxBsonObjectSize sd - docSize)
-- size of auxiliary part of delete
-- document should be subtracted from
-- the overall size
(maxWriteBatchSize sd)
deletes
let chunks =
if ordered
then takeRightsUpToLeft preChunks
else rights preChunks
ctx <- ask
let lens = map length chunks
let lSums = 0 : (zipWith (+) lSums lens)
blockResult <- liftIO $ interruptibleFor ordered (zip lSums chunks) $ \b -> do
dr <- runReaderT (deleteBlock ordered col b) ctx
return dr
`catch` \(e :: Failure) -> do
return $ WriteResult True 0 Nothing 0 [] [e] []
return $ foldl1' mergeWriteResults blockResult
addFailureIndex :: Int -> Failure -> Failure
addFailureIndex i (WriteFailure ind code s) = WriteFailure (ind + i) code s
addFailureIndex _ f = f
deleteBlock :: (MonadIO m)
=> Bool -> Collection -> (Int, [Document]) -> Action m WriteResult
deleteBlock ordered col (prevCount, docs) = do
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd < 2)
then liftIO $ ioError $ userError "deleteMany doesn't support mongodb older than 2.6"
else do
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
doc <- runCommand $ deleteCommandDocument col ordered docs writeConcern
let n = fromMaybe 0 $ doc !? "n"
let successResults = WriteResult False 0 Nothing n [] [] []
let writeErrorsResults =
case look "writeErrors" doc of
Nothing -> WriteResult False 0 Nothing 0 [] [] []
Just (Array err) -> WriteResult True 0 Nothing 0 [] (map (anyToWriteError prevCount) err) []
Just unknownErr -> WriteResult
True
0
Nothing
0
[]
[ ProtocolFailure
prevCount
$ "Expected array of error docs, but received: "
++ (show unknownErr)]
[]
let writeConcernResults =
case look "writeConcernError" doc of
Nothing -> WriteResult False 0 Nothing 0 [] [] []
Just (Doc err) -> WriteResult
True
0
Nothing
0
[]
[]
[ WriteConcernFailure
(fromMaybe (-1) $ err !? "code")
(fromMaybe "" $ err !? "errmsg")
]
Just unknownErr -> WriteResult
True
0
Nothing
0
[]
[]
[ ProtocolFailure
prevCount
$ "Expected doc in writeConcernError, but received: "
++ (show unknownErr)]
return $ foldl1' mergeWriteResults [successResults, writeErrorsResults, writeConcernResults]
anyToWriteError :: Int -> Value -> Failure
anyToWriteError _ (Doc d) = docToWriteError d
anyToWriteError ind _ = ProtocolFailure ind "Unknown bson value"
-- * Read
data ReadMode =
Fresh -- ^ read from master only
| StaleOk -- ^ read from slave ok
deriving (Show, Eq)
readModeOption :: ReadMode -> [QueryOption]
readModeOption Fresh = []
readModeOption StaleOk = [SlaveOK]
-- ** Query
-- | Use 'select' to create a basic query with defaults, then modify if desired. For example, @(select sel col) {limit = 10}@
data Query = Query {
options :: [QueryOption], -- ^ Default = []
selection :: Selection,
project :: Projector, -- ^ \[\] = all fields. Default = []
skip :: Word32, -- ^ Number of initial matching documents to skip. Default = 0
limit :: Limit, -- ^ Maximum number of documents to return, 0 = no limit. Default = 0
sort :: Order, -- ^ Sort results by this order, [] = no sort. Default = []
snapshot :: Bool, -- ^ If true assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (even if the object were updated). If an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode. Note that short query responses (less than 1MB) are always effectively snapshotted. Default = False
batchSize :: BatchSize, -- ^ The number of document to return in each batch response from the server. 0 means use Mongo default. Default = 0
hint :: Order -- ^ Force MongoDB to use this index, [] = no hint. Default = []
} deriving (Show, Eq)
type Projector = Document
-- ^ Fields to return, analogous to the select clause in SQL. @[]@ means return whole document (analogous to * in SQL). @[\"x\" =: 1, \"y\" =: 1]@ means return only @x@ and @y@ fields of each document. @[\"x\" =: 0]@ means return all fields except @x@.
type Limit = Word32
-- ^ Maximum number of documents to return, i.e. cursor will close after iterating over this number of documents. 0 means no limit.
type Order = Document
-- ^ Fields to sort by. Each one is associated with 1 or -1. Eg. @[\"x\" =: 1, \"y\" =: -1]@ means sort by @x@ ascending then @y@ descending
type BatchSize = Word32
-- ^ The number of document to return in each batch response from the server. 0 means use Mongo default.
query :: Selector -> Collection -> Query
-- ^ Selects documents in collection that match selector. It uses no query options, projects all fields, does not skip any documents, does not limit result size, uses default batch size, does not sort, does not hint, and does not snapshot.
query sel col = Query [] (Select sel col) [] 0 0 [] False 0 []
find :: MonadIO m => Query -> Action m Cursor
-- ^ Fetch documents satisfying query
find q@Query{selection, batchSize} = do
db <- thisDatabase
pipe <- asks mongoPipe
qr <- queryRequest False q
dBatch <- liftIO $ request pipe [] qr
newCursor db (coll selection) batchSize dBatch
findOne :: (MonadIO m) => Query -> Action m (Maybe Document)
-- ^ Fetch first document satisfying query or Nothing if none satisfy it
findOne q = do
pipe <- asks mongoPipe
qr <- queryRequest False q {limit = 1}
rq <- liftIO $ request pipe [] qr
Batch _ _ docs <- liftDB $ fulfill rq
return (listToMaybe docs)
fetch :: (MonadIO m) => Query -> Action m Document
-- ^ Same as 'findOne' except throw 'DocNotFound' if none match
fetch q = findOne q >>= maybe (liftIO $ throwIO $ DocNotFound $ selection q) return
data FindAndModifyOpts = FamRemove Bool
| FamUpdate
{ famUpdate :: Document
, famNew :: Bool
, famUpsert :: Bool
}
deriving Show
defFamUpdateOpts :: Document -> FindAndModifyOpts
defFamUpdateOpts ups = FamUpdate
{ famNew = True
, famUpsert = False
, famUpdate = ups
}
-- | runs the findAndModify command as an update without an upsert and new set to true.
-- Returns a single updated document (new option is set to true).
--
-- see 'findAndModifyOpts' if you want to use findAndModify in a differnt way
findAndModify :: MonadIO m
=> Query
-> Document -- ^ updates
-> Action m (Either String Document)
findAndModify q ups = do
eres <- findAndModifyOpts q (defFamUpdateOpts ups)
return $ case eres of
Left l -> Left l
Right r -> case r of
-- only possible when upsert is True and new is False
Nothing -> Left "findAndModify: impossible null result"
Just doc -> Right doc
-- | runs the findAndModify command,
-- allows more options than 'findAndModify'
findAndModifyOpts :: MonadIO m
=> Query
->FindAndModifyOpts
-> Action m (Either String (Maybe Document))
findAndModifyOpts (Query {
selection = Select sel collection
, project = project
, sort = sort
}) famOpts = do
result <- runCommand
([ "findAndModify" := String collection
, "query" := Doc sel
, "fields" := Doc project
, "sort" := Doc sort
] ++
case famOpts of
FamRemove shouldRemove -> [ "remove" := Bool shouldRemove ]
FamUpdate {..} ->
[ "update" := Doc famUpdate
, "new" := Bool famNew -- return updated document, not original document
, "upsert" := Bool famUpsert -- insert if nothing is found
])
return $ case lookupErr result of
Just e -> leftErr e
Nothing -> case lookup "value" result of
Left err -> leftErr $ "no document found: " `mappend` err
Right mdoc -> case mdoc of
Just doc@(_:_) -> Right (Just doc)
Just [] -> case famOpts of
FamUpdate { famUpsert = True, famNew = False } -> Right Nothing
_ -> leftErr $ show result
_ -> leftErr $ show result
where
leftErr err = Left $ "findAndModify " `mappend` show collection
`mappend` "\nfrom query: " `mappend` show sel
`mappend` "\nerror: " `mappend` err
-- return Nothing means ok, Just is the error message
lookupErr result = case lookup "lastErrorObject" result of
Right errObject -> lookup "err" errObject
Left err -> Just err
explain :: (MonadIO m) => Query -> Action m Document
-- ^ Return performance stats of query execution
explain q = do -- same as findOne but with explain set to true
pipe <- asks mongoPipe
qr <- queryRequest True q {limit = 1}
r <- liftIO $ request pipe [] qr
Batch _ _ docs <- liftDB $ fulfill r
return $ if null docs then error ("no explain: " ++ show q) else head docs
count :: (MonadIO m) => Query -> Action m Int
-- ^ Fetch number of documents satisfying query (including effect of skip and/or limit if present)
count Query{selection = Select sel col, skip, limit} = at "n" `liftM` runCommand
(["count" =: col, "query" =: sel, "skip" =: (fromIntegral skip :: Int32)]
++ ("limit" =? if limit == 0 then Nothing else Just (fromIntegral limit :: Int32)))
distinct :: (MonadIO m) => Label -> Selection -> Action m [Value]
-- ^ Fetch distinct values of field in selected documents
distinct k (Select sel col) = at "values" `liftM` runCommand ["distinct" =: col, "key" =: k, "query" =: sel]
queryRequest :: (Monad m) => Bool -> Query -> Action m (Request, Maybe Limit)
-- ^ Translate Query to Protocol.Query. If first arg is true then add special $explain attribute.
queryRequest isExplain Query{..} = do
ctx <- ask
return $ queryRequest' (mongoReadMode ctx) (mongoDatabase ctx)
where
queryRequest' rm db = (P.Query{..}, remainingLimit) where
qOptions = readModeOption rm ++ options
qFullCollection = db <.> coll selection
qSkip = fromIntegral skip
(qBatchSize, remainingLimit) = batchSizeRemainingLimit batchSize (if limit == 0 then Nothing else Just limit)
qProjector = project
mOrder = if null sort then Nothing else Just ("$orderby" =: sort)
mSnapshot = if snapshot then Just ("$snapshot" =: True) else Nothing
mHint = if null hint then Nothing else Just ("$hint" =: hint)
mExplain = if isExplain then Just ("$explain" =: True) else Nothing
special = catMaybes [mOrder, mSnapshot, mHint, mExplain]
qSelector = if null special then s else ("$query" =: s) : special where s = selector selection
batchSizeRemainingLimit :: BatchSize -> (Maybe Limit) -> (Int32, Maybe Limit)
-- ^ Given batchSize and limit return P.qBatchSize and remaining limit
batchSizeRemainingLimit batchSize mLimit =
let remaining =
case mLimit of
Nothing -> batchSize
Just limit ->
if 0 < batchSize && batchSize < limit
then batchSize
else limit
in (fromIntegral remaining, mLimit)
type DelayedBatch = IO Batch
-- ^ A promised batch which may fail
data Batch = Batch (Maybe Limit) CursorId [Document]
-- ^ CursorId = 0 means cursor is finished. Documents is remaining documents to serve in current batch. Limit is number of documents to return. Nothing means no limit.
request :: Pipe -> [Notice] -> (Request, Maybe Limit) -> IO DelayedBatch
-- ^ Send notices and request and return promised batch
request pipe ns (req, remainingLimit) = do
promise <- liftIOE ConnectionFailure $ P.call pipe ns req
let protectedPromise = liftIOE ConnectionFailure promise
return $ fromReply remainingLimit =<< protectedPromise
fromReply :: Maybe Limit -> Reply -> DelayedBatch
-- ^ Convert Reply to Batch or Failure
fromReply limit Reply{..} = do
mapM_ checkResponseFlag rResponseFlags
return (Batch limit rCursorId rDocuments)
where
-- If response flag indicates failure then throw it, otherwise do nothing
checkResponseFlag flag = case flag of
AwaitCapable -> return ()
CursorNotFound -> throwIO $ CursorNotFoundFailure rCursorId
QueryError -> throwIO $ QueryFailure (at "code" $ head rDocuments) (at "$err" $ head rDocuments)
fulfill :: DelayedBatch -> Action IO Batch
-- ^ Demand and wait for result, raise failure if exception
fulfill = liftIO
-- *** Cursor
data Cursor = Cursor FullCollection BatchSize (MVar DelayedBatch)
-- ^ Iterator over results of a query. Use 'next' to iterate or 'rest' to get all results. A cursor is closed when it is explicitly closed, all results have been read from it, garbage collected, or not used for over 10 minutes (unless 'NoCursorTimeout' option was specified in 'Query'). Reading from a closed cursor raises a 'CursorNotFoundFailure'. Note, a cursor is not closed when the pipe is closed, so you can open another pipe to the same server and continue using the cursor.
newCursor :: MonadIO m => Database -> Collection -> BatchSize -> DelayedBatch -> Action m Cursor
-- ^ Create new cursor. If you don't read all results then close it. Cursor will be closed automatically when all results are read from it or when eventually garbage collected.
newCursor db col batchSize dBatch = do
var <- liftIO $ MV.newMVar dBatch
let cursor = Cursor (db <.> col) batchSize var
_ <- liftDB $ mkWeakMVar var (closeCursor cursor)
return cursor
nextBatch :: MonadIO m => Cursor -> Action m [Document]
-- ^ Return next batch of documents in query result, which will be empty if finished.
nextBatch (Cursor fcol batchSize var) = liftDB $ modifyMVar var $ \dBatch -> do
-- Pre-fetch next batch promise from server and return current batch.
Batch mLimit cid docs <- liftDB $ fulfill' fcol batchSize dBatch
let newLimit = do
limit <- mLimit
return $ limit - (min limit $ fromIntegral $ length docs)
let emptyBatch = return $ Batch (Just 0) 0 []
let getNextBatch = nextBatch' fcol batchSize newLimit cid
let resultDocs = (maybe id (take . fromIntegral) mLimit) docs
case (cid, newLimit) of
(0, _) -> return (emptyBatch, resultDocs)
(_, Just 0) -> do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [KillCursors [cid]]
return (emptyBatch, resultDocs)
(_, _) -> (, resultDocs) <$> getNextBatch
fulfill' :: FullCollection -> BatchSize -> DelayedBatch -> Action IO Batch
-- Discard pre-fetched batch if empty with nonzero cid.
fulfill' fcol batchSize dBatch = do
b@(Batch limit cid docs) <- fulfill dBatch
if cid /= 0 && null docs && (limit > (Just 0))
then nextBatch' fcol batchSize limit cid >>= fulfill
else return b
nextBatch' :: (MonadIO m) => FullCollection -> BatchSize -> (Maybe Limit) -> CursorId -> Action m DelayedBatch
nextBatch' fcol batchSize limit cid = do
pipe <- asks mongoPipe
liftIO $ request pipe [] (GetMore fcol batchSize' cid, remLimit)
where (batchSize', remLimit) = batchSizeRemainingLimit batchSize limit
next :: MonadIO m => Cursor -> Action m (Maybe Document)
-- ^ Return next document in query result, or Nothing if finished.
next (Cursor fcol batchSize var) = liftDB $ modifyMVar var nextState where
-- Pre-fetch next batch promise from server when last one in current batch is returned.
-- nextState:: DelayedBatch -> Action m (DelayedBatch, Maybe Document)
nextState dBatch = do
Batch mLimit cid docs <- liftDB $ fulfill' fcol batchSize dBatch
if mLimit == (Just 0)
then return (return $ Batch (Just 0) 0 [], Nothing)
else
case docs of
doc : docs' -> do
let newLimit = do
limit <- mLimit
return $ limit - 1
dBatch' <- if null docs' && cid /= 0 && ((newLimit > (Just 0)) || (isNothing newLimit))
then nextBatch' fcol batchSize newLimit cid
else return $ return (Batch newLimit cid docs')
when (newLimit == (Just 0)) $ unless (cid == 0) $ do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [KillCursors [cid]]
return (dBatch', Just doc)
[] -> if cid == 0
then return (return $ Batch (Just 0) 0 [], Nothing) -- finished
else do
nb <- nextBatch' fcol batchSize mLimit cid
return (nb, Nothing)
nextN :: MonadIO m => Int -> Cursor -> Action m [Document]
-- ^ Return next N documents or less if end is reached
nextN n c = catMaybes `liftM` replicateM n (next c)
rest :: MonadIO m => Cursor -> Action m [Document]
-- ^ Return remaining documents in query result
rest c = loop (next c)
closeCursor :: MonadIO m => Cursor -> Action m ()
closeCursor (Cursor _ _ var) = liftDB $ modifyMVar var $ \dBatch -> do
Batch _ cid _ <- fulfill dBatch
unless (cid == 0) $ do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [KillCursors [cid]]
return $ (return $ Batch (Just 0) 0 [], ())
isCursorClosed :: MonadIO m => Cursor -> Action m Bool
isCursorClosed (Cursor _ _ var) = do
Batch _ cid docs <- liftDB $ fulfill =<< readMVar var
return (cid == 0 && null docs)
-- ** Aggregate
type Pipeline = [Document]
-- ^ The Aggregate Pipeline
aggregate :: MonadIO m => Collection -> Pipeline -> Action m [Document]
-- ^ Runs an aggregate and unpacks the result. See <http://docs.mongodb.org/manual/core/aggregation/> for details.
aggregate aColl agg = do
aggregateCursor aColl agg def >>= rest
data AggregateConfig = AggregateConfig {}
deriving Show
instance Default AggregateConfig where
def = AggregateConfig {}
aggregateCursor :: MonadIO m => Collection -> Pipeline -> AggregateConfig -> Action m Cursor
-- ^ Runs an aggregate and unpacks the result. See <http://docs.mongodb.org/manual/core/aggregation/> for details.
aggregateCursor aColl agg _ = do
response <- runCommand ["aggregate" =: aColl, "pipeline" =: agg, "cursor" =: ([] :: Document)]
case true1 "ok" response of
True -> do
cursor :: Document <- lookup "cursor" response
firstBatch :: [Document] <- lookup "firstBatch" cursor
cursorId :: Int64 <- lookup "id" cursor
db <- thisDatabase
newCursor db aColl 0 $ return $ Batch Nothing cursorId firstBatch
False -> liftIO $ throwIO $ AggregateFailure $ at "errmsg" response
-- ** Group
-- | Groups documents in collection by key then reduces (aggregates) each group
data Group = Group {
gColl :: Collection,
gKey :: GroupKey, -- ^ Fields to group by
gReduce :: Javascript, -- ^ @(doc, agg) -> ()@. The reduce function reduces (aggregates) the objects iterated. Typical operations of a reduce function include summing and counting. It takes two arguments, the current document being iterated over and the aggregation value, and updates the aggregate value.
gInitial :: Document, -- ^ @agg@. Initial aggregation value supplied to reduce
gCond :: Selector, -- ^ Condition that must be true for a row to be considered. [] means always true.
gFinalize :: Maybe Javascript -- ^ @agg -> () | result@. An optional function to be run on each item in the result set just before the item is returned. Can either modify the item (e.g., add an average field given a count and a total) or return a replacement object (returning a new object with just _id and average fields).
} deriving (Show, Eq)
data GroupKey = Key [Label] | KeyF Javascript deriving (Show, Eq)
-- ^ Fields to group by, or function (@doc -> key@) returning a "key object" to be used as the grouping key. Use KeyF instead of Key to specify a key that is not an existing member of the object (or, to access embedded members).
groupDocument :: Group -> Document
-- ^ Translate Group data into expected document form
groupDocument Group{..} =
("finalize" =? gFinalize) ++ [
"ns" =: gColl,
case gKey of Key k -> "key" =: map (=: True) k; KeyF f -> "$keyf" =: f,
"$reduce" =: gReduce,
"initial" =: gInitial,
"cond" =: gCond ]
group :: (MonadIO m) => Group -> Action m [Document]
-- ^ Execute group query and return resulting aggregate value for each distinct key
group g = at "retval" `liftM` runCommand ["group" =: groupDocument g]
-- ** MapReduce
-- | Maps every document in collection to a list of (key, value) pairs, then for each unique key reduces all its associated values to a single result. There are additional parameters that may be set to tweak this basic operation.
-- This implements the latest version of map-reduce that requires MongoDB 1.7.4 or greater. To map-reduce against an older server use runCommand directly as described in http://www.mongodb.org/display/DOCS/MapReduce.
data MapReduce = MapReduce {
rColl :: Collection,
rMap :: MapFun,
rReduce :: ReduceFun,
rSelect :: Selector, -- ^ Operate on only those documents selected. Default is [] meaning all documents.
rSort :: Order, -- ^ Default is [] meaning no sort
rLimit :: Limit, -- ^ Default is 0 meaning no limit
rOut :: MROut, -- ^ Output to a collection with a certain merge policy. Default is no collection ('Inline'). Note, you don't want this default if your result set is large.
rFinalize :: Maybe FinalizeFun, -- ^ Function to apply to all the results when finished. Default is Nothing.
rScope :: Document, -- ^ Variables (environment) that can be accessed from map/reduce/finalize. Default is [].
rVerbose :: Bool -- ^ Provide statistics on job execution time. Default is False.
} deriving (Show, Eq)
type MapFun = Javascript
-- ^ @() -> void@. The map function references the variable @this@ to inspect the current object under consideration. The function must call @emit(key,value)@ at least once, but may be invoked any number of times, as may be appropriate.
type ReduceFun = Javascript
-- ^ @(key, [value]) -> value@. The reduce function receives a key and an array of values and returns an aggregate result value. The MapReduce engine may invoke reduce functions iteratively; thus, these functions must be idempotent. That is, the following must hold for your reduce function: @reduce(k, [reduce(k,vs)]) == reduce(k,vs)@. If you need to perform an operation only once, use a finalize function. The output of emit (the 2nd param) and reduce should be the same format to make iterative reduce possible.
type FinalizeFun = Javascript
-- ^ @(key, value) -> final_value@. A finalize function may be run after reduction. Such a function is optional and is not necessary for many map/reduce cases. The finalize function takes a key and a value, and returns a finalized value.
data MROut =
Inline -- ^ Return results directly instead of writing them to an output collection. Results must fit within 16MB limit of a single document
| Output MRMerge Collection (Maybe Database) -- ^ Write results to given collection, in other database if specified. Follow merge policy when entry already exists
deriving (Show, Eq)
data MRMerge =
Replace -- ^ Clear all old data and replace it with new data
| Merge -- ^ Leave old data but overwrite entries with the same key with new data
| Reduce -- ^ Leave old data but combine entries with the same key via MR's reduce function
deriving (Show, Eq)
type MRResult = Document
-- ^ Result of running a MapReduce has some stats besides the output. See http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Resultobject
mrDocument :: MapReduce -> Document
-- ^ Translate MapReduce data into expected document form
mrDocument MapReduce{..} =
("mapreduce" =: rColl) :
("out" =: mrOutDoc rOut) :
("finalize" =? rFinalize) ++ [
"map" =: rMap,
"reduce" =: rReduce,
"query" =: rSelect,
"sort" =: rSort,
"limit" =: (fromIntegral rLimit :: Int),
"scope" =: rScope,
"verbose" =: rVerbose ]
mrOutDoc :: MROut -> Document
-- ^ Translate MROut into expected document form
mrOutDoc Inline = ["inline" =: (1 :: Int)]
mrOutDoc (Output mrMerge coll mDB) = (mergeName mrMerge =: coll) : mdb mDB where
mergeName Replace = "replace"
mergeName Merge = "merge"
mergeName Reduce = "reduce"
mdb Nothing = []
mdb (Just db) = ["db" =: db]
mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce
-- ^ MapReduce on collection with given map and reduce functions. Remaining attributes are set to their defaults, which are stated in their comments.
mapReduce col map' red = MapReduce col map' red [] [] 0 Inline Nothing [] False
runMR :: MonadIO m => MapReduce -> Action m Cursor
-- ^ Run MapReduce and return cursor of results. Error if map/reduce fails (because of bad Javascript)
runMR mr = do
res <- runMR' mr
case look "result" res of
Just (String coll) -> find $ query [] coll
Just (Doc doc) -> useDb (at "db" doc) $ find $ query [] (at "collection" doc)
Just x -> error $ "unexpected map-reduce result field: " ++ show x
Nothing -> newCursor "" "" 0 $ return $ Batch (Just 0) 0 (at "results" res)
runMR' :: (MonadIO m) => MapReduce -> Action m MRResult
-- ^ Run MapReduce and return a MR result document containing stats and the results if Inlined. Error if the map/reduce failed (because of bad Javascript).
runMR' mr = do
doc <- runCommand (mrDocument mr)
return $ if true1 "ok" doc then doc else error $ "mapReduce error:\n" ++ show doc ++ "\nin:\n" ++ show mr
-- * Command
type Command = Document
-- ^ A command is a special query or action against the database. See <http://www.mongodb.org/display/DOCS/Commands> for details.
runCommand :: (MonadIO m) => Command -> Action m Document
-- ^ Run command against the database and return its result
runCommand c = maybe err id `liftM` findOne (query c "$cmd") where
err = error $ "Nothing returned for command: " ++ show c
runCommand1 :: (MonadIO m) => Text -> Action m Document
-- ^ @runCommand1 foo = runCommand [foo =: 1]@
runCommand1 c = runCommand [c =: (1 :: Int)]
eval :: (MonadIO m, Val v) => Javascript -> Action m v
-- ^ Run code on server
eval code = at "retval" `liftM` runCommand ["$eval" =: code]
modifyMVar :: MVar a -> (a -> Action IO (a, b)) -> Action IO b
modifyMVar v f = do
ctx <- ask
liftIO $ MV.modifyMVar v (\x -> runReaderT (f x) ctx)
mkWeakMVar :: MVar a -> Action IO () -> Action IO (Weak (MVar a))
mkWeakMVar m closing = do
ctx <- ask
#if MIN_VERSION_base(4,6,0)
liftIO $ MV.mkWeakMVar m $ runReaderT closing ctx
#else
liftIO $ MV.addMVarFinalizer m $ runReaderT closing ctx
#endif
{- Authors: Tony Hannan <tony@10gen.com>
Copyright 2011 10gen Inc.
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. -}
|
Yuras/mongodb
|
Database/MongoDB/Query.hs
|
Haskell
|
apache-2.0
| 69,101
|
{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types,
RecordWildCards, UnboxedTuples, UnliftedFFITypes #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- |
-- Module : Data.Text.Array
-- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Portability : portable
--
-- Packed, unboxed, heap-resident arrays. Suitable for performance
-- critical use, both in terms of large data quantities and high
-- speed.
--
-- This module is intended to be imported @qualified@, to avoid name
-- clashes with "Prelude" functions, e.g.
--
-- > import qualified Data.Text.Array as A
--
-- The names in this module resemble those in the 'Data.Array' family
-- of modules, but are shorter due to the assumption of qualified
-- naming.
module Data.Text.Array
(
-- * Types
Array(Array, aBA)
, MArray(MArray, maBA)
-- * Functions
, copyM
, copyI
, empty
, equal
#if defined(ASSERTS)
, length
#endif
, run
, run2
, toList
, unsafeFreeze
, unsafeIndex
, new
, unsafeWrite
) where
#if defined(ASSERTS)
-- This fugly hack is brought by GHC's apparent reluctance to deal
-- with MagicHash and UnboxedTuples when inferring types. Eek!
# define CHECK_BOUNDS(_func_,_len_,_k_) \
if (_k_) < 0 || (_k_) >= (_len_) then error ("Data.Text.Array." ++ (_func_) ++ ": bounds error, offset " ++ show (_k_) ++ ", length " ++ show (_len_)) else
#else
# define CHECK_BOUNDS(_func_,_len_,_k_)
#endif
#include "MachDeps.h"
#if defined(ASSERTS)
import Control.Exception (assert)
#endif
#if MIN_VERSION_base(4,4,0)
import Control.Monad.ST.Unsafe (unsafeIOToST)
#else
import Control.Monad.ST (unsafeIOToST)
#endif
import Data.Bits ((.&.), xor)
import Data.Text.Internal.Unsafe (inlinePerformIO)
import Data.Text.Internal.Unsafe.Shift (shiftL, shiftR)
#if MIN_VERSION_base(4,5,0)
import Foreign.C.Types (CInt(CInt), CSize(CSize))
#else
import Foreign.C.Types (CInt, CSize)
#endif
import GHC.Base (ByteArray#, MutableByteArray#, Int(..),
indexWord16Array#, newByteArray#,
unsafeFreezeByteArray#, writeWord16Array#)
import GHC.ST (ST(..), runST)
import GHC.Word (Word16(..))
import Prelude hiding (length, read)
-- | Immutable array type.
--
-- The 'Array' constructor is exposed since @text-1.1.1.3@
data Array = Array {
aBA :: ByteArray#
#if defined(ASSERTS)
, aLen :: {-# UNPACK #-} !Int -- length (in units of Word16, not bytes)
#endif
}
-- | Mutable array type, for use in the ST monad.
--
-- The 'MArray' constructor is exposed since @text-1.1.1.3@
data MArray s = MArray {
maBA :: MutableByteArray# s
#if defined(ASSERTS)
, maLen :: {-# UNPACK #-} !Int -- length (in units of Word16, not bytes)
#endif
}
#if defined(ASSERTS)
-- | Operations supported by all arrays.
class IArray a where
-- | Return the length of an array.
length :: a -> Int
instance IArray Array where
length = aLen
{-# INLINE length #-}
instance IArray (MArray s) where
length = maLen
{-# INLINE length #-}
#endif
-- | Create an uninitialized mutable array.
new :: forall s. Int -> ST s (MArray s)
new n
| n < 0 || n .&. highBit /= 0 = array_size_error
| otherwise = ST $ \s1# ->
case newByteArray# len# s1# of
(# s2#, marr# #) -> (# s2#, MArray marr#
#if defined(ASSERTS)
n
#endif
#)
where !(I# len#) = bytesInArray n
highBit = maxBound `xor` (maxBound `shiftR` 1)
{-# INLINE new #-}
array_size_error :: a
array_size_error = error "Data.Text.Array.new: size overflow"
-- | Freeze a mutable array. Do not mutate the 'MArray' afterwards!
unsafeFreeze :: MArray s -> ST s Array
unsafeFreeze MArray{..} = ST $ \s1# ->
case unsafeFreezeByteArray# maBA s1# of
(# s2#, ba# #) -> (# s2#, Array ba#
#if defined(ASSERTS)
maLen
#endif
#)
{-# INLINE unsafeFreeze #-}
-- | Indicate how many bytes would be used for an array of the given
-- size.
bytesInArray :: Int -> Int
bytesInArray n = n `shiftL` 1
{-# INLINE bytesInArray #-}
-- | Unchecked read of an immutable array. May return garbage or
-- crash on an out-of-bounds access.
unsafeIndex :: Array -> Int -> Word16
unsafeIndex Array{..} i@(I# i#) =
CHECK_BOUNDS("unsafeIndex",aLen,i)
case indexWord16Array# aBA i# of r# -> (W16# r#)
{-# INLINE unsafeIndex #-}
-- | Unchecked write of a mutable array. May return garbage or crash
-- on an out-of-bounds access.
unsafeWrite :: MArray s -> Int -> Word16 -> ST s ()
unsafeWrite MArray{..} i@(I# i#) (W16# e#) = ST $ \s1# ->
CHECK_BOUNDS("unsafeWrite",maLen,i)
case writeWord16Array# maBA i# e# s1# of
s2# -> (# s2#, () #)
{-# INLINE unsafeWrite #-}
-- | Convert an immutable array to a list.
toList :: Array -> Int -> Int -> [Word16]
toList ary off len = loop 0
where loop i | i < len = unsafeIndex ary (off+i) : loop (i+1)
| otherwise = []
-- | An empty immutable array.
empty :: Array
empty = runST (new 0 >>= unsafeFreeze)
-- | Run an action in the ST monad and return an immutable array of
-- its result.
run :: (forall s. ST s (MArray s)) -> Array
run k = runST (k >>= unsafeFreeze)
-- | Run an action in the ST monad and return an immutable array of
-- its result paired with whatever else the action returns.
run2 :: (forall s. ST s (MArray s, a)) -> (Array, a)
run2 k = runST (do
(marr,b) <- k
arr <- unsafeFreeze marr
return (arr,b))
{-# INLINE run2 #-}
-- | Copy some elements of a mutable array.
copyM :: MArray s -- ^ Destination
-> Int -- ^ Destination offset
-> MArray s -- ^ Source
-> Int -- ^ Source offset
-> Int -- ^ Count
-> ST s ()
copyM dest didx src sidx count
| count <= 0 = return ()
| otherwise =
#if defined(ASSERTS)
assert (sidx + count <= length src) .
assert (didx + count <= length dest) .
#endif
unsafeIOToST $ memcpyM (maBA dest) (fromIntegral didx)
(maBA src) (fromIntegral sidx)
(fromIntegral count)
{-# INLINE copyM #-}
-- | Copy some elements of an immutable array.
copyI :: MArray s -- ^ Destination
-> Int -- ^ Destination offset
-> Array -- ^ Source
-> Int -- ^ Source offset
-> Int -- ^ First offset in destination /not/ to
-- copy (i.e. /not/ length)
-> ST s ()
copyI dest i0 src j0 top
| i0 >= top = return ()
| otherwise = unsafeIOToST $
memcpyI (maBA dest) (fromIntegral i0)
(aBA src) (fromIntegral j0)
(fromIntegral (top-i0))
{-# INLINE copyI #-}
-- | Compare portions of two arrays for equality. No bounds checking
-- is performed.
equal :: Array -- ^ First
-> Int -- ^ Offset into first
-> Array -- ^ Second
-> Int -- ^ Offset into second
-> Int -- ^ Count
-> Bool
equal arrA offA arrB offB count = inlinePerformIO $ do
i <- memcmp (aBA arrA) (fromIntegral offA)
(aBA arrB) (fromIntegral offB) (fromIntegral count)
return $! i == 0
{-# INLINE equal #-}
foreign import ccall unsafe "_hs_text_memcpy" memcpyI
:: MutableByteArray# s -> CSize -> ByteArray# -> CSize -> CSize -> IO ()
foreign import ccall unsafe "_hs_text_memcmp" memcmp
:: ByteArray# -> CSize -> ByteArray# -> CSize -> CSize -> IO CInt
foreign import ccall unsafe "_hs_text_memcpy" memcpyM
:: MutableByteArray# s -> CSize -> MutableByteArray# s -> CSize -> CSize
-> IO ()
|
bgamari/text
|
src/Data/Text/Array.hs
|
Haskell
|
bsd-2-clause
| 7,903
|
module Compiler.CodeGeneration.CompilationState where
import Control.Monad.State
import Data.Set as Set
import Data.Ix
import Compiler.CodeGeneration.InstructionSet
import Compiler.CodeGeneration.SymbolResolution
import Compiler.CodeGeneration.LabelResolution
import Compiler.CodeGeneration.LabelTable
import Compiler.SymbolTable
data CompilationBlock = CompilationBlock {
symbolTable :: SymbolTable,
labelTable :: LabelTable,
instructions :: [Instruction],
stackPointer :: Int
}
data CompilationState = CompilationState {
usedRegisters :: Set Int,
instCounter :: Int, -- ^Current program address
blocks :: [CompilationBlock]
}
newBlock = do top <- topBlock
return $ top { instructions = [] }
initBlock = CompilationBlock {
symbolTable = initSymbolTable,
labelTable = initLabelTable,
instructions = [],
stackPointer = -3
}
type Compiler a = State CompilationState a
-- |Compiles something within a compilation environment,
-- |returning the resulting instructions
withCompiler x = instructions $ head $ blocks $ execState x init
where init = CompilationState {
usedRegisters = empty,
instCounter = 0,
blocks = [initBlock]
}
emit i = do b <- topBlock
i' <- return $ (instructions b) ++ [i]
replaceTopBlock $ b { instructions = i' }
unless (isComment i) incrementAddress
-- |Return the address at which the next instruction will be
-- |placed
currentAddress = do st <- get :: Compiler CompilationState
return $ instCounter st
incrementAddress = do st <- get
put $ st { instCounter = (instCounter st) + 1 }
currentStackPointer = do b <- topBlock
return $ stackPointer b
incrementStackPointer i = do b <- topBlock
b' <- return $ b { stackPointer = (stackPointer b) - i }
replaceTopBlock b'
currentSymbolTable = do b <- topBlock
return $ symbolTable b
availableRegisters st = toList $ all `difference` used
where all = fromList $ range (0,8)
reserved = fromList [pc, gp, fp, ac]
used = usedRegisters st
-- |This is the poor man's register allocator. Think of it like a
-- |penny tray at a convenience store: "need a register? take a
-- |register. have a register? leave a register." What if there
-- |are no free registers, you ask? Tough shit, it isn't smart
-- |enough to spill to memory.
claimRegister = do st <- get :: Compiler CompilationState
case availableRegisters st of
[] -> error "ow, my brain! there's no free registers!"
(x:xs) -> do put $ st { usedRegisters = insert x (usedRegisters st) }
return x
freeRegister r = do st <- get :: Compiler CompilationState
put $ st { usedRegisters = delete r (usedRegisters st) }
declareSymbol s = declareSymbols [s]
declareSymbols syms = do b <- topBlock
table' <- return $ insertSymbols (symbolTable b) syms
replaceTopBlock $ b { symbolTable = table' }
-- |Pushes a new compilation block to the stack. All labels within
-- |a block are isolated from their surrounding environment
pushBlock = do st <- get :: Compiler CompilationState
b <- newBlock
blocks' <- return $ b:(blocks st)
put $ st { blocks = blocks' }
return ()
popBlock = do st <- get :: Compiler CompilationState
(x:xs) <- return $ blocks st
put $ st { blocks = xs }
return x
topBlock = do st <- get :: Compiler CompilationState
return $ head $ blocks st
appendInstructions i = do top <- topBlock
top' <- return $ top { instructions = (instructions top) ++ i }
replaceTopBlock top'
defineLabel name address = do b <- topBlock
replaceTopBlock $ b { labelTable = (insertLabel (labelTable b) name address) }
replaceTopBlock x = do st <- get
xs <- return $ tail $ blocks st
put $ st { blocks = (x:xs) }
finalizeBlock b = do i' <- return $ resolveSymbols (symbolTable b) (instructions b)
i'' <- return $ resolveLabels i' (labelTable b)
appendInstructions i''
withBlock x = do pushBlock
x
b <- popBlock
finalizeBlock b
withBlockRet x = do pushBlock
ret <- x
b <- popBlock
finalizeBlock b
return ret
comment x = emit $ COMMENT x
label name = do a <- currentAddress
comment ("label " ++ name ++ " defined at " ++ show a)
defineLabel name a
|
michaelmelanson/cminus-compiler
|
Compiler/CodeGeneration/CompilationState.hs
|
Haskell
|
bsd-2-clause
| 5,583
|
module RePack where
import CLaSH.Prelude
topEntity :: (Unsigned 1,Unsigned 1)
topEntity = (unpack (pack True), unpack (pack False))
|
ggreif/clash-compiler
|
tests/shouldwork/BitVector/RePack.hs
|
Haskell
|
bsd-2-clause
| 134
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Trustworthy #-}
-- | Provide primitives to communicate among family members. It provides an API for sequential 'linkMAC' and concurrent ('forkMAC') setting
module MAC.Control
(
-- Defined here
linkMAC -- Secure communication for sequential programs
, forkMAC -- Spawing threads
, forkMACMVar -- Returning futures
)
where
import MAC.Lattice
import MAC.Core (MAC(),ioTCB,runMAC)
import MAC.Exception
import MAC.Labeled
import MAC.MVar
import Control.Exception
import Control.Concurrent
{-|
Primitive which allows family members to safely communicate. The function
finishes even if an exception is raised---the exception is rethrown when
the returned value gets inspected
-}
linkMAC :: (Less l l') => MAC l' a -> MAC l (Labeled l' a)
linkMAC m = (ioTCB . runMAC)
(catchMAC m (\(e :: SomeException) -> throwMAC e)) >>= label
-- | Safely spawning new threads
forkMAC :: Less l l' => MAC l' () -> MAC l ()
forkMAC m = (ioTCB . forkIO . runMAC) m >> return ()
{-|
Safely spawning new threads. The function returns a labeled 'MVar' where
the outcome of the thread is stored
-}
forkMACMVar :: (Less l' l', Less l l') => MAC l' a -> MAC l (MACMVar l' a)
forkMACMVar m = do lmv <- newMACEmptyMVar
forkMAC (m >>= putMACMVar lmv)
return lmv
|
alejandrorusso/mac-privacy
|
MAC/Control.hs
|
Haskell
|
bsd-3-clause
| 1,392
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Tinfoil.Key(
genSymmetricKey
) where
import P
import System.IO (IO)
import Tinfoil.Data.Key
import Tinfoil.Data.Random
import Tinfoil.Random
-- | Generate a 256-bit symmetric cryptographic key.
genSymmetricKey :: IO SymmetricKey
genSymmetricKey = fmap (SymmetricKey . unEntropy) $ entropy symmetricKeyLength
|
ambiata/tinfoil
|
src/Tinfoil/Key.hs
|
Haskell
|
bsd-3-clause
| 445
|
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, BangPatterns, CPP #-}
--
-- | Interacting with the interpreter, whether it is running on an
-- external process or in the current process.
--
module GHCi
( -- * High-level interface to the interpreter
evalStmt, EvalStatus_(..), EvalStatus, EvalResult(..), EvalExpr(..)
, resumeStmt
, abandonStmt
, evalIO
, evalString
, evalStringToIOString
, mallocData
, createBCOs
, addSptEntry
, mkCostCentres
, costCentreStackInfo
, newBreakArray
, enableBreakpoint
, breakpointStatus
, getBreakpointVar
, getClosure
, seqHValue
-- * The object-code linker
, initObjLinker
, lookupSymbol
, lookupClosure
, loadDLL
, loadArchive
, loadObj
, unloadObj
, addLibrarySearchPath
, removeLibrarySearchPath
, resolveObjs
, findSystemLibrary
-- * Lower-level API using messages
, iservCmd, Message(..), withIServ, stopIServ
, iservCall, readIServ, writeIServ
, purgeLookupSymbolCache
, freeHValueRefs
, mkFinalizedHValue
, wormhole, wormholeRef
, mkEvalOpts
, fromEvalResult
) where
import GhcPrelude
import GHCi.Message
#if defined(HAVE_INTERNAL_INTERPRETER)
import GHCi.Run
#endif
import GHCi.RemoteTypes
import GHCi.ResolvedBCO
import GHCi.BreakArray (BreakArray)
import Fingerprint
import HscTypes
import UniqFM
import Panic
import DynFlags
import ErrUtils
import Outputable
import Exception
import BasicTypes
import FastString
import Util
import Hooks
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Data.Binary
import Data.Binary.Put
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import Data.IORef
import Foreign hiding (void)
import GHC.Exts.Heap
import GHC.Stack.CCS (CostCentre,CostCentreStack)
import System.Exit
import Data.Maybe
import GHC.IO.Handle.Types (Handle)
#if defined(mingw32_HOST_OS)
import Foreign.C
import GHC.IO.Handle.FD (fdToHandle)
#else
import System.Posix as Posix
#endif
import System.Directory
import System.Process
import GHC.Conc (getNumProcessors, pseq, par)
{- Note [Remote GHCi]
When the flag -fexternal-interpreter is given to GHC, interpreted code
is run in a separate process called iserv, and we communicate with the
external process over a pipe using Binary-encoded messages.
Motivation
~~~~~~~~~~
When the interpreted code is running in a separate process, it can
use a different "way", e.g. profiled or dynamic. This means
- compiling Template Haskell code with -prof does not require
building the code without -prof first
- when GHC itself is profiled, it can interpret unprofiled code,
and the same applies to dynamic linking.
- An unprofiled GHCi can load and run profiled code, which means it
can use the stack-trace functionality provided by profiling without
taking the performance hit on the compiler that profiling would
entail.
For other reasons see remote-GHCi on the wiki.
Implementation Overview
~~~~~~~~~~~~~~~~~~~~~~~
The main pieces are:
- libraries/ghci, containing:
- types for talking about remote values (GHCi.RemoteTypes)
- the message protocol (GHCi.Message),
- implementation of the messages (GHCi.Run)
- implementation of Template Haskell (GHCi.TH)
- a few other things needed to run interpreted code
- top-level iserv directory, containing the codefor the external
server. This is a fairly simple wrapper, most of the functionality
is provided by modules in libraries/ghci.
- This module (GHCi) which provides the interface to the server used
by the rest of GHC.
GHC works with and without -fexternal-interpreter. With the flag, all
interpreted code is run by the iserv binary. Without the flag,
interpreted code is run in the same process as GHC.
Things that do not work with -fexternal-interpreter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
dynCompileExpr cannot work, because we have no way to run code of an
unknown type in the remote process. This API fails with an error
message if it is used with -fexternal-interpreter.
Other Notes on Remote GHCi
~~~~~~~~~~~~~~~~~~~~~~~~~~
* This wiki page has an implementation overview:
https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/external-interpreter
* Note [External GHCi pointers] in compiler/ghci/GHCi.hs
* Note [Remote Template Haskell] in libraries/ghci/GHCi/TH.hs
-}
#if !defined(HAVE_INTERNAL_INTERPRETER)
needExtInt :: IO a
needExtInt = throwIO
(InstallationError "this operation requires -fexternal-interpreter")
#endif
-- | Run a command in the interpreter's context. With
-- @-fexternal-interpreter@, the command is serialized and sent to an
-- external iserv process, and the response is deserialized (hence the
-- @Binary@ constraint). With @-fno-external-interpreter@ we execute
-- the command directly here.
iservCmd :: Binary a => HscEnv -> Message a -> IO a
iservCmd hsc_env@HscEnv{..} msg
| gopt Opt_ExternalInterpreter hsc_dflags =
withIServ hsc_env $ \iserv ->
uninterruptibleMask_ $ do -- Note [uninterruptibleMask_]
iservCall iserv msg
| otherwise = -- Just run it directly
#if defined(HAVE_INTERNAL_INTERPRETER)
run msg
#else
needExtInt
#endif
-- Note [uninterruptibleMask_ and iservCmd]
--
-- If we receive an async exception, such as ^C, while communicating
-- with the iserv process then we will be out-of-sync and not be able
-- to recoever. Thus we use uninterruptibleMask_ during
-- communication. A ^C will be delivered to the iserv process (because
-- signals get sent to the whole process group) which will interrupt
-- the running computation and return an EvalException result.
-- | Grab a lock on the 'IServ' and do something with it.
-- Overloaded because this is used from TcM as well as IO.
withIServ
:: (MonadIO m, ExceptionMonad m)
=> HscEnv -> (IServ -> m a) -> m a
withIServ HscEnv{..} action =
gmask $ \restore -> do
m <- liftIO $ takeMVar hsc_iserv
-- start the iserv process if we haven't done so yet
iserv <- maybe (liftIO $ startIServ hsc_dflags) return m
`gonException` (liftIO $ putMVar hsc_iserv Nothing)
-- free any ForeignHValues that have been garbage collected.
let iserv' = iserv{ iservPendingFrees = [] }
a <- (do
liftIO $ when (not (null (iservPendingFrees iserv))) $
iservCall iserv (FreeHValueRefs (iservPendingFrees iserv))
-- run the inner action
restore $ action iserv)
`gonException` (liftIO $ putMVar hsc_iserv (Just iserv'))
liftIO $ putMVar hsc_iserv (Just iserv')
return a
-- -----------------------------------------------------------------------------
-- Wrappers around messages
-- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for
-- each of the results.
evalStmt
:: HscEnv -> Bool -> EvalExpr ForeignHValue
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
evalStmt hsc_env step foreign_expr = do
let dflags = hsc_dflags hsc_env
status <- withExpr foreign_expr $ \expr ->
iservCmd hsc_env (EvalStmt (mkEvalOpts dflags step) expr)
handleEvalStatus hsc_env status
where
withExpr :: EvalExpr ForeignHValue -> (EvalExpr HValueRef -> IO a) -> IO a
withExpr (EvalThis fhv) cont =
withForeignRef fhv $ \hvref -> cont (EvalThis hvref)
withExpr (EvalApp fl fr) cont =
withExpr fl $ \fl' ->
withExpr fr $ \fr' ->
cont (EvalApp fl' fr')
resumeStmt
:: HscEnv -> Bool -> ForeignRef (ResumeContext [HValueRef])
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
resumeStmt hsc_env step resume_ctxt = do
let dflags = hsc_dflags hsc_env
status <- withForeignRef resume_ctxt $ \rhv ->
iservCmd hsc_env (ResumeStmt (mkEvalOpts dflags step) rhv)
handleEvalStatus hsc_env status
abandonStmt :: HscEnv -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
abandonStmt hsc_env resume_ctxt = do
withForeignRef resume_ctxt $ \rhv ->
iservCmd hsc_env (AbandonStmt rhv)
handleEvalStatus
:: HscEnv -> EvalStatus [HValueRef]
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
handleEvalStatus hsc_env status =
case status of
EvalBreak a b c d e f -> return (EvalBreak a b c d e f)
EvalComplete alloc res ->
EvalComplete alloc <$> addFinalizer res
where
addFinalizer (EvalException e) = return (EvalException e)
addFinalizer (EvalSuccess rs) = do
EvalSuccess <$> mapM (mkFinalizedHValue hsc_env) rs
-- | Execute an action of type @IO ()@
evalIO :: HscEnv -> ForeignHValue -> IO ()
evalIO hsc_env fhv = do
liftIO $ withForeignRef fhv $ \fhv ->
iservCmd hsc_env (EvalIO fhv) >>= fromEvalResult
-- | Execute an action of type @IO String@
evalString :: HscEnv -> ForeignHValue -> IO String
evalString hsc_env fhv = do
liftIO $ withForeignRef fhv $ \fhv ->
iservCmd hsc_env (EvalString fhv) >>= fromEvalResult
-- | Execute an action of type @String -> IO String@
evalStringToIOString :: HscEnv -> ForeignHValue -> String -> IO String
evalStringToIOString hsc_env fhv str = do
liftIO $ withForeignRef fhv $ \fhv ->
iservCmd hsc_env (EvalStringToString fhv str) >>= fromEvalResult
-- | Allocate and store the given bytes in memory, returning a pointer
-- to the memory in the remote process.
mallocData :: HscEnv -> ByteString -> IO (RemotePtr ())
mallocData hsc_env bs = iservCmd hsc_env (MallocData bs)
mkCostCentres
:: HscEnv -> String -> [(String,String)] -> IO [RemotePtr CostCentre]
mkCostCentres hsc_env mod ccs =
iservCmd hsc_env (MkCostCentres mod ccs)
-- | Create a set of BCOs that may be mutually recursive.
createBCOs :: HscEnv -> [ResolvedBCO] -> IO [HValueRef]
createBCOs hsc_env rbcos = do
n_jobs <- case parMakeCount (hsc_dflags hsc_env) of
Nothing -> liftIO getNumProcessors
Just n -> return n
-- Serializing ResolvedBCO is expensive, so if we're in parallel mode
-- (-j<n>) parallelise the serialization.
if (n_jobs == 1)
then
iservCmd hsc_env (CreateBCOs [runPut (put rbcos)])
else do
old_caps <- getNumCapabilities
if old_caps == n_jobs
then void $ evaluate puts
else bracket_ (setNumCapabilities n_jobs)
(setNumCapabilities old_caps)
(void $ evaluate puts)
iservCmd hsc_env (CreateBCOs puts)
where
puts = parMap doChunk (chunkList 100 rbcos)
-- make sure we force the whole lazy ByteString
doChunk c = pseq (LB.length bs) bs
where bs = runPut (put c)
-- We don't have the parallel package, so roll our own simple parMap
parMap _ [] = []
parMap f (x:xs) = fx `par` (fxs `pseq` (fx : fxs))
where fx = f x; fxs = parMap f xs
addSptEntry :: HscEnv -> Fingerprint -> ForeignHValue -> IO ()
addSptEntry hsc_env fpr ref =
withForeignRef ref $ \val ->
iservCmd hsc_env (AddSptEntry fpr val)
costCentreStackInfo :: HscEnv -> RemotePtr CostCentreStack -> IO [String]
costCentreStackInfo hsc_env ccs =
iservCmd hsc_env (CostCentreStackInfo ccs)
newBreakArray :: HscEnv -> Int -> IO (ForeignRef BreakArray)
newBreakArray hsc_env size = do
breakArray <- iservCmd hsc_env (NewBreakArray size)
mkFinalizedHValue hsc_env breakArray
enableBreakpoint :: HscEnv -> ForeignRef BreakArray -> Int -> Bool -> IO ()
enableBreakpoint hsc_env ref ix b = do
withForeignRef ref $ \breakarray ->
iservCmd hsc_env (EnableBreakpoint breakarray ix b)
breakpointStatus :: HscEnv -> ForeignRef BreakArray -> Int -> IO Bool
breakpointStatus hsc_env ref ix = do
withForeignRef ref $ \breakarray ->
iservCmd hsc_env (BreakpointStatus breakarray ix)
getBreakpointVar :: HscEnv -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
getBreakpointVar hsc_env ref ix =
withForeignRef ref $ \apStack -> do
mb <- iservCmd hsc_env (GetBreakpointVar apStack ix)
mapM (mkFinalizedHValue hsc_env) mb
getClosure :: HscEnv -> ForeignHValue -> IO (GenClosure ForeignHValue)
getClosure hsc_env ref =
withForeignRef ref $ \hval -> do
mb <- iservCmd hsc_env (GetClosure hval)
mapM (mkFinalizedHValue hsc_env) mb
seqHValue :: HscEnv -> ForeignHValue -> IO ()
seqHValue hsc_env ref =
withForeignRef ref $ \hval ->
iservCmd hsc_env (Seq hval) >>= fromEvalResult
-- -----------------------------------------------------------------------------
-- Interface to the object-code linker
initObjLinker :: HscEnv -> IO ()
initObjLinker hsc_env = iservCmd hsc_env InitLinker
lookupSymbol :: HscEnv -> FastString -> IO (Maybe (Ptr ()))
lookupSymbol hsc_env@HscEnv{..} str
| gopt Opt_ExternalInterpreter hsc_dflags =
-- Profiling of GHCi showed a lot of time and allocation spent
-- making cross-process LookupSymbol calls, so I added a GHC-side
-- cache which sped things up quite a lot. We have to be careful
-- to purge this cache when unloading code though.
withIServ hsc_env $ \iserv@IServ{..} -> do
cache <- readIORef iservLookupSymbolCache
case lookupUFM cache str of
Just p -> return (Just p)
Nothing -> do
m <- uninterruptibleMask_ $
iservCall iserv (LookupSymbol (unpackFS str))
case m of
Nothing -> return Nothing
Just r -> do
let p = fromRemotePtr r
writeIORef iservLookupSymbolCache $! addToUFM cache str p
return (Just p)
| otherwise =
#if defined(HAVE_INTERNAL_INTERPRETER)
fmap fromRemotePtr <$> run (LookupSymbol (unpackFS str))
#else
needExtInt
#endif
lookupClosure :: HscEnv -> String -> IO (Maybe HValueRef)
lookupClosure hsc_env str =
iservCmd hsc_env (LookupClosure str)
purgeLookupSymbolCache :: HscEnv -> IO ()
purgeLookupSymbolCache hsc_env@HscEnv{..} =
when (gopt Opt_ExternalInterpreter hsc_dflags) $
withIServ hsc_env $ \IServ{..} ->
writeIORef iservLookupSymbolCache emptyUFM
-- | loadDLL loads a dynamic library using the OS's native linker
-- (i.e. dlopen() on Unix, LoadLibrary() on Windows). It takes either
-- an absolute pathname to the file, or a relative filename
-- (e.g. "libfoo.so" or "foo.dll"). In the latter case, loadDLL
-- searches the standard locations for the appropriate library.
--
-- Returns:
--
-- Nothing => success
-- Just err_msg => failure
loadDLL :: HscEnv -> String -> IO (Maybe String)
loadDLL hsc_env str = iservCmd hsc_env (LoadDLL str)
loadArchive :: HscEnv -> String -> IO ()
loadArchive hsc_env path = do
path' <- canonicalizePath path -- Note [loadObj and relative paths]
iservCmd hsc_env (LoadArchive path')
loadObj :: HscEnv -> String -> IO ()
loadObj hsc_env path = do
path' <- canonicalizePath path -- Note [loadObj and relative paths]
iservCmd hsc_env (LoadObj path')
unloadObj :: HscEnv -> String -> IO ()
unloadObj hsc_env path = do
path' <- canonicalizePath path -- Note [loadObj and relative paths]
iservCmd hsc_env (UnloadObj path')
-- Note [loadObj and relative paths]
-- the iserv process might have a different current directory from the
-- GHC process, so we must make paths absolute before sending them
-- over.
addLibrarySearchPath :: HscEnv -> String -> IO (Ptr ())
addLibrarySearchPath hsc_env str =
fromRemotePtr <$> iservCmd hsc_env (AddLibrarySearchPath str)
removeLibrarySearchPath :: HscEnv -> Ptr () -> IO Bool
removeLibrarySearchPath hsc_env p =
iservCmd hsc_env (RemoveLibrarySearchPath (toRemotePtr p))
resolveObjs :: HscEnv -> IO SuccessFlag
resolveObjs hsc_env = successIf <$> iservCmd hsc_env ResolveObjs
findSystemLibrary :: HscEnv -> String -> IO (Maybe String)
findSystemLibrary hsc_env str = iservCmd hsc_env (FindSystemLibrary str)
-- -----------------------------------------------------------------------------
-- Raw calls and messages
-- | Send a 'Message' and receive the response from the iserv process
iservCall :: Binary a => IServ -> Message a -> IO a
iservCall iserv@IServ{..} msg =
remoteCall iservPipe msg
`catch` \(e :: SomeException) -> handleIServFailure iserv e
-- | Read a value from the iserv process
readIServ :: IServ -> Get a -> IO a
readIServ iserv@IServ{..} get =
readPipe iservPipe get
`catch` \(e :: SomeException) -> handleIServFailure iserv e
-- | Send a value to the iserv process
writeIServ :: IServ -> Put -> IO ()
writeIServ iserv@IServ{..} put =
writePipe iservPipe put
`catch` \(e :: SomeException) -> handleIServFailure iserv e
handleIServFailure :: IServ -> SomeException -> IO a
handleIServFailure IServ{..} e = do
ex <- getProcessExitCode iservProcess
case ex of
Just (ExitFailure n) ->
throw (InstallationError ("ghc-iserv terminated (" ++ show n ++ ")"))
_ -> do
terminateProcess iservProcess
_ <- waitForProcess iservProcess
throw e
-- -----------------------------------------------------------------------------
-- Starting and stopping the iserv process
startIServ :: DynFlags -> IO IServ
startIServ dflags = do
let flavour
| WayProf `elem` ways dflags = "-prof"
| WayDyn `elem` ways dflags = "-dyn"
| otherwise = ""
prog = pgm_i dflags ++ flavour
opts = getOpts dflags opt_i
debugTraceMsg dflags 3 $ text "Starting " <> text prog
let createProc = lookupHook createIservProcessHook
(\cp -> do { (_,_,_,ph) <- createProcess cp
; return ph })
dflags
(ph, rh, wh) <- runWithPipes createProc prog opts
lo_ref <- newIORef Nothing
cache_ref <- newIORef emptyUFM
return $ IServ
{ iservPipe = Pipe { pipeRead = rh
, pipeWrite = wh
, pipeLeftovers = lo_ref }
, iservProcess = ph
, iservLookupSymbolCache = cache_ref
, iservPendingFrees = []
}
stopIServ :: HscEnv -> IO ()
stopIServ HscEnv{..} =
gmask $ \_restore -> do
m <- takeMVar hsc_iserv
maybe (return ()) stop m
putMVar hsc_iserv Nothing
where
stop iserv = do
ex <- getProcessExitCode (iservProcess iserv)
if isJust ex
then return ()
else iservCall iserv Shutdown
runWithPipes :: (CreateProcess -> IO ProcessHandle)
-> FilePath -> [String] -> IO (ProcessHandle, Handle, Handle)
#if defined(mingw32_HOST_OS)
foreign import ccall "io.h _close"
c__close :: CInt -> IO CInt
foreign import ccall unsafe "io.h _get_osfhandle"
_get_osfhandle :: CInt -> IO CInt
runWithPipes createProc prog opts = do
(rfd1, wfd1) <- createPipeFd -- we read on rfd1
(rfd2, wfd2) <- createPipeFd -- we write on wfd2
wh_client <- _get_osfhandle wfd1
rh_client <- _get_osfhandle rfd2
let args = show wh_client : show rh_client : opts
ph <- createProc (proc prog args)
rh <- mkHandle rfd1
wh <- mkHandle wfd2
return (ph, rh, wh)
where mkHandle :: CInt -> IO Handle
mkHandle fd = (fdToHandle fd) `onException` (c__close fd)
#else
runWithPipes createProc prog opts = do
(rfd1, wfd1) <- Posix.createPipe -- we read on rfd1
(rfd2, wfd2) <- Posix.createPipe -- we write on wfd2
setFdOption rfd1 CloseOnExec True
setFdOption wfd2 CloseOnExec True
let args = show wfd1 : show rfd2 : opts
ph <- createProc (proc prog args)
closeFd wfd1
closeFd rfd2
rh <- fdToHandle rfd1
wh <- fdToHandle wfd2
return (ph, rh, wh)
#endif
-- -----------------------------------------------------------------------------
{- Note [External GHCi pointers]
We have the following ways to reference things in GHCi:
HValue
------
HValue is a direct reference to a value in the local heap. Obviously
we cannot use this to refer to things in the external process.
RemoteRef
---------
RemoteRef is a StablePtr to a heap-resident value. When
-fexternal-interpreter is used, this value resides in the external
process's heap. RemoteRefs are mostly used to send pointers in
messages between GHC and iserv.
A RemoteRef must be explicitly freed when no longer required, using
freeHValueRefs, or by attaching a finalizer with mkForeignHValue.
To get from a RemoteRef to an HValue you can use 'wormholeRef', which
fails with an error message if -fexternal-interpreter is in use.
ForeignRef
----------
A ForeignRef is a RemoteRef with a finalizer that will free the
'RemoteRef' when it is garbage collected. We mostly use ForeignHValue
on the GHC side.
The finalizer adds the RemoteRef to the iservPendingFrees list in the
IServ record. The next call to iservCmd will free any RemoteRefs in
the list. It was done this way rather than calling iservCmd directly,
because I didn't want to have arbitrary threads calling iservCmd. In
principle it would probably be ok, but it seems less hairy this way.
-}
-- | Creates a 'ForeignRef' that will automatically release the
-- 'RemoteRef' when it is no longer referenced.
mkFinalizedHValue :: HscEnv -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue HscEnv{..} rref = mkForeignRef rref free
where
!external = gopt Opt_ExternalInterpreter hsc_dflags
hvref = toHValueRef rref
free :: IO ()
free
| not external = freeRemoteRef hvref
| otherwise =
modifyMVar_ hsc_iserv $ \mb_iserv ->
case mb_iserv of
Nothing -> return Nothing -- already shut down
Just iserv@IServ{..} ->
return (Just iserv{iservPendingFrees = hvref : iservPendingFrees})
freeHValueRefs :: HscEnv -> [HValueRef] -> IO ()
freeHValueRefs _ [] = return ()
freeHValueRefs hsc_env refs = iservCmd hsc_env (FreeHValueRefs refs)
-- | Convert a 'ForeignRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
wormhole :: DynFlags -> ForeignRef a -> IO a
wormhole dflags r = wormholeRef dflags (unsafeForeignRefToRemoteRef r)
-- | Convert an 'RemoteRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
wormholeRef :: DynFlags -> RemoteRef a -> IO a
wormholeRef dflags _r
| gopt Opt_ExternalInterpreter dflags
= throwIO (InstallationError
"this operation requires -fno-external-interpreter")
#if defined(HAVE_INTERNAL_INTERPRETER)
| otherwise
= localRef _r
#else
| otherwise
= throwIO (InstallationError
"can't wormhole a value in a stage1 compiler")
#endif
-- -----------------------------------------------------------------------------
-- Misc utils
mkEvalOpts :: DynFlags -> Bool -> EvalOpts
mkEvalOpts dflags step =
EvalOpts
{ useSandboxThread = gopt Opt_GhciSandbox dflags
, singleStep = step
, breakOnException = gopt Opt_BreakOnException dflags
, breakOnError = gopt Opt_BreakOnError dflags }
fromEvalResult :: EvalResult a -> IO a
fromEvalResult (EvalException e) = throwIO (fromSerializableException e)
fromEvalResult (EvalSuccess a) = return a
|
sdiehl/ghc
|
compiler/ghci/GHCi.hs
|
Haskell
|
bsd-3-clause
| 22,786
|
{-# LANGUAGE OverloadedStrings #-}
module CommitMsgParsers
( loadParsers
, findCategory
, unknownCategory
, ParserDef
, getParserName
) where
import Text.Regex.Posix
import Data.Map as Map
import Data.List as List
import Data.Maybe
import Control.Applicative
import qualified Data.Yaml as Y
import Data.Yaml (FromJSON(..), (.:), (.:?))
import qualified Data.ByteString.Char8 as BS
import Paths_hstats
type RegExp = String
data ParserDef = ParserDef { name :: String
, matcher :: RegExp
} deriving (Show)
instance FromJSON ParserDef where
parseJSON (Y.Object v) =
ParserDef <$>
v .: "name" <*>
v .: "matcher"
unknownCategory = "unknown"
loadParsers :: IO [ParserDef]
loadParsers = do
conf <- getDataFileName "data/commitMsgPrefixes.yaml" >>= BS.readFile
return $ fromMaybe [] $ (Y.decode conf :: Maybe [ParserDef])
findCategory :: [ParserDef] -> String -> String
findCategory defs msg = maybe unknownCategory name . List.find match $ defs
where match p = msg =~ matcher p :: Bool
getParserName :: ParserDef -> String
getParserName = name
|
LFDM/hstats
|
src/lib/CommitMsgParsers.hs
|
Haskell
|
bsd-3-clause
| 1,128
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | This module includes the machinery necessary to use hint to load
-- action code dynamically. It includes a Template Haskell function
-- to gather the necessary compile-time information about code
-- location, compiler arguments, etc, and bind that information into
-- the calls to the dynamic loader.
module Snap.Loader.Hint where
import Data.List (groupBy, intercalate, isPrefixOf, nub)
import Control.Concurrent (forkIO, myThreadId)
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad (when)
import Control.Monad.Trans (liftIO)
import Data.Maybe (catMaybes)
import Data.Time.Clock
import Language.Haskell.Interpreter hiding (lift, liftIO)
import Language.Haskell.Interpreter.Unsafe
import Language.Haskell.TH
import Prelude hiding (catch)
import System.Environment (getArgs)
------------------------------------------------------------------------------
import Snap.Types
import qualified Snap.Loader.Static as Static
------------------------------------------------------------------------------
-- | This function derives all the information necessary to use the
-- interpreter from the compile-time environment, and compiles it in
-- to the generated code.
--
-- This could be considered a TH wrapper around a function
--
-- > loadSnap :: IO a -> (a -> IO ()) -> (a -> Snap ()) -> IO (IO (), Snap ())
--
-- with a magical implementation.
--
-- The returned IO action does nothing. The returned Snap action does
-- initialization, runs the action, and does the cleanup. This means
-- that the whole application state will be loaded and unloaded for
-- each request. To make this worthwhile, those steps should be made
-- quite fast.
--
-- The upshot is that you shouldn't need to recompile your server
-- during development unless your .cabal file changes, or the code
-- that uses this splice changes.
loadSnapTH :: Name -> Name -> Name -> Q Exp
loadSnapTH initialize cleanup action = do
args <- runIO getArgs
let initMod = nameModule initialize
initBase = nameBase initialize
cleanMod = nameModule cleanup
cleanBase = nameBase cleanup
actMod = nameModule action
actBase = nameBase action
modules = catMaybes [initMod, cleanMod, actMod]
opts = getHintOpts args
let static = Static.loadSnapTH initialize cleanup action
-- The let in this block causes the static expression to be
-- pattern-matched, providing an extra check that the types were
-- correct at compile-time, at least.
[| do let _ = $static :: IO (IO (), Snap ())
hint <- hintSnap opts modules initBase cleanBase actBase
return (return (), hint) |]
------------------------------------------------------------------------------
-- | Convert the command-line arguments passed in to options for the
-- hint interpreter. This is somewhat brittle code, based on a few
-- experimental datapoints regarding the structure of the command-line
-- arguments cabal produces.
getHintOpts :: [String] -> [String]
getHintOpts args = removeBad opts
where
bad = ["-threaded", "-O"]
removeBad = filter (\x -> not $ any (`isPrefixOf` x) bad)
hideAll = filter (== "-hide-all-packages") args
srcOpts = filter (\x -> "-i" `isPrefixOf` x
&& not ("-idist" `isPrefixOf` x)) args
toCopy = init' $ dropWhile (not . ("-package" `isPrefixOf`)) args
copy = map (intercalate " ") . groupBy (\_ s -> not $ "-" `isPrefixOf` s)
opts = hideAll ++ srcOpts ++ copy toCopy
init' [] = []
init' xs = init xs
------------------------------------------------------------------------------
-- | This function creates the Snap handler that actually is
-- responsible for doing the dynamic loading of actions via hint,
-- given all of the configuration information that the interpreter
-- needs. It also ensures safe concurrent access to the interpreter,
-- and caches the interpreter results for a short time before allowing
-- it to run again.
--
-- This constructs an expression of type Snap (), that is essentially
--
-- > bracketSnap initialization cleanup handler
--
-- for the values of initialization, cleanup, and handler passed in.
--
-- Generally, this won't be called manually. Instead, loadSnapTH will
-- generate a call to it at compile-time, calculating all the
-- arguments from its environment.
hintSnap :: [String] -- ^ A list of command-line options for the interpreter
-> [String] -- ^ A list of modules that need to be
-- interpreted. This should contain only the
-- modules which contain the initialization,
-- cleanup, and handler actions. Everything else
-- they require will be loaded transitively.
-> String -- ^ The name of the initialization action
-> String -- ^ The name of the cleanup action
-> String -- ^ The name of the handler action
-> IO (Snap ())
hintSnap opts modules initialization cleanup handler = do
let action = intercalate " " [ "bracketSnap"
, initialization
, cleanup
, handler
]
interpreter = do
loadModules . nub $ modules
let imports = "Prelude" : "Snap.Types" : modules
setImports . nub $ imports
interpret action (as :: Snap ())
loadInterpreter = unsafeRunInterpreterWithArgs opts interpreter
-- Protect the interpreter from concurrent and high-speed serial
-- access.
loadAction <- protectedActionEvaluator 3 loadInterpreter
return $ do
interpreterResult <- liftIO loadAction
case interpreterResult of
Left err -> error $ format err
Right handlerAction -> handlerAction
------------------------------------------------------------------------------
-- | Convert an InterpreterError to a String for presentation
format :: InterpreterError -> String
format (UnknownError e) = "Unknown interpreter error:\r\n\r\n" ++ e
format (NotAllowed e) = "Interpreter action not allowed:\r\n\r\n" ++ e
format (GhcException e) = "GHC error:\r\n\r\n" ++ e
format (WontCompile errs) = "Compile errors:\r\n\r\n" ++
(intercalate "\r\n" $ nub $ map errMsg errs)
------------------------------------------------------------------------------
-- | Create a wrapper for an action that protects the action from
-- concurrent or rapid evaluation.
--
-- There will be at least the passed-in 'NominalDiffTime' delay
-- between the finish of one execution of the action the start of the
-- next. Concurrent calls to the wrapper, and calls within the delay
-- period, end up with the same calculated value returned.
--
-- If an exception is raised during the processing of the action, it
-- will be thrown to all waiting threads, and for all requests made
-- before the delay time has expired after the exception was raised.
protectedActionEvaluator :: NominalDiffTime -> IO a -> IO (IO a)
protectedActionEvaluator minReEval action = do
-- The list of requesters waiting for a result. Contains the
-- ThreadId in case of exceptions, and an empty MVar awaiting a
-- successful result.
--
-- type: MVar [(ThreadId, MVar a)]
readerContainer <- newMVar []
-- Contains the previous result, and the time it was stored, if a
-- previous result has been computed. The result stored is either
-- the actual result, or the exception thrown by the calculation.
--
-- type: MVar (Maybe (Either SomeException a, UTCTime))
resultContainer <- newMVar Nothing
-- The model used for the above MVars in the returned action is
-- "keep them full, unless updating them." In every case, when
-- one of those MVars is emptied, the next action is to fill that
-- same MVar. This makes deadlocking on MVar wait impossible.
return $ do
existingResult <- readMVar resultContainer
now <- getCurrentTime
case existingResult of
Just (res, ts) | diffUTCTime now ts < minReEval ->
-- There's an existing result, and it's still valid
case res of
Right val -> return val
Left e -> throwIO e
_ -> do
-- Need to calculate a new result
tid <- myThreadId
reader <- newEmptyMVar
readers <- takeMVar readerContainer
-- Some strictness is employed to ensure the MVar
-- isn't holding on to a chain of unevaluated thunks.
let pair = (tid, reader)
newReaders = readers `seq` pair `seq` (pair : readers)
putMVar readerContainer $! newReaders
-- If this is the first reader, kick off evaluation of
-- the action in a new thread. This is slightly
-- careful to block asynchronous exceptions to that
-- thread except when actually running the action.
when (null readers) $ do
let runAndFill = block $ do
a <- unblock action
clearAndNotify (Right a) (flip putMVar a . snd)
killWaiting :: SomeException -> IO ()
killWaiting e = block $ do
clearAndNotify (Left e) (flip throwTo e . fst)
throwIO e
clearAndNotify r f = do
t <- getCurrentTime
_ <- swapMVar resultContainer $ Just (r, t)
allReaders <- swapMVar readerContainer []
mapM_ f allReaders
_ <- forkIO $ runAndFill `catch` killWaiting
return ()
-- Wait for the evaluation of the action to complete,
-- and return its result.
takeMVar reader
|
janrain/snap
|
src/Snap/Loader/Hint.hs
|
Haskell
|
bsd-3-clause
| 10,281
|
module CSPM.Evaluator.Dot (
combineDots, dataTypeInfo,
extensions, extensionsSet, oneFieldExtensions,
productions, productionsSet, splitIntoFields,
compressIntoEnumeratedSet,
) where
import CSPM.Syntax.Names
import {-# SOURCE #-} CSPM.Evaluator.Exceptions
import CSPM.Evaluator.Monad
import CSPM.Evaluator.Values
import CSPM.Evaluator.ValueSet hiding (cartesianProduct)
import qualified CSPM.Evaluator.ValueSet as S
import Data.List (groupBy, sortBy)
import Data.Maybe (catMaybes, isJust)
import Util.Annotated
import Util.List
import Util.Prelude
dataTypeInfo :: Name -> EvaluationMonad (Value, Int, Array Int ValueSet)
dataTypeInfo n = do
VTuple dta <- lookupVar n
let VInt a = dta!1
VTuple fs = dta!2
return $ (dta!0, a, fmap (\(VSet s) -> s) fs)
{-# INLINE dataTypeInfo #-}
-- | The number of fields this datatype or channel has.
arityOfDataTypeClause :: Name -> EvaluationMonad Int
arityOfDataTypeClause n = do
(_, a, _) <- dataTypeInfo n
return a
-- | Returns true if the value is a complete field.
isCompleteField :: Value -> EvaluationMonad Bool
isCompleteField (v@(VDot vs)) =
case maybeNamedDot v of
Nothing -> return True
Just n -> do
arity <- arityOfDataTypeClause n
if arity == length vs -1 then
isCompleteField (last vs)
else return False
isCompleteField _ = return True
-- | Takes two values and dots then together appropriately.
combineDots :: SrcSpan -> Value -> Value -> EvaluationMonad Value
combineDots loc v1 v2 =
let
-- | Dots the given value onto the right of the given base, providing
-- the left hand value is a field.
maybeDotFieldOn :: Value -> Value -> EvaluationMonad (Maybe Value)
maybeDotFieldOn vbase v = do
fields <-
case maybeNamedDot vbase of
Just n -> do
(_, _, fs) <- dataTypeInfo n
let VDot (nd:_) = vbase
return $! S.cartesianProduct CartDot $
fromList [nd] : elems fs
Nothing -> return S.emptySet
dotNamedFieldOn (maybeNamedDot vbase) fields vbase v
dotNamedFieldOn :: Maybe Name -> ValueSet -> Value -> Value ->
EvaluationMonad (Maybe Value)
dotNamedFieldOn (Just n) allowedValues (VDot vs) v = do
let fieldCount = length vs -1
lastField = last vs
getField ix = splitFieldSet ix (VDot vs) allowedValues
b <- isCompleteField lastField
arity <- arityOfDataTypeClause n
if b then
if arity == fieldCount then return Nothing
else do
let newValue = VDot (vs++[v])
fieldSet = getField fieldCount
checkIsValidForField fieldSet newValue fieldCount v $
return $ Just newValue
else do
let fieldSet = getField (fieldCount-1)
vLast <- dotNamedFieldOn (maybeNamedDot lastField) fieldSet
lastField v
case vLast of
Nothing -> return Nothing
Just vLast -> do
let newValue = VDot (replaceLast vs vLast)
checkIsValidForField fieldSet newValue fieldCount vLast $
return $ Just newValue
dotNamedFieldOn Nothing _ _ _ = return Nothing
checkIsValidForField :: ValueSet -> Value -> Int ->
Value -> EvaluationMonad a -> EvaluationMonad a
checkIsValidForField allowedSet overallValue field v result = do
b <- isCompleteField v
if not b then result else do
if member v allowedSet then result
else throwError' $
dotIsNotValidMessage overallValue field v allowedSet loc
splitFieldSet :: Int -> Value -> ValueSet -> ValueSet
splitFieldSet ix v fieldSet =
case fastUnDotCartProduct fieldSet v of
Just restrictByField ->restrictByField!!(ix+1)
Nothing -> slowMatchDotPrefix (\ _ vs -> vs!!(ix+1)) fieldSet v
-- | Dots the two values together, ensuring that if either the left or
-- the right value is a dot list combines them into one dot list.
-- This function assumes that any data values are not meant to be split
-- apart.
dotAndReduce :: Value -> Value -> Value
-- We don't need to split v2 into fields because whenever we call
-- this function the second value is simply being dotted onto the right
-- and not put into a field of any sort
dotAndReduce v1 v2 = VDot (splitIntoFields v1 ++ [v2])
-- | Given a base value and the value of a field dots the field onto
-- the right of the base. Assumes that the value provided is a field.
dotFieldOn :: Value -> Value -> EvaluationMonad Value
dotFieldOn vBase vField = do
mv <- maybeDotFieldOn vBase vField
case mv of
Just v -> return v
Nothing -> return $ dotAndReduce vBase vField
-- | Split a value up into the values that could be used as fields.
splitIntoFields :: Value -> [Value]
splitIntoFields (v@(VDot (VDataType n:_))) = [v]
splitIntoFields (v@(VDot (VChannel n:_))) = [v]
splitIntoFields (VDot vs) = vs
splitIntoFields v = [v]
-- | Given a base value and a list of many fields dots the fields onto
-- the base. Assumes that the values provided are fields.
dotManyFieldsOn :: Value -> [Value] -> EvaluationMonad Value
dotManyFieldsOn v [] = return v
dotManyFieldsOn vBase (v:vs) = do
vBase' <- dotFieldOn vBase v
dotManyFieldsOn vBase' vs
in
-- Split v2 up into its composite fields and then dot them onto v1.
dotManyFieldsOn v1 (splitIntoFields v2)
-- | Returns an x such that ev.x has been extended by exactly one atomic field.
-- This could be inside a subfield or elsewhere.
oneFieldExtensions :: Value -> EvaluationMonad [Value]
oneFieldExtensions v =
let
exts :: [ValueSet] -> Value -> EvaluationMonad [Value]
exts fieldSets (VDot vs) = do
case maybeNamedDot (VDot vs) of
Nothing -> return [VDot []]
Just n -> do
let fieldCount = length vs -1
b <- isCompleteField (last vs)
if b then return $!
if length fieldSets == fieldCount then [VDot []]
else toList (fieldSets!!fieldCount)
else do
let field = fieldSets!!(fieldCount-1)
case fastUnDotCartProduct field (last vs) of
Just restrictByField ->
exts (tail restrictByField) (last vs)
Nothing -> return $! toList $ slowMatchDotPrefix
(\ i v -> v!!i) field (last vs)
exts _ _ = return [VDot []]
in do
case maybeNamedDot v of
Just n -> do
(_, _, fieldSets) <- dataTypeInfo n
exts (elems fieldSets) v
Nothing -> return [VDot []]
maybeNamedDot :: Value -> Maybe Name
maybeNamedDot (VDot (VChannel n : _)) = Just n
maybeNamedDot (VDot (VDataType n : _)) = Just n
maybeNamedDot _ = Nothing
-- | Takes a datatype or a channel value and then computes all x such that
-- ev.x is a full datatype/event. Each of the returned values is guaranteed
-- to be a VDot.
extensions :: Value -> EvaluationMonad [Value]
extensions v = extensionsSet v >>= return . toList
extensionsSet :: Value -> EvaluationMonad ValueSet
extensionsSet v = do
case maybeNamedDot v of
Nothing -> return S.emptySet
Just n -> do
b <- isCompleteField v
if b then return $! S.fromList [VDot []] else do
(_, _, fieldSets) <- dataTypeInfo n
sets <- extensionsSets (elems fieldSets) v
return $
case sets of
[s] -> s
sets -> S.cartesianProduct CartDot sets
-- | Takes a value and returns a set of fields such that ev.x is a full thing.
-- Further, the field sets are guaranteed to be representable as a full
-- carteisan product.
extensionsSets :: [ValueSet] -> Value -> EvaluationMonad [ValueSet]
extensionsSets fieldSets (VDot vs) = do
let fieldCount = length vs - 1
maybeWrap [v] = v
maybeWrap vs = VDot vs
-- Firstly, complete the last field in the current value (in case
-- it is only half formed).
exsLast <-
if fieldCount == 0 || not (isJust (maybeNamedDot (last vs))) then
return []
else do
b <- isCompleteField (last vs)
if b then return []
else do
let field = fieldSets!!(fieldCount-1)
case fastUnDotCartProduct field (last vs) of
Just restrictByField ->
extensionsSets (tail restrictByField) (last vs)
Nothing -> -- Need to do a slow scan
return $!
[slowMatchDotPrefix (\ i v -> maybeWrap (drop i v))
field (last vs)]
return $! exsLast ++ drop fieldCount fieldSets
extensionsSets _ _ = return []
-- | Given a set of dotted values, and a dotted value, scans the set of dotted
-- values and calls the specified function for each value that matches.
slowMatchDotPrefix :: (Int -> [Value] -> Value) -> ValueSet -> Value -> ValueSet
slowMatchDotPrefix f set v1 =
let
matches v2 | v2 `isProductionOf` v1 =
let VDot vs' = v2
VDot vs = v1
in [f (length vs) vs']
matches _ = []
in
fromList (concatMap matches (toList set))
-- | Given two dot lists, the second of which may be an incomplete dot-list,
-- returns True if the first is a production of the second.
isProductionOf :: Value -> Value -> Bool
isProductionOf (VDot (n1:fs1)) (VDot (n2:fs2)) =
n1 == n2 && length fs1 >= length fs2 && listIsProductionOf fs1 fs2
where
listIsProductionOf _ [] = True
listIsProductionOf [] _ = False
listIsProductionOf (f1:fs1) [f2] = f1 `isProductionOf` f2
listIsProductionOf (f1:fs1) (f2:fs2) =
f1 == f2 && listIsProductionOf fs1 fs2
isProductionOf v1 v2 = v1 == v2
-- | Takes a datatype or a channel value and computes v.x for all x that
-- complete the value.
productions :: Value -> EvaluationMonad [Value]
productions v = productionsSet v >>= return . toList
productionsSet :: Value -> EvaluationMonad ValueSet
productionsSet v = do
case maybeNamedDot v of
Nothing -> return S.emptySet
Just n -> do
b <- isCompleteField v
if b then return $! S.fromList [v] else do
(_, _, fieldSets) <- dataTypeInfo n
sets <- productionsSets (elems fieldSets) v
return $! S.cartesianProduct CartDot sets
productionsSets :: [ValueSet] -> Value -> EvaluationMonad [ValueSet]
productionsSets fieldSets (VDot vs) = do
let fieldCount = length vs - 1
psLast <-
if fieldCount == 0 then return []
else if not (isJust (maybeNamedDot (last vs))) then return []
else do
b <- isCompleteField (last vs)
if b then return []
else do
let field = fieldSets!!(fieldCount-1)
case fastUnDotCartProduct field (last vs) of
Just restrictByField -> do
sets <- productionsSets (tail restrictByField) (last vs)
return [S.cartesianProduct CartDot sets]
Nothing -> return
[slowMatchDotPrefix (\ _ -> VDot) field (last vs)]
let psSets = case psLast of
[] -> map (\v -> fromList [v]) vs
_ ->
-- We cannot express this as a simple cart product, as
-- the resulting item has dots at two levels. Thus,
-- dot together this lot and form an explicit set,
-- then we proceed as before
map (\v -> fromList [v]) (init vs) ++ psLast
return $! psSets ++ drop fieldCount fieldSets
productionsSets _ v = return []
takeFields :: Int -> [Value] -> EvaluationMonad ([Value], [Value])
takeFields 0 vs = return ([], vs)
takeFields 1 vs = do
(f, vs) <- takeFirstField False vs
return ([f], vs)
takeFields n vs = do
(f, vs') <- takeFirstField False vs
(fs, vs'') <- takeFields (n-1) vs'
return (f:fs, vs'')
takeFirstField :: Bool -> [Value] -> EvaluationMonad (Value, [Value])
takeFirstField True (VDataType n : vs) = return (VDataType n, vs)
takeFirstField True (VChannel n : vs) = return (VChannel n, vs)
takeFirstField False (VDataType n : vs) = do
(_, arity, fieldSets) <- dataTypeInfo n
(fs, vs) <- takeFields arity vs
return $ (VDot (VDataType n : fs), vs)
takeFirstField False (VChannel n : vs) = do
(_, arity, fieldSets) <- dataTypeInfo n
(fs, vs) <- takeFields arity vs
return $ (VDot (VChannel n : fs), vs)
takeFirstField forceSplit (v:vs) = return (v, vs)
-- | Takes a set of dotted values (i.e. a set of VDot _) and returns a list of
-- sets such that the cartesian product is equal to the original set.
--
-- This throws an error if the set cannot be decomposed.
splitIntoFields :: Bool -> Name -> ValueSet -> EvaluationMonad [ValueSet]
splitIntoFields forceSplit n vs = do
case unDotProduct vs of
Just ss -> return ss
Nothing -> manuallySplitValues forceSplit n vs (toList vs)
isDot :: Value -> Bool
isDot (VDot _ ) = True
isDot _ = False
manuallySplitValues :: Bool -> Name -> ValueSet -> [Value] ->
EvaluationMonad [ValueSet]
manuallySplitValues forceSplit n vs (values@(VDot fs : _)) = do
let extract (VDot vs) = vs
-- | Splits a dot list into the separate fields.
split :: [Value] -> EvaluationMonad [Value]
split [] = return []
split vs = do
(v, vs') <- takeFirstField forceSplit vs
ss <- split vs'
return $ v:ss
splitValues <- mapM (split . extract) (toList vs)
if splitValues == [] then return [] else do
let fieldCount = length (head splitValues)
combine [] = replicate fieldCount []
combine (vs:vss) = zipWith (:) vs (combine vss)
-- | The list of values such that cart producting them together should
-- yield the overall datatype.
cartProductFields :: [[Value]]
cartProductFields = combine splitValues
-- | Given a set, recursively checks that it is ok, and reconstruct the
-- set as a cart product.
recursivelySplit vs = do
if length vs > 0 && isDot (head vs)
&& length (extract (head vs)) > 1 then do
-- We've got a dotted field - check to see if this field is
-- recursively decomposable
sets <- splitIntoFields True n (fromList vs)
if length sets == 1 then return $ head sets
else return $ S.cartesianProduct S.CartDot sets
else return $! fromList vs
if or (map isMixedList cartProductFields) then
if forceSplit || length cartProductFields == 1 then return [vs]
else throwError $ setNotRectangularErrorMessage (nameDefinition n) vs
Nothing
else do
sets <- mapM recursivelySplit cartProductFields
let cartProduct =
if length sets == 1 && isDot (head (toList (head sets))) then do
-- Don't wrap with extra dots if we already have some
head sets
else S.cartesianProduct S.CartDot sets
if cartProduct /= vs then
if forceSplit then
return [vs]
else throwError $
setNotRectangularErrorMessage (nameDefinition n) vs
(Just cartProduct)
else return $ sets
manuallySplitValues _ _ vs _ = return [vs]
isMixedList :: [Value] -> Bool
isMixedList [] = False
isMixedList [x] = False
isMixedList (VInt _ : (xs@(VInt _ : _))) = isMixedList xs
isMixedList (VBool _ : (xs@(VBool _ : _))) = isMixedList xs
isMixedList (VChar _ : (xs@(VChar _ : _))) = isMixedList xs
isMixedList (VTuple t1 : (xs@(VTuple t2 : _))) =
let vs1 = elems t1
vs2 = elems t2
in length vs1 /= length vs2
|| or (zipWith (\ x y -> isMixedList [x,y]) vs1 vs2)
|| isMixedList xs
isMixedList (VDot vs1 : (xs@(VDot vs2 : _))) =
length vs1 /= length vs2
|| or (zipWith (\ x y -> isMixedList [x,y]) vs1 vs2)
|| isMixedList xs
isMixedList (VChannel _ : (xs@(VChannel _ : _))) = isMixedList xs
isMixedList (VDataType _ : (xs@(VDataType _ : _))) = isMixedList xs
isMixedList (VProc _ : (xs@(VProc _ : _))) = isMixedList xs
isMixedList (VList vs1 : (xs@(VList vs2 : _))) =
(length vs1 > 0 && length vs2 > 0 && isMixedList [head vs1, head vs2])
|| isMixedList xs
isMixedList (VSet s1 : (xs@(VSet s2 : _))) =
let vs1 = toList s1
vs2 = toList s2
in (length vs1 > 0 && length vs2 > 0 && isMixedList [head vs1, head vs2])
|| isMixedList xs
isMixedList _ = True
-- | Takes a set and returns a list of values xs such that
-- Union({productions(x) | x <- xs}) == xs. For example, if c is a channel of
-- type {0,1} then {c.0, c.1} would return [c].
--
-- This is primarily used for display purposes.
compressIntoEnumeratedSet :: ValueSet -> EvaluationMonad (Maybe [Value])
compressIntoEnumeratedSet vs =
let
haveAllOfLastField :: [[Value]] -> EvaluationMonad Bool
haveAllOfLastField ys = do
let n = case head (head ys) of
VDataType n -> n
VChannel n -> n
fieldIx = length (head ys) - 2
(_, _, fieldSets) <- dataTypeInfo n
if fromList (map last ys) == fieldSets!fieldIx then
-- All values are used
return True
else return False
splitGroup :: [[Value]] -> EvaluationMonad (Maybe [Value])
splitGroup ([_]:_) = return Nothing
splitGroup vs = do
b <- haveAllOfLastField vs
if b then
-- have everything, and inits are equal, so can compress.
-- Since the inits are equal just take the init of the first
-- item.
return $ Just $ init (head vs)
else return $ Nothing
forceRepeatablyCompress :: [[Value]] -> EvaluationMonad [Value]
forceRepeatablyCompress vs = do
mt <- repeatablyCompress vs
return $! case mt of
Just vs -> vs
Nothing -> map VDot vs
-- | Repeatably compresses the supplied values from the back, returning
-- the compressed set.
repeatablyCompress :: [[Value]] -> EvaluationMonad (Maybe [Value])
repeatablyCompress [] = return Nothing
repeatablyCompress vs = do
let initiallyEqual :: [[[Value]]]
initiallyEqual = groupBy (\ xs ys ->
head xs == head ys && init xs == init ys) $
sortBy (\ xs ys -> compare (head xs) (head ys)
`thenCmp` compare (init xs) (init ys)) vs
-- head is required above (consider [x]).
processNothing Nothing vss = map VDot vss
processNothing (Just _) vss = []
gs <- mapM splitGroup initiallyEqual
let vsDone = zipWith processNothing gs initiallyEqual
-- Now, repeatably compress the prefixes that were equal.
case catMaybes gs of
[] -> return Nothing
xs -> do
vsRecursive <- forceRepeatablyCompress xs
return $! Just (vsRecursive ++ concat vsDone)
in case toList vs of
[] -> return Nothing
(vs @ (VDot ((VChannel _) :_) : _)) ->
repeatablyCompress (map (\ (VDot xs) -> xs) vs)
_ -> return Nothing -- must be a set that we cannot handle
|
sashabu/libcspm
|
src/CSPM/Evaluator/Dot.hs
|
Haskell
|
bsd-3-clause
| 20,468
|
-- | Parsing argument-like things.
module Data.Attoparsec.Args (EscapingMode(..), argsParser) where
import Control.Applicative
import Data.Attoparsec.Text ((<?>))
import qualified Data.Attoparsec.Text as P
import Data.Attoparsec.Types (Parser)
import Data.Text (Text)
-- | Mode for parsing escape characters.
data EscapingMode
= Escaping
| NoEscaping
deriving (Show,Eq,Enum)
-- | A basic argument parser. It supports space-separated text, and
-- string quotation with identity escaping: \x -> x.
argsParser :: EscapingMode -> Parser Text [String]
argsParser mode = many (P.skipSpace *> (quoted <|> unquoted)) <*
P.skipSpace <* (P.endOfInput <?> "unterminated string")
where
unquoted = P.many1 naked
quoted = P.char '"' *> string <* P.char '"'
string = many (case mode of
Escaping -> escaped <|> nonquote
NoEscaping -> nonquote)
escaped = P.char '\\' *> P.anyChar
nonquote = P.satisfy (not . (=='"'))
naked = P.satisfy (not . flip elem ("\" " :: String))
|
hesselink/stack
|
src/Data/Attoparsec/Args.hs
|
Haskell
|
bsd-3-clause
| 1,096
|
{-# LANGUAGE ParallelListComp, OverloadedStrings #-}
module Main where
import Web.Scotty
import Graphics.Blank
import Control.Concurrent
import Control.Monad
import Data.Array
import Data.Maybe
-- import Data.Binary (decodeFile)
import System.Environment
import System.FilePath
import BreakthroughGame
import GenericGame
import ThreadLocal
import AgentGeneric
import MinimalNN
import qualified Data.HashMap as HashMap
import Text.Printf
data Fill = FillEmpty | FillP1 | FillP2
data BG = BGLight | BGDark | BGSelected | BGPossible deriving (Eq,Read,Show,Ord)
data DrawingBoard = DrawingBoard { getArrDB :: (Array (Int,Int) Field) }
data Field = Field { fFill :: Fill
, fBG :: BG
, fSuperBG :: Maybe BG
}
-- | enable feedback on moving mouse. works poorly with big latency links.
enableMouseMoveFeedback :: Bool
enableMouseMoveFeedback = False
-- | path where static directory resides
staticDataPath :: FilePath
staticDataPath = "."
-- game params
maxTiles, offset, side :: (Num a) => a
side = 50
maxTiles = 8
offset = 50
drawPointEv :: Event -> Canvas ()
drawPointEv e = do
case e of
Event _ (Just (x,y)) -> drawPoint x y
_ -> return ()
drawPoint :: Int -> Int -> Canvas ()
drawPoint x y = do
font "bold 20pt Mono"
textBaseline "middle"
textAlign "center"
strokeStyle "rgb(240, 124, 50)"
strokeText ("+",fromIntegral x, fromIntegral y)
return ()
bgToStyle BGLight = "rgb(218, 208, 199)"
bgToStyle BGDark = "rgb(134, 113, 92)"
bgToStyle BGSelected = "rgb(102,153,0)"
bgToStyle BGPossible = "rgb(153,204,0)"
drawField :: (Float,Float) -> Bool -> Field -> Canvas ()
drawField baseXY@(x,y) highlight field = do
let s2 = side/2
s4 = side/4
-- background
let actualBG = fromMaybe (fBG field) (fSuperBG field)
fillStyle (bgToStyle actualBG)
fillRect (x,y,side,side)
-- border
strokeStyle "rgb(10,10,10)"
strokeRect (x,y,side,side)
-- fill
let drawFill style1 style2 = do
save
beginPath
-- lineWidth 4
let px = x+s2
py = y+s2
arc (px,py, s4, 0, (2*pi), False)
custom $ unlines $ [
printf "var grd=c.createRadialGradient(%f,%f,3,%f,%f,10); " px py px py
,printf "grd.addColorStop(0,%s); " (show style1)
,printf "grd.addColorStop(1,%s); " (show style2)
,"c.fillStyle=grd; "
]
fill
restore
case (fFill field) of
FillEmpty -> return ()
FillP1 -> drawFill "rgb(250,250,250)" "rgb(240,240,240)"
FillP2 -> drawFill "rgb(50,50,50)" "rgb(40,40,40)"
-- highlight
when highlight $ do
strokeStyle "rgb(120, 210, 30)"
strokeRect (x+side*0.1,y+side*0.1,side*0.8,side*0.8)
return ()
positionToIndex :: (Int,Int) -> Maybe (Int,Int)
positionToIndex (px,py) = do
cx <- toCoord px
cy <- toCoord py
return (cx, cy)
where
toCoord val = case (val-offset) `div` side of
x | x < 0 -> Nothing
| x >= maxTiles -> Nothing
| otherwise -> Just x
drawFills :: [Fill] -> Canvas ()
drawFills boardFills = do
let pos = zip (zip boardFills (cycle [True,False,False]))
[ (((offset + x*side),(offset + y*side)),bg)
| y <- [0..maxTiles-1], x <- [0..maxTiles-1] | bg <- boardBackgrounds ]
mapM_ (\ ((f,hl),((x,y),bg)) -> drawField (fromIntegral x, fromIntegral y) hl (Field f bg Nothing)) pos
boardBackgrounds = let xs = (take maxTiles $ cycle [BGLight, BGDark]) in cycle (xs ++ reverse xs)
ixToBackground (x,y) = if ((x-y) `mod` 2) == 0 then BGLight else BGDark
newDemoBoard = DrawingBoard $ array ((0,0), ((maxTiles-1),(maxTiles-1)))
[ ((x,y),(Field f bg Nothing)) | y <- [0..maxTiles-1], x <- [0..maxTiles-1]
| bg <- boardBackgrounds
| f <- cycle [FillEmpty, FillP1, FillP2, FillP2, FillP1]
]
drawBoard maybeHighlightPos (DrawingBoard arr) = mapM_ (\ (pos,field) -> drawField (fi pos) (hl pos) field) (assocs arr)
where
hl p = Just p == maybeHighlightPos
fi (x,y) = (offset+side*(fromIntegral x), offset+side*(fromIntegral y))
drawBreakthroughGame :: Breakthrough -> DrawingBoard
drawBreakthroughGame br = let (w,h) = boardSize br
toFill Nothing = FillEmpty
toFill (Just P1) = FillP1
toFill (Just P2) = FillP2
getFill pos = toFill $ HashMap.lookup pos (board br)
arr = array ((0,0), (w-1,h-1))
[ ((x,y),(Field (getFill (x,y)) (ixToBackground (x,y)) Nothing)) | y <- [0..w-1], x <- [0..h-1]]
result = DrawingBoard arr
in result
data CanvasGameState = CanvasGameState { boardDrawn :: DrawingBoard
, lastHighlight :: (Maybe Position)
, boardState :: Breakthrough
, playerNow :: Player2
, allFinished :: Bool
}
makeCGS b p = CanvasGameState (drawBreakthroughGame b) Nothing b p False
drawUpdateCGS ctx cgs getPName = send ctx $ do
drawBoard (lastHighlight cgs) (boardDrawn cgs)
let p = playerNow cgs
drawCurrentPlayer p (getPName p)
let win = winner (boardState cgs)
case win of
Nothing -> return ()
Just w -> drawWinner w
return (cgs { allFinished = (win /= Nothing) })
p2Txt :: Player2 -> String
p2Txt P1 = "Player 1"
p2Txt P2 = "Player 2"
drawWinner w = do
let txt = p2Txt w ++ " wins the game!"
tpx = offset + (maxTiles * side / 2)
tpy = offset + (maxTiles * side / 2)
rpx = offset
rpy = offset
rdimx = maxTiles * side
rdimy = maxTiles * side
globalAlpha 0.75
fillStyle "gray"
fillRect (rpx,rpy,rdimx,rdimy)
globalAlpha 1
textBaseline "middle"
textAlign "center"
font "bold 20pt Sans"
strokeStyle (if w == P1 then "darkred" else "darkgreen")
strokeText (txt, tpx, tpy)
drawCurrentPlayer pl plName = do
-- put text
let txt = printf ("Current move: %s (%s)"::String) (p2Txt pl) plName
font "15pt Sans"
clearRect (0,0,1500,offset*0.9) -- fix for damaging board border
fillStyle "black"
fillText (txt, offset, offset/2)
-- put symbol on the left side
clearRect (0,0,offset*0.9,1500)
let px = offset/2
py = offset + (side * pside)
pside = 0.5 + if pl == P1 then 0 else (maxTiles-1)
pcol = if pl == P1 then "red" else "blue"
save
font "bold 20pt Mono"
textBaseline "middle"
textAlign "center"
strokeStyle "rgb(240, 124, 50)"
custom $ unlines $ [
printf "var grd=c.createRadialGradient(%f,%f,3,%f,%f,10); " px py px py
,printf "grd.addColorStop(0,%s); " (show pcol)
,"grd.addColorStop(1,\"white\"); "
,"c.strokeStyle=grd; "
]
strokeText ("+",px,py)
restore
main :: IO ()
main = do
-- crude command line parsing
args <- getArgs
let port = case args of
(x:_) -> read x
_ -> 3000
print ("port",port)
let dbn = case args of
(_:fn:_) -> fn
_ -> "assets/dbn.bin"
print ("dbn",dbn)
network <- MinimalNN.decodeFile dbn
-- apps
let app1 = ("/pvc", (pvc network))
app2 = ("/pvp", pvp)
apps <- mapM (\ (path, app) -> blankCanvasParamsScotty app staticDataPath False path) [app1, app2]
-- main page
let index = get "/" (file (staticDataPath </> "static" </> "global-index.html"))
-- launch server
scotty port (sequence_ (apps ++ [index]))
pvc :: TNetwork -> Context -> IO ()
pvc network context = do
let agent'0 = runThrLocMainIO (mkTimed "wtf3" network) :: IO (AgentTrace (AgentSimple TNetwork))
agent'1 = runThrLocMainIO (mkTimed "rnd" ()) :: IO (AgentTrace AgentRandom)
agent'2 = runThrLocMainIO (mkTimed "wtf2" 1000) :: IO (AgentTrace AgentMCTS)
-- agent'3 = runThrLocMainIO (mkTimed "tree" (network, 4)) :: IO (AgentTrace AgentGameTree)
agent'4 = runThrLocMainIO (mkTimed "wtf" (2, 50, network)) :: IO (AgentTrace (AgentParMCTS (AgentSimple TNetwork)))
-- let agent'0 = runThrLocMainIO (mkAgent network) :: IO ((AgentSimple TNetwork))
-- agent'1 = runThrLocMainIO (mkAgent ()) :: IO (AgentRandom)
-- agent'2 = runThrLocMainIO (mkAgent 1000) :: IO (AgentMCTS)
-- agent'3 = runThrLocMainIO (mkAgent (network, 4)) :: IO (AgentGameTree)
-- agent'4 = runThrLocMainIO (mkAgent (2, 50, network)) :: IO ((AgentParMCTS (AgentSimple TNetwork)))
agent <- agent'0
let initial = makeCGS br P1
br = freshGame (maxTiles,maxTiles) :: Breakthrough
getPlayerName P1 = "human"
getPlayerName P2 = agentName agent
drawCGS' cgs = drawUpdateCGS context cgs getPlayerName
var <- newMVar =<< drawCGS' initial
let drawMove mPos = modifyMVar_ var $ \ cgs -> if allFinished cgs then return cgs else do
let prevPos = lastHighlight cgs
when (mPos /= prevPos) (send context (drawBoard mPos (boardDrawn cgs)))
return (cgs { lastHighlight = mPos })
autoPlay cgs | allFinished cgs = return cgs
| otherwise = do
let board = boardState cgs
player = playerNow cgs
newBoard <- runThrLocMainIO (applyAgent agent board player)
drawCGS' (makeCGS newBoard (nextPlayer player))
clearSuperBG (Field f bg _) = (Field f bg Nothing)
lastSelect cgs = case filter (\ (pos,(Field _ _ sup)) -> sup == Just BGSelected) (assocs (getArrDB $ boardDrawn cgs)) of
[(pos,_)] -> Just pos
_ -> Nothing -- no matches or more than one match
clickSelect ix cgs = do
let DrawingBoard brd = boardDrawn cgs
brdClean = fmap clearSuperBG brd
brd' = accum (\ (Field f bg _) sup -> (Field f bg sup)) brdClean [(ix,(Just BGSelected))]
send context (drawBoard (Just ix) (DrawingBoard brd'))
return (cgs { boardDrawn = DrawingBoard brd' })
clickClear cgs = do
let DrawingBoard brd = boardDrawn cgs
brd' = fmap clearSuperBG brd
send context (drawBoard (lastHighlight cgs) (DrawingBoard brd'))
return (cgs { boardDrawn = DrawingBoard brd' })
drawClick Nothing = return ()
drawClick mPos@(Just sndPos@(x,y)) = modifyMVar_ var $ \ cgs -> if allFinished cgs then return cgs else do
let valid state = state `elem` moves (boardState cgs) (playerNow cgs)
case lastSelect cgs of
Nothing -> clickSelect sndPos cgs
Just fstPos | fstPos == sndPos -> clickClear cgs
| otherwise -> case applyMove (boardState cgs) (fstPos,sndPos) of
Nothing -> clickSelect sndPos cgs
Just newState | valid newState -> do
newCGS <- drawCGS' (makeCGS newState (nextPlayer (playerNow cgs)))
autoPlay newCGS
| otherwise -> clickSelect sndPos cgs
when enableMouseMoveFeedback $ do
moveQ <- events context MouseMove
void $ forkIO $ forever $ do
evnt <- readEventQueue moveQ
case jsMouse evnt of
Nothing -> return ()
Just xy -> do
drawMove (positionToIndex xy)
downQ <- events context MouseDown
forkIO $ forever $ do
evnt <- readEventQueue downQ
case jsMouse evnt of
Nothing -> return ()
Just xy -> do
drawClick (positionToIndex xy)
return ()
pvp :: Context -> IO ()
pvp context = do
let initial = makeCGS br P1
br = freshGame (maxTiles,maxTiles) :: Breakthrough
drawCGS' cgs = drawUpdateCGS context cgs (const ("human" :: String))
var <- newMVar =<< drawCGS' initial
let drawMove mPos = modifyMVar_ var $ \ cgs -> if allFinished cgs then return cgs else do
let prevPos = lastHighlight cgs
when (mPos /= prevPos) (send context (drawBoard mPos (boardDrawn cgs)))
return (cgs { lastHighlight = mPos })
clearSuperBG (Field f bg _) = (Field f bg Nothing)
lastSelect cgs = case filter (\ (pos,(Field _ _ sup)) -> sup == Just BGSelected) (assocs (getArrDB $ boardDrawn cgs)) of
[(pos,_)] -> Just pos
_ -> Nothing -- no matches or more than one match
clickSelect ix cgs = do
let DrawingBoard brd = boardDrawn cgs
brdClean = fmap clearSuperBG brd
brd' = accum (\ (Field f bg _) sup -> (Field f bg sup)) brdClean [(ix,(Just BGSelected))]
send context (drawBoard (Just ix) (DrawingBoard brd'))
return (cgs { boardDrawn = DrawingBoard brd' })
clickClear cgs = do
let DrawingBoard brd = boardDrawn cgs
brd' = fmap clearSuperBG brd
send context (drawBoard (lastHighlight cgs) (DrawingBoard brd'))
return (cgs { boardDrawn = DrawingBoard brd' })
drawClick Nothing = return ()
drawClick mPos@(Just sndPos@(x,y)) = modifyMVar_ var $ \ cgs -> if allFinished cgs then return cgs else do
let valid state = state `elem` moves (boardState cgs) (playerNow cgs)
case lastSelect cgs of
Nothing -> clickSelect sndPos cgs
Just fstPos | fstPos == sndPos -> clickClear cgs
| otherwise -> case applyMove (boardState cgs) (fstPos,sndPos) of
Nothing -> clickSelect sndPos cgs
Just newState | valid newState -> drawCGS' (makeCGS newState (nextPlayer (playerNow cgs)))
| otherwise -> clickSelect sndPos cgs
-- -- disabled: requires unreleased null-canvas-0.2.8
-- when True $ do
-- clickQ <- events context Click
-- void $ forkIO $ forever $ do
-- evnt <- readEventQueue clickQ
-- print ("click",evnt)
when enableMouseMoveFeedback $ do
moveQ <- events context MouseMove
void $ forkIO $ forever $ do
evnt <- readEventQueue moveQ
case jsMouse evnt of
Nothing -> return ()
Just xy -> drawMove (positionToIndex xy)
downQ <- events context MouseDown
forkIO $ forever $ do
evnt <- readEventQueue downQ
case jsMouse evnt of
Nothing -> return ()
Just xy -> drawClick (positionToIndex xy)
return ()
|
Tener/deeplearning-thesis
|
gui/breakthrough-gui.hs
|
Haskell
|
bsd-3-clause
| 14,979
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Serv.Api.Types
( EntityId(..)
, failure
, failureNoBody
, failureReqBody
, ResponseStatus(..)
, Response(..)
, success
, successNoBody
) where
import Control.Lens (mapped, (&), (?~))
-- import Data.Aeson
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..),
object, withObject, (.!=), (.:), (.:?), (.=))
import qualified Data.Swagger as Swagger
import Data.Text (Text)
import qualified Data.Text.Lazy as LT
import GHC.Generics
import Servant.API
import Servant.Swagger
-- | Entity Identifier
newtype EntityId = EntityId Int
deriving (Show, Eq, Ord, ToHttpApiData, FromHttpApiData, Generic)
instance FromJSON EntityId
instance ToJSON EntityId
instance Swagger.ToParamSchema EntityId
instance Swagger.ToSchema EntityId
type StatusCode = Int
type StatusDetails = Maybe LT.Text
-- | Response status
data ResponseStatus = ResponseStatus
{ code :: StatusCode
, details :: StatusDetails
} deriving (Show, Generic)
instance FromJSON ResponseStatus
instance ToJSON ResponseStatus where
toJSON (ResponseStatus code Nothing) = object [ "code" .= code
]
toJSON (ResponseStatus code details) = object [ "code" .= code
, "details" .= details
]
instance Swagger.ToSchema ResponseStatus where
declareNamedSchema proxy = Swagger.genericDeclareNamedSchema Swagger.defaultSchemaOptions proxy
& mapped.Swagger.schema.Swagger.description ?~ "Response status example"
& mapped.Swagger.schema.Swagger.example ?~ toJSON (ResponseStatus 0 (Just "Success"))
-- | Response body
data Response a = Response
{ body :: Maybe a
, status :: ResponseStatus
} deriving (Show, Generic)
instance (FromJSON a) => FromJSON (Response a) where
parseJSON =
withObject "Response" (\o ->
Response <$> ( o .:? "data")
<*> (o .: "status")
)
instance (ToJSON a) => ToJSON (Response a) where
toJSON (Response Nothing status) = object [ "status" .= status
]
toJSON (Response body status) = object [ "data" .= body
, "status" .= status
]
instance (Swagger.ToSchema a) => Swagger.ToSchema (Response a) where
declareNamedSchema proxy = Swagger.genericDeclareNamedSchema Swagger.defaultSchemaOptions proxy
& mapped.Swagger.schema.Swagger.description ?~ "Response example"
& mapped.Swagger.schema.Swagger.example ?~ toJSON successNoBody
mkResp :: (ToJSON a) => StatusCode -> StatusDetails -> Maybe a -> Response a
mkResp c d b = Response { body = b, status = ResponseStatus c d}
success b = mkResp 0 Nothing (Just b)
successNoBody :: Response LT.Text
successNoBody = mkResp 0 Nothing Nothing
failure b = mkResp 700 Nothing (Just b)
failureNoBody :: Response LT.Text
failureNoBody = mkResp 700 Nothing Nothing
--failureReqBody :: Response LT.Text
failureReqBody d = mkResp 701 (Just d) (Nothing :: Maybe LT.Text)
|
orangefiredragon/bear
|
src/Serv/Api/Types.hs
|
Haskell
|
bsd-3-clause
| 3,478
|
{-# LANGUAGE Unsafe, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Metrology.Unsafe
-- Copyright : (C) 2013 Richard Eisenberg
-- License : BSD-style (see LICENSE)
-- Maintainer : Richard Eisenberg (rae@cs.brynmawr.edu)
-- Stability : experimental
-- Portability : non-portable
--
-- This module exports the constructor of the 'Qu' type. This allows you
-- to write code that takes creates and reads quantities at will,
-- which may lead to dimension unsafety. Use at your peril.
--
-- This module also exports 'UnsafeQu', which is a simple wrapper around
-- 'Qu' that has 'Functor', etc., instances. The reason 'Qu' itself doesn't
-- have a 'Functor' instance is that it would be unit-unsafe, allowing you,
-- say, to add 1 to a quantity.... but 1 what? That's the problem. However,
-- a 'Functor' instance is likely useful, hence 'UnsafeQu'.
-----------------------------------------------------------------------------
module Data.Metrology.Unsafe (
-- * The 'Qu' type
Qu(..),
-- * 'UnsafeQu'
UnsafeQu(..)
) where
import Data.Metrology.Qu
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
import Data.Foldable
import Data.Traversable
#endif
-- | A basic wrapper around 'Qu' that has more instances.
newtype UnsafeQu d l n = UnsafeQu { qu :: Qu d l n }
instance Functor (UnsafeQu d l) where
fmap f (UnsafeQu (Qu x)) = UnsafeQu (Qu (f x))
instance Applicative (UnsafeQu d l) where
pure x = UnsafeQu (Qu x)
UnsafeQu (Qu f) <*> UnsafeQu (Qu x) = UnsafeQu (Qu (f x))
instance Foldable (UnsafeQu d l) where
foldMap f (UnsafeQu (Qu x)) = f x
instance Traversable (UnsafeQu d l) where
traverse f (UnsafeQu (Qu x)) = UnsafeQu . Qu <$> f x
|
goldfirere/units
|
units/Data/Metrology/Unsafe.hs
|
Haskell
|
bsd-3-clause
| 1,751
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
module Lucid.Ink.Internal where
import GHC.Exts (IsString(..))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Monoid ((<>))
data Orientation
= Vertical
| Horizontal
deriving (Eq,Ord,Show)
newtype Direction (o :: Orientation) = Direction
{ getDirection :: Text
} deriving (Eq,Ord,Show,IsString,Monoid)
newtype Size = Size
{ getSize :: Text
} deriving (Eq,Ord,Show,IsString,Monoid)
onAll_, onTiny_, onSmall_, onMedium_, onLarge_, onXLarge_ :: Size -> Text
onAll_ = sp . prefix "all" . getSize
onTiny_ = sp . prefix "tiny" . getSize
onSmall_ = sp . prefix "small" . getSize
onMedium_ = sp . prefix "medium" . getSize
onLarge_ = sp . prefix "large" . getSize
onXLarge_ = sp . prefix "xlarge" . getSize
auto_ :: Size
auto_ = "auto"
perc_ :: Int -> Size
perc_ = (<> "%") . gShow
getOrientation :: Orientation -> Text
getOrientation = \case
Vertical -> "vertical"
Horizontal -> "horizontal"
push_ :: Direction o -> Text
push_ = sp . prefix "push" . getDirection
align_ :: Direction Horizontal -> Text
align_ = sp . prefix "align" . getDirection
top_, middle_, bottom_ :: Direction Vertical
left_, center_, right_ :: Direction Horizontal
top_ = "top"
middle_ = "middle"
bottom_ = "bottom"
left_ = "left"
center_ = "center"
right_ = "right"
padding_ :: Text -> Text
padding_ = sp . postfix "padding"
space_ :: Text -> Text
space_ = sp . postfix "space"
ink_ :: Text -> Text
ink_ = sp . prefix "ink"
over_ :: Text -> Text
over_ = sp . prefix "over"
fw_ :: Int -> Text
fw_ = sp . prefix "fw" . tShow
tShow :: Show a => a -> Text
tShow = T.pack . show
gShow :: (Show a, IsString b) => a -> b
gShow = fromString . show
sp :: Text -> Text
sp t = " " <> t <> " "
prefix :: Text -> Text -> Text
prefix p s = p <> "-" <> s
postfix :: Text -> Text -> Text
postfix = flip prefix
|
kylcarte/ink-ui
|
src/Lucid/Ink/Internal.hs
|
Haskell
|
bsd-3-clause
| 2,010
|
{-# LANGUAGE CPP #-}
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.Internal.PQResultUtils
-- Copyright: (c) 2011 MailRank, Inc.
-- (c) 2011-2012 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <leon@melding-monads.com>
-- Stability: experimental
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.Internal.PQResultUtils
( finishQueryWith
, finishQueryWithV
, finishQueryWithVU
, getRowWith
) where
import Control.Exception as E
import Data.ByteString (ByteString)
import Data.Foldable (for_)
import Database.PostgreSQL.Simple.FromField (ResultError(..))
import Database.PostgreSQL.Simple.Ok
import Database.PostgreSQL.Simple.Types (Query(..))
import Database.PostgreSQL.Simple.Internal as Base hiding (result, row)
import Database.PostgreSQL.Simple.TypeInfo
import qualified Database.PostgreSQL.LibPQ as PQ
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as MVU
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State.Strict
finishQueryWith :: RowParser r -> Connection -> Query -> PQ.Result -> IO [r]
finishQueryWith parser conn q result = finishQueryWith' q result $ do
nrows <- PQ.ntuples result
ncols <- PQ.nfields result
forM' 0 (nrows-1) $ \row ->
getRowWith parser row ncols conn result
finishQueryWithV :: RowParser r -> Connection -> Query -> PQ.Result -> IO (V.Vector r)
finishQueryWithV parser conn q result = finishQueryWith' q result $ do
nrows <- PQ.ntuples result
let PQ.Row nrows' = nrows
ncols <- PQ.nfields result
mv <- MV.unsafeNew (fromIntegral nrows')
for_ [ 0 .. nrows-1 ] $ \row -> do
let PQ.Row row' = row
value <- getRowWith parser row ncols conn result
MV.unsafeWrite mv (fromIntegral row') value
V.unsafeFreeze mv
finishQueryWithVU :: VU.Unbox r => RowParser r -> Connection -> Query -> PQ.Result -> IO (VU.Vector r)
finishQueryWithVU parser conn q result = finishQueryWith' q result $ do
nrows <- PQ.ntuples result
let PQ.Row nrows' = nrows
ncols <- PQ.nfields result
mv <- MVU.unsafeNew (fromIntegral nrows')
for_ [ 0 .. nrows-1 ] $ \row -> do
let PQ.Row row' = row
value <- getRowWith parser row ncols conn result
MVU.unsafeWrite mv (fromIntegral row') value
VU.unsafeFreeze mv
finishQueryWith' :: Query -> PQ.Result -> IO a -> IO a
finishQueryWith' q result k = do
status <- PQ.resultStatus result
case status of
PQ.TuplesOk -> k
PQ.EmptyQuery -> queryErr "query: Empty query"
PQ.CommandOk -> queryErr "query resulted in a command response (did you mean to use `execute` or forget a RETURNING?)"
PQ.CopyOut -> queryErr "query: COPY TO is not supported"
PQ.CopyIn -> queryErr "query: COPY FROM is not supported"
#if MIN_VERSION_postgresql_libpq(0,9,3)
PQ.CopyBoth -> queryErr "query: COPY BOTH is not supported"
#endif
#if MIN_VERSION_postgresql_libpq(0,9,2)
PQ.SingleTuple -> queryErr "query: single-row mode is not supported"
#endif
PQ.BadResponse -> throwResultError "query" result status
PQ.NonfatalError -> throwResultError "query" result status
PQ.FatalError -> throwResultError "query" result status
where
queryErr msg = throwIO $ QueryError msg q
getRowWith :: RowParser r -> PQ.Row -> PQ.Column -> Connection -> PQ.Result -> IO r
getRowWith parser row ncols conn result = do
let rw = Row row result
let unCol (PQ.Col x) = fromIntegral x :: Int
okvc <- runConversion (runStateT (runReaderT (unRP parser) rw) 0) conn
case okvc of
Ok (val,col) | col == ncols -> return val
| otherwise -> do
vals <- forM' 0 (ncols-1) $ \c -> do
tinfo <- getTypeInfo conn =<< PQ.ftype result c
v <- PQ.getvalue result row c
return ( tinfo
, fmap ellipsis v )
throw (ConversionFailed
(show (unCol ncols) ++ " values: " ++ show vals)
Nothing
""
(show (unCol col) ++ " slots in target type")
"mismatch between number of columns to convert and number in target type")
Errors [] -> throwIO $ ConversionFailed "" Nothing "" "" "unknown error"
Errors [x] -> throwIO x
Errors xs -> throwIO $ ManyErrors xs
ellipsis :: ByteString -> ByteString
ellipsis bs
| B.length bs > 15 = B.take 10 bs `B.append` "[...]"
| otherwise = bs
forM' :: (Ord n, Num n) => n -> n -> (n -> IO a) -> IO [a]
forM' lo hi m = loop hi []
where
loop !n !as
| n < lo = return as
| otherwise = do
a <- m n
loop (n-1) (a:as)
{-# INLINE forM' #-}
|
tomjaguarpaw/postgresql-simple
|
src/Database/PostgreSQL/Simple/Internal/PQResultUtils.hs
|
Haskell
|
bsd-3-clause
| 5,167
|
{-# LANGUAGE LambdaCase, TupleSections, RecordWildCards #-}
module Transformations.Optimising.SparseCaseOptimisation where
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Functor.Foldable as Foldable
import Control.Monad.Trans.Except
import Grin.Grin
import Grin.Pretty
import Grin.TypeEnv
import Transformations.Util
sparseCaseOptimisation :: TypeEnv -> Exp -> Either String Exp
sparseCaseOptimisation TypeEnv{..} = runExcept . anaM builder where
builder :: Exp -> Except String (ExpF Exp)
builder = \case
-- TODO: reduce noise and redundancy
ECase scrut@(Var name) alts -> do
scrutType <- lookupExcept (notInTyEnv scrut) name _variable
let alts' = filterAlts scrutType alts
pure $ ECaseF scrut alts'
ECase scrut@(ConstTagNode tag _) alts -> do
let scrutType = T_NodeSet $ Map.singleton tag mempty
alts' = filterAlts scrutType alts
pure $ ECaseF scrut alts'
ECase scrut@(Lit l) alts -> do
let scrutType = typeOfLit l
alts' = filterAlts scrutType alts
pure $ ECaseF scrut alts'
ECase scrut@(Undefined ty) alts -> do
let alts' = filterAlts ty alts
pure $ ECaseF scrut alts'
ECase scrut _ -> throwE $ unsuppScrut scrut
exp -> pure . project $ exp
notInTyEnv v = "SCO: Variable " ++ show (PP v) ++ " not found in type env"
unsuppScrut scrut = "SCO: Unsupported case scrutinee: " ++ show (PP scrut)
filterAlts :: Type -> [Exp] -> [Exp]
filterAlts scrutTy alts =
[ alt
| alt@(Alt cpat body) <- alts
, possible scrutTy allPatTags cpat
] where allPatTags = Set.fromList [tag | Alt (NodePat tag _) _ <- alts]
possible :: Type -> Set Tag -> CPat -> Bool
possible (T_NodeSet nodeSet) allPatTags cpat = case cpat of
NodePat tag _args -> Map.member tag nodeSet
-- HINT: the default case is redundant if normal cases fully cover the domain
DefaultPat -> not $ null (Set.difference (Map.keysSet nodeSet) allPatTags)
_ -> False
possible ty@T_SimpleType{} _ cpat = case cpat of
LitPat lit -> ty == typeOfLit lit
DefaultPat -> True -- HINT: the value domain is unknown, it is not possible to prove if it overlaps or it is fully covered
_ -> False
possible ty _ _ = ty /= dead_t -- bypass everything else
|
andorp/grin
|
grin/src/Transformations/Optimising/SparseCaseOptimisation.hs
|
Haskell
|
bsd-3-clause
| 2,324
|
execSymZCFA :: Call -> StateSpace Sym_Delta ZCFA_AAM
execSymZCFA = exec Sym_Delta ZCFA_AAM
|
davdar/quals
|
writeup-old/sections/03AAMByExample/05Recovering0CFA/02Exec.hs
|
Haskell
|
bsd-3-clause
| 91
|
-----------------------------------------------------------------------------
-- |
-- Module : Tests.Simple
-- Copyright : (c)2011, Texas Instruments France
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : c-favergeon-borgialli@ti.com
-- Stability : provisional
-- Portability : portable
--
-- QuickCheck tests
--
-----------------------------------------------------------------------------
module Tests.Simple(
-- * Validation tests
runSimpleTests
) where
import Test.QuickCheck.Monadic
import Benchmark
import Test.QuickCheck
import TestTools
import Kernels
import Data.Bits(shiftL)
import Data.List(findIndex)
import Data.Int
{-
Properties to test
-}
-- | Test addition of a constant to a list of one float
floatTest :: Options -> Float -> Property
floatTest opts l = monadicIO $ do
run $ gpuRoundingMode opts
let a = l -- 4.384424 --a = -1.565178
c = 10.0
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D 1)) (simpleAdd (CLFloatArray [a]) c 1 (clFloatArrayOO 1))
let result = head . fromFloatResult $ (head r)
assert $ result ~= (a + c)
-- | Test addition of a constant to a list of float
add4Test :: Options -> [Float4] -> Property
add4Test opts l = (not . null) l ==> monadicIO $ do
run $ gpuRoundingMode opts
let nb = length l
d = (10.0,5.0,1.0,8.0)
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D nb)) (simpleAdd4 (CLFloat4Array l) d nb (clFloat4ArrayOO nb))
assert $ fromFloat4Result (head r) ~= map (vecAdd d) l
where
vecAdd (x0,y0,z0,t0) (x1,y1,z1,t1) = (x0+x1,y0+y1,z0+z1,t0+t1)
-- | Test addition of a constant to a list of float
addTest :: Options -> [Float] -> Property
addTest opts l = (not . null) l ==> monadicIO $ do
run $ gpuRoundingMode opts
let nb = length l
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D nb)) (simpleAdd (CLFloatArray l) 10.0 nb (clFloatArrayOO nb))
assert $ fromFloatResult (head r) ~= map (+ 10.0) l
-- | Test addition of a constant to a list of float
moveIntTest :: Options -> Property
moveIntTest opts =
forAll (choose (1,60)) $ \num -> do
let randomInt32 = (choose (-200,200) :: Gen Int) >>= return . fromIntegral
forAll (vectorOf (num*4) (randomInt32)) $ \l -> monadicIO $ do
let nb = num*4
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D num)) (simpleIntMove (CLIntArray l) nb (clIntArrayOO nb))
assert $ fromIntResult (head r) == l
-- | Test copy of a vector
moveTest :: Options -> [Float] -> Property
moveTest opts l = (not . null) l ==> monadicIO $ do
let nb = length l
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D nb)) (simpleMove (CLFloatArray l) nb (clFloatArrayOO nb))
assert $ fromFloatResult (head r) ~= l
complexMoveTest :: Options -> Property
complexMoveTest opts = do
forAll (choose (0,5)) $ \num -> do
let copiesInKernel = 1 `shiftL` num
i = 320 `div` copiesInKernel
forAll (vectorOf (copiesInKernel*i) (choose (-200.0,200.0))) $ \l -> do
let a = CLFloatArray l
monadicIO $ do
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D i)) (complexMove a num (clFloatArrayOO (copiesInKernel*i)))
assert $ fromFloatResult (head r) ~= l
-- | Test atensor product of two vectors
tensorTest :: Options -> [Float] -> Property
tensorTest opts l = (not . null) l ==> monadicIO $ do
run $ gpuRoundingMode opts
let nb = length l
r <- run $ onBoardOnlyData opts (simpleNDRange (size1D nb)) (simpleTensor nb (CLFloatArray l) (CLFloatArray l) (clFloatArrayOO nb))
--reference <- run $ mapM (withGPURounding . (\x -> x * x) . gpuF) $ l
assert $ fromFloatResult (head r) ~= map (\x -> x * x) l
-- | Test addition of a constant to a matrix
-- We generate a random width between 2 and 20
-- A random height between 2 and 20
-- A random list of width*height elements with the elements being random between -200 and 200.
addConstantMatrixTest :: Options -> Property
addConstantMatrixTest opts =
forAll (choose (2,20)) $ \cols ->
forAll (choose (2,20)) $ \rows ->
forAll (vectorOf (cols * rows) (choose (-200.0,200.0))) $ \l ->
classify (cols > rows) "cols > rows" $
classify (cols < rows) "cols < rows" $
classify (cols == rows) "cols == rows" $
monadicIO $ do
run $ gpuRoundingMode opts
let nb = length l
r <- run $ onBoardOnlyData opts (simpleNDRange (size2D cols rows))
(simpleAddConstantToMatrix cols (CLFloatArray l) 10.0 (clFloatArrayOO nb))
assert $ fromFloatResult (head r) ~= map (+ 10.0) l
{-
Test Driver
-}
-- | Test an OpenCL kernel
test :: Testable prop
=> Int -- ^ Max nb of tests
-> (Options -> prop) -- ^ Property to test
-> (Options -> IO ()) -- ^ Test
test n a = \opts -> quickCheckWith (stdArgs {maxSuccess=n}) (a opts)
-- | List of test categories and the tests
tests = [("SIMPLE TEST",[
("floatTest", test 20 floatTest)
, ("simpleIntAddTest",test 20 moveIntTest)
, ("addTest",test 20 addTest)
, ("add4Test",test 20 add4Test)
, ("moveTest",test 20 moveTest)
, ("complexMoveTest",test 20 complexMoveTest)
, ("tensorTest",test 20 tensorTest)
, ("addConstantMatrixTest",test 20 addConstantMatrixTest)
])
]
-- | Run a test with given title and options to connect to the server
runATest opts (title,a) = do
putStrLn title
a opts
putStrLn ""
-- | Run a test category
runACategory opts (title,tests) = do
putStrLn title
putStrLn ""
mapM_ (runATest opts) tests
-- | Run all tests
runSimpleTests opts = mapM_ (runACategory opts) tests
|
ChristopheF/OpenCLTestFramework
|
Client/Tests/Simple.hs
|
Haskell
|
bsd-3-clause
| 5,676
|
{-# LANGUAGE ScopedTypeVariables, TypeOperators, OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric, FlexibleInstances, QuasiQuotes #-}
{-# LANGUAGE CPP, FlexibleContexts, UndecidableInstances, RecordWildCards #-}
{-# LANGUAGE DeriveFunctor, LambdaCase, OverloadedStrings #-}
{-# LANGUAGE TupleSections, GeneralizedNewtypeDeriving #-}
#ifndef _SERVER_IS_MAIN_
module Server where
#endif
import Web.Scotty (ScottyM, ActionM, json)
import Control.Concurrent
import Data.Aeson.QQ
import Control.Monad.IO.Class
import Network.Wai.Handler.Warp
( defaultSettings
, openFreePort
, Port
)
import GHC.Generics
import Data.Aeson hiding (json)
import Data.Text (Text)
import qualified Web.Scotty as Scotty
import qualified Data.Text as T
import Data.Monoid
import Wrecker
import Wrecker.Runner
import Control.Concurrent.NextRef (NextRef)
import qualified Control.Concurrent.NextRef as NextRef
import qualified Control.Immortal as Immortal
import qualified Wrecker.Statistics as Wrecker
import qualified Network.Wai.Handler.Warp as Warp
import qualified Network.Wai as Wai
import Network.Socket (Socket)
import qualified Network.Socket as N
import Control.Exception
import Data.Maybe (listToMaybe)
import System.Environment
import Control.Applicative
data Envelope a = Envelope { value :: a }
deriving (Show, Eq, Generic)
instance ToJSON a => ToJSON (Envelope a)
rootRef :: Int -> Text
rootRef port = T.pack $ "http://localhost:" ++ show port
jsonE :: ToJSON a => a -> ActionM ()
jsonE = json . Envelope
data Root a = Root
{ root :: a
, products :: a
, cartsIndex :: a
, cartsIndexItems :: a
, usersIndex :: a
, login :: a
, checkout :: a
} deriving (Show, Eq, Functor)
type RootInt = Root Int
instance Applicative Root where
pure x = Root
{ root = x
, products = x
, login = x
, usersIndex = x
, cartsIndex = x
, cartsIndexItems = x
, checkout = x
}
f <*> x = Root
{ root = root f $ root x
, products = products f $ products x
, login = login f $ login x
, usersIndex = usersIndex f $ usersIndex x
, cartsIndex = cartsIndex f $ cartsIndex x
, cartsIndexItems = cartsIndexItems f $ cartsIndexItems x
, checkout = checkout f $ checkout x
}
app :: RootInt -> Port -> ScottyM ()
app Root {..} port = do
let host = rootRef port
Scotty.get "/root" $ do
liftIO $ threadDelay root
jsonE [aesonQQ|
{ "products" : #{host <> "/products" }
, "carts" : #{host <> "/carts" }
, "users" : #{host <> "/users" }
, "login" : #{host <> "/login" }
, "checkout" : #{host <> "/checkout" }
}
|]
Scotty.get "/products" $ do
liftIO $ threadDelay products
jsonE [aesonQQ|
[ #{host <> "/products/0"}
]
|]
Scotty.get "/product/:id" $ do
liftIO $ threadDelay products
jsonE [aesonQQ|
{ "summary" : "shirt" }
|]
Scotty.get "/carts" $ do
-- sleepDist gen carts
jsonE [aesonQQ|
[ #{host <> "/carts/0"}
]
|]
Scotty.get "/carts/:id" $ do
liftIO $ threadDelay cartsIndex
jsonE [aesonQQ|
{ "items" : #{host <> "/carts/0/items"}
}
|]
Scotty.post "/carts/:id/items" $ do
liftIO $ threadDelay cartsIndexItems
jsonE [aesonQQ|
#{host <> "/carts/0/items"}
|]
Scotty.get "/users" $ do
-- sleepDist gen users
jsonE [aesonQQ|
[ #{host <> "/users/0"}
]
|]
Scotty.get "/users/:id" $ do
liftIO $ threadDelay usersIndex
jsonE [aesonQQ|
{ "cart" : #{host <> "/carts/0"}
, "username" : "example"
}
|]
Scotty.post "/login" $ do
liftIO $ threadDelay login
jsonE [aesonQQ|
#{host <> "/users/0"}
|]
Scotty.post "/checkout" $ do
liftIO $ threadDelay checkout
jsonE ()
run :: RootInt -> IO (Port, Immortal.Thread, ThreadId, NextRef AllStats)
run = start Nothing
stop :: (Port, ThreadId, NextRef AllStats) -> IO AllStats
stop (_, threadId, ref) = do
killThread threadId
NextRef.readLast ref
toKey :: Wai.Request -> String
toKey x = case Wai.pathInfo x of
["root"] -> "/root"
["products"] -> "/products"
"carts" : _ : "items" : _ -> "/carts/0/items"
"carts" : _ : _ -> "/carts/0"
"users" : _ -> "/users/0"
["login"] -> "/login"
["checkout"] -> "/checkout"
_ -> error "FAIL! UNKNOWN REQUEST FOR EXAMPLE!"
recordMiddleware :: Recorder -> Wai.Application -> Wai.Application
recordMiddleware recorder waiApp req sendResponse
= record recorder (toKey req) $! waiApp req $ \res -> sendResponse res
getASocket :: Maybe Port -> IO (Port, Socket)
getASocket = \case
Just port -> do s <- N.socket N.AF_INET N.Stream N.defaultProtocol
localhost <- N.inet_addr "127.0.0.1"
N.bind s (N.SockAddrInet (fromIntegral port) localhost)
N.listen s 1000
return (port, s)
Nothing -> openFreePort
start :: Maybe Port -> RootInt -> IO ( Port
, Immortal.Thread
, ThreadId
, NextRef AllStats
)
start mport dist = do
(port, socket) <- getASocket mport
(ref, recorderThread, recorder) <- newStandaloneRecorder
scottyApp <- Scotty.scottyApp $ app dist port
threadId <- flip forkFinally (\_ -> N.close socket)
$ Warp.runSettingsSocket defaultSettings socket
$ recordMiddleware recorder
$ scottyApp
return (port, recorderThread, threadId, ref)
main :: IO ()
main = do
xs <- getArgs
let delay = maybe 0 read $ listToMaybe xs
(port, socket) <- getASocket $ Just 3000
(ref, recorderThread, recorder) <- newStandaloneRecorder
scottyApp <- Scotty.scottyApp $ app (pure delay) port
(Warp.runSettingsSocket defaultSettings socket
$ recordMiddleware recorder
$ scottyApp) `finally`
( do N.close socket
Immortal.stop recorderThread
allStats <- NextRef.readLast ref
putStrLn $ Wrecker.pprStats Nothing Path allStats
)
|
skedgeme/wrecker
|
examples/Server.hs
|
Haskell
|
bsd-3-clause
| 6,724
|
module Chipher where
import Control.Arrow
import Data.Char
import Data.List
type Keyword = String
charPairs :: Keyword -> String -> [(Char, Char)]
charPairs k s =
reverse . snd $
foldl'
(\ (k, acc) s ->
if s == ' ' then (k, (' ', ' ') : acc)
else
let (kh : kt) = k
in (kt, (kh, s) : acc)
)
(concat . repeat $ k, [])
s
ordPairs :: Keyword -> String -> [(Int, Int)]
ordPairs k s = map ((\k -> ord k - ord 'A') *** ord) $ charPairs k s
encode :: Keyword -> String -> String
encode k s =
let shifted =
map
(\(k, s) ->
let n = if s == 32 then 32 else s + k in
if n > ord 'Z' then n - (ord 'Z' - ord 'A') else n)
(ordPairs k s)
in map chr shifted
--in shifted
main :: IO ()
main = print $ encode "foo" "bar"
|
vasily-kirichenko/haskell-book
|
src/Chipher.hs
|
Haskell
|
bsd-3-clause
| 844
|
module ProjectEuler.Problem092 (solution092, genericSolution092) where
import Data.Digits
import Util
digitsSquareSum :: Integer -> Integer
digitsSquareSum = sum . map sq . digits 10
chainEndsWith :: Integer -> Integer
chainEndsWith x =
let next = digitsSquareSum x in
if next == 1 || next == 89
then next
else chainEndsWith next
genericSolution092 :: Integer -> Integer
genericSolution092 = toInteger . length . filter (== 89) . map chainEndsWith . enumFromTo 1
solution092 :: Integer
solution092 = genericSolution092 1e7
|
guillaume-nargeot/project-euler-haskell
|
src/ProjectEuler/Problem092.hs
|
Haskell
|
bsd-3-clause
| 564
|
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude
, BangPatterns
, MagicHash
, UnboxedTuples
#-}
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.ForeignPtr
-- Copyright : (c) The University of Glasgow, 1992-2003
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- GHC's implementation of the 'ForeignPtr' data type.
--
-----------------------------------------------------------------------------
module GHC.ForeignPtr
(
ForeignPtr(..),
ForeignPtrContents(..),
FinalizerPtr,
FinalizerEnvPtr,
newForeignPtr_,
mallocForeignPtr,
mallocPlainForeignPtr,
mallocForeignPtrBytes,
mallocPlainForeignPtrBytes,
mallocForeignPtrAlignedBytes,
mallocPlainForeignPtrAlignedBytes,
addForeignPtrFinalizer,
addForeignPtrFinalizerEnv,
touchForeignPtr,
unsafeForeignPtrToPtr,
castForeignPtr,
newConcForeignPtr,
addForeignPtrConcFinalizer,
finalizeForeignPtr
) where
import Foreign.Storable
import Data.Foldable ( sequence_ )
import Data.Typeable
import GHC.Show
import GHC.Base
import GHC.IORef
import GHC.STRef ( STRef(..) )
import GHC.Ptr ( Ptr(..), FunPtr(..) )
-- |The type 'ForeignPtr' represents references to objects that are
-- maintained in a foreign language, i.e., that are not part of the
-- data structures usually managed by the Haskell storage manager.
-- The essential difference between 'ForeignPtr's and vanilla memory
-- references of type @Ptr a@ is that the former may be associated
-- with /finalizers/. A finalizer is a routine that is invoked when
-- the Haskell storage manager detects that - within the Haskell heap
-- and stack - there are no more references left that are pointing to
-- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
-- routines in the foreign language that free the resources bound by
-- the foreign object.
--
-- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
-- type argument of 'ForeignPtr' should normally be an instance of
-- class 'Storable'.
--
data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
deriving Typeable
-- we cache the Addr# in the ForeignPtr object, but attach
-- the finalizer to the IORef (or the MutableByteArray# in
-- the case of a MallocPtr). The aim of the representation
-- is to make withForeignPtr efficient; in fact, withForeignPtr
-- should be just as efficient as unpacking a Ptr, and multiple
-- withForeignPtrs can share an unpacked ForeignPtr. Note
-- that touchForeignPtr only has to touch the ForeignPtrContents
-- object, because that ensures that whatever the finalizer is
-- attached to is kept alive.
data Finalizers
= NoFinalizers
| CFinalizers (Weak# ())
| HaskellFinalizers [IO ()]
data ForeignPtrContents
= PlainForeignPtr !(IORef Finalizers)
| MallocPtr (MutableByteArray# RealWorld) !(IORef Finalizers)
| PlainPtr (MutableByteArray# RealWorld)
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
-- |A finalizer is represented as a pointer to a foreign function that, at
-- finalisation time, gets as an argument a plain pointer variant of the
-- foreign pointer that the finalizer is associated with.
--
-- Note that the foreign function /must/ use the @ccall@ calling convention.
--
type FinalizerPtr a = FunPtr (Ptr a -> IO ())
type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
--
-- ^Turns a plain memory reference into a foreign object by
-- associating a finalizer - given by the monadic operation - with the
-- reference. The storage manager will start the finalizer, in a
-- separate thread, some time after the last reference to the
-- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
-- in fact there is no guarantee that the finalizer will eventually
-- run at all.
--
-- Note that references from a finalizer do not necessarily prevent
-- another object from being finalized. If A's finalizer refers to B
-- (perhaps using 'touchForeignPtr', then the only guarantee is that
-- B's finalizer will never be started before A's. If both A and B
-- are unreachable, then both finalizers will start together. See
-- 'touchForeignPtr' for more on finalizer ordering.
--
newConcForeignPtr p finalizer
= do fObj <- newForeignPtr_ p
addForeignPtrConcFinalizer fObj finalizer
return fObj
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
-- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
-- will be released automatically when the 'ForeignPtr' is discarded.
--
-- 'mallocForeignPtr' is equivalent to
--
-- > do { p <- malloc; newForeignPtr finalizerFree p }
--
-- although it may be implemented differently internally: you may not
-- assume that the memory returned by 'mallocForeignPtr' has been
-- allocated with 'Foreign.Marshal.Alloc.malloc'.
--
-- GHC notes: 'mallocForeignPtr' has a heavily optimised
-- implementation in GHC. It uses pinned memory in the garbage
-- collected heap, so the 'ForeignPtr' does not require a finalizer to
-- free the memory. Use of 'mallocForeignPtr' and associated
-- functions is strongly recommended in preference to 'newForeignPtr'
-- with a finalizer.
--
mallocForeignPtr = doMalloc undefined
where doMalloc :: Storable b => b -> IO (ForeignPtr b)
doMalloc a
| I# size < 0 = error "mallocForeignPtr: size must be >= 0"
| otherwise = do
r <- newIORef NoFinalizers
IO $ \s ->
case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
(# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
(MallocPtr mbarr# r) #)
}
where !(I# size) = sizeOf a
!(I# align) = alignment a
-- | This function is similar to 'mallocForeignPtr', except that the
-- size of the memory required is given explicitly as a number of bytes.
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes size | size < 0 =
error "mallocForeignPtrBytes: size must be >= 0"
mallocForeignPtrBytes (I# size) = do
r <- newIORef NoFinalizers
IO $ \s ->
case newPinnedByteArray# size s of { (# s', mbarr# #) ->
(# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
(MallocPtr mbarr# r) #)
}
-- | This function is similar to 'mallocForeignPtrBytes', except that the
-- size and alignment of the memory required is given explicitly as numbers of
-- bytes.
mallocForeignPtrAlignedBytes :: Int -> Int -> IO (ForeignPtr a)
mallocForeignPtrAlignedBytes size _align | size < 0 =
error "mallocForeignPtrAlignedBytes: size must be >= 0"
mallocForeignPtrAlignedBytes (I# size) (I# align) = do
r <- newIORef NoFinalizers
IO $ \s ->
case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
(# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
(MallocPtr mbarr# r) #)
}
-- | Allocate some memory and return a 'ForeignPtr' to it. The memory
-- will be released automatically when the 'ForeignPtr' is discarded.
--
-- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
-- implementation in GHC. It uses pinned memory in the garbage
-- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
-- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
-- It is not possible to add a finalizer to a ForeignPtr created with
-- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
-- only inside Haskell (such as those created for packed strings).
-- Attempts to add a finalizer to a ForeignPtr created this way, or to
-- finalize such a pointer, will throw an exception.
--
mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
mallocPlainForeignPtr = doMalloc undefined
where doMalloc :: Storable b => b -> IO (ForeignPtr b)
doMalloc a
| I# size < 0 = error "mallocForeignPtr: size must be >= 0"
| otherwise = IO $ \s ->
case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
(# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
(PlainPtr mbarr#) #)
}
where !(I# size) = sizeOf a
!(I# align) = alignment a
-- | This function is similar to 'mallocForeignPtrBytes', except that
-- the internally an optimised ForeignPtr representation with no
-- finalizer is used. Attempts to add a finalizer will cause an
-- exception to be thrown.
mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocPlainForeignPtrBytes size | size < 0 =
error "mallocPlainForeignPtrBytes: size must be >= 0"
mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
case newPinnedByteArray# size s of { (# s', mbarr# #) ->
(# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
(PlainPtr mbarr#) #)
}
-- | This function is similar to 'mallocForeignPtrAlignedBytes', except that
-- the internally an optimised ForeignPtr representation with no
-- finalizer is used. Attempts to add a finalizer will cause an
-- exception to be thrown.
mallocPlainForeignPtrAlignedBytes :: Int -> Int -> IO (ForeignPtr a)
mallocPlainForeignPtrAlignedBytes size _align | size < 0 =
error "mallocPlainForeignPtrAlignedBytes: size must be >= 0"
mallocPlainForeignPtrAlignedBytes (I# size) (I# align) = IO $ \s ->
case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
(# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
(PlainPtr mbarr#) #)
}
addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
-- ^This function adds a finalizer to the given foreign object. The
-- finalizer will run /before/ all other finalizers for the same
-- object which have already been registered.
addForeignPtrFinalizer (FunPtr fp) (ForeignPtr p c) = case c of
PlainForeignPtr r -> f r >> return ()
MallocPtr _ r -> f r >> return ()
_ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
where
f r = insertCFinalizer r fp 0# nullAddr# p
addForeignPtrFinalizerEnv ::
FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
-- ^ Like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
-- passed an additional environment parameter to be passed to the
-- finalizer. The environment passed to the finalizer is fixed by the
-- second argument to 'addForeignPtrFinalizerEnv'
addForeignPtrFinalizerEnv (FunPtr fp) (Ptr ep) (ForeignPtr p c) = case c of
PlainForeignPtr r -> f r >> return ()
MallocPtr _ r -> f r >> return ()
_ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
where
f r = insertCFinalizer r fp 1# ep p
addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
-- ^This function adds a finalizer to the given @ForeignPtr@. The
-- finalizer will run /before/ all other finalizers for the same
-- object which have already been registered.
--
-- This is a variant of @addForeignPtrFinalizer@, where the finalizer
-- is an arbitrary @IO@ action. When it is invoked, the finalizer
-- will run in a new thread.
--
-- NB. Be very careful with these finalizers. One common trap is that
-- if a finalizer references another finalized value, it does not
-- prevent that value from being finalized. In particular, 'Handle's
-- are finalized objects, so a finalizer should not refer to a 'Handle'
-- (including @stdout@, @stdin@ or @stderr@).
--
addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer =
addForeignPtrConcFinalizer_ c finalizer
addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()
addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do
noFinalizers <- insertHaskellFinalizer r finalizer
if noFinalizers
then IO $ \s ->
case r of { IORef (STRef r#) ->
case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, _ #) ->
(# s1, () #) }}
else return ()
addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
noFinalizers <- insertHaskellFinalizer r finalizer
if noFinalizers
then IO $ \s ->
case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
(# s1, _ #) -> (# s1, () #)
else return ()
addForeignPtrConcFinalizer_ _ _ =
error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
insertHaskellFinalizer :: IORef Finalizers -> IO () -> IO Bool
insertHaskellFinalizer r f = do
!wasEmpty <- atomicModifyIORef r $ \finalizers -> case finalizers of
NoFinalizers -> (HaskellFinalizers [f], True)
HaskellFinalizers fs -> (HaskellFinalizers (f:fs), False)
_ -> noMixingError
return wasEmpty
-- | A box around Weak#, private to this module.
data MyWeak = MyWeak (Weak# ())
insertCFinalizer ::
IORef Finalizers -> Addr# -> Int# -> Addr# -> Addr# -> IO ()
insertCFinalizer r fp flag ep p = do
MyWeak w <- ensureCFinalizerWeak r
IO $ \s -> case addCFinalizerToWeak# fp p flag ep w s of
(# s1, 1# #) -> (# s1, () #)
-- Failed to add the finalizer because some other thread
-- has finalized w by calling foreignPtrFinalizer. We retry now.
-- This won't be an infinite loop because that thread must have
-- replaced the content of r before calling finalizeWeak#.
(# s1, _ #) -> unIO (insertCFinalizer r fp flag ep p) s1
ensureCFinalizerWeak :: IORef Finalizers -> IO MyWeak
ensureCFinalizerWeak ref@(IORef (STRef r#)) = do
fin <- readIORef ref
case fin of
CFinalizers weak -> return (MyWeak weak)
HaskellFinalizers{} -> noMixingError
NoFinalizers -> IO $ \s ->
case mkWeakNoFinalizer# r# () s of { (# s1, w #) ->
case atomicModifyMutVar# r# (update w) s1 of
{ (# s2, (weak, needKill ) #) ->
if needKill
then case finalizeWeak# w s2 of { (# s3, _, _ #) ->
(# s3, weak #) }
else (# s2, weak #) }}
where
update _ fin@(CFinalizers w) = (fin, (MyWeak w, True))
update w NoFinalizers = (CFinalizers w, (MyWeak w, False))
update _ _ = noMixingError
noMixingError :: a
noMixingError = error $
"GHC.ForeignPtr: attempt to mix Haskell and C finalizers " ++
"in the same ForeignPtr"
foreignPtrFinalizer :: IORef Finalizers -> IO ()
foreignPtrFinalizer r = do
fs <- atomicModifyIORef r $ \fs -> (NoFinalizers, fs) -- atomic, see #7170
case fs of
NoFinalizers -> return ()
CFinalizers w -> IO $ \s -> case finalizeWeak# w s of
(# s1, 1#, f #) -> f s1
(# s1, _, _ #) -> (# s1, () #)
HaskellFinalizers actions -> sequence_ actions
newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
-- ^Turns a plain memory reference into a foreign pointer that may be
-- associated with finalizers by using 'addForeignPtrFinalizer'.
newForeignPtr_ (Ptr obj) = do
r <- newIORef NoFinalizers
return (ForeignPtr obj (PlainForeignPtr r))
touchForeignPtr :: ForeignPtr a -> IO ()
-- ^This function ensures that the foreign object in
-- question is alive at the given place in the sequence of IO
-- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
-- does a 'touchForeignPtr' after it
-- executes the user action.
--
-- Note that this function should not be used to express dependencies
-- between finalizers on 'ForeignPtr's. For example, if the finalizer
-- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
-- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
-- for @F2@ is never started before the finalizer for @F1@. They
-- might be started together if for example both @F1@ and @F2@ are
-- otherwise unreachable, and in that case the scheduler might end up
-- running the finalizer for @F2@ first.
--
-- In general, it is not recommended to use finalizers on separate
-- objects with ordering constraints between them. To express the
-- ordering robustly requires explicit synchronisation using @MVar@s
-- between the finalizers, but even then the runtime sometimes runs
-- multiple finalizers sequentially in a single thread (for
-- performance reasons), so synchronisation between finalizers could
-- result in artificial deadlock. Another alternative is to use
-- explicit reference counting.
--
touchForeignPtr (ForeignPtr _ r) = touch r
touch :: ForeignPtrContents -> IO ()
touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
-- ^This function extracts the pointer component of a foreign
-- pointer. This is a potentially dangerous operations, as if the
-- argument to 'unsafeForeignPtrToPtr' is the last usage
-- occurrence of the given foreign pointer, then its finalizer(s) will
-- be run, which potentially invalidates the plain pointer just
-- obtained. Hence, 'touchForeignPtr' must be used
-- wherever it has to be guaranteed that the pointer lives on - i.e.,
-- has another usage occurrence.
--
-- To avoid subtle coding errors, hand written marshalling code
-- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
-- than combinations of 'unsafeForeignPtrToPtr' and
-- 'touchForeignPtr'. However, the latter routines
-- are occasionally preferred in tool generated marshalling code.
unsafeForeignPtrToPtr (ForeignPtr fo _) = Ptr fo
castForeignPtr :: ForeignPtr a -> ForeignPtr b
-- ^This function casts a 'ForeignPtr'
-- parameterised by one type into another type.
castForeignPtr f = unsafeCoerce# f
-- | Causes the finalizers associated with a foreign pointer to be run
-- immediately.
finalizeForeignPtr :: ForeignPtr a -> IO ()
finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
finalizeForeignPtr (ForeignPtr _ foreignPtr) = foreignPtrFinalizer refFinalizers
where
refFinalizers = case foreignPtr of
(PlainForeignPtr ref) -> ref
(MallocPtr _ ref) -> ref
PlainPtr _ ->
error "finalizeForeignPtr PlainPtr"
|
spacekitteh/smcghc
|
libraries/base/GHC/ForeignPtr.hs
|
Haskell
|
bsd-3-clause
| 18,737
|
module Main where
import Control.Applicative
import Evaluate
import Parser.AST
import Parser.RPN
import Pipes
import qualified Pipes.Prelude as P
import System.IO
import Text.Parsec.Error (errorMessages, messageString)
evaluatePrint :: Consumer String IO ()
evaluatePrint = do
lift $ putStr "> " >> hFlush stdout
str <- await
lift $ case evaluate <$> parseRpn str of
Left err -> print err
Right (IntLit i) -> print i
Right (DoubleLit d) -> print d
Right ast -> print ast
evaluatePrint
main :: IO ()
main = runEffect $ P.stdinLn >-> evaluatePrint
|
lightquake/sym
|
REPL.hs
|
Haskell
|
bsd-3-clause
| 691
|
{-# LANGUAGE OverloadedStrings, Rank2Types, PatternGuards #-}
module Haste.Config (
Config (..), AppStart, def, stdJSLibs, startCustom, fastMultiply,
safeMultiply, debugLib) where
import Data.JSTarget
import Control.Shell (replaceExtension, (</>))
import Data.ByteString.Builder
import Data.Monoid
import Haste.Environment
import Outputable (Outputable)
import Data.Default
import Data.List (stripPrefix, nub)
type AppStart = Builder -> Builder
stdJSLibs :: [FilePath]
stdJSLibs = map (jsDir </>) [
"rts.js", "floatdecode.js", "stdlib.js", "jsstring.js", "endian.js",
"MVar.js", "StableName.js", "Integer.js", "Int64.js", "md5.js", "array.js",
"pointers.js", "cheap-unicode.js", "Canvas.js", "Handle.js", "Weak.js",
"Foreign.js"
]
debugLib :: FilePath
debugLib = jsDir </> "debug.js"
-- | Execute the program as soon as it's loaded into memory.
-- Evaluate the result of applying main, as we might get a thunk back if
-- we're doing TCE. This is so cheap, small and non-intrusive we might
-- as well always do it this way, to simplify the config a bit.
startASAP :: AppStart
startASAP mainSym =
mainSym <> "();"
-- | Launch the application using a custom command.
startCustom :: String -> AppStart
startCustom "onload" = startOnLoadComplete
startCustom "asap" = startASAP
startCustom "onexec" = startASAP
startCustom str = insertSym str
-- | Replace the first occurrence of $HASTE_MAIN with Haste's entry point
-- symbol.
insertSym :: String -> AppStart
insertSym [] _ = stringUtf8 ""
insertSym str sym
| Just r <- stripPrefix "$HASTE_MAIN" str = sym <> stringUtf8 r
| (l,r) <- span (/= '$') str = stringUtf8 l <> insertSym r sym
-- | Execute the program when the document has finished loading.
startOnLoadComplete :: AppStart
startOnLoadComplete mainSym =
"window.onload = " <> mainSym <> ";"
-- | Int op wrapper for strictly 32 bit (|0).
strictly32Bits :: Exp -> Exp
strictly32Bits = flip (binOp BitOr) (litN 0)
-- | Safe Int multiplication.
safeMultiply :: Exp -> Exp -> Exp
safeMultiply a b = callForeign "imul" [a, b]
-- | Fast but unsafe Int multiplication.
fastMultiply :: Exp -> Exp -> Exp
fastMultiply = binOp Mul
-- | Compiler configuration.
data Config = Config {
-- | Runtime files to dump into the JS blob.
rtsLibs :: [FilePath],
-- | Path to directory where system jsmods are located.
libPaths :: [FilePath],
-- | Write all jsmods to this path.
targetLibPath :: FilePath,
-- | A function that takes the main symbol as its input and outputs the
-- code that starts the program.
appStart :: AppStart,
-- | Wrap the program in its own namespace?
wrapProg :: Bool,
-- | Options to the pretty printer.
ppOpts :: PPOpts,
-- | A function that takes the name of the a target as its input and
-- outputs the name of the file its JS blob should be written to.
outFile :: Config -> String -> String,
-- | Link the program?
performLink :: Bool,
-- | A function to call on each Int arithmetic primop.
wrapIntMath :: Exp -> Exp,
-- | Operation to use for Int multiplication.
multiplyIntOp :: Exp -> Exp -> Exp,
-- | Be verbose about warnings, etc.?
verbose :: Bool,
-- | Perform optimizations over the whole program at link time?
wholeProgramOpts :: Bool,
-- | Allow the possibility that some tail recursion may not be optimized
-- in order to gain slightly smaller code?
sloppyTCE :: Bool,
-- | Turn on run-time tracing of primops?
tracePrimops :: Bool,
-- | Run the entire thing through Google Closure when done?
useGoogleClosure :: Maybe FilePath,
-- | Extra flags for Google Closure to take?
useGoogleClosureFlags :: [String],
-- | Any external Javascript to link into the JS bundle.
jsExternals :: [FilePath],
-- | Produce a skeleton HTML file containing the program rather than a
-- JS file.
outputHTML :: Bool,
-- | GHC DynFlags used for STG generation.
-- Currently only used for printing StgSyn values.
showOutputable :: forall a. Outputable a => a -> String,
-- | Which module contains the program's main function?
-- Defaults to Just ("main", "Main")
mainMod :: Maybe (String, String),
-- | Perform optimizations.
-- Defaults to True.
optimize :: Bool,
-- | Emit @"use strict";@ declaration. Does not affect minification, but
-- *does* affect any external JS.
-- Defaults to True.
useStrict :: Bool
}
-- | Default compiler configuration.
defConfig :: Config
defConfig = Config {
rtsLibs = stdJSLibs,
libPaths = nub [jsmodUserDir, jsmodSysDir],
targetLibPath = ".",
appStart = startOnLoadComplete,
wrapProg = False,
ppOpts = def,
outFile = \cfg f -> let ext = if outputHTML cfg
then "html"
else "js"
in replaceExtension f ext,
performLink = True,
wrapIntMath = strictly32Bits,
multiplyIntOp = safeMultiply,
verbose = False,
wholeProgramOpts = False,
sloppyTCE = False,
tracePrimops = False,
useGoogleClosure = Nothing,
useGoogleClosureFlags = [],
jsExternals = [],
outputHTML = False,
showOutputable = const "No showOutputable defined in config!",
mainMod = Just ("main", "Main"),
optimize = True,
useStrict = True
}
instance Default Config where
def = defConfig
|
akru/haste-compiler
|
src/Haste/Config.hs
|
Haskell
|
bsd-3-clause
| 5,667
|
-------------------------------------------------------------------------
--
-- Main.hs
--
-- The main module of the Huffman example
--
-- (c) Addison-Wesley, 1996-2011.
--
-------------------------------------------------------------------------
-- The main module of the Huffman example
module Main (main, codeMessage, decodeMessage, codes, codeTable ) where
import Types ( Tree(Leaf,Node), Bit(L,R), HCode , Table )
import Coding ( codeMessage, decodeMessage )
import MakeCode ( codes, codeTable )
main = print decoded
-- Examples
-- ^^^^^^^^
-- The coding table generated from the text "there is a green hill".
tableEx :: Table
tableEx = codeTable (codes "there is a green hill")
-- The Huffman tree generated from the text "there is a green hill",
-- from which tableEx is produced by applying codeTable.
treeEx :: Tree
treeEx = codes "there is a green hill"
-- A message to be coded.
message :: String
message = "there are green hills here"
-- The message in code.
coded :: HCode
coded = codeMessage tableEx message
-- The coded message decoded.
decoded :: String
decoded = decodeMessage treeEx coded
|
Numberartificial/workflow
|
snipets/src/Craft/Chapter15/Main.hs
|
Haskell
|
mit
| 1,168
|
-- | Response types used by the security feature
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Distribution.Server.Features.Security.ResponseContentTypes (
TUFFile(..)
, mkTUFFile
, IsTUFFile(..)
, Timestamp(..)
, Snapshot(..)
, Root(..)
, Mirrors(..)
) where
-- stdlib
import Happstack.Server
import Control.DeepSeq
import Data.Typeable
import Data.SafeCopy
import qualified Data.ByteString.Lazy as BS.Lazy
-- hackage
import Distribution.Server.Features.Security.FileInfo
import Distribution.Server.Features.Security.Orphans ()
import Distribution.Server.Features.Security.MD5
import Distribution.Server.Features.Security.SHA256
import Distribution.Server.Framework.ResponseContentTypes
import Distribution.Server.Framework.MemSize
import Text.JSON.Canonical (Int54)
-- | Serialized TUF file along with some metadata necessary to serve the file
data TUFFile = TUFFile {
_tufFileContent :: !BS.Lazy.ByteString
, _tufFileLength :: !Int54
, _tufFileHashMD5 :: !MD5Digest
, _tufFileHashSHA256 :: !SHA256Digest
}
deriving (Typeable, Show, Eq)
deriveSafeCopy 0 'base ''TUFFile
instance NFData TUFFile where
rnf (TUFFile a b c d) = rnf (a, b, c, d)
instance MemSize TUFFile where
memSize (TUFFile a b c d) = memSize4 a b c d
instance ToMessage TUFFile where
toResponse file =
mkResponseLen (tufFileContent file) (fromIntegral (tufFileLength file)) [
("Content-Type", "application/json")
, ("Content-MD5", formatMD5Digest (tufFileHashMD5 file))
]
instance HasFileInfo TUFFile where
fileInfo file = FileInfo (tufFileLength file) (tufFileHashSHA256 file) (Just $ tufFileHashMD5 file)
mkTUFFile :: BS.Lazy.ByteString -> TUFFile
mkTUFFile content =
TUFFile {
_tufFileContent = content,
_tufFileLength = fromIntegral $ BS.Lazy.length content,
_tufFileHashMD5 = md5 content,
_tufFileHashSHA256 = sha256 content
}
{-------------------------------------------------------------------------------
Wrappers around TUFFile
(We originally had a phantom type argument here indicating what kind of TUF
file this is, but that lead to problems with 'deriveSafeCopy'; now we use a
bunch of newtype wrappers instead.)
-------------------------------------------------------------------------------}
class IsTUFFile a where
tufFileContent :: a -> BS.Lazy.ByteString
tufFileLength :: a -> Int54
tufFileHashMD5 :: a -> MD5Digest
tufFileHashSHA256 :: a -> SHA256Digest
instance IsTUFFile TUFFile where
tufFileContent TUFFile{..} = _tufFileContent
tufFileLength TUFFile{..} = _tufFileLength
tufFileHashMD5 TUFFile{..} = _tufFileHashMD5
tufFileHashSHA256 TUFFile{..} = _tufFileHashSHA256
newtype Timestamp = Timestamp { timestampFile :: TUFFile }
deriving (Typeable, Show, Eq, NFData, MemSize,
ToMessage, IsTUFFile, HasFileInfo)
newtype Snapshot = Snapshot { snapshotFile :: TUFFile }
deriving (Typeable, Show, Eq, NFData, MemSize,
ToMessage, IsTUFFile, HasFileInfo)
newtype Root = Root { rootFile :: TUFFile }
deriving (Typeable, Show, Eq, NFData, MemSize,
ToMessage, IsTUFFile, HasFileInfo)
newtype Mirrors = Mirrors { mirrorsFile :: TUFFile }
deriving (Typeable, Show, Eq, NFData, MemSize,
ToMessage, IsTUFFile, HasFileInfo)
deriveSafeCopy 0 'base ''Timestamp
deriveSafeCopy 0 'base ''Snapshot
deriveSafeCopy 0 'base ''Root
deriveSafeCopy 0 'base ''Mirrors
|
agrafix/hackage-server
|
Distribution/Server/Features/Security/ResponseContentTypes.hs
|
Haskell
|
bsd-3-clause
| 3,578
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Haddock
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module deals with the @haddock@ and @hscolour@ commands.
-- It uses information about installed packages (from @ghc-pkg@) to find the
-- locations of documentation for dependent packages, so it can create links.
--
-- The @hscolour@ support allows generating HTML versions of the original
-- source, with coloured syntax highlighting.
module Distribution.Simple.Haddock (
haddock, hscolour,
haddockPackagePaths
) where
import Prelude ()
import Distribution.Compat.Prelude
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
-- local
import Distribution.Backpack.DescribeUnitId
import Distribution.Types.ForeignLib
import Distribution.Types.UnqualComponentName
import Distribution.Types.ComponentLocalBuildInfo
import Distribution.Types.ExecutableScope
import Distribution.Package
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription as PD hiding (Flag)
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.Program.GHC
import Distribution.Simple.Program.ResponseFile
import Distribution.Simple.Program
import Distribution.Simple.PreProcess
import Distribution.Simple.Setup
import Distribution.Simple.Build
import Distribution.Simple.InstallDirs
import Distribution.Simple.LocalBuildInfo hiding (substPathTemplate)
import Distribution.Simple.BuildPaths
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
import Distribution.InstalledPackageInfo ( InstalledPackageInfo )
import Distribution.Simple.Utils
import Distribution.System
import Distribution.Text
import Distribution.Utils.NubList
import Distribution.Version
import Distribution.Verbosity
import Language.Haskell.Extension
import Distribution.Compat.Semigroup (All (..), Any (..))
import Data.Either ( rights )
import System.Directory (doesFileExist)
import System.FilePath ( (</>), (<.>), normalise, isAbsolute )
import System.IO (hClose, hPutStrLn, hSetEncoding, utf8)
-- ------------------------------------------------------------------------------
-- Types
-- | A record that represents the arguments to the haddock executable, a product
-- monoid.
data HaddockArgs = HaddockArgs {
argInterfaceFile :: Flag FilePath,
-- ^ Path to the interface file, relative to argOutputDir, required.
argPackageName :: Flag PackageIdentifier,
-- ^ Package name, required.
argHideModules :: (All,[ModuleName.ModuleName]),
-- ^ (Hide modules ?, modules to hide)
argIgnoreExports :: Any,
-- ^ Ignore export lists in modules?
argLinkSource :: Flag (Template,Template,Template),
-- ^ (Template for modules, template for symbols, template for lines).
argCssFile :: Flag FilePath,
-- ^ Optional custom CSS file.
argContents :: Flag String,
-- ^ Optional URL to contents page.
argVerbose :: Any,
argOutput :: Flag [Output],
-- ^ HTML or Hoogle doc or both? Required.
argInterfaces :: [(FilePath, Maybe String)],
-- ^ [(Interface file, URL to the HTML docs for links)].
argOutputDir :: Directory,
-- ^ Where to generate the documentation.
argTitle :: Flag String,
-- ^ Page title, required.
argPrologue :: Flag String,
-- ^ Prologue text, required.
argGhcOptions :: Flag (GhcOptions, Version),
-- ^ Additional flags to pass to GHC.
argGhcLibDir :: Flag FilePath,
-- ^ To find the correct GHC, required.
argTargets :: [FilePath]
-- ^ Modules to process.
} deriving Generic
-- | The FilePath of a directory, it's a monoid under '(</>)'.
newtype Directory = Dir { unDir' :: FilePath } deriving (Read,Show,Eq,Ord)
unDir :: Directory -> FilePath
unDir = normalise . unDir'
type Template = String
data Output = Html | Hoogle
-- ------------------------------------------------------------------------------
-- Haddock support
haddock :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HaddockFlags
-> IO ()
haddock pkg_descr _ _ haddockFlags
| not (hasLibs pkg_descr)
&& not (fromFlag $ haddockExecutables haddockFlags)
&& not (fromFlag $ haddockTestSuites haddockFlags)
&& not (fromFlag $ haddockBenchmarks haddockFlags)
&& not (fromFlag $ haddockForeignLibs haddockFlags)
=
warn (fromFlag $ haddockVerbosity haddockFlags) $
"No documentation was generated as this package does not contain "
++ "a library. Perhaps you want to use the --executables, --tests,"
++ " --benchmarks or --foreign-libraries flags."
haddock pkg_descr lbi suffixes flags' = do
let verbosity = flag haddockVerbosity
comp = compiler lbi
platform = hostPlatform lbi
flags = case haddockTarget of
ForDevelopment -> flags'
ForHackage -> flags'
{ haddockHoogle = Flag True
, haddockHtml = Flag True
, haddockHtmlLocation = Flag (pkg_url ++ "/docs")
, haddockContents = Flag (toPathTemplate pkg_url)
, haddockHscolour = Flag True
}
pkg_url = "/package/$pkg-$version"
flag f = fromFlag $ f flags
tmpFileOpts = defaultTempFileOptions
{ optKeepTempFiles = flag haddockKeepTempFiles }
htmlTemplate = fmap toPathTemplate . flagToMaybe . haddockHtmlLocation
$ flags
haddockTarget =
fromFlagOrDefault ForDevelopment (haddockForHackage flags')
(haddockProg, version, _) <-
requireProgramVersion verbosity haddockProgram
(orLaterVersion (mkVersion [2,0])) (withPrograms lbi)
-- various sanity checks
when ( flag haddockHoogle
&& version < mkVersion [2,2]) $
die' verbosity "haddock 2.0 and 2.1 do not support the --hoogle flag."
haddockGhcVersionStr <- getProgramOutput verbosity haddockProg
["--ghc-version"]
case (simpleParse haddockGhcVersionStr, compilerCompatVersion GHC comp) of
(Nothing, _) -> die' verbosity "Could not get GHC version from Haddock"
(_, Nothing) -> die' verbosity "Could not get GHC version from compiler"
(Just haddockGhcVersion, Just ghcVersion)
| haddockGhcVersion == ghcVersion -> return ()
| otherwise -> die' verbosity $
"Haddock's internal GHC version must match the configured "
++ "GHC version.\n"
++ "The GHC version is " ++ display ghcVersion ++ " but "
++ "haddock is using GHC version " ++ display haddockGhcVersion
-- the tools match the requests, we can proceed
when (flag haddockHscolour) $
hscolour' (warn verbosity) haddockTarget pkg_descr lbi suffixes
(defaultHscolourFlags `mappend` haddockToHscolour flags)
libdirArgs <- getGhcLibDir verbosity lbi
let commonArgs = mconcat
[ libdirArgs
, fromFlags (haddockTemplateEnv lbi (packageId pkg_descr)) flags
, fromPackageDescription haddockTarget pkg_descr ]
withAllComponentsInBuildOrder pkg_descr lbi $ \component clbi -> do
componentInitialBuildSteps (flag haddockDistPref) pkg_descr lbi clbi verbosity
preprocessComponent pkg_descr component lbi clbi False verbosity suffixes
let
doExe com = case (compToExe com) of
Just exe -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
exeArgs <- fromExecutable verbosity tmp lbi clbi htmlTemplate
version exe
let exeArgs' = commonArgs `mappend` exeArgs
runHaddock verbosity tmpFileOpts comp platform
haddockProg exeArgs'
Nothing -> do
warn (fromFlag $ haddockVerbosity flags)
"Unsupported component, skipping..."
return ()
-- We define 'smsg' once and then reuse it inside the case, so that
-- we don't say we are running Haddock when we actually aren't
-- (e.g., Haddock is not run on non-libraries)
smsg :: IO ()
smsg = setupMessage' verbosity "Running Haddock on" (packageId pkg_descr)
(componentLocalName clbi) (maybeComponentInstantiatedWith clbi)
case component of
CLib lib -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
smsg
libArgs <- fromLibrary verbosity tmp lbi clbi htmlTemplate
version lib
let libArgs' = commonArgs `mappend` libArgs
runHaddock verbosity tmpFileOpts comp platform haddockProg libArgs'
CFLib flib -> when (flag haddockForeignLibs) $ do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
smsg
flibArgs <- fromForeignLib verbosity tmp lbi clbi htmlTemplate
version flib
let libArgs' = commonArgs `mappend` flibArgs
runHaddock verbosity tmpFileOpts comp platform haddockProg libArgs'
CExe _ -> when (flag haddockExecutables) $ smsg >> doExe component
CTest _ -> when (flag haddockTestSuites) $ smsg >> doExe component
CBench _ -> when (flag haddockBenchmarks) $ smsg >> doExe component
for_ (extraDocFiles pkg_descr) $ \ fpath -> do
files <- matchFileGlob fpath
for_ files $ copyFileTo verbosity (unDir $ argOutputDir commonArgs)
-- ------------------------------------------------------------------------------
-- Contributions to HaddockArgs (see also Doctest.hs for very similar code).
fromFlags :: PathTemplateEnv -> HaddockFlags -> HaddockArgs
fromFlags env flags =
mempty {
argHideModules = (maybe mempty (All . not)
$ flagToMaybe (haddockInternal flags), mempty),
argLinkSource = if fromFlag (haddockHscolour flags)
then Flag ("src/%{MODULE/./-}.html"
,"src/%{MODULE/./-}.html#%{NAME}"
,"src/%{MODULE/./-}.html#line-%{LINE}")
else NoFlag,
argCssFile = haddockCss flags,
argContents = fmap (fromPathTemplate . substPathTemplate env)
(haddockContents flags),
argVerbose = maybe mempty (Any . (>= deafening))
. flagToMaybe $ haddockVerbosity flags,
argOutput =
Flag $ case [ Html | Flag True <- [haddockHtml flags] ] ++
[ Hoogle | Flag True <- [haddockHoogle flags] ]
of [] -> [ Html ]
os -> os,
argOutputDir = maybe mempty Dir . flagToMaybe $ haddockDistPref flags
}
fromPackageDescription :: HaddockTarget -> PackageDescription -> HaddockArgs
fromPackageDescription haddockTarget pkg_descr =
mempty { argInterfaceFile = Flag $ haddockName pkg_descr,
argPackageName = Flag $ packageId $ pkg_descr,
argOutputDir = Dir $
"doc" </> "html" </> haddockDirName haddockTarget pkg_descr,
argPrologue = Flag $ if null desc then synopsis pkg_descr
else desc,
argTitle = Flag $ showPkg ++ subtitle
}
where
desc = PD.description pkg_descr
showPkg = display (packageId pkg_descr)
subtitle | null (synopsis pkg_descr) = ""
| otherwise = ": " ++ synopsis pkg_descr
componentGhcOptions :: Verbosity -> LocalBuildInfo
-> BuildInfo -> ComponentLocalBuildInfo -> FilePath
-> GhcOptions
componentGhcOptions verbosity lbi bi clbi odir =
let f = case compilerFlavor (compiler lbi) of
GHC -> GHC.componentGhcOptions
GHCJS -> GHCJS.componentGhcOptions
_ -> error $
"Distribution.Simple.Haddock.componentGhcOptions:" ++
"haddock only supports GHC and GHCJS"
in f verbosity lbi bi clbi odir
mkHaddockArgs :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> [FilePath]
-> BuildInfo
-> IO HaddockArgs
mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles bi = do
ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate
let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) {
-- Noooooooooo!!!!!111
-- haddock stomps on our precious .hi
-- and .o files. Workaround by telling
-- haddock to write them elsewhere.
ghcOptObjDir = toFlag tmp,
ghcOptHiDir = toFlag tmp,
ghcOptStubDir = toFlag tmp
} `mappend` getGhcCppOpts haddockVersion bi
sharedOpts = vanillaOpts {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra =
toNubListR $ hcSharedOptions GHC bi
}
opts <- if withVanillaLib lbi
then return vanillaOpts
else if withSharedLib lbi
then return sharedOpts
else die' verbosity $ "Must have vanilla or shared libraries "
++ "enabled in order to run haddock"
ghcVersion <- maybe (die' verbosity "Compiler has no GHC version")
return
(compilerCompatVersion GHC (compiler lbi))
return ifaceArgs {
argGhcOptions = toFlag (opts, ghcVersion),
argTargets = inFiles
}
fromLibrary :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> Library
-> IO HaddockArgs
fromLibrary verbosity tmp lbi clbi htmlTemplate haddockVersion lib = do
inFiles <- map snd `fmap` getLibSourceFiles verbosity lbi lib clbi
args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion
inFiles (libBuildInfo lib)
return args {
argHideModules = (mempty, otherModules (libBuildInfo lib))
}
fromExecutable :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> Executable
-> IO HaddockArgs
fromExecutable verbosity tmp lbi clbi htmlTemplate haddockVersion exe = do
inFiles <- map snd `fmap` getExeSourceFiles verbosity lbi exe clbi
args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate
haddockVersion inFiles (buildInfo exe)
return args {
argOutputDir = Dir $ unUnqualComponentName $ exeName exe,
argTitle = Flag $ unUnqualComponentName $ exeName exe
}
fromForeignLib :: Verbosity
-> FilePath
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> ForeignLib
-> IO HaddockArgs
fromForeignLib verbosity tmp lbi clbi htmlTemplate haddockVersion flib = do
inFiles <- map snd `fmap` getFLibSourceFiles verbosity lbi flib clbi
args <- mkHaddockArgs verbosity tmp lbi clbi htmlTemplate
haddockVersion inFiles (foreignLibBuildInfo flib)
return args {
argOutputDir = Dir $ unUnqualComponentName $ foreignLibName flib,
argTitle = Flag $ unUnqualComponentName $ foreignLibName flib
}
compToExe :: Component -> Maybe Executable
compToExe comp =
case comp of
CTest test@TestSuite { testInterface = TestSuiteExeV10 _ f } ->
Just Executable {
exeName = testName test,
modulePath = f,
exeScope = ExecutablePublic,
buildInfo = testBuildInfo test
}
CBench bench@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f } ->
Just Executable {
exeName = benchmarkName bench,
modulePath = f,
exeScope = ExecutablePublic,
buildInfo = benchmarkBuildInfo bench
}
CExe exe -> Just exe
_ -> Nothing
getInterfaces :: Verbosity
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> IO HaddockArgs
getInterfaces verbosity lbi clbi htmlTemplate = do
(packageFlags, warnings) <- haddockPackageFlags verbosity lbi clbi htmlTemplate
traverse_ (warn (verboseUnmarkOutput verbosity)) warnings
return $ mempty {
argInterfaces = packageFlags
}
getGhcCppOpts :: Version
-> BuildInfo
-> GhcOptions
getGhcCppOpts haddockVersion bi =
mempty {
ghcOptExtensions = toNubListR [EnableExtension CPP | needsCpp],
ghcOptCppOptions = toNubListR defines
}
where
needsCpp = EnableExtension CPP `elem` usedExtensions bi
defines = [haddockVersionMacro]
haddockVersionMacro = "-D__HADDOCK_VERSION__="
++ show (v1 * 1000 + v2 * 10 + v3)
where
[v1, v2, v3] = take 3 $ versionNumbers haddockVersion ++ [0,0]
getGhcLibDir :: Verbosity -> LocalBuildInfo
-> IO HaddockArgs
getGhcLibDir verbosity lbi = do
l <- case compilerFlavor (compiler lbi) of
GHC -> GHC.getLibDir verbosity lbi
GHCJS -> GHCJS.getLibDir verbosity lbi
_ -> error "haddock only supports GHC and GHCJS"
return $ mempty { argGhcLibDir = Flag l }
-- ------------------------------------------------------------------------------
-- | Call haddock with the specified arguments.
runHaddock :: Verbosity
-> TempFileOptions
-> Compiler
-> Platform
-> ConfiguredProgram
-> HaddockArgs
-> IO ()
runHaddock verbosity tmpFileOpts comp platform haddockProg args = do
let haddockVersion = fromMaybe (error "unable to determine haddock version")
(programVersion haddockProg)
renderArgs verbosity tmpFileOpts haddockVersion comp platform args $
\(flags,result)-> do
runProgram verbosity haddockProg flags
notice verbosity $ "Documentation created: " ++ result
renderArgs :: Verbosity
-> TempFileOptions
-> Version
-> Compiler
-> Platform
-> HaddockArgs
-> (([String], FilePath) -> IO a)
-> IO a
renderArgs verbosity tmpFileOpts version comp platform args k = do
let haddockSupportsUTF8 = version >= mkVersion [2,14,4]
haddockSupportsResponseFiles = version > mkVersion [2,16,2]
createDirectoryIfMissingVerbose verbosity True outputDir
withTempFileEx tmpFileOpts outputDir "haddock-prologue.txt" $
\prologueFileName h -> do
do
when haddockSupportsUTF8 (hSetEncoding h utf8)
hPutStrLn h $ fromFlag $ argPrologue args
hClose h
let pflag = "--prologue=" ++ prologueFileName
renderedArgs = pflag : renderPureArgs version comp platform args
if haddockSupportsResponseFiles
then
withResponseFile
verbosity
tmpFileOpts
outputDir
"haddock-response.txt"
(if haddockSupportsUTF8 then Just utf8 else Nothing)
renderedArgs
(\responseFileName -> k (["@" ++ responseFileName], result))
else
k (renderedArgs, result)
where
outputDir = (unDir $ argOutputDir args)
result = intercalate ", "
. map (\o -> outputDir </>
case o of
Html -> "index.html"
Hoogle -> pkgstr <.> "txt")
$ arg argOutput
where
pkgstr = display $ packageName pkgid
pkgid = arg argPackageName
arg f = fromFlag $ f args
renderPureArgs :: Version -> Compiler -> Platform -> HaddockArgs -> [String]
renderPureArgs version comp platform args = concat
[ (:[]) . (\f -> "--dump-interface="++ unDir (argOutputDir args) </> f)
. fromFlag . argInterfaceFile $ args
, if isVersion 2 16
then (\pkg -> [ "--package-name=" ++ display (pkgName pkg)
, "--package-version="++display (pkgVersion pkg)
])
. fromFlag . argPackageName $ args
else []
, (\(All b,xs) -> bool (map (("--hide=" ++). display) xs) [] b)
. argHideModules $ args
, bool ["--ignore-all-exports"] [] . getAny . argIgnoreExports $ args
, maybe [] (\(m,e,l) ->
["--source-module=" ++ m
,"--source-entity=" ++ e]
++ if isVersion 2 14 then ["--source-entity-line=" ++ l]
else []
) . flagToMaybe . argLinkSource $ args
, maybe [] ((:[]) . ("--css="++)) . flagToMaybe . argCssFile $ args
, maybe [] ((:[]) . ("--use-contents="++)) . flagToMaybe . argContents $ args
, bool [] [verbosityFlag] . getAny . argVerbose $ args
, map (\o -> case o of Hoogle -> "--hoogle"; Html -> "--html")
. fromFlag . argOutput $ args
, renderInterfaces . argInterfaces $ args
, (:[]) . ("--odir="++) . unDir . argOutputDir $ args
, (:[]) . ("--title="++)
. (bool (++" (internal documentation)")
id (getAny $ argIgnoreExports args))
. fromFlag . argTitle $ args
, [ "--optghc=" ++ opt | (opts, _ghcVer) <- flagToList (argGhcOptions args)
, opt <- renderGhcOptions comp platform opts ]
, maybe [] (\l -> ["-B"++l]) $
flagToMaybe (argGhcLibDir args) -- error if Nothing?
, argTargets $ args
]
where
renderInterfaces =
map (\(i,mh) -> "--read-interface=" ++
maybe "" (++",") mh ++ i)
bool a b c = if c then a else b
isVersion major minor = version >= mkVersion [major,minor]
verbosityFlag
| isVersion 2 5 = "--verbosity=1"
| otherwise = "--verbose"
---------------------------------------------------------------------------------
-- | Given a list of 'InstalledPackageInfo's, return a list of interfaces and
-- HTML paths, and an optional warning for packages with missing documentation.
haddockPackagePaths :: [InstalledPackageInfo]
-> Maybe (InstalledPackageInfo -> FilePath)
-> NoCallStackIO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackagePaths ipkgs mkHtmlPath = do
interfaces <- sequenceA
[ case interfaceAndHtmlPath ipkg of
Nothing -> return (Left (packageId ipkg))
Just (interface, html) -> do
exists <- doesFileExist interface
if exists
then return (Right (interface, html))
else return (Left pkgid)
| ipkg <- ipkgs, let pkgid = packageId ipkg
, pkgName pkgid `notElem` noHaddockWhitelist
]
let missing = [ pkgid | Left pkgid <- interfaces ]
warning = "The documentation for the following packages are not "
++ "installed. No links will be generated to these packages: "
++ intercalate ", " (map display missing)
flags = rights interfaces
return (flags, if null missing then Nothing else Just warning)
where
-- Don't warn about missing documentation for these packages. See #1231.
noHaddockWhitelist = map mkPackageName [ "rts" ]
-- Actually extract interface and HTML paths from an 'InstalledPackageInfo'.
interfaceAndHtmlPath :: InstalledPackageInfo
-> Maybe (FilePath, Maybe FilePath)
interfaceAndHtmlPath pkg = do
interface <- listToMaybe (InstalledPackageInfo.haddockInterfaces pkg)
html <- case mkHtmlPath of
Nothing -> fmap fixFileUrl
(listToMaybe (InstalledPackageInfo.haddockHTMLs pkg))
Just mkPath -> Just (mkPath pkg)
return (interface, if null html then Nothing else Just html)
where
-- The 'haddock-html' field in the hc-pkg output is often set as a
-- native path, but we need it as a URL. See #1064.
fixFileUrl f | isAbsolute f = "file://" ++ f
| otherwise = f
haddockPackageFlags :: Verbosity
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackageFlags verbosity lbi clbi htmlTemplate = do
let allPkgs = installedPkgs lbi
directDeps = map fst (componentPackageDeps clbi)
transitiveDeps <- case PackageIndex.dependencyClosure allPkgs directDeps of
Left x -> return x
Right inf -> die' verbosity $ "internal error when calculating transitive "
++ "package dependencies.\nDebug info: " ++ show inf
haddockPackagePaths (PackageIndex.allPackages transitiveDeps) mkHtmlPath
where
mkHtmlPath = fmap expandTemplateVars htmlTemplate
expandTemplateVars tmpl pkg =
fromPathTemplate . substPathTemplate (env pkg) $ tmpl
env pkg = haddockTemplateEnv lbi (packageId pkg)
haddockTemplateEnv :: LocalBuildInfo -> PackageIdentifier -> PathTemplateEnv
haddockTemplateEnv lbi pkg_id =
(PrefixVar, prefix (installDirTemplates lbi))
-- We want the legacy unit ID here, because it gives us nice paths
-- (Haddock people don't care about the dependencies)
: initialPathTemplateEnv
pkg_id
(mkLegacyUnitId pkg_id)
(compilerInfo (compiler lbi))
(hostPlatform lbi)
-- ------------------------------------------------------------------------------
-- hscolour support.
hscolour :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour = hscolour' dieNoVerbosity ForDevelopment
hscolour' :: (String -> IO ()) -- ^ Called when the 'hscolour' exe is not found.
-> HaddockTarget
-> PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour' onNoHsColour haddockTarget pkg_descr lbi suffixes flags =
either onNoHsColour (\(hscolourProg, _, _) -> go hscolourProg) =<<
lookupProgramVersion verbosity hscolourProgram
(orLaterVersion (mkVersion [1,8])) (withPrograms lbi)
where
go :: ConfiguredProgram -> IO ()
go hscolourProg = do
setupMessage verbosity "Running hscolour for" (packageId pkg_descr)
createDirectoryIfMissingVerbose verbosity True $
hscolourPref haddockTarget distPref pkg_descr
withAllComponentsInBuildOrder pkg_descr lbi $ \comp clbi -> do
componentInitialBuildSteps distPref pkg_descr lbi clbi verbosity
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
let
doExe com = case (compToExe com) of
Just exe -> do
let outputDir = hscolourPref haddockTarget distPref pkg_descr
</> unUnqualComponentName (exeName exe) </> "src"
runHsColour hscolourProg outputDir =<< getExeSourceFiles verbosity lbi exe clbi
Nothing -> do
warn (fromFlag $ hscolourVerbosity flags)
"Unsupported component, skipping..."
return ()
case comp of
CLib lib -> do
let outputDir = hscolourPref haddockTarget distPref pkg_descr </> "src"
runHsColour hscolourProg outputDir =<< getLibSourceFiles verbosity lbi lib clbi
CFLib flib -> do
let outputDir = hscolourPref haddockTarget distPref pkg_descr
</> unUnqualComponentName (foreignLibName flib) </> "src"
runHsColour hscolourProg outputDir =<< getFLibSourceFiles verbosity lbi flib clbi
CExe _ -> when (fromFlag (hscolourExecutables flags)) $ doExe comp
CTest _ -> when (fromFlag (hscolourTestSuites flags)) $ doExe comp
CBench _ -> when (fromFlag (hscolourBenchmarks flags)) $ doExe comp
stylesheet = flagToMaybe (hscolourCSS flags)
verbosity = fromFlag (hscolourVerbosity flags)
distPref = fromFlag (hscolourDistPref flags)
runHsColour prog outputDir moduleFiles = do
createDirectoryIfMissingVerbose verbosity True outputDir
case stylesheet of -- copy the CSS file
Nothing | programVersion prog >= Just (mkVersion [1,9]) ->
runProgram verbosity prog
["-print-css", "-o" ++ outputDir </> "hscolour.css"]
| otherwise -> return ()
Just s -> copyFileVerbose verbosity s (outputDir </> "hscolour.css")
for_ moduleFiles $ \(m, inFile) ->
runProgram verbosity prog
["-css", "-anchor", "-o" ++ outFile m, inFile]
where
outFile m = outputDir </>
intercalate "-" (ModuleName.components m) <.> "html"
haddockToHscolour :: HaddockFlags -> HscolourFlags
haddockToHscolour flags =
HscolourFlags {
hscolourCSS = haddockHscolourCss flags,
hscolourExecutables = haddockExecutables flags,
hscolourTestSuites = haddockTestSuites flags,
hscolourBenchmarks = haddockBenchmarks flags,
hscolourForeignLibs = haddockForeignLibs flags,
hscolourVerbosity = haddockVerbosity flags,
hscolourDistPref = haddockDistPref flags
}
-- ------------------------------------------------------------------------------
-- Boilerplate Monoid instance.
instance Monoid HaddockArgs where
mempty = gmempty
mappend = (<>)
instance Semigroup HaddockArgs where
(<>) = gmappend
instance Monoid Directory where
mempty = Dir "."
mappend = (<>)
instance Semigroup Directory where
Dir m <> Dir n = Dir $ m </> n
|
themoritz/cabal
|
Cabal/Distribution/Simple/Haddock.hs
|
Haskell
|
bsd-3-clause
| 31,077
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Дополнение Eval Villain</title>
<maps>
<homeID>evalvillain</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Содержание</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Избранное</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/evalvillain/src/main/javahelp/org/zaproxy/addon/evalvillain/resources/help_ru_RU/helpset_ru_RU.hs
|
Haskell
|
apache-2.0
| 1,018
|
module Main where
import Eval
import Type
import Check
import Parser
import Pretty
import Syntax
import Data.Maybe
import Control.Monad.Trans
import System.Console.Haskeline
eval' :: Expr -> Expr
eval' = fromJust . eval
process :: String -> IO ()
process line = do
let res = parseExpr line
case res of
Left err -> print err
Right ex -> do
let chk = check ex
case chk of
Left err -> print err
Right ty -> putStrLn $ (ppexpr $ eval' ex) ++ " : " ++ (pptype ty)
main :: IO ()
main = runInputT defaultSettings loop
where
loop = do
minput <- getInputLine "Arith> "
case minput of
Nothing -> outputStrLn "Goodbye."
Just input -> (liftIO $ process input) >> loop
|
yupferris/write-you-a-haskell
|
chapter5/calc_typed/Main.hs
|
Haskell
|
mit
| 726
|
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Prompt.AppLauncher
-- Copyright : (C) 2008 Luis Cabellos
-- License : BSD3
--
-- Maintainer : zhen.sydow@gmail.com
-- Stability : unstable
-- Portability : unportable
--
-- A module for launch applicationes that receive parameters in the command
-- line. The launcher call a prompt to get the parameters.
--
-----------------------------------------------------------------------------
module XMonad.Prompt.AppLauncher ( -- * Usage
-- $usage
launchApp
,module XMonad.Prompt
-- * Use case: launching gimp with file
-- $tip
-- * Types
,Application, AppPrompt,
) where
import XMonad (X(),MonadIO)
import XMonad.Core (spawn)
import XMonad.Prompt (XPrompt(showXPrompt), mkXPrompt, XPConfig())
import XMonad.Prompt.Shell (getShellCompl)
{- $usage
This module is intended to allow the launch of the same application
but changing the parameters using the user response. For example, when
you want to open a image in gimp program, you can open gimp and then use
the File Menu to open the image or you can use this module to select
the image in the command line.
We use Prompt to get the user command line. This also allow to autoexpand
the names of the files when we are writing the command line.
-}
{- $tip
First, you need to import necessary modules. Prompt is used to get the promp
configuration and the AppLauncher module itself.
> import XMonad.Prompt
> import XMonad.Prompt.AppLauncher as AL
Then you can add the bindings to the applications.
> ...
> , ((modm, xK_g), AL.launchApp defaultXPConfig "gimp" )
> , ((modm, xK_g), AL.launchApp defaultXPConfig "evince" )
> ...
-}
-- A customized prompt
data AppPrompt = AppPrompt String
instance XPrompt AppPrompt where
showXPrompt (AppPrompt n) = n ++ " "
type Application = String
type Parameters = String
{- | Given an application and its parameters, launch the application. -}
launch :: MonadIO m => Application -> Parameters -> m ()
launch app params = spawn ( app ++ " " ++ params )
{- | Get the user's response to a prompt an launch an application using the
input as command parameters of the application.-}
launchApp :: XPConfig -> Application -> X ()
launchApp config app = mkXPrompt (AppPrompt app) config (getShellCompl []) $ launch app
|
adinapoli/xmonad-contrib
|
XMonad/Prompt/AppLauncher.hs
|
Haskell
|
bsd-3-clause
| 2,634
|
module B1 where
data Data1 a
= C1 a Int Int | C4 Float | C2 Int | C3 Float
addedC4 = error "added C4 Float to Data1"
g (C1 x y z) = y
g (C4 a) = addedC4
g (C2 x) = x
g (C3 x) = 42
|
kmate/HaRe
|
old/testing/addCon/B1AST.hs
|
Haskell
|
bsd-3-clause
| 189
|
-- | A description of the platform we're compiling for.
--
module Platform (
Platform(..),
Arch(..),
OS(..),
ArmISA(..),
ArmISAExt(..),
ArmABI(..),
PPC_64ABI(..),
target32Bit,
isARM,
osElfTarget,
osMachOTarget,
platformUsesFrameworks,
platformBinariesAreStaticLibs,
)
where
-- | Contains enough information for the native code generator to emit
-- code for this platform.
data Platform
= Platform {
platformArch :: Arch,
platformOS :: OS,
-- Word size in bytes (i.e. normally 4 or 8,
-- for 32bit and 64bit platforms respectively)
platformWordSize :: {-# UNPACK #-} !Int,
platformUnregisterised :: Bool,
platformHasGnuNonexecStack :: Bool,
platformHasIdentDirective :: Bool,
platformHasSubsectionsViaSymbols :: Bool,
platformIsCrossCompiling :: Bool
}
deriving (Read, Show, Eq)
-- | Architectures that the native code generator knows about.
-- TODO: It might be nice to extend these constructors with information
-- about what instruction set extensions an architecture might support.
--
data Arch
= ArchUnknown
| ArchX86
| ArchX86_64
| ArchPPC
| ArchPPC_64
{ ppc_64ABI :: PPC_64ABI
}
| ArchSPARC
| ArchSPARC64
| ArchARM
{ armISA :: ArmISA
, armISAExt :: [ArmISAExt]
, armABI :: ArmABI
}
| ArchARM64
| ArchAlpha
| ArchMipseb
| ArchMipsel
| ArchJavaScript
deriving (Read, Show, Eq)
isARM :: Arch -> Bool
isARM (ArchARM {}) = True
isARM ArchARM64 = True
isARM _ = False
-- | Operating systems that the native code generator knows about.
-- Having OSUnknown should produce a sensible default, but no promises.
data OS
= OSUnknown
| OSLinux
| OSDarwin
| OSiOS
| OSSolaris2
| OSMinGW32
| OSFreeBSD
| OSDragonFly
| OSOpenBSD
| OSNetBSD
| OSKFreeBSD
| OSHaiku
| OSQNXNTO
| OSAndroid
| OSAIX
deriving (Read, Show, Eq)
-- | ARM Instruction Set Architecture, Extensions and ABI
--
data ArmISA
= ARMv5
| ARMv6
| ARMv7
deriving (Read, Show, Eq)
data ArmISAExt
= VFPv2
| VFPv3
| VFPv3D16
| NEON
| IWMMX2
deriving (Read, Show, Eq)
data ArmABI
= SOFT
| SOFTFP
| HARD
deriving (Read, Show, Eq)
-- | PowerPC 64-bit ABI
--
data PPC_64ABI
= ELF_V1
| ELF_V2
deriving (Read, Show, Eq)
-- | This predicate tells us whether the platform is 32-bit.
target32Bit :: Platform -> Bool
target32Bit p = platformWordSize p == 4
-- | This predicate tells us whether the OS supports ELF-like shared libraries.
osElfTarget :: OS -> Bool
osElfTarget OSLinux = True
osElfTarget OSFreeBSD = True
osElfTarget OSDragonFly = True
osElfTarget OSOpenBSD = True
osElfTarget OSNetBSD = True
osElfTarget OSSolaris2 = True
osElfTarget OSDarwin = False
osElfTarget OSiOS = False
osElfTarget OSMinGW32 = False
osElfTarget OSKFreeBSD = True
osElfTarget OSHaiku = True
osElfTarget OSQNXNTO = False
osElfTarget OSAndroid = True
osElfTarget OSAIX = False
osElfTarget OSUnknown = False
-- Defaulting to False is safe; it means don't rely on any
-- ELF-specific functionality. It is important to have a default for
-- portability, otherwise we have to answer this question for every
-- new platform we compile on (even unreg).
-- | This predicate tells us whether the OS support Mach-O shared libraries.
osMachOTarget :: OS -> Bool
osMachOTarget OSDarwin = True
osMachOTarget _ = False
osUsesFrameworks :: OS -> Bool
osUsesFrameworks OSDarwin = True
osUsesFrameworks OSiOS = True
osUsesFrameworks _ = False
platformUsesFrameworks :: Platform -> Bool
platformUsesFrameworks = osUsesFrameworks . platformOS
osBinariesAreStaticLibs :: OS -> Bool
osBinariesAreStaticLibs OSiOS = True
osBinariesAreStaticLibs _ = False
platformBinariesAreStaticLibs :: Platform -> Bool
platformBinariesAreStaticLibs = osBinariesAreStaticLibs . platformOS
|
olsner/ghc
|
compiler/utils/Platform.hs
|
Haskell
|
bsd-3-clause
| 4,415
|
import Test.Cabal.Prelude
-- Test building a vanilla library/executable which uses Template Haskell
main = setupAndCabalTest $ setup_build []
|
mydaum/cabal
|
cabal-testsuite/PackageTests/TemplateHaskell/vanilla/setup.test.hs
|
Haskell
|
bsd-3-clause
| 142
|
{-# LANGUAGE DeriveFoldable #-}
module Main where
import Data.Semigroup
-- Just a list without any special fusion rules.
data List a = Nil | Cons a (List a) deriving Foldable
instance Semigroup (List a) where
Nil <> ys = ys
Cons x xs <> ys = Cons x (xs <> ys)
replicateList :: Int -> a -> List a
replicateList 0 x = Nil
replicateList n x = Cons x (replicateList (n - 1) x)
newtype ListList a = ListList (List (List a)) deriving Foldable
long :: Int -> Bool
long n = null $ ListList $ replicateList n Nil <> Cons (Cons () Nil) Nil
main :: IO ()
main = print $ long (10^(6 :: Int))
|
ezyang/ghc
|
testsuite/tests/perf/should_run/DeriveNull.hs
|
Haskell
|
bsd-3-clause
| 591
|
{-# LANGUAGE TypeFamilies, ConstraintKinds, UndecidableInstances #-}
module Ctx where
import GHC.Prim( Constraint )
type family Indirect :: * -> Constraint
type instance Indirect = Show
class Cls a where
f :: a -> String
instance Indirect a => Cls [a] where
f = show
|
tibbe/ghc
|
testsuite/tests/typecheck/should_compile/tc255.hs
|
Haskell
|
bsd-3-clause
| 279
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Foo where
class C a
instance C Int
newtype Foo = Foo Int
deriving C
|
wxwxwwxxx/ghc
|
testsuite/tests/parser/should_compile/read057.hs
|
Haskell
|
bsd-3-clause
| 128
|
module Main where
import qualified Data.ByteString as B
import Language.STL.Lex
import Language.STL.Lex.Normalize
import Language.STL.Parse
import Prelude hiding (lex)
import System.IO
main :: IO ()
main = withFile "main.stl" ReadMode $ \h -> do
m <- fmap lex (B.hGetContents h)
case m of
Success ts -> do
let ns = normalize ts
print $ parse "main.stl" ns
e -> error $ show e
|
pikajude/stl
|
src/stl.hs
|
Haskell
|
mit
| 426
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
-------------------------------------------
-- |
-- Module : Web.Stripe.Balance
-- Copyright : (c) David Johnson, 2014
-- Maintainer : djohnson.m@gmail.com
-- Stability : experimental
-- Portability : POSIX
--
-- < https:/\/\stripe.com/docs/api#balance >
--
-- @
-- {-\# LANGUAGE OverloadedStrings \#-}
-- import Web.Stripe
-- import Web.Stripe.Balance (getBalance)
--
-- main :: IO ()
-- main = do
-- let config = StripeConfig (StripeKey "secret_key")
-- result <- stripe config getBalance
-- case result of
-- Right balance -> print balance
-- Left stripeError -> print stripeError
-- @
module Web.Stripe.Balance
( -- * API
GetBalance
, getBalance
, GetBalanceTransaction
, getBalanceTransaction
, GetBalanceTransactionHistory
, getBalanceTransactionHistory
-- * Types
, AvailableOn (..)
, Balance (..)
, BalanceAmount (..)
, BalanceTransaction (..)
, Created (..)
, Currency (..)
, EndingBefore (..)
, ExpandParams (..)
, Limit (..)
, Source (..)
, StartingAfter (..)
, StripeList (..)
, TimeRange (..)
, TransactionId (..)
, TransactionType (..)
) where
import Web.Stripe.StripeRequest (Method (GET), StripeHasParam,
StripeRequest (..),
StripeReturn, ToStripeParam(..),
mkStripeRequest)
import Web.Stripe.Util ((</>))
import Web.Stripe.Types (AvailableOn(..), Balance (..),
BalanceAmount(..), BalanceTransaction(..),
Created(..), Currency(..),
EndingBefore(..), ExpandParams(..),
Limit(..), Source(..), StartingAfter(..),
StripeList (..), TimeRange(..),
TransferId(..), TransactionId (..),
TransactionType(..))
import Web.Stripe.Types.Util (getTransactionId)
------------------------------------------------------------------------------
-- | Retrieve the current `Balance` for your Stripe account
getBalance :: StripeRequest GetBalance
getBalance = request
where request = mkStripeRequest GET url params
url = "balance"
params = []
data GetBalance
type instance StripeReturn GetBalance = Balance
------------------------------------------------------------------------------
-- | Retrieve a 'BalanceTransaction' by 'TransactionId'
getBalanceTransaction
:: TransactionId -- ^ The `TransactionId` of the `Transaction` to retrieve
-> StripeRequest GetBalanceTransaction
getBalanceTransaction
transactionid = request
where request = mkStripeRequest GET url params
url = "balance" </> "history" </> getTransactionId transactionid
params = []
data GetBalanceTransaction
type instance StripeReturn GetBalanceTransaction = BalanceTransaction
instance StripeHasParam GetBalanceTransaction ExpandParams
------------------------------------------------------------------------------
-- | Retrieve the history of `BalanceTransaction`s
getBalanceTransactionHistory
:: StripeRequest GetBalanceTransactionHistory
getBalanceTransactionHistory
= request
where request = mkStripeRequest GET url params
url = "balance" </> "history"
params = []
data GetBalanceTransactionHistory
type instance StripeReturn GetBalanceTransactionHistory = (StripeList BalanceTransaction)
instance StripeHasParam GetBalanceTransactionHistory AvailableOn
instance StripeHasParam GetBalanceTransactionHistory (TimeRange AvailableOn)
instance StripeHasParam GetBalanceTransactionHistory Created
instance StripeHasParam GetBalanceTransactionHistory (TimeRange Created)
instance StripeHasParam GetBalanceTransactionHistory Currency
instance StripeHasParam GetBalanceTransactionHistory (EndingBefore TransactionId)
instance StripeHasParam GetBalanceTransactionHistory Limit
instance StripeHasParam GetBalanceTransactionHistory (StartingAfter TransactionId)
instance (ToStripeParam a) => StripeHasParam GetBalanceTransactionHistory (Source a)
instance StripeHasParam GetBalanceTransactionHistory TransferId
instance StripeHasParam GetBalanceTransactionHistory TransactionType
|
dmjio/stripe
|
stripe-core/src/Web/Stripe/Balance.hs
|
Haskell
|
mit
| 4,788
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DeriveGeneric #-}
module FP15.Evaluator.FPValue where
import GHC.Generics(Generic)
import Data.IORef
import Control.DeepSeq
import FP15.Disp
import FP15.Value
type Rev = (Int, Int)
data FPRef a = FPRef Rev (IORef a)
-- | The 'FPValue' type represents all possible values in the FP15 runtime. This
-- includes the well-behaved values and the unserializable values such as
-- functions and the @RealWorld@.
type FPValue = XValue Extended
data Extended = Lambda !(FPValue -> FPValue)
| Ref !(FPRef FPValue)
| RealWorld !RealWorld
deriving (Generic)
instance NFData Extended where rnf x = seq x ()
data RealWorld = RW deriving (Eq, Show, Read, Ord, Generic)
instance NFData RealWorld where rnf x = seq x ()
fromFPValue :: FPValue -> Maybe Value
fromFPValue = convToValue
instance Disp Extended where
disp (Lambda _) = "#<lambda>"
disp (Ref _) = "#<ref>"
disp (RealWorld _) = "#<RealWorld>"
instance Disp FPValue where
pretty = prettyXValue pretty
class FPValueConvertible t where
toFPValue :: t -> FPValue
default (FPValue)
instance Num FPValue where
(+) _ _ = undefined
(*) _ _ = undefined
abs _ = undefined
signum _ = undefined
fromInteger _ = undefined
negate _ = undefined
instance FPValueConvertible RealWorld where
toFPValue = Extended . RealWorld
instance FPValueConvertible Value where
toFPValue = fmap (\_ -> error "toFPValue")
instance FPValueConvertible FPValue where
toFPValue = id
instance FPValueConvertible Bool where
toFPValue = Bool
instance FPValueConvertible Char where
toFPValue = Char
instance FPValueConvertible Integer where
toFPValue = Int
instance FPValueConvertible Int where
toFPValue = Int . fromIntegral
instance FPValueConvertible Double where
toFPValue = Real
instance FPValueConvertible String where
toFPValue = String
instance FPValueConvertible a => FPValueConvertible [a] where
toFPValue = List . map toFPValue
instance (FPValueConvertible a, FPValueConvertible b)
=> FPValueConvertible (a, b) where
toFPValue (a, b) = List [toFPValue a, toFPValue b]
instance (FPValueConvertible a, FPValueConvertible b, FPValueConvertible c)
=> FPValueConvertible (a, b, c) where
toFPValue (a, b, c) = List [toFPValue a, toFPValue b, toFPValue c]
instance (FPValueConvertible a, FPValueConvertible b, FPValueConvertible c,
FPValueConvertible d)
=> FPValueConvertible (a, b, c, d) where
toFPValue (a, b, c, d) = List [toFPValue a, toFPValue b, toFPValue c, toFPValue d]
instance (FPValueConvertible a, FPValueConvertible b, FPValueConvertible c,
FPValueConvertible d, FPValueConvertible e)
=> FPValueConvertible (a, b, c, d, e) where
toFPValue (a, b, c, d, e) = List [toFPValue a, toFPValue b, toFPValue c, toFPValue d
, toFPValue e]
|
Ming-Tang/FP15
|
src/FP15/Evaluator/FPValue.hs
|
Haskell
|
mit
| 2,944
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.