code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Tree.RBT where
import Data.List (foldl')
data Color = R | B deriving (Eq, Show)
data Tree a = Empty | Node Color (Tree a) a (Tree a) deriving (Eq, Show)
-- All empty nodes considered to be black (so no color field for Empty)
-- Every RBT satisfy the following two balance invariants:
-- - No red node has a red child
-- - Every path from the root to an empty node contains the same number of black nodes
left :: Tree a -> Tree a
left Empty = undefined
left (Node _ l _ _) = l
right :: Tree a -> Tree a
right Empty = undefined
right (Node _ _ _ r) = r
color :: Tree a -> Color
color Empty = undefined
color (Node c _ _ _) = c
value :: Tree a -> Maybe a
value Empty = Nothing
value (Node _ _ v _) = Just v
pp :: Show a => Tree a -> IO ()
pp = mapM_ putStrLn . treeIndent
where
treeIndent Empty = ["-- /-"]
treeIndent (Node c lb v rb) =
["--" ++ show c ++ ' ':show v] ++
map (" |" ++) ls ++
(" `" ++ r) : map (" " ++) rs
where
(r:rs) = treeIndent rb
ls = treeIndent lb
makeLeaf :: Color -> a -> Tree a
makeLeaf c v = Node c Empty v Empty
makeLeft :: Color -> a -> Tree a -> Tree a
makeLeft c v l = Node c l v Empty
makeRight :: Color -> a -> Tree a -> Tree a
makeRight c = Node c Empty
-- *RBT> rbt2
-- Node B (Node B Empty 0 Empty) 1 (Node R (Node B (Node R Empty 3 Empty) 4 (Node R Empty 5 Empty)) 6 (Node B Empty 7 Empty))
-- *RBT> pp rbt2
-- --B 1
-- |--B 0
-- | |-- /-
-- | `-- /-
-- `--R 6
-- |--B 4
-- | |--R 3
-- | | |-- /-
-- | | `-- /-
-- | `--R 5
-- | |-- /-
-- | `-- /-
-- `--B 7
-- |-- /-
-- `-- /-
-- FIXME: Improve the data type to create a constructor of meta data (color + value for RBT and just value for AVL)
-- This way, we can factor some functions for those data structures
rebalance :: Tree a -> Tree a
rebalance (Node B (Node R (Node R a x b) y c) z d) = Node R (Node B a x b) y (Node B c z d)
rebalance (Node B a x (Node R b y (Node R c z d))) = Node R (Node B a x b) y (Node B c z d)
rebalance (Node B (Node R a x (Node R b y c)) z d) = Node R (Node B a x b) y (Node B c z d)
rebalance (Node B a x (Node R (Node R b y c) z d)) = Node R (Node B a x b) y (Node B c z d)
rebalance r = r
insert :: Ord a => Tree a -> a -> Tree a
insert t y = Node B l v r -- force the root to be black
where Node _ l v r = ins t
ins Empty = makeLeaf R y
ins n@(Node c tl x tr)
| x == y = n
| x < y = rebalance $ Node c tl x (ins tr)
| otherwise = rebalance $ Node c (ins tl) x tr
-- Creates a new Red-Black Tree from a given list
fromList :: Ord a => [a] -> Tree a
fromList = foldl' insert Empty
contains :: Ord a => Tree a -> a -> Bool
contains Empty _ = False
contains (Node _ l x r) y = case compare y x of
EQ -> True
LT -> contains l y
GT -> contains r y
toSortedList :: Tree a -> [a]
toSortedList Empty = []
toSortedList (Node _ l v r) = toSortedList l ++ v : toSortedList r
toList :: Tree a -> [a]
toList Empty = []
toList (Node _ l x r) = x : toList l ++ toList r
-- Returns how many Reds and Blacks in the given Tree as (redcount, blackcount)
countRB :: Tree a -> (Int, Int)
countRB Empty = (0, 0)
countRB (Node c l _ r) =
if c == B then (rc, 1 + bc) else (1 + rc, bc)
where (lrc, lbc) = countRB l
(rrc, rbc) = countRB r
rc = lrc + rrc
bc = lbc + rbc
blackHeight :: Tree a -> Int
blackHeight Empty = 1
blackHeight (Node c l _ _) = (if c == B then 1 else 0) + blackHeight l
-- FIXME create my own type to permit the behaviour sharing between RBT and BST as a RBT is a BST
-- This function is repeated and adapted from the BST module, this is not DRY!
isBST :: (Ord a) => Tree a -> Bool
isBST Empty = True
isBST (Node _ l x r) =
case [value l, value r] of
[Nothing, Nothing] -> True
[Nothing, Just z] -> and [x < z, isBST l, isBST r]
[Just y, Nothing] -> and [y <= x, isBST l, isBST r]
[Just y, Just z] -> and [y <= x, x < z, isBST l, isBST r]
isRBT :: (Ord a, Eq a) => Tree a -> Bool
isRBT Empty = True
isRBT t@(Node _ l _ r) = and [isBST t, noRedRed t, blackHeight l == blackHeight r]
-- Returns whether the given tree contains Red-Red nodes or not
noRedRed :: Tree a -> Bool
noRedRed Empty = True
noRedRed (Node R (Node R _ _ _) _ _) = False
noRedRed (Node R _ _ (Node R _ _ _)) = False
noRedRed (Node _ l _ r) = noRedRed l && noRedRed r
-- Returns all paths from root to leaves --
paths :: Tree a -> [[(Color, a)]]
paths Empty = [[]]
paths (Node c Empty v Empty) = [[(c, v)]]
paths (Node c l v r) = [ cv : p | p <- paths l ++ paths r ]
where cv = (c, v)
|
ardumont/haskell-lab
|
src/Tree/RBT.hs
|
gpl-2.0
| 4,879 | 0 | 14 | 1,569 | 2,015 | 1,029 | 986 | 91 | 4 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, TemplateHaskell, NoImplicitPrelude, RecordWildCards, GeneralizedNewtypeDeriving #-}
module Lamdu.Eval.Results
( Body(..), _RRecExtend, _RInject, _RFunc, _RRecEmpty, _RPrimVal, _RError
, Val(..), payload, body
, ScopeId(..), scopeIdInt, topLevelScopeId
, EvalError(..)
, EvalResults(..), erExprValues, erAppliesOfLam, empty
, extractField
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Data.Binary (Binary)
import Data.Map (Map)
import qualified Data.Map as Map
import Lamdu.Data.Definition (FFIName)
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.Calc.Val as V
import Prelude.Compat
newtype ScopeId = ScopeId { getScopeId :: Int }
deriving (Show, Eq, Ord, Binary)
scopeIdInt :: Lens.Iso' ScopeId Int
scopeIdInt = Lens.iso getScopeId ScopeId
data EvalError
= EvalHole
| EvalTypeError String
| EvalLoadGlobalFailed V.Var
| EvalMissingBuiltin FFIName
| EvalTodoError String
| EvalIndexError String
deriving Show
topLevelScopeId :: ScopeId
topLevelScopeId = ScopeId 0
data Body val
= RRecExtend (V.RecExtend val)
| RInject (V.Inject val)
| RFunc
| RRecEmpty
| RPrimVal V.PrimVal
| RArray [val]
| RError EvalError
deriving (Show, Functor, Foldable, Traversable)
data Val pl = Val
{ _payload :: pl
, _body :: Body (Val pl)
} deriving (Show, Functor, Foldable, Traversable)
extractField :: T.Tag -> Val () -> Val ()
extractField tag (Val () (RRecExtend (V.RecExtend vt vv vr)))
| vt == tag = vv
| otherwise = extractField tag vr
extractField _ v@(Val () RError {}) = v
extractField tag x =
"Expected record with tag: " ++ show tag ++ " got: " ++ show x
& EvalTypeError & RError & Val ()
data EvalResults srcId =
EvalResults
{ _erExprValues :: Map srcId (Map ScopeId (Val ()))
, _erAppliesOfLam :: Map srcId (Map ScopeId [(ScopeId, Val ())])
} deriving Show
empty :: EvalResults srcId
empty =
EvalResults
{ _erExprValues = Map.empty
, _erAppliesOfLam = Map.empty
}
Lens.makeLenses ''EvalResults
Lens.makeLenses ''Val
Lens.makePrisms ''Body
|
da-x/lamdu
|
Lamdu/Eval/Results.hs
|
gpl-3.0
| 2,260 | 0 | 15 | 502 | 688 | 389 | 299 | 65 | 1 |
-- Ripple Balances
-- Copyright (C) 2015 Jonathan Lamothe <[email protected]>
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Main (main) where
import qualified Network.Ripple as Ripple
import Network.Ripple.Balances
import System.Exit (exitSuccess, exitFailure)
import Test.HUnit ( Test (..)
, Counts (..)
, runTestTT
, (@=?)
)
main :: IO ()
main = runTestTT tests >>= checkCounts
tests = TestList [filterBalancesTest]
filterBalancesTest = TestLabel "filterBalances" $
TestCase $ [nonzero] @=? filterBalances [zero, nonzero]
where
zero = Ripple.Balance 0 "" Nothing
nonzero = Ripple.Balance 100 "" Nothing
checkCounts :: Counts -> IO ()
checkCounts counts = if (errors counts > 0 || failures counts > 0)
then exitFailure
else exitSuccess
-- jl
|
jlamothe/ripple-balances
|
tests.hs
|
gpl-3.0
| 1,446 | 0 | 10 | 311 | 224 | 132 | 92 | 19 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
module Type where
import Control.Monad.Reader (ReaderT)
import Data.Int (Int)
import Data.Maybe (Maybe)
import Data.String (String)
import System.IO (IO)
import Text.Show (Show)
data Config = Config
{ url :: !String
, credentials :: !(Maybe (String, String))
, refreshDelay :: !Int
, boringNames :: ![String]
} deriving Show
type M = ReaderT Config IO
|
FPBrno/jenkins-dashboard
|
src/Type.hs
|
gpl-3.0
| 411 | 0 | 12 | 80 | 132 | 79 | 53 | 23 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Progress
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Portability : portable
--
-- Common types for dependency resolution.
-----------------------------------------------------------------------------
module Progress (
Progress(..),
fold, unfold, fromList,
) where
import Prelude hiding (fail)
-- | A type to represent the unfolding of an expensive long running
-- calculation that may fail. We may get intermediate steps before the final
-- retult which may be used to indicate progress and\/or logging messages.
--
data Progress step fail done = Step step (Progress step fail done)
| Fail fail
| Done done
-- | Consume a 'Progress' calculation. Much like 'foldr' for lists but with
-- two base cases, one for a final result and one for failure.
--
-- Eg to convert into a simple 'Either' result use:
--
-- > foldProgress (flip const) Left Right
--
fold :: (step -> a -> a) -> (fail -> a) -> (done -> a)
-> Progress step fail done -> a
fold step fail done = go
where
go (Step s p) = step s (go p)
go (Fail f) = fail f
go (Done r) = done r
unfold :: (s -> Either (Either fail done) (step, s))
-> s -> Progress step fail done
unfold f = go
where
go s = case f s of
Left (Left fail) -> Fail fail
Left (Right done) -> Done done
Right (step, s') -> Step step (go s')
fromList :: [a] -> Progress () b [a]
fromList xs0 = unfold next xs0
where
next [] = Left (Right xs0)
next (_:xs) = Right ((), xs)
instance Functor (Progress step fail) where
fmap f = fold Step Fail (Done . f)
instance Monad (Progress step fail) where
return a = Done a
p >>= f = fold Step Fail f p
|
Heather/hackport
|
Progress.hs
|
gpl-3.0
| 1,844 | 0 | 12 | 475 | 517 | 276 | 241 | 29 | 3 |
module While.Domain.Sign.DomainSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Test.Hspec.QuickCheck
import Data.Maybe()
import Data.Ord()
import Abstat.Interface.PosetProp
import Abstat.Interface.LatticeProp
import Abstat.Interface.AbstractDomain()
import Abstat.Common.AbstractState
import Abstat.Common.FlatDomainProp
import While.Domain.Sign.Domain
spec :: Spec
spec =
modifyMaxSuccess (*10) $
modifyMaxDiscardRatio (*10) $
modifyMaxSize (`div` 10) $
parallel $ do
describe "Domain" $ do
testLatticeProperties (arbitrary :: Gen Domain)
testPosetProperties (arbitrary :: Gen Domain)
testFlatDomainProperties (arbitrary :: Gen Sign)
describe "State Domain" $ do
testLatticeProperties (arbitrary :: Gen (State Domain))
testPosetProperties (arbitrary :: Gen (State Domain))
|
fpoli/abstat
|
test/While/Domain/Sign/DomainSpec.hs
|
gpl-3.0
| 861 | 0 | 15 | 149 | 241 | 133 | 108 | 25 | 1 |
module Lamdu.GUI.Scroll
( focusAreaIntoWindow
) where
import Control.Lens (Lens')
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Data.Maybe (fromMaybe)
import Data.Vector.Vector2 (Vector2(..))
import qualified Graphics.UI.Bottle.Rect as Rect
import Graphics.UI.Bottle.Widget (Widget)
import qualified Graphics.UI.Bottle.Widget as Widget
focusAreaIntoWindow :: Widget.Size -> Widget f -> Widget f
focusAreaIntoWindow winSize widget =
widget
& intoWindow _1
& intoWindow _2
where
widgetSize = widget ^. Widget.size
center = winSize / 2
allowedScroll = winSize - widgetSize
intoWindow rawLens
| widgetSize ^. l > winSize ^. l && movement < 0 =
Widget.translate (0 & l .~ max (allowedScroll ^. l) movement)
| otherwise = id
where
movement = center ^. l - focalPoint ^. l
l :: Lens' (Vector2 Widget.R) Widget.R
l = Lens.cloneLens rawLens
focalPoint =
widget ^? Widget.mFocus . Lens._Just . Widget.focalArea
<&> (^. Rect.center)
& fromMaybe 0
|
da-x/lamdu
|
Lamdu/GUI/Scroll.hs
|
gpl-3.0
| 1,251 | 0 | 14 | 397 | 335 | 186 | 149 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- | This module defines data type and some helpers to facilitate
-- properties creation.
module Test.RSCoin.Full.Property
( FullProperty
, FullPropertyEmulation
, FullPropertyRealMode
, launchPure
, toTestable
, assertFP
, pickFP
, runWorkModeFP
, runTestEnvFP
, doActionFP
) where
import Control.Monad.Catch (onException)
import Control.Monad.Reader (ask, runReaderT)
import Control.Monad.Trans (MonadIO, lift)
import Formatting (build, sformat, (%))
import System.Random (StdGen)
import Test.QuickCheck (Gen, Property,
Testable (property),
ioProperty)
import Test.QuickCheck.Monadic (PropertyM (..), assert,
monadic, pick)
import Serokell.Util (listBuilderJSONIndent)
import Control.TimeWarp.Timed (Microsecond)
import Control.TimeWarp.Rpc (DelaysSpecifier)
import RSCoin.Core (ContextArgument (CADefault),
EmulationMode, RealMode,
WithNamedLogger (..),
WorkMode, logDebug,
runEmulationMode,
runRealModeUntrusted,
testingLoggerName)
import Test.RSCoin.Full.Action (Action (doAction))
import Test.RSCoin.Full.Arbitrary ()
import Test.RSCoin.Full.Context (MintetteNumber,
Scenario (DefaultScenario),
TestEnv, UserNumber)
import Test.RSCoin.Full.Gen (genValidActions)
import Test.RSCoin.Full.Initialization (finishTest, mkTestContext)
type FullProperty m = TestEnv m (PropertyM m)
type FullPropertyEmulation = FullProperty EmulationMode
type FullPropertyRealMode = FullProperty RealMode
launchPure ::
DelaysSpecifier delays =>
StdGen -> delays -> EmulationMode a -> IO a
launchPure gen = runEmulationMode (Just gen)
launchReal :: RealMode a -> IO a
launchReal = runRealModeUntrusted testingLoggerName CADefault
instance (WithNamedLogger m, MonadIO m) =>
WithNamedLogger (PropertyM m) where
getLoggerName = lift getLoggerName
modifyLoggerName how (MkPropertyM m) = MkPropertyM $
\c -> modifyLoggerName how <$> m c
toPropertyM
:: WorkMode m
=> FullProperty m a -> MintetteNumber -> UserNumber -> PropertyM m a
toPropertyM fp mNum uNum = do
acts <- pick $ genValidActions uNum
context <- lift $ mkTestContext mNum uNum DefaultScenario
let runTestEnv a = runReaderT a context
runTestEnvSafe a = runTestEnv a `onException` runTestEnv finishTest
logDebug $
sformat ("Actions are: " % build) $ listBuilderJSONIndent 3 acts
lift $ runTestEnvSafe (mapM_ doAction acts)
runReaderT fp context <* lift (runTestEnv finishTest)
toTestable
:: forall a.
forall m. WorkMode m => (forall b. m b -> IO b) -> FullProperty m a -> MintetteNumber -> UserNumber -> Property
toTestable launcher fp mNum uNum = monadic unwrapProperty wrappedProperty
where
(unwrapProperty :: m Property -> Property) = ioProperty . launcher
(wrappedProperty :: PropertyM m a) = toPropertyM fp mNum uNum
instance Testable (FullPropertyEmulation a) where
property fp =
property $
\gen ->
toTestable (launchPure gen delays) fp
where
delays :: (Microsecond, Microsecond)
delays = (0, 1000)
instance Testable (FullPropertyRealMode a) where
property = property . toTestable launchReal
assertFP
:: Monad m
=> Bool -> FullProperty m ()
assertFP = lift . assert
pickFP
:: (Monad m, Show a)
=> Gen a -> FullProperty m a
pickFP = lift . pick
runWorkModeFP
:: WorkMode m
=> m a -> FullProperty m a
runWorkModeFP a = do
ctx <- ask
lift . lift $ a `onException` runReaderT finishTest ctx
runTestEnvFP
:: WorkMode m
=> TestEnv m m a -> FullProperty m a
runTestEnvFP a = runWorkModeFP . runReaderT a =<< ask
doActionFP
:: (WorkMode m, Action a)
=> a -> FullProperty m ()
doActionFP = runTestEnvFP . doAction
|
input-output-hk/rscoin-haskell
|
test/Test/RSCoin/Full/Property.hs
|
gpl-3.0
| 4,875 | 0 | 12 | 1,704 | 1,118 | 605 | 513 | 107 | 1 |
module Idme.Util (condA, constF, pairOf, (>>-)) where
import Control.Applicative (Applicative, pure)
import Data.Functor ((<$))
-- | inject into function, apply effect, and return itself operator
(>>-) :: (Functor m, Monad m) => m a -> (a -> m b) -> m a
(>>-) x f = x >>= constF f
infixl 8 >>-
-- | const for Functors
constF :: Functor f => (a -> f b) -> a -> f a
constF f a = a <$ f a
-- | Duplicate single item to pair of itself
pairOf :: a -> (a, a)
pairOf a = (a, a)
-- | Inspect given value and optionally execute action
condA :: Applicative a => b -> (b -> Bool) -> (b -> a c) -> a b
condA v t a = if t v then constF a v else pure v
|
awagner83/IdMe
|
src/Idme/Util.hs
|
gpl-3.0
| 646 | 0 | 11 | 149 | 275 | 150 | 125 | 12 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Variables.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all GTM Variables of a Container.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.variables.list@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Variables.List
(
-- * REST Resource
AccountsContainersWorkspacesVariablesListResource
-- * Creating a Request
, accountsContainersWorkspacesVariablesList
, AccountsContainersWorkspacesVariablesList
-- * Request Lenses
, acwvlParent
, acwvlXgafv
, acwvlUploadProtocol
, acwvlAccessToken
, acwvlUploadType
, acwvlPageToken
, acwvlCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.variables.list@ method which the
-- 'AccountsContainersWorkspacesVariablesList' request conforms to.
type AccountsContainersWorkspacesVariablesListResource
=
"tagmanager" :>
"v2" :>
Capture "parent" Text :>
"variables" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListVariablesResponse
-- | Lists all GTM Variables of a Container.
--
-- /See:/ 'accountsContainersWorkspacesVariablesList' smart constructor.
data AccountsContainersWorkspacesVariablesList =
AccountsContainersWorkspacesVariablesList'
{ _acwvlParent :: !Text
, _acwvlXgafv :: !(Maybe Xgafv)
, _acwvlUploadProtocol :: !(Maybe Text)
, _acwvlAccessToken :: !(Maybe Text)
, _acwvlUploadType :: !(Maybe Text)
, _acwvlPageToken :: !(Maybe Text)
, _acwvlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesVariablesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acwvlParent'
--
-- * 'acwvlXgafv'
--
-- * 'acwvlUploadProtocol'
--
-- * 'acwvlAccessToken'
--
-- * 'acwvlUploadType'
--
-- * 'acwvlPageToken'
--
-- * 'acwvlCallback'
accountsContainersWorkspacesVariablesList
:: Text -- ^ 'acwvlParent'
-> AccountsContainersWorkspacesVariablesList
accountsContainersWorkspacesVariablesList pAcwvlParent_ =
AccountsContainersWorkspacesVariablesList'
{ _acwvlParent = pAcwvlParent_
, _acwvlXgafv = Nothing
, _acwvlUploadProtocol = Nothing
, _acwvlAccessToken = Nothing
, _acwvlUploadType = Nothing
, _acwvlPageToken = Nothing
, _acwvlCallback = Nothing
}
-- | GTM Workspace\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}
acwvlParent :: Lens' AccountsContainersWorkspacesVariablesList Text
acwvlParent
= lens _acwvlParent (\ s a -> s{_acwvlParent = a})
-- | V1 error format.
acwvlXgafv :: Lens' AccountsContainersWorkspacesVariablesList (Maybe Xgafv)
acwvlXgafv
= lens _acwvlXgafv (\ s a -> s{_acwvlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
acwvlUploadProtocol :: Lens' AccountsContainersWorkspacesVariablesList (Maybe Text)
acwvlUploadProtocol
= lens _acwvlUploadProtocol
(\ s a -> s{_acwvlUploadProtocol = a})
-- | OAuth access token.
acwvlAccessToken :: Lens' AccountsContainersWorkspacesVariablesList (Maybe Text)
acwvlAccessToken
= lens _acwvlAccessToken
(\ s a -> s{_acwvlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
acwvlUploadType :: Lens' AccountsContainersWorkspacesVariablesList (Maybe Text)
acwvlUploadType
= lens _acwvlUploadType
(\ s a -> s{_acwvlUploadType = a})
-- | Continuation token for fetching the next page of results.
acwvlPageToken :: Lens' AccountsContainersWorkspacesVariablesList (Maybe Text)
acwvlPageToken
= lens _acwvlPageToken
(\ s a -> s{_acwvlPageToken = a})
-- | JSONP
acwvlCallback :: Lens' AccountsContainersWorkspacesVariablesList (Maybe Text)
acwvlCallback
= lens _acwvlCallback
(\ s a -> s{_acwvlCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesVariablesList
where
type Rs AccountsContainersWorkspacesVariablesList =
ListVariablesResponse
type Scopes AccountsContainersWorkspacesVariablesList
=
'["https://www.googleapis.com/auth/tagmanager.edit.containers",
"https://www.googleapis.com/auth/tagmanager.readonly"]
requestClient
AccountsContainersWorkspacesVariablesList'{..}
= go _acwvlParent _acwvlXgafv _acwvlUploadProtocol
_acwvlAccessToken
_acwvlUploadType
_acwvlPageToken
_acwvlCallback
(Just AltJSON)
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesVariablesListResource)
mempty
|
brendanhay/gogol
|
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Variables/List.hs
|
mpl-2.0
| 6,098 | 0 | 18 | 1,350 | 789 | 460 | 329 | 123 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.LiveBroadcasts.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Delete a given broadcast.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.liveBroadcasts.delete@.
module Network.Google.Resource.YouTube.LiveBroadcasts.Delete
(
-- * REST Resource
LiveBroadcastsDeleteResource
-- * Creating a Request
, liveBroadcastsDelete
, LiveBroadcastsDelete
-- * Request Lenses
, lbdXgafv
, lbdUploadProtocol
, lbdAccessToken
, lbdUploadType
, lbdOnBehalfOfContentOwner
, lbdOnBehalfOfContentOwnerChannel
, lbdId
, lbdCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.liveBroadcasts.delete@ method which the
-- 'LiveBroadcastsDelete' request conforms to.
type LiveBroadcastsDeleteResource =
"youtube" :>
"v3" :>
"liveBroadcasts" :>
QueryParam "id" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "onBehalfOfContentOwnerChannel" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Delete a given broadcast.
--
-- /See:/ 'liveBroadcastsDelete' smart constructor.
data LiveBroadcastsDelete =
LiveBroadcastsDelete'
{ _lbdXgafv :: !(Maybe Xgafv)
, _lbdUploadProtocol :: !(Maybe Text)
, _lbdAccessToken :: !(Maybe Text)
, _lbdUploadType :: !(Maybe Text)
, _lbdOnBehalfOfContentOwner :: !(Maybe Text)
, _lbdOnBehalfOfContentOwnerChannel :: !(Maybe Text)
, _lbdId :: !Text
, _lbdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbdXgafv'
--
-- * 'lbdUploadProtocol'
--
-- * 'lbdAccessToken'
--
-- * 'lbdUploadType'
--
-- * 'lbdOnBehalfOfContentOwner'
--
-- * 'lbdOnBehalfOfContentOwnerChannel'
--
-- * 'lbdId'
--
-- * 'lbdCallback'
liveBroadcastsDelete
:: Text -- ^ 'lbdId'
-> LiveBroadcastsDelete
liveBroadcastsDelete pLbdId_ =
LiveBroadcastsDelete'
{ _lbdXgafv = Nothing
, _lbdUploadProtocol = Nothing
, _lbdAccessToken = Nothing
, _lbdUploadType = Nothing
, _lbdOnBehalfOfContentOwner = Nothing
, _lbdOnBehalfOfContentOwnerChannel = Nothing
, _lbdId = pLbdId_
, _lbdCallback = Nothing
}
-- | V1 error format.
lbdXgafv :: Lens' LiveBroadcastsDelete (Maybe Xgafv)
lbdXgafv = lens _lbdXgafv (\ s a -> s{_lbdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
lbdUploadProtocol :: Lens' LiveBroadcastsDelete (Maybe Text)
lbdUploadProtocol
= lens _lbdUploadProtocol
(\ s a -> s{_lbdUploadProtocol = a})
-- | OAuth access token.
lbdAccessToken :: Lens' LiveBroadcastsDelete (Maybe Text)
lbdAccessToken
= lens _lbdAccessToken
(\ s a -> s{_lbdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
lbdUploadType :: Lens' LiveBroadcastsDelete (Maybe Text)
lbdUploadType
= lens _lbdUploadType
(\ s a -> s{_lbdUploadType = a})
-- | *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwner* parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
lbdOnBehalfOfContentOwner :: Lens' LiveBroadcastsDelete (Maybe Text)
lbdOnBehalfOfContentOwner
= lens _lbdOnBehalfOfContentOwner
(\ s a -> s{_lbdOnBehalfOfContentOwner = a})
-- | This parameter can only be used in a properly authorized request.
-- *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwnerChannel* parameter specifies the
-- YouTube channel ID of the channel to which a video is being added. This
-- parameter is required when a request specifies a value for the
-- onBehalfOfContentOwner parameter, and it can only be used in conjunction
-- with that parameter. In addition, the request must be authorized using a
-- CMS account that is linked to the content owner that the
-- onBehalfOfContentOwner parameter specifies. Finally, the channel that
-- the onBehalfOfContentOwnerChannel parameter value specifies must be
-- linked to the content owner that the onBehalfOfContentOwner parameter
-- specifies. This parameter is intended for YouTube content partners that
-- own and manage many different YouTube channels. It allows content owners
-- to authenticate once and perform actions on behalf of the channel
-- specified in the parameter value, without having to provide
-- authentication credentials for each separate channel.
lbdOnBehalfOfContentOwnerChannel :: Lens' LiveBroadcastsDelete (Maybe Text)
lbdOnBehalfOfContentOwnerChannel
= lens _lbdOnBehalfOfContentOwnerChannel
(\ s a -> s{_lbdOnBehalfOfContentOwnerChannel = a})
-- | Broadcast to delete.
lbdId :: Lens' LiveBroadcastsDelete Text
lbdId = lens _lbdId (\ s a -> s{_lbdId = a})
-- | JSONP
lbdCallback :: Lens' LiveBroadcastsDelete (Maybe Text)
lbdCallback
= lens _lbdCallback (\ s a -> s{_lbdCallback = a})
instance GoogleRequest LiveBroadcastsDelete where
type Rs LiveBroadcastsDelete = ()
type Scopes LiveBroadcastsDelete =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl"]
requestClient LiveBroadcastsDelete'{..}
= go (Just _lbdId) _lbdXgafv _lbdUploadProtocol
_lbdAccessToken
_lbdUploadType
_lbdOnBehalfOfContentOwner
_lbdOnBehalfOfContentOwnerChannel
_lbdCallback
(Just AltJSON)
youTubeService
where go
= buildClient
(Proxy :: Proxy LiveBroadcastsDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/LiveBroadcasts/Delete.hs
|
mpl-2.0
| 7,369 | 0 | 19 | 1,559 | 899 | 530 | 369 | 125 | 1 |
module BlockchainState
( initialBlockchainState
)
where
import Blockchain (Blockchain, genesisBlock)
import Control.Concurrent.MVar (MVar, newMVar)
initialBlockchainState :: IO (MVar Blockchain)
initialBlockchainState = newMVar [genesisBlock]
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/playpen/blockchain/blockchain-framework-DELETE/src/BlockchainState.hs
|
unlicense
| 283 | 0 | 7 | 63 | 59 | 35 | 24 | 6 | 1 |
module JDBC.Types.Clob
( freeClob,
getAsciiStreamClob,
getCharacterStreamClob,
getCharacterStreamClob2,
getSubStringClob,
lengthClob,
positionClob,
positionClob2,
setAsciiStreamClob,
setCharacterStreamClob,
setStringClob,
setStringClob2,
truncateClob)
where
import Java
import Interop.Java.IO
import JDBC.Types
foreign import java unsafe "@interface free" freeClob :: Java Clob ()
foreign import java unsafe "@interface getAsciiStream" getAsciiStreamClob :: Java Clob InputStream
foreign import java unsafe "@interface getCharacterStream" getCharacterStreamClob :: Java Clob Reader
foreign import java unsafe "@interface getCharacterStream" getCharacterStreamClob2 ::
Int64 -> Int64 -> Java Clob Reader
foreign import java unsafe "@interface getSubString" getSubStringClob :: Int64 -> Int -> Java Clob JString
foreign import java unsafe "@interface length" lengthClob :: Java Clob Int64
foreign import java unsafe "@interface position" positionClob :: Clob -> Int64 -> Java Clob Int64
foreign import java unsafe "@interface position" positionClob2 :: JString -> Int64 -> Java Clob Int64
foreign import java unsafe "@interface setAsciiStream" setAsciiStreamClob :: Int64 -> Java Clob OutputStream
foreign import java unsafe "@interface setCharacterStream" setCharacterStreamClob :: Int64 -> Java Clob Writer
foreign import java unsafe "@interface setString" setStringClob :: Int64 -> JString -> Java Clob Int
foreign import java unsafe "@interface setString" setStringClob2_ ::
Int64 -> JByteArray -> Int -> Int -> Java Clob Int
--Wrapper
setStringClob2 :: Int64 -> [Byte] -> Int -> Int -> Java Clob Int
setStringClob2 t1 t2 t3 t4 = setStringClob2_ t1 (toJava t2) t3 t4
--End Wrapper
foreign import java unsafe "@interface tuncate" truncateClob :: Int64 -> Java Clob ()
|
Jyothsnasrinivas/eta-jdbc
|
src/JDBC/Types/Clob.hs
|
apache-2.0
| 1,840 | 38 | 8 | 299 | 453 | 238 | 215 | -1 | -1 |
module Problem006 where
main =
print $ sum [2 * x * y | x <- [1..100], y <- [(x + 1)..100]]
|
vasily-kartashov/playground
|
euler/problem-006.hs
|
apache-2.0
| 95 | 0 | 12 | 25 | 60 | 33 | 27 | 3 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module HERMIT.Dictionary.WorkerWrapper.Fix
( -- * The Worker/Wrapper Transformation
-- | Note that many of these operations require 'Data.Function.fix' to be in scope.
HERMIT.Dictionary.WorkerWrapper.Fix.externals
, wwFacBR
, wwSplitR
, wwSplitStaticArg
, wwGenerateFusionT
, wwFusionBR
, wwAssA
, wwAssB
, wwAssC
, wwAssAimpliesAssB
, wwAssBimpliesAssC
, wwAssAimpliesAssC
, wwSplit
) where
import Control.Arrow
import Data.String (fromString)
import HERMIT.Core
import HERMIT.External
import HERMIT.GHC
import HERMIT.Kure hiding ((<$>))
import HERMIT.Lemma
import HERMIT.Monad
import HERMIT.Name
import HERMIT.ParserCore
import HERMIT.Utilities
import HERMIT.Dictionary.AlphaConversion
import HERMIT.Dictionary.Common
import HERMIT.Dictionary.FixPoint
import HERMIT.Dictionary.Function
import HERMIT.Dictionary.Local
import HERMIT.Dictionary.Navigation
import HERMIT.Dictionary.Reasoning
import HERMIT.Dictionary.Unfold
import HERMIT.Dictionary.WorkerWrapper.Common
import Prelude.Compat
--------------------------------------------------------------------------------------------------
-- | Externals for manipulating fixed points, and for the worker/wrapper transformation.
externals :: [External]
externals =
[
external "ww-factorisation" ((\ wrap unwrap assC -> promoteExprBiR $ wwFac (mkWWAssC assC) wrap unwrap)
:: CoreString -> CoreString -> RewriteH LCore -> BiRewriteH LCore)
[ "Worker/Wrapper Factorisation",
"For any \"f :: A -> A\", and given \"wrap :: B -> A\" and \"unwrap :: A -> B\" as arguments,",
"and a proof of Assumption C (fix A (\\ a -> wrap (unwrap (f a))) ==> fix A f), then",
"fix A f ==> wrap (fix B (\\ b -> unwrap (f (wrap b))))"
] .+ Introduce .+ Context
, external "ww-factorisation-unsafe" ((\ wrap unwrap -> promoteExprBiR $ wwFac Nothing wrap unwrap)
:: CoreString -> CoreString -> BiRewriteH LCore)
[ "Unsafe Worker/Wrapper Factorisation",
"For any \"f :: A -> A\", and given \"wrap :: B -> A\" and \"unwrap :: A -> B\" as arguments, then",
"fix A f <==> wrap (fix B (\\ b -> unwrap (f (wrap b))))",
"Note: the pre-condition \"fix A (\\ a -> wrap (unwrap (f a))) == fix A f\" is expected to hold."
] .+ Introduce .+ Context .+ PreCondition
, external "ww-split" ((\ wrap unwrap assC -> promoteDefR $ wwSplit (mkWWAssC assC) wrap unwrap)
:: CoreString -> CoreString -> RewriteH LCore -> RewriteH LCore)
[ "Worker/Wrapper Split",
"For any \"prog :: A\", and given \"wrap :: B -> A\" and \"unwrap :: A -> B\" as arguments,",
"and a proof of Assumption C (fix A (\\ a -> wrap (unwrap (f a))) ==> fix A f), then",
"prog = expr ==> prog = let f = \\ prog -> expr",
" in let work = unwrap (f (wrap work))",
" in wrap work"
] .+ Introduce .+ Context
, external "ww-split-unsafe" ((\ wrap unwrap -> promoteDefR $ wwSplit Nothing wrap unwrap)
:: CoreString -> CoreString -> RewriteH LCore)
[ "Unsafe Worker/Wrapper Split",
"For any \"prog :: A\", and given \"wrap :: B -> A\" and \"unwrap :: A -> B\" as arguments, then",
"prog = expr ==> prog = let f = \\ prog -> expr",
" in let work = unwrap (f (wrap work))",
" in wrap work",
"Note: the pre-condition \"fix A (wrap . unwrap . f) == fix A f\" is expected to hold."
] .+ Introduce .+ Context .+ PreCondition
, external "ww-split-static-arg" ((\ n is wrap unwrap assC -> promoteDefR $ wwSplitStaticArg n is (mkWWAssC assC) wrap unwrap)
:: Int -> [Int] -> CoreString -> CoreString -> RewriteH LCore -> RewriteH LCore)
[ "Worker/Wrapper Split - Static Argument Variant",
"Perform the static argument transformation on the first n arguments, then perform the worker/wrapper split,",
"applying the given wrap and unwrap functions to the specified (by index) static arguments before use."
] .+ Introduce .+ Context
, external "ww-split-static-arg-unsafe" ((\ n is wrap unwrap -> promoteDefR $ wwSplitStaticArg n is Nothing wrap unwrap)
:: Int -> [Int] -> CoreString -> CoreString -> RewriteH LCore)
[ "Unsafe Worker/Wrapper Split - Static Argument Variant",
"Perform the static argument transformation on the first n arguments, then perform the (unsafe) worker/wrapper split,",
"applying the given wrap and unwrap functions to the specified (by index) static arguments before use."
] .+ Introduce .+ Context .+ PreCondition
, external "ww-assumption-A" ((\ wrap unwrap assA -> promoteExprBiR $ wwA (Just $ extractR assA) wrap unwrap)
:: CoreString -> CoreString -> RewriteH LCore -> BiRewriteH LCore)
[ "Worker/Wrapper Assumption A",
"For a \"wrap :: B -> A\" and an \"unwrap :: A -> B\",",
"and given a proof of \"wrap (unwrap a) ==> a\", then",
"wrap (unwrap a) <==> a"
] .+ Introduce .+ Context
, external "ww-assumption-B" ((\ wrap unwrap f assB -> promoteExprBiR $ wwB (Just $ extractR assB) wrap unwrap f)
:: CoreString -> CoreString -> CoreString -> RewriteH LCore -> BiRewriteH LCore)
[ "Worker/Wrapper Assumption B",
"For a \"wrap :: B -> A\", an \"unwrap :: A -> B\", and an \"f :: A -> A\",",
"and given a proof of \"wrap (unwrap (f a)) ==> f a\", then",
"wrap (unwrap (f a)) <==> f a"
] .+ Introduce .+ Context
, external "ww-assumption-C" ((\ wrap unwrap f assC -> promoteExprBiR $ wwC (Just $ extractR assC) wrap unwrap f)
:: CoreString -> CoreString -> CoreString -> RewriteH LCore -> BiRewriteH LCore)
[ "Worker/Wrapper Assumption C",
"For a \"wrap :: B -> A\", an \"unwrap :: A -> B\", and an \"f :: A -> A\",",
"and given a proof of \"fix A (\\ a -> wrap (unwrap (f a))) ==> fix A f\", then",
"fix A (\\ a -> wrap (unwrap (f a))) <==> fix A f"
] .+ Introduce .+ Context
, external "ww-assumption-A-unsafe" ((\ wrap unwrap -> promoteExprBiR $ wwA Nothing wrap unwrap)
:: CoreString -> CoreString -> BiRewriteH LCore)
[ "Unsafe Worker/Wrapper Assumption A",
"For a \"wrap :: B -> A\" and an \"unwrap :: A -> B\", then",
"wrap (unwrap a) <==> a",
"Note: only use this if it's true!"
] .+ Introduce .+ Context .+ PreCondition
, external "ww-assumption-B-unsafe" ((\ wrap unwrap f -> promoteExprBiR $ wwB Nothing wrap unwrap f)
:: CoreString -> CoreString -> CoreString -> BiRewriteH LCore)
[ "Unsafe Worker/Wrapper Assumption B",
"For a \"wrap :: B -> A\", an \"unwrap :: A -> B\", and an \"f :: A -> A\", then",
"wrap (unwrap (f a)) <==> f a",
"Note: only use this if it's true!"
] .+ Introduce .+ Context .+ PreCondition
, external "ww-assumption-C-unsafe" ((\ wrap unwrap f -> promoteExprBiR $ wwC Nothing wrap unwrap f)
:: CoreString -> CoreString -> CoreString -> BiRewriteH LCore)
[ "Unsafe Worker/Wrapper Assumption C",
"For a \"wrap :: B -> A\", an \"unwrap :: A -> B\", and an \"f :: A -> A\", then",
"fix A (\\ a -> wrap (unwrap (f a))) <==> fix A f",
"Note: only use this if it's true!"
] .+ Introduce .+ Context .+ PreCondition
, external "ww-AssA-to-AssB" (promoteExprR . wwAssAimpliesAssB . extractR :: RewriteH LCore -> RewriteH LCore)
[ "Convert a proof of worker/wrapper Assumption A into a proof of worker/wrapper Assumption B."
]
, external "ww-AssB-to-AssC" (promoteExprR . wwAssBimpliesAssC . extractR :: RewriteH LCore -> RewriteH LCore)
[ "Convert a proof of worker/wrapper Assumption B into a proof of worker/wrapper Assumption C."
]
, external "ww-AssA-to-AssC" (promoteExprR . wwAssAimpliesAssC . extractR :: RewriteH LCore -> RewriteH LCore)
[ "Convert a proof of worker/wrapper Assumption A into a proof of worker/wrapper Assumption C."
]
, external "ww-generate-fusion" (wwGenerateFusionT . mkWWAssC :: RewriteH LCore -> TransformH LCore ())
[ "Given a proof of Assumption C (fix A (\\ a -> wrap (unwrap (f a))) ==> fix A f), then",
"execute this command on \"work = unwrap (f (wrap work))\" to enable the \"ww-fusion\" rule thereafter.",
"Note that this is performed automatically as part of \"ww-split\"."
] .+ Experiment .+ TODO
, external "ww-generate-fusion-unsafe" (wwGenerateFusionT Nothing :: TransformH LCore ())
[ "Execute this command on \"work = unwrap (f (wrap work))\" to enable the \"ww-fusion\" rule thereafter.",
"The precondition \"fix A (wrap . unwrap . f) == fix A f\" is expected to hold.",
"Note that this is performed automatically as part of \"ww-split\"."
] .+ Experiment .+ TODO
, external "ww-fusion" (promoteExprBiR wwFusion :: BiRewriteH LCore)
[ "Worker/Wrapper Fusion",
"unwrap (wrap work) <==> work",
"Note: you are required to have previously executed the command \"ww-generate-fusion\" on the definition",
" work = unwrap (f (wrap work))"
] .+ Introduce .+ Context .+ PreCondition .+ TODO
]
where
mkWWAssC :: RewriteH LCore -> Maybe WWAssumption
mkWWAssC r = Just (WWAssumption C (extractR r))
--------------------------------------------------------------------------------------------------
-- | For any @f :: A -> A@, and given @wrap :: B -> A@ and @unwrap :: A -> B@ as arguments, then
-- @fix A f@ \<==\> @wrap (fix B (\\ b -> unwrap (f (wrap b))))@
wwFacBR :: Maybe WWAssumption -> CoreExpr -> CoreExpr -> BiRewriteH CoreExpr
wwFacBR mAss wrap unwrap = beforeBiR (wrapUnwrapTypes wrap unwrap)
(\ (tyA,tyB) -> bidirectional (wwL tyA tyB) wwR)
where
wwL :: Type -> Type -> RewriteH CoreExpr
wwL tyA tyB = prefixFailMsg "worker/wrapper factorisation failed: " $
do (tA,f) <- isFixExprT
guardMsg (eqType tyA tA) ("wrapper/unwrapper types do not match fix body type.")
whenJust (verifyWWAss wrap unwrap f) mAss
b <- constT (newIdH "x" tyB)
App wrap <$> buildFixT (Lam b (App unwrap (App f (App wrap (Var b)))))
wwR :: RewriteH CoreExpr
wwR = prefixFailMsg "(reverse) worker/wrapper factorisation failed: " $
withPatFailMsg "not an application." $
do App wrap2 fx <- idR
withPatFailMsg wrongFixBody $
do (_, Lam b (App unwrap1 (App f (App wrap1 (Var b'))))) <- isFixExprT <<< constant fx
guardMsg (b == b') wrongFixBody
guardMsg (equivalentBy exprAlphaEq [wrap, wrap1, wrap2]) "wrappers do not match."
guardMsg (exprAlphaEq unwrap unwrap1) "unwrappers do not match."
whenJust (verifyWWAss wrap unwrap f) mAss
buildFixT f
wrongFixBody :: String
wrongFixBody = "body of fix does not have the form Lam b (App unwrap (App f (App wrap (Var b))))"
-- | For any @f :: A -> A@, and given @wrap :: B -> A@ and @unwrap :: A -> B@ as arguments, then
-- @fix A f@ \<==\> @wrap (fix B (\\ b -> unwrap (f (wrap b))))@
wwFac :: Maybe WWAssumption -> CoreString -> CoreString -> BiRewriteH CoreExpr
wwFac mAss = parse2beforeBiR (wwFacBR mAss)
--------------------------------------------------------------------------------------------------
-- | Given @wrap :: B -> A@, @unwrap :: A -> B@ and @work :: B@ as arguments, then
-- @unwrap (wrap work)@ \<==\> @work@
wwFusionBR :: BiRewriteH CoreExpr
wwFusionBR =
beforeBiR (prefixFailMsg "worker/wrapper fusion failed: " $
withPatFailMsg "malformed WW Fusion rule." $
do Equiv w (App unwrap (App _f (App wrap w'))) <- constT (lemmaC <$> findLemma workLabel)
guardMsg (exprSyntaxEq w w') "malformed WW Fusion rule."
return (wrap,unwrap,w)
)
(\ (wrap,unwrap,work) -> bidirectional (fusL wrap unwrap work) (fusR wrap unwrap work))
where
fusL :: CoreExpr -> CoreExpr -> CoreExpr -> RewriteH CoreExpr
fusL wrap unwrap work =
prefixFailMsg "worker/wrapper fusion failed: " $
withPatFailMsg (wrongExprForm "unwrap (wrap work)") $
do App unwrap' (App wrap' work') <- idR
guardMsg (exprAlphaEq wrap wrap') "wrapper does not match."
guardMsg (exprAlphaEq unwrap unwrap') "unwrapper does not match."
guardMsg (exprAlphaEq work work') "worker does not match."
return work
fusR :: CoreExpr -> CoreExpr -> CoreExpr -> RewriteH CoreExpr
fusR wrap unwrap work =
prefixFailMsg "(reverse) worker/wrapper fusion failed: " $
do work' <- idR
guardMsg (exprAlphaEq work work') "worker does not match."
return $ App unwrap (App wrap work)
-- | Given @wrap :: B -> A@, @unwrap :: A -> B@ and @work :: B@ as arguments, then
-- @unwrap (wrap work)@ \<==\> @work@
wwFusion :: BiRewriteH CoreExpr
wwFusion = wwFusionBR
--------------------------------------------------------------------------------------------------
-- | Save the recursive definition of work in the stash, so that we can later verify uses of 'wwFusionBR'.
-- Must be applied to a definition of the form: @work = unwrap (f (wrap work))@
-- Note that this is performed automatically as part of 'wwSplitR'.
wwGenerateFusionT :: Maybe WWAssumption -> TransformH LCore ()
wwGenerateFusionT mAss =
prefixFailMsg "generate WW fusion failed: " $
withPatFailMsg wrongForm $
do Def w e@(App unwrap (App f (App wrap (Var w')))) <- projectT
guardMsg (w == w') wrongForm
whenJust (verifyWWAss wrap unwrap f) mAss
insertLemmaT workLabel $ Lemma (Equiv (varToCoreExpr w) e) Proven NotUsed
where
wrongForm = "definition does not have the form: work = unwrap (f (wrap work))"
--------------------------------------------------------------------------------------------------
-- | \\ wrap unwrap -> (@prog = expr@ ==> @prog = let f = \\ prog -> expr in let work = unwrap (f (wrap work)) in wrap work)@
wwSplitR :: Maybe WWAssumption -> CoreExpr -> CoreExpr -> RewriteH CoreDef
wwSplitR mAss wrap unwrap =
fixIntroRecR
>>> defAllR idR ( appAllR idR (letIntroR "f")
>>> letFloatArgR
>>> letAllR idR ( forwardT (wwFacBR mAss wrap unwrap)
>>> appAllR idR ( unfoldNameR (fromString "Data.Function.fix")
>>> alphaLetWithR ["work"]
>>> letRecAllR (\ _ -> defAllR idR (betaReduceR >>> letNonRecSubstR)
>>> (extractT (wwGenerateFusionT mAss) >> idR)
)
idR
)
>>> letFloatArgR
)
)
-- | \\ wrap unwrap -> (@prog = expr@ ==> @prog = let f = \\ prog -> expr in let work = unwrap (f (wrap work)) in wrap work)@
wwSplit :: Maybe WWAssumption -> CoreString -> CoreString -> RewriteH CoreDef
wwSplit mAss wrapS unwrapS = (parseCoreExprT wrapS &&& parseCoreExprT unwrapS) >>= uncurry (wwSplitR mAss)
-- | As 'wwSplit' but performs the static-argument transformation for @n@ static arguments first, and optionally provides some of those arguments (specified by index) to all calls of wrap and unwrap.
-- This is useful if, for example, the expression, and wrap and unwrap, all have a @forall@ type.
wwSplitStaticArg :: Int -> [Int] -> Maybe WWAssumption -> CoreString -> CoreString -> RewriteH CoreDef
wwSplitStaticArg 0 _ = wwSplit
wwSplitStaticArg n is = \ mAss wrapS unwrapS ->
prefixFailMsg "worker/wrapper split (static argument variant) failed: " $
do guardMsg (all (< n) is) "arguments for wrap and unwrap must be chosen from the statically transformed arguments."
bs <- defT successT (arr collectBinders) (\ () -> take n . fst)
let args = varsToCoreExprs [ b | (i,b) <- zip [0..] bs, i `elem` is ]
staticArgPosR [0..(n-1)] >>> defAllR idR
(let wwSplitArgsR :: RewriteH CoreDef
wwSplitArgsR = do wrap <- parseCoreExprT wrapS
unwrap <- parseCoreExprT unwrapS
wwSplitR mAss (mkCoreApps wrap args) (mkCoreApps unwrap args)
in
extractR $ do p <- considerConstructT LetExpr
localPathR p $ promoteExprR (letRecAllR (const wwSplitArgsR) idR >>> letSubstR)
)
--------------------------------------------------------------------------------------------------
-- | Convert a proof of WW Assumption A into a proof of WW Assumption B.
wwAssAimpliesAssB :: RewriteH CoreExpr -> RewriteH CoreExpr
wwAssAimpliesAssB = id
-- | Convert a proof of WW Assumption B into a proof of WW Assumption C.
wwAssBimpliesAssC :: RewriteH CoreExpr -> RewriteH CoreExpr
wwAssBimpliesAssC assB = appAllR idR (lamAllR idR assB >>> etaReduceR)
-- | Convert a proof of WW Assumption A into a proof of WW Assumption C.
wwAssAimpliesAssC :: RewriteH CoreExpr -> RewriteH CoreExpr
wwAssAimpliesAssC = wwAssBimpliesAssC . wwAssAimpliesAssB
--------------------------------------------------------------------------------------------------
-- | @wrap (unwrap a)@ \<==\> @a@
wwAssA :: Maybe (RewriteH CoreExpr) -- ^ WW Assumption A
-> CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> BiRewriteH CoreExpr
wwAssA mr wrap unwrap = beforeBiR (do whenJust (verifyAssA wrap unwrap) mr
wrapUnwrapTypes wrap unwrap
)
(\ (tyA,_) -> bidirectional wwAL (wwAR tyA))
where
wwAL :: RewriteH CoreExpr
wwAL = withPatFailMsg (wrongExprForm "App wrap (App unwrap x)") $
do App wrap' (App unwrap' x) <- idR
guardMsg (exprAlphaEq wrap wrap') "given wrapper does not match wrapper in expression."
guardMsg (exprAlphaEq unwrap unwrap') "given unwrapper does not match unwrapper in expression."
return x
wwAR :: Type -> RewriteH CoreExpr
wwAR tyA = do x <- idR
guardMsg (exprKindOrType x `eqType` tyA) "type of expression does not match types of wrap/unwrap."
return $ App wrap (App unwrap x)
-- | @wrap (unwrap a)@ \<==\> @a@
wwA :: Maybe (RewriteH CoreExpr) -- ^ WW Assumption A
-> CoreString -- ^ wrap
-> CoreString -- ^ unwrap
-> BiRewriteH CoreExpr
wwA mr = parse2beforeBiR (wwAssA mr)
-- | @wrap (unwrap (f a))@ \<==\> @f a@
wwAssB :: Maybe (RewriteH CoreExpr) -- ^ WW Assumption B
-> CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> CoreExpr -- ^ f
-> BiRewriteH CoreExpr
wwAssB mr wrap unwrap f = beforeBiR (whenJust (verifyAssB wrap unwrap f) mr)
(\ () -> bidirectional wwBL wwBR)
where
assA :: BiRewriteH CoreExpr
assA = wwAssA Nothing wrap unwrap
wwBL :: RewriteH CoreExpr
wwBL = withPatFailMsg (wrongExprForm "App wrap (App unwrap (App f a))") $
do App _ (App _ (App f' _)) <- idR
guardMsg (exprAlphaEq f f') "given body function does not match expression."
forwardT assA
wwBR :: RewriteH CoreExpr
wwBR = withPatFailMsg (wrongExprForm "App f a") $
do App f' _ <- idR
guardMsg (exprAlphaEq f f') "given body function does not match expression."
backwardT assA
-- | @wrap (unwrap (f a))@ \<==\> @f a@
wwB :: Maybe (RewriteH CoreExpr) -- ^ WW Assumption B
-> CoreString -- ^ wrap
-> CoreString -- ^ unwrap
-> CoreString -- ^ f
-> BiRewriteH CoreExpr
wwB mr = parse3beforeBiR (wwAssB mr)
-- | @fix A (\ a -> wrap (unwrap (f a)))@ \<==\> @fix A f@
wwAssC :: Maybe (RewriteH CoreExpr) -- ^ WW Assumption C
-> CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> CoreExpr -- ^ f
-> BiRewriteH CoreExpr
wwAssC mr wrap unwrap f = beforeBiR (do _ <- isFixExprT
whenJust (verifyAssC wrap unwrap f) mr
)
(\ () -> bidirectional wwCL wwCR)
where
assB :: BiRewriteH CoreExpr
assB = wwAssB Nothing wrap unwrap f
wwCL :: RewriteH CoreExpr
wwCL = wwAssBimpliesAssC (forwardT assB)
wwCR :: RewriteH CoreExpr
wwCR = appAllR idR (etaExpandR "a" >>> lamAllR idR (backwardT assB))
-- | @fix A (\ a -> wrap (unwrap (f a)))@ \<==\> @fix A f@
wwC :: Maybe (RewriteH CoreExpr) -- ^ WW Assumption C
-> CoreString -- ^ wrap
-> CoreString -- ^ unwrap
-> CoreString -- ^ f
-> BiRewriteH CoreExpr
wwC mr = parse3beforeBiR (wwAssC mr)
--------------------------------------------------------------------------------------------------
verifyWWAss :: CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> CoreExpr -- ^ f
-> WWAssumption
-> TransformH x ()
verifyWWAss wrap unwrap f (WWAssumption tag ass) =
case tag of
A -> verifyAssA wrap unwrap ass
B -> verifyAssB wrap unwrap f ass
C -> verifyAssC wrap unwrap f ass
verifyAssA :: CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> RewriteH CoreExpr -- ^ WW Assumption A
-> TransformH x ()
verifyAssA wrap unwrap assA =
prefixFailMsg ("verification of worker/wrapper Assumption A failed: ") $
do _ <- wrapUnwrapTypes wrap unwrap -- this check is redundant, but will produce a better error message
verifyRetractionT wrap unwrap assA
verifyAssB :: CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> CoreExpr -- ^ f
-> RewriteH CoreExpr -- ^ WW Assumption B
-> TransformH x ()
verifyAssB wrap unwrap f assB =
prefixFailMsg ("verification of worker/wrapper assumption B failed: ") $
do (tyA,_) <- wrapUnwrapTypes wrap unwrap
a <- constT (newIdH "a" tyA)
let lhs = App wrap (App unwrap (App f (Var a)))
rhs = App f (Var a)
verifyEqualityLeftToRightT lhs rhs assB
verifyAssC :: CoreExpr -- ^ wrap
-> CoreExpr -- ^ unwrap
-> CoreExpr -- ^ f
-> RewriteH CoreExpr -- ^ WW Assumption C
-> TransformH a ()
verifyAssC wrap unwrap f assC =
prefixFailMsg ("verification of worker/wrapper assumption C failed: ") $
do (tyA,_) <- wrapUnwrapTypes wrap unwrap
a <- constT (newIdH "a" tyA)
rhs <- buildFixT f
lhs <- buildFixT (Lam a (App wrap (App unwrap (App f (Var a)))))
verifyEqualityLeftToRightT lhs rhs assC
--------------------------------------------------------------------------------------------------
wrapUnwrapTypes :: MonadCatch m => CoreExpr -> CoreExpr -> m (Type,Type)
wrapUnwrapTypes wrap unwrap = setFailMsg "given expressions have the wrong types to form a valid wrap/unwrap pair." $
funExprsWithInverseTypes unwrap wrap
--------------------------------------------------------------------------------------------------
|
beni55/hermit
|
src/HERMIT/Dictionary/WorkerWrapper/Fix.hs
|
bsd-2-clause
| 25,995 | 0 | 24 | 8,928 | 4,566 | 2,328 | 2,238 | 355 | 3 |
import NLP.LTAG.V1
import qualified Data.Set as S
-- | The set of initial trees.
ltag :: LTAG String String
ltag = LTAG
{ startSym = "S"
, iniTrees = S.fromList
[ INode "S"
[ FNode (Right "e") ] ]
, auxTrees = S.fromList
[ AuxTree (INode "S"
[ FNode (Right "a")
, INode "T"
[ FNode (Right "S")
, FNode (Right "b") ] ]) [1, 0]
, AuxTree (INode "T"
[ FNode (Right "a")
, INode "S"
[ FNode (Right "T")
, FNode (Right "b") ] ]) [1, 0] ] }
|
kawu/ltag
|
examples/v1/example2.hs
|
bsd-2-clause
| 608 | 0 | 17 | 264 | 213 | 114 | 99 | 19 | 1 |
module Process.Peer.Sender
( start )
where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.Reader
import qualified Data.ByteString.Lazy as L
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString.Lazy
import Prelude hiding (getContents)
import Process
import Supervisor
data CF = CF { chan :: TMVar L.ByteString
, sock :: Socket }
instance Logging CF where
logName _ = "Process.Peer.Sender"
-- | The raw sender process, it does nothing but send out what it syncs on.
start :: Socket -> TMVar L.ByteString -> SupervisorChannel -> IO ThreadId
start s ch supC = spawnP (CF ch s) () ({-# SCC "Sender" #-}
(cleanupP pgm
(defaultStopHandler supC)
(liftIO $ close s)))
pgm :: Process CF () ()
pgm = do
ch <- asks chan
s <- asks sock
_ <- liftIO $ do
r <- atomically $ takeTMVar ch
sendAll s r
pgm
|
jlouis/combinatorrent
|
src/Process/Peer/Sender.hs
|
bsd-2-clause
| 1,039 | 0 | 13 | 319 | 284 | 154 | 130 | 28 | 1 |
import Text.JSON.String (readJSTopType, runGetJSON)
import Text.PrettyPrint.HughesPJ (render)
import Text.JSON.Pretty (pp_value)
main = do
s <- getContents
case runGetJSON readJSTopType s of
Left e -> error e
Right j -> putStrLn . render $ pp_value j
|
polux/json-pprint
|
Main.hs
|
bsd-3-clause
| 265 | 0 | 11 | 49 | 93 | 48 | 45 | 8 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
-- The imports bring functions and datatypes into the namespace
import Network.Remote.RPC
import GuessTheNumberSupport
import System.Environment
-- Note 1: Haskell is not a scripting language.
-- Like Java, the order of top level declaration does not matter.
-- Note 2: Haskell syntax can be whitespace dependent.
-- The rules for this are easy! Just write your code how you would
-- in an imperative C syntax style language with semicolons
-- and curlybraces, keeping logical code blocks grouped by indentation
-- (or spaces), then remove the semicolons and curlybraces.
-- If this bothers you, just leave in the semicolons and curlybraces!
-- Fist, the worlds which services run on need to be declared.
-- for now they will run on different ports only, but we could
-- change their hosts.
$(makeHost "Keeper" "localhost" 9001) -- the server
$(makeHost "Guesser" "localhost" 9000) -- the client
-- Note 3: newGameServer is an "action". This is to haskell what a zero argument
-- function/method would be in most other languages. Rather than calling it
-- by writing "newGameServer();" we only have to write "newGameServer".
-- when newGameServer gets called, it returns a function representing
-- a new instance of the game! The function it returns compares a guessed number against
-- the server's number.
newGameServer = do -- "do" is a keyword a bit like "{" but without a matching "}"
-- first we declare that this action was intended to run on the host "Keeper"
onHost Keeper
-- the next line assigns the new variable r to be a random Integer.
r <- newRandomInteger
-- numberGuesser is a closure. It captures the variable r and uses it in a function
-- which leaves the scope of this action.
let numberGuesser(k) = compareTwo(k,r)
-- while haskell has the word "return", it is just an ordinary function. Rather than
-- exiting the code block with the given value, "return" just sets the resulting value
-- of the code block at this point to the given value. In fact, every line in a "do"
-- block sets the resulting value of the code block at that point to "a" value, return just
-- lets you set it manually.
return numberGuesser
-- All three above lines can be written "flip compare <$> newRandomInteger"
-- instead. Don't worry too much.
guesserClient = do
onHost Guesser
-- here we actually make a call to newGameServer to get an instance of the game.
-- the function never actually leaves the server,
-- it just allows us to make calls to the server.
guessingInstance <- $(rpcCall 'newGameServer)
repeateWhileTrue $ do
printLine "guess a number!"
answer <- readLine -- haskell type infers what you type you want to read from the terminal
result <- guessingInstance( answer ) -- the parens here are unecessary.
case result of
-- remember, we aren't exiting the action when we write "return",
-- just saying that the do block in the while statement executed to true or false.
EQ -> return False -- like break
LT -> do printLine "you guessed low. guess again"
return True -- like continue
GT -> do printLine "you guessed high. guess again"
return True -- like continue
printLine "you guessed correctly! want to play again? Input \"True\" or \"False\""
answer <- readLine
if answer
then guesserClient -- play again by calling recursivly.
else printLine "thanks for playing."
-- This is the point that actually gets run.
main = do
args <- getArgs
case args of
["-server"] -> runServer $(autoService 'Keeper)
["-client"] -> runServer guesserClient
_ -> do
putStrLn "running both the client and the server. -server or -client"
-- find all services that should run on the host Keeper,
-- and runs them on a background server
runServerBG $(autoService 'Keeper)
-- run the client as a forground process
runServer guesserClient
|
mmirman/cmu-skillswap-2012
|
GuessTheNumber.hs
|
bsd-3-clause
| 4,041 | 0 | 15 | 900 | 363 | 191 | 172 | 39 | 4 |
{-# LANGUAGE
FlexibleContexts
, FlexibleInstances
, MultiParamTypeClasses
, StandaloneDeriving
, UndecidableInstances #-}
{- |
Copyright : (c) Andy Sonnenburg 2013
License : BSD3
Maintainer : [email protected]
-}
module Control.Monad.Unify.Bool
( module Control.Monad.Unify
, Term
, true
, false
, not
, (/\)
, (\/)
, unify
, proxyTerm
) where
import Control.Monad (MonadPlus, (>=>), liftM, liftM2, mzero, when)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State.Strict (evalStateT, get, modify)
import Control.Monad.Unify
import Data.Function (fix)
import Data.List (find)
import Data.Proxy (Proxy (Proxy))
import Prelude hiding (Bool (..), not)
import Prelude (Bool)
import qualified Prelude
infixr 3 /\
infixr 2 \/
data Term var
= Var !(var (Term var))
| True
| False
| Not !(Term var)
| !(Term var) :&& !(Term var)
| !(Term var) :|| !(Term var)
deriving instance Show (var (Term var)) => Show (Term var)
proxyTerm :: Term var -> Term Proxy
proxyTerm = fix $ \ rec t -> case t of
Var _ -> Var Proxy
True -> True
False -> False
Not t' -> Not (rec t')
p :&& q -> rec p :&& rec q
p :|| q -> rec p :|| rec q
instance MonadUnify var (Term var) where
fresh = liftM Var freshVar
is = unify mzero
true :: Term var
true = True
false :: Term var
false = False
not :: Term var -> Term var
not t = case t of
Var _ -> Not t
True -> False
False -> True
Not t' -> t'
p :&& q -> not p \/ not q
p :|| q -> not p /\ not q
(/\) :: Term var -> Term var -> Term var
p /\ q = case (p, q) of
(True, _) -> q
(False, _) -> False
(_, True) -> p
(_, False) -> False
_ -> p :&& q
(\/) :: Term var -> Term var -> Term var
p \/ q = case (p, q) of
(True, _) -> True
(False, _) -> q
(_, True) -> True
(_, False) -> p
_ -> p :|| q
unify :: MonadVar var m => m () -> Term var -> Term var -> m ()
unify m p q = do
t <- semiprune $ p <+> q
cc <- unify0 t =<< freeVars t
whenM (always cc) m
semiprune :: MonadVar var m => Term var -> m (Term var)
semiprune = fix $ \ rec t -> case t of
Var var -> readVar var >>= return t `maybe` (rec >=> \ t' -> do
writeVar var t'
case t' of
Var _ -> return t'
True -> return t'
False -> return t'
_ -> return t)
True -> return True
False -> return False
Not t' -> liftM not (rec t')
p :&& q -> liftM2 (/\) (rec p) (rec q)
p :|| q -> liftM2 (\/) (rec p) (rec q)
freeVars :: MonadVar var m => Term var -> m [var (Term var)]
freeVars = liftM (keys . filter snd) . ($ []) . fix (\ rec t -> case t of
Var x -> \ xs -> if any (sameVar x . fst) xs then return xs else
readVar x >>= return ((x, Prelude.True):xs) `maybe` \ t' ->
rec t' ((x, Prelude.False):xs)
True -> return
False -> return
Not t' -> rec t'
p :&& q -> rec p >=> rec q
p :|| q -> rec p >=> rec q)
unify0 :: MonadVar var m => Term var -> [var (Term var)] -> m (Term var)
unify0 t [] = return t
unify0 t (x:xs) = do
t0 <- (x ~> false) t
t1 <- (x ~> true) t
x' <- fresh
writeVar x $! t0 \/ (x' /\ not t1)
unify0 (t0 /\ t1) xs
(~>) :: MonadVar var m => var (Term var) -> Term var -> Term var -> m (Term var)
x ~> a = flip evalStateT [(x, a)] . fix (\ rec t -> get >>= \ xs -> case t of
Var x' -> whenNothing (lookupBy (sameVar x') xs) $
lift (readVar x') >>= return t `maybe` \ t' -> do
t'' <- rec t'
modify ((x', t''):)
return t''
True -> return True
False -> return False
Not t' -> liftM not (rec t')
p :&& q -> liftM2 (/\) (rec p) (rec q)
p :|| q -> liftM2 (\/) (rec p) (rec q))
always :: MonadVar var m => Term var -> m Bool
always t = do
p <- eval t
return $! case p of
T -> Prelude.True
_ -> Prelude.False
eval :: MonadVar var m => Term var -> m Kleene
eval = fix $ \ rec t -> case t of
Var x -> readVar x >>= return I `maybe` \ t' -> do
p <- rec t'
case p of
T -> do
writeVar x True
return T
I -> return I
F -> do
writeVar x False
return F
True -> return T
False -> return F
Not t' -> notM $ rec t'
p :&& q -> rec p `andM` rec q
p :|| q -> rec p `orM` rec q
data Kleene = T | I | F
notM :: Monad m => m Kleene -> m Kleene
notM m = do
p <- m
return $! case p of
T -> F
I -> I
F -> T
andM :: Monad m => m Kleene -> m Kleene -> m Kleene
andM m n = do
p <- m
case p of
T -> n
I -> do
q <- n
return $! case q of
F -> F
_ -> I
F -> return F
orM :: Monad m => m Kleene -> m Kleene -> m Kleene
orM m n = do
p <- m
case p of
T -> return T
I -> do
q <- n
return $! case q of
T -> T
_ -> I
F -> n
(<+>) :: Term var -> Term var -> Term var
p <+> q = (p \/ q) /\ not (p /\ q)
whenM :: Monad m => m Bool -> m () -> m ()
whenM m n = m >>= flip when n
whenNothing :: Monad m => Maybe a -> m a -> m a
whenNothing p m = maybe m return p
lookupBy :: (a -> Bool) -> [(a, b)] -> Maybe b
lookupBy f = fmap snd . find (f . fst)
keys :: [(a, b)] -> [a]
keys = map fst
|
sonyandy/unvar
|
src/Control/Monad/Unify/Bool.hs
|
bsd-3-clause
| 5,114 | 0 | 21 | 1,569 | 2,636 | 1,318 | 1,318 | 197 | 9 |
module Test.FFmpeg.H264 where
import Test.Hspec (hspec, specify, describe, shouldBe)
import FFmpeg.Config as X
import Data.SL
import FFmpeg.Data.H264 as X
test :: IO ()
test = hspec $
describe "save/load" $ do
let c = defaultCfg :: H264
specify "save" $
save c "test/tmp/测试.h264"
specify "load" $ do
obj <- load "test/tmp/测试.h264"
obj `shouldBe` c
|
YLiLarry/compress-video
|
test/Test/FFmpeg/H264.hs
|
bsd-3-clause
| 408 | 0 | 12 | 106 | 128 | 69 | 59 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-------------------------------------------------------------------------------
-- |
-- Module : Bart.Departure.Proc
-- Copyright : (c) 2012 Paulo Tanimoto
-- License : BSD3
--
-- Maintainer : Paulo Tanimoto <[email protected]>
--
-------------------------------------------------------------------------------
module Bart.Departure.Proc
( bart
) where
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
import Bart.Departure.HTTP
import Bart.Departure.Parser
import Bart.Departure.Types
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.Trans.Class (MonadTrans (lift))
import Control.Lens hiding (left)
import Control.Error
import Data.Default (Default (..))
import Data.Conduit (Conduit, Pipe, ResourceT, Sink,
Source, ($$), ($=), (=$))
import qualified Data.Conduit as C
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Network.HTTP.Conduit as H
import System.Exit (exitFailure)
-------------------------------------------------------------------------------
-- Processing
-------------------------------------------------------------------------------
formatResult :: Result -> Text
formatResult Result {..} =
T.intercalate " "
[ resDest
, resColor
, T.intercalate ", " resMins
, "min"
]
bart :: Options -> IO ()
bart Departure {..} = do
res <- runEitherT $ do
-- Check if user provided a station
stn <- flip tryHead station "Error: provide a station"
-- Download the departure data
man <- lift $ H.newManager H.def
may <- lift $ C.runResourceT $ do
getDepart man $ T.pack stn
dep <- flip tryJust may "Error: could not download data"
-- Parse the departure data
return $ map parse $ dep
^. departStationsL
^. to (headDef def)
^. stationEtdsL
-- Display the results
case res of
Left msg -> err msg
Right xs -> mapM_ (T.putStrLn . formatResult) xs
where
parse Etd {..} = def
& resDestL .~ etdAbbr
& resColorL .~ (headDef def etdEsts ^. estColorL)
& resMinsL .~ (map estMinutes etdEsts)
err msg = do
errLn msg
exitFailure
|
tanimoto/bart
|
src/Bart/Departure/Proc.hs
|
bsd-3-clause
| 2,739 | 0 | 17 | 761 | 535 | 304 | 231 | 51 | 2 |
module Scheme.Evaluator.IO where
import DeepControl.MonadTrans (liftIO)
import Scheme.Parser (readSchemeCode)
import Scheme.Evaluator.Micro
import Scheme.DataType.Error.Eval
import Scheme.LISP as L
import qualified Prelude as P (foldr, foldl, length, mapM, zip)
import Prelude hiding (foldr, foldl, length, mapM, zip)
import Data.List
import qualified Data.Map as M
import System.IO
import System.FilePath ((</>))
--------------------------------------------------
-- GEnv
--------------------------------------------------
ioGEnv :: GEnv
ioGEnv = M.fromList [
("load", SYNT "load" evalLoad)
, ("newline", PROC "newline" evalNewline)
, ("display", PROC "display" evalDisplay)
, ("print", AFUNC "print" evalPrint)
, ("read", PROC "read" evalRead)
, ("printC", AFUNC "printC" evalPrintC)
, ("stacktrace", SYNT "stacktrace" evalStackTrace)
, ("stacktracelength", SYNT "stacktracelength" evalStackTraceLength)
, ("scheme-env", PROC "scheme-env" evalSchemeEnv)
, ("show", PROC "show" evalShow)
, ("showExpr", SYNT "showExpr" evalShowExpr)
, ("unittest", SYNT "stacktrace" evalUnitTest)
]
-------------------------------------------------------------
-- Procedure
-------------------------------------------------------------
-- load
evalLoad :: Synt
evalLoad (CELL (STR filename) NIL _) = do
config <- askConfig
mmv <- liftIO $ loadSchemeCodes (startDir config </> filename)
case mmv of
Left err -> throwScmError $ strMsg $ show err
Right codes -> do
ccodes <- codes >- P.mapM evalMacro
mapM_ thisEval ccodes
(*:) $ RETURN $ STR $ "load: "++ filename
evalLoad e = throwEvalError $ INVALIDForm $ show (cell (sym "load") e)
-- newline
evalNewline :: Proc
evalNewline NIL = (display "") >> (*:) VOID
evalNewline e = throwEvalError $ INVALIDForm $ show (cell (sym "newline") e)
-- display
evalDisplay :: Proc
evalDisplay (CELL (STR x) NIL _) = (*:) VOID << (liftIO $ putStr x)
evalDisplay (CELL expr NIL _) = (*:) VOID << (liftIO $ putStr $ show expr)
evalDisplay e = throwEvalError $ INVALIDForm $ show (cell (sym "display") e)
-- print
evalPrint :: AFunc
evalPrint (CELL (STR x) NIL _) = do
display x
(*:) $ STR x
evalPrint (CELL expr NIL _) = do
display $ show expr
(*:) expr
evalPrint e = throwEvalError $ INVALIDForm $ show (cell (sym "print") e)
-------------------------------------------------------------
-- Command
-------------------------------------------------------------
-- read
evalRead :: Proc
evalRead NIL = do
line <- liftIO $ getLine
read line
where
read :: String -> Scm ReturnE
read [] = throwEvalError $ INVALIDForm $ show (cell (sym "read-scheme") NIL)
read xs = case readSchemeCode xs of
Left error -> (*:) $ RETURN $ STR (show error)
Right (COMMENT s, _) -> evalRead NIL
Right (LINEBREAK, _) -> evalRead NIL
Right (EXPR expr, rest) -> (*:) $ RETURN expr
Right (EOF, _) -> evalRead NIL
evalRead e = throwEvalError $ INVALIDForm $ show (cell (sym "read-scheme") e)
-------------------------------------------------------------
-- Chaitin
-------------------------------------------------------------
-- printC: print & capture
evalPrintC :: AFunc
evalPrintC (CELL (STR x) NIL _) = do
display x
capture $ STR x
(*:) $ STR x
evalPrintC (CELL expr NIL _) = do
display $ show expr
capture expr
(*:) expr
evalPrintC e = throwEvalError $ INVALIDForm $ show (cell (sym "printC") e)
--------------------------------------------------
-- for debug
--------------------------------------------------
-- stacktrace
evalStackTrace :: Synt
evalStackTrace (CELL e NIL msp) = evalStackTrace $ CELL e (cell (INT (toInteger 10)) nil) msp
evalStackTrace (CELL e (CELL (INT n) NIL _) _) = do
st <- getStackTrace
v <- eval e
st' <- getStackTrace
let th = traceHeap st
th' = traceHeap st'
let thisst = st' >- setTraceHeap (drop (P.length th) th')
>- setTraceLength (fromInteger n)
liftIO $ printStackTrace thisst
(*:) v
evalStackTrace e = throwEvalError $ INVALIDForm $ show (cell (sym "stacktrace") e)
-- stacktracelength
evalStackTraceLength :: Synt
evalStackTraceLength (CELL (INT n) NIL _) = do
st <- getStackTrace
putStackTrace $ setTraceLength (fromInteger n) st
(*:) VOID
evalStackTraceLength e = throwEvalError $ INVALIDForm $ show (cell (sym "stackTraceLngth") e)
-- scheme-env
evalSchemeEnv :: Proc
evalSchemeEnv (CELL (STR name) NIL _) = (*:) VOID << do
genv <- getGEnv
case M.lookup name genv of
Nothing -> display $ "[env] not found: "++ name
Just v -> display $ "[env] "++ name ++": "++ show v
evalSchemeEnv NIL = (*:) VOID << do
genv <- getGEnv
display $ "[env Begin]"
liftIO $ mapM_ (\(i,x) -> putStrLn $ " "++ show i ++". "++ fst x ++": "++ show (snd x)) $ P.zip [1..] (M.toList genv)
display $ "[env End]"
evalSchemeEnv e = throwEvalError $ INVALIDForm $ show (cell (sym "scheme-env" ) e)
--------------------------------------------------
-- show
--------------------------------------------------
-- show
evalShow :: Proc
evalShow (CELL v NIL _) = do
liftIO $ putStr $ show v
(*:) VOID
evalShow e = throwEvalError $ INVALIDForm $ show (cell (sym "show") e)
-- showExpr
evalShowExpr :: Synt
evalShowExpr (CELL expr NIL _) = do
display $ showppExpr expr
(*:) VOID
evalShowExpr e = throwEvalError $ INVALIDForm $ show (cell (sym "showExpr") e)
--------------------------------------------------
-- UnitTest
--------------------------------------------------
-- unittest
evalUnitTest :: Synt
evalUnitTest (CELL (STR name) (CELL pairs@(CELL _ _ _) NIL _) _) = do
rec (L.length pairs, 0, 0, 0, "") pairs
where
rec :: (Int, Int, Int, Int, String) -> Expr -> Scm ReturnE
rec (cases, tried, 0, 0, "") NIL = do
display $ "unittest ["++ name ++"] - "++
"Cases: "++ show cases ++" "++
"Tried: "++ show tried ++" "++
"Errors: 0 "++
"Failures: 0"
(*:) VOID
rec (cases, tried, errors, failures, mes) NIL = do
display $ "////////////////////////////////////////////////////////////////////"
display $ "/// - unittest ["++ name ++"]"
liftIO $ putStr $ mes
display $ "/// - "++
"Cases: "++ show cases ++" "++
"Tried: "++ show tried ++" "++
"Errors: "++ show errors ++" "++
"Failures: "++ show failures
display $ "/// - unittest ["++ name ++"]"
display $ "////////////////////////////////////////////////////////////////////"
(*:) $ VOID
rec (cases, tried, errors, failures, mes) (CELL pair d _) = do
case pair of
CELL expr NIL msp' -> localMSP msp' $ do {
expected <- eval expr;
if expected /= VOID
then do
let v = (\(RETURN r) -> r) expected
let str1 = "/// ### failured in: "++ name ++": at "++ showMSP msp' ++"\n"
str2 = "/// tried: "++ show expr ++"\n"++
"/// expected: -" ++"\n"++
"/// but got: "++ show v ++"\n"
rec (cases, tried+1, errors, failures+1, mes ++ str1 ++ str2) d
else do
rec (cases, tried+1, errors, failures, mes) d } <| catch
CELL expr (CELL answer NIL _) msp' -> localMSP msp' $ do {
v <- eval expr >>= catchVoid;
if v /= answer
then do
let str1 = "/// ### failured in: "++ name ++": at "++ showMSP' msp' ++"\n"
str2 = "/// tried: "++ show expr ++"\n"++
"/// expected: "++ show answer ++"\n"++
"/// but got: "++ show v ++"\n"
rec (cases, tried+1, errors, failures+1, mes ++ str1 ++ str2) d
else do
rec (cases, tried+1, errors, failures, mes) d } <| catch
CELL _ _ msp' -> localMSP msp' $ throwEvalError $ strMsg $ "invalid unittest form: pair required, but got "++ show pair
_ -> throwEvalError $ strMsg $ "invalid unittest form: list required, but got "++ show pairs
where
catch x = x `catchScmError` \e -> do
msp' <- askMSP
let str = "/// ### errored in: "++ name ++": at "++ showMSP' msp' ++"\n"
++ (show e >- lines
>- P.foldr (\line acc -> "/// "++ line ++"\n"++ acc) "") ++"/// \n"
rec (cases, tried+1, errors+1, failures, mes ++ str) d
(*:) VOID
showMSP' Nothing = "---"
showMSP' (Just sp) = show sp
rec _ _ = throwEvalError $ strMsg $ "invalid unittest form: list required, but got "++ show pairs
evalUnitTest e = throwEvalError $ INVALIDForm $ show (cell (sym "unittest") e)
|
ocean0yohsuke/Scheme
|
src/Scheme/Evaluator/IO.hs
|
bsd-3-clause
| 9,123 | 30 | 27 | 2,535 | 2,968 | 1,526 | 1,442 | 177 | 10 |
{-# LANGUAGE TemplateHaskell, PackageImports, TypeFamilies, FlexibleContexts,
FlexibleInstances, TupleSections #-}
module Text.Papillon.Core (
-- * For Text.Papillon library
papillonCore,
Source(..),
SourceList(..),
-- ** For parse error message
ParseError,
mkParseError,
peDerivs,
peReading,
peMessage,
peCode,
peComment,
pePosition,
pePositionS,
Pos(..),
ListPos(..),
-- * For papillon command
papillonFile,
PPragma(..),
ModuleName,
Exports,
Code,
(<*>),
(<$>),
runError
) where
import Language.Haskell.TH hiding (infixApp, doE)
import "monads-tf" Control.Monad.State
import "monads-tf" Control.Monad.Identity
import "monads-tf" Control.Monad.Error
import Control.Applicative
import Text.Papillon.Parser
import Data.Maybe
import Data.IORef
import Data.Char
import Text.Papillon.List
import System.IO.Unsafe
dvPosN :: String -> Name
dvPosN prefix = mkName $ prefix ++ "position"
mkPrName :: String -> String -> Name
mkPrName prefix = mkName . (prefix ++)
mkPrUName :: String -> String -> Name
mkPrUName prefix = mkName . (capitalize prefix ++)
where
capitalize "" = ""
capitalize (h : t) = toUpper h : t
papillonCore :: String -> DecsQ
papillonCore str = case flip evalState Nothing $ runErrorT $ peg $ parse str of
Right (stpegq, _) -> do
let (monad, src, prefix, parsed) = stpegq
decParsed True monad src prefix parsed
Left err -> error $ "parse error: " ++ showParseError err
papillonFile :: String ->
Q ([PPragma], ModuleName, Maybe Exports, Code, DecsQ, Code)
papillonFile str = case flip evalState Nothing $ runErrorT $ pegFile $ parse str of
Right (pegfileq, _) -> do
let (prgm, mn, ppp, pp, (monad, src, prefix, parsed), atp) = pegfileq
lu = listUsed parsed
ou = optionalUsed parsed
addApplicative = if lu || ou
then "import Control.Applicative" ++
"(Applicative, (<$>), (<*>))\n" else ""
addIdentity = if isJust monad then ""
else "import \"monads-tf\" Control.Monad.Identity\n"
return (prgm, mn, ppp,
addApplicative ++ addIdentity ++ pp,
decs monad src prefix parsed, atp)
where
decs = decParsed False
Left err -> error $ "parse error: " ++ showParseError err
decParsed :: Bool -> Maybe Type -> Type -> String -> Peg -> DecsQ
decParsed th monad src prefix parsed = do
let d = derivs th (fromMaybe (ConT $ identityN th) monad) src prefix parsed
pt = SigD (mkPrName prefix "parse") $
src `arrT` ConT (mkPrUName prefix "Derivs")
p <- funD (mkPrName prefix "parse") [mkParseBody th (isJust monad) prefix parsed]
d' <- d
return [d', pt, p]
derivs :: Bool -> Type -> Type -> String -> Peg -> DecQ
derivs th monad src prefix pg = do
ns <- notStrict
return $ DataD [] (mkPrUName prefix "Derivs") [] Nothing [
RecC (mkPrUName prefix "Derivs") $ map (derivs1 ns) pg ++ [
(mkPrName prefix dvCharsN, ns, resultT tkn),
(dvPosN prefix, ns, resultT $ ConT (mkName "Pos") `AppT` src)
]] []
where
tkn = ConT (mkName "Token") `AppT` src
derivs1 ns (name, Just t, _) = (mkPrName prefix name, ns, resultT t)
derivs1 ns (name, Nothing, _) =
(mkPrName prefix name, ns, resultT $ TupleT 0)
resultT typ = ConT (errorTTN th)
`AppT` (ConT (mkName "ParseError")
`AppT` (ConT (mkName "Pos") `AppT` src)
`AppT` ConT (mkPrUName prefix "Derivs"))
`AppT` monad
`AppT` (TupleT 2 `AppT` typ `AppT` ConT (mkPrUName prefix "Derivs"))
type Variables = [(String, [Name])]
newVariable :: IORef Int -> Variables -> String -> Q Variables
newVariable g vs n = (: vs) . (n ,) <$> vars
where vars = runIO $ unsafeInterleaveIO $ (:)
<$> runQ (newNewName g n) <*> runQ vars
getVariable :: String -> Variables -> Name
getVariable = ((head . fromJust) .) . lookup
nextVariable :: String -> Variables -> Variables
nextVariable n vs = (n, tail $ fromJust $ lookup n vs) : vs
mkParseBody :: Bool -> Bool -> String -> Peg -> ClauseQ
mkParseBody th monadic prefix pg = do
glb <- runIO $ newIORef 1
vars <- foldM (newVariable glb) [] [
"parse", "chars", "pos", "d", "c", "s", "s'", "x", "t", "err", "b",
"list", "list1", "optional"]
let pgn = getVariable "parse" vars
rets <- mapM (newNewName glb . \(n, _, _) -> prefix ++ n) pg
rules <- mapM (newNewName glb . \(n, _, _) -> prefix ++ n) pg
let decs = flip evalState vars $ (:)
<$> (FunD pgn <$> (: []) <$> mkParseCore th prefix rets rules)
<*> zipWithM mkr rules pg
list = if not $ listUsed pg then return [] else listDec
(getVariable "list" vars) (getVariable "list1" vars) th
opt = if not $ optionalUsed pg then return [] else optionalDec
(getVariable "optional" vars) th
lst <- list
op <- opt
return $ flip (Clause []) (decs ++ lst ++ op) $ NormalB $
VarE pgn `AppE` VarE (mkName "initialPos")
where
mkr rule (_, _, sel) =
flip (ValD $ VarP rule) [] . NormalB <$> mkRule th monadic prefix sel
mkParseCore :: Bool -> String -> [Name] -> [Name] -> State Variables Clause
mkParseCore th prefix rets rules = do
arr <- mapM (gets . getVariable) ["chars", "pos", "s", "d"]
let [ch, p, s, d] = arr
let def ret rule = flip (ValD $ VarP ret) [] $
NormalB $ VarE (runStateTN th) `AppE` VarE rule `AppE` VarE d
pc <- parseChar th prefix
return $ Clause [VarP p, VarP s] (NormalB $ VarE d) $ [
flip (ValD $ VarP d) [] $ NormalB $ foldl1 AppE $
ConE (mkPrUName prefix "Derivs") : map VarE rets ++ [VarE ch,
VarE (mkName "return") `AppE` TupE [VarE p, VarE d]]
] ++ zipWith def rets rules ++ [pc]
parseChar :: Bool -> String -> State Variables Dec
parseChar th prefix = do
arr <- mapM (gets . getVariable)
["parse", "chars", "pos", "c", "s", "s'", "d"]
let [prs, ch, p, c, s, s', d] = arr
let emsg = "end of input"
np = VarE (mkName "updatePos") `AppE` VarE c `AppE` VarE p
return $ flip (ValD $ VarP ch) [] $ NormalB $ VarE (runStateTN th) `AppE`
CaseE (VarE (mkName "getToken") `AppE` VarE s) [
Match (mkName "Just" `ConP` [TupP [VarP c, VarP s']])
(NormalB $ DoE $ map NoBindS [
VarE (putN th) `AppE`
(VarE prs `AppE` np
`AppE` VarE s'),
VarE (mkName "return") `AppE` VarE c])
[],
flip (Match WildP) [] $ NormalB $
throwErrorTH th prefix (mkName "undefined") [] emsg "" ""
] `AppE` VarE d
mkRule :: Bool -> Bool -> String -> Selection -> State Variables Exp
mkRule t m prefix s = (VarE (mkName "foldl1") `AppE` VarE (mplusN t) `AppE`) . ListE <$>
case s of
exs -> expression t m prefix `mapM` exs
expression :: Bool -> Bool -> String -> Expression -> State Variables Exp
expression th m prefix (Left (e, r)) =
-- (doE . (++ [NoBindS $ retLift `AppE` r]) . concat <$>) $
(doE . (++ [NoBindS $ mkRetLift r]) . concat <$>) $
forM e $ \(la, ck) ->
lookahead th prefix la (show $ pprCheck ck) (getReadings ck) =<<
check th m prefix ck
where
mkRetLift (Just rr) = retLift rr
mkRetLift Nothing = VarE (mkName "return") `AppE` TupE []
retLift x = if m
then VarE (liftN th) `AppE` (VarE (liftN th) `AppE` x)
else VarE (mkName "return") `AppE` x
getReadings (Left (_, rf, _)) = readings rf
getReadings (Right _) = [dvCharsN]
expression th _ prefix (Right e) = do
c <- gets $ getVariable "c"
modify $ nextVariable "c"
let e' = [(Here, Left ((VarP c, ""), FromVariable Nothing,
Just (e `AppE` VarE c, "")))]
r = VarE c
expression th False prefix (Left (e', Just r))
check :: Bool -> Bool -> String -> Check -> State Variables [Stmt]
check th monadic prefix (Left ((n, nc), rf, test)) = do
t <- gets $ getVariable "t"
d <- gets $ getVariable "d"
b <- gets $ getVariable "b"
modify $ nextVariable "t"
modify $ nextVariable "d"
modify $ nextVariable "b"
case (n, test) of
(WildP, Just p) -> ((BindS (VarP d) (VarE $ getN th) :) .
(: afterCheck th monadic prefix b p d (readings rf))) .
BindS WildP <$> transReadFrom th monadic prefix rf
(_, Just p)
| notHaveOthers n -> do
let bd = BindS (VarP d) $ VarE $ getN th
m = LetS [ValD n (NormalB $ VarE t) []]
c = afterCheck th monadic prefix b p d (readings rf)
s <- BindS (VarP t) <$> transReadFrom th monadic prefix rf
return $ [bd, s, m] ++ c
| otherwise -> do
let bd = BindS (VarP d) $ VarE $ getN th
m = beforeMatch th prefix t n d (readings rf) nc
c = afterCheck th monadic prefix b p d (readings rf)
s <- BindS (VarP t) <$> transReadFrom th monadic prefix rf
return $ [bd, s] ++ m ++ c
(WildP, _) -> sequence [
BindS WildP <$> transReadFrom th monadic prefix rf,
return $ NoBindS $ VarE (mkName "return") `AppE` TupE []
]
_ | notHaveOthers n ->
(: []) . BindS n <$> transReadFrom th monadic prefix rf
| otherwise -> do
let bd = BindS (VarP d) $ VarE $ getN th
m = beforeMatch th prefix t n d (readings rf) nc
s <- BindS (VarP t) <$> transReadFrom th monadic prefix rf
return $ bd : s : m
where
notHaveOthers (VarP _) = True
notHaveOthers (TupP pats) = all notHaveOthers pats
notHaveOthers (BangP _) = True
notHaveOthers _ = False
check th monadic prefix (Right (c, l)) =
check th monadic prefix
(Left ((WildP, ""), FromL l $ FromSelection sel, Nothing))
where
sel = [Left
([(Here, Left ((LitP $ CharL c, ""), FromVariable Nothing, Nothing))],
Just $ if monadic then VarE (mkName "return") `AppE` TupE [] else TupE [])]
lookahead :: Bool -> String -> Lookahead -> String -> [String] -> [Stmt] ->
State Variables [Stmt]
lookahead _ _ Here _ _ ret = return ret
lookahead th _ Ahead _ _ ret = do
d <- gets $ getVariable "d"
modify $ nextVariable "d"
return [BindS (VarP d) $ VarE (getN th),
BindS WildP $ doE ret,
NoBindS $ VarE (putN th) `AppE` VarE d]
lookahead th prefix (NAhead com) ck ns ret = do
d <- gets $ getVariable "d"
modify $ nextVariable "d"
n <- negative th prefix ('!' : ck) com
d ns (doE ret)
return [BindS (VarP d) $ VarE (getN th),
NoBindS n,
NoBindS $ VarE (putN th) `AppE` VarE d]
negative :: Bool -> String -> String -> String -> Name -> [String] -> Exp ->
State Variables Exp
negative th prefix code com d ns act = do
err <- gets $ getVariable "err"
modify $ nextVariable "err"
return $ DoE [
BindS (VarP err) $ infixApp
(infixApp act (VarE $ mkName ">>")
(VarE (mkName "return") `AppE`
ConE (mkName "False")))
(VarE $ catchErrorN th)
(VarE (mkName "const") `AppE`
(VarE (mkName "return") `AppE`
ConE (mkName "True"))),
NoBindS $ VarE (unlessN th) `AppE` VarE err `AppE`
throwErrorTH th prefix d ns "not match: " code com]
transReadFrom :: Bool -> Bool -> String -> ReadFrom -> State Variables Exp
transReadFrom th _ prefix (FromVariable Nothing) = return $
ConE (stateTN th) `AppE` VarE (mkPrName prefix dvCharsN)
transReadFrom th _ prefix (FromVariable (Just var)) = return $
ConE (stateTN th) `AppE` VarE (mkPrName prefix var)
transReadFrom th m prefix (FromSelection sel) = mkRule th m prefix sel
transReadFrom th m prefix (FromL List rf) = do
list <- gets $ getVariable "list"
(VarE list `AppE`) <$> transReadFrom th m prefix rf
transReadFrom th m prefix (FromL List1 rf) = do
list1 <- gets $ getVariable "list1"
(VarE list1 `AppE`) <$> transReadFrom th m prefix rf
transReadFrom th m prefix (FromL Optional rf) = do
opt <- gets $ getVariable "optional"
(VarE opt `AppE`) <$> transReadFrom th m prefix rf
beforeMatch :: Bool -> String -> Name -> Pat -> Name -> [String] -> String -> [Stmt]
beforeMatch th prefix t nn d ns nc = [
NoBindS $ CaseE (VarE t) [
flip (Match $ vpw nn) [] $ NormalB $
VarE (mkName "return") `AppE` TupE [],
flip (Match WildP) [] $ NormalB $
throwErrorTH th prefix d ns "not match pattern: " (show $ ppr nn) nc],
LetS [ValD nn (NormalB $ VarE t) []],
NoBindS $ VarE (mkName "return") `AppE` TupE []]
where
vpw (VarP _) = WildP
vpw (ConP n ps) = ConP n $ map vpw ps
vpw (InfixP p1 n p2) = InfixP (vpw p1) n (vpw p2)
vpw (UInfixP p1 n p2) = InfixP (vpw p1) n (vpw p2)
vpw (ListP ps) = ListP $ vpw `map` ps
vpw (TupP ps) = TupP $ vpw `map` ps
vpw o = o
afterCheck :: Bool -> Bool -> String -> Name -> (Exp, String) -> Name -> [String] -> [Stmt]
afterCheck th monadic prefix b (pp, pc) d ns = [
BindS (VarP b) $ retLift pp,
NoBindS $ VarE (unlessN th) `AppE` VarE b `AppE`
throwErrorTH th prefix d ns "not match: " (show $ ppr pp) pc]
where
retLift x = if monadic
then VarE (liftN th) `AppE` (VarE (liftN th) `AppE` x)
else VarE (mkName "return") `AppE` x
listUsed, optionalUsed :: Peg -> Bool
listUsed = any $ sel . \(_, _, s) -> s
where
sel = any ex
ex (Left e) = any (either (rf . \(_, r, _) -> r) chr . snd) $ fst e
ex (Right _) = False
chr (_, List) = True
chr (_, List1) = True
chr (_, _) = False
rf (FromL List _) = True
rf (FromL List1 _) = True
rf (FromSelection s) = sel s
rf _ = False
optionalUsed = any $ sel . \(_, _, s) -> s
where
sel = any ex
ex (Left e) = any (either (rf . \(_, r, _) -> r) chr . snd) $ fst e
ex (Right _) = False
chr (_, Optional) = True
chr (_, _) = False
rf (FromL Optional _) = True
rf (FromSelection s) = sel s
rf _ = False
throwErrorTH :: Bool -> String -> Name -> [String] -> String -> String -> String -> Exp
throwErrorTH th prefix d ns msg code com = InfixE
(Just $ ConE (stateTN th) `AppE` VarE (dvPosN prefix))
(VarE $ mkName ">>=")
(Just $ InfixE
(Just $ VarE $ throwErrorN th)
(VarE $ mkName ".")
(Just $ VarE (mkName "mkParseError")
`AppE` LitE (StringL code)
`AppE` LitE (StringL msg)
`AppE` LitE (StringL com)
`AppE` VarE d
`AppE` ListE (map (LitE . StringL) ns)))
newNewName :: IORef Int -> String -> Q Name
newNewName g base = do
n <- runIO $ readIORef g
runIO $ modifyIORef g succ
newName $ base ++ show n
showParseError :: ParseError (Pos String) Derivs -> String
showParseError pe =
unwords (map (showReading d) ns) ++ (if null ns then "" else " ") ++
m ++ c ++ " at position: " ++ show p
where
[c, m, _] = ($ pe) `map` [peCode, peMessage, peComment]
ns = peReading pe
d = peDerivs pe
p = pePositionS pe
showReading :: Derivs -> String -> String
showReading d n
| n == dvCharsN = case flip evalState Nothing $ runErrorT $ char d of
Right (c, _) -> show c
Left _ -> error "bad"
showReading d "hsw" = case flip evalState Nothing $ runErrorT $ hsw d of
Right (c, _) -> show c
Left _ -> error "bad"
showReading _ n = "yet: " ++ n
doE :: [Stmt] -> Exp
doE [NoBindS ex] = ex
doE stmts = DoE stmts
arrT :: Type -> Type -> Type
arrT a r = ArrowT `AppT` a `AppT` r
infixApp :: Exp -> Exp -> Exp -> Exp
infixApp e1 op e2 = InfixE (Just e1) op (Just e2)
stateTN, runStateTN, putN, getN :: Bool -> Name
stateTN True = 'StateT
stateTN False = mkName "StateT"
runStateTN True = 'runStateT
runStateTN False = mkName "runStateT"
putN True = 'put
putN False = mkName "put"
getN True = 'get
getN False = mkName "get"
unlessN, mplusN :: Bool -> Name
unlessN True = 'unless
unlessN False = mkName "unless"
mplusN True = 'mplus
mplusN False = mkName "mplus"
throwErrorN, catchErrorN :: Bool -> Name
throwErrorN True = 'throwError
throwErrorN False = mkName "throwError"
catchErrorN True = 'catchError
catchErrorN False = mkName "catchError"
errorTTN, identityN :: Bool -> Name
errorTTN True = ''ErrorT
errorTTN False = mkName "ErrorT"
identityN True = ''Identity
identityN False = mkName "Identity"
liftN :: Bool -> Name
liftN True = 'lift
liftN False = mkName "lift"
readings :: ReadFrom -> [String]
readings (FromVariable (Just s)) = [s]
readings (FromVariable _) = [dvCharsN]
readings (FromL _ rf) = readings rf
readings (FromSelection s) = concat $
(mapM $ either
(either (readings . \(_, rf, _) -> rf) (const [dvCharsN]) . snd .
head . fst)
(const [dvCharsN])) s
|
YoshikuniJujo/papillon
|
src/Text/Papillon/Core.hs
|
bsd-3-clause
| 15,470 | 293 | 22 | 3,351 | 7,481 | 3,845 | 3,636 | 395 | 8 |
{-
Copyright 2014 Google Inc. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import Data.Foldable (for_)
import Data.Monoid
import Data.Text.Lazy as TL
import Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Lazy.IO as TL
import Github.Auth
import Github.PullRequests
import Github.Repos.Webhooks.Validate (isValidPayload)
import Network.HTTP.Types.Status (forbidden403)
import Options.Applicative hiding (header)
import System.IO (stderr)
import System.Posix.Process (forkProcess, getProcessStatus)
import Web.Scotty
import Github.PullRequests.Mailer
import Github.PullRequests.Mailer.Opts
-- | A helper function that parses given data to a JSON object.
parse :: (A.FromJSON a) => BL.ByteString -> ActionM a
parse payload =
maybe (raise $ "jsonData - no parse: " <> TL.decodeUtf8 payload) return
. A.decode $ payload
main :: IO ()
main = do
opts <- parseOptsAndEnv id
-- TODO udate description for the server
( progDesc "Receive GitHub pull request webbooks and send\
\ the patch series via email"
)
case opts of
Opts { optsSecret = Nothing } ->
die $ "The server needs to have " ++ secretEnvVar ++ " set to verify\
\ GitHub's webhooks."
Opts { optsNoThreadTracking = False
, optsAuth = Nothing
} ->
die $ "Thread tracking requires " ++ tokenEnvVar ++ " to be set."
Opts { optsNoThreadTracking = False
, optsDiscussionLocation = Nothing
} ->
die $ "Thread tracking requires --discussion-location."
-- Passive mode (no thread tracking).
Opts { optsNoThreadTracking = True
, optsAuth = m'auth
, optsSecret = Just secret
, optsRecipient = recipient
, optsReplyTo = replyTo
, optsPostCheckoutHook = checkoutHookCmd
} ->
pullRequestToThreadServer m'auth secret recipient replyTo
checkoutHookCmd Nothing
-- Normal mode (thread tracking).
Opts { optsNoThreadTracking = False
, optsAuth = m'auth@(Just _)
, optsSecret = Just secret
, optsDiscussionLocation = m'loc@(Just _)
, optsRecipient = recipient
, optsReplyTo = replyTo
, optsPostCheckoutHook = checkoutHookCmd
} ->
pullRequestToThreadServer m'auth secret recipient replyTo
checkoutHookCmd m'loc
-- | Runs an action in a separate unix process. Blocks until finished.
forkWait :: IO () -> IO ()
forkWait f = forkProcess f >>= void . getProcessStatus True False
pullRequestToThreadServer :: Maybe GithubAuth -- ^ Github authentication
-> String -- ^ Hook verification secret
-> String -- ^ recipient email address
-> Maybe String -- ^ reply-to email address
-> Maybe String -- ^ post-checkout hook program
-> Maybe String -- ^ discussion location; Nothing
-- disables posting/tracking
-> IO ()
pullRequestToThreadServer m'auth
secret
recipient
replyTo
checkoutHookCmd
m'discussionLocation =
scotty 8014 $ do
-- The exception-catching `defaultHandler` must come before the other
-- routes to catch its exceptions, see http://stackoverflow.com/q/26747855
defaultHandler $ \errText -> do
-- We do not want to disclose the text of IO exceptions to the client;
-- we log them to stderr instead.
liftIO $ TL.hPutStrLn stderr errText
text "Internal server error\r\n"
post "/" $ do
digest <- fmap TL.unpack <$> header "X-Hub-Signature"
payload <- body
if isValidPayload secret digest (BL.toStrict payload)
then do
run payload
text ""
else do
status forbidden403
text "Invalid or missing hook verification digest"
where
run payload = do
pre <- parse payload :: ActionM PullRequestEvent
when (pullRequestEventAction pre `elem`
[ PullRequestOpened, PullRequestSynchronized ]) . liftIO $ do
-- TODO: Logging
let pr = pullRequestEventPullRequest pre
prid = detailedPullRequestToPRID pr
-- Fork process so that cd'ing into temporary directories doesn't
-- change the cwd of the server.
forkWait $ do
-- Pull code, send the mail.
tInfo <- pullRequestToThread m'auth prid recipient replyTo
checkoutHookCmd
-- Post comment into PR if enabled and we have auth.
for_ m'auth $ \auth ->
for_ m'discussionLocation $ \discussionLocation ->
postMailerInfoComment auth prid discussionLocation tInfo
|
google/pull-request-mailer
|
executables/pull-request-mailer-server/Main.hs
|
bsd-3-clause
| 5,410 | 0 | 19 | 1,789 | 888 | 480 | 408 | 99 | 5 |
--------------------------------------------------------------------------------
-- Copyright © 2011 National Institute of Aerospace / Galois, Inc.
--------------------------------------------------------------------------------
-- | Stream construction.
{-# LANGUAGE Trustworthy #-}
module Copilot.Language.Operators.Temporal
( (++)
, drop
) where
import Copilot.Core (Typed)
import Copilot.Language.Prelude
import Copilot.Language.Stream
import Prelude ()
--------------------------------------------------------------------------------
infixr 1 ++
(++) :: Typed a => [a] -> Stream a -> Stream a
(++) = (`Append` Nothing)
drop :: Typed a => Int -> Stream a -> Stream a
drop 0 s = s
drop _ ( Const j ) = Const j
drop i ( Drop j s ) = Drop (fromIntegral i + j) s
drop i s = Drop (fromIntegral i) s
|
leepike/copilot-language
|
src/Copilot/Language/Operators/Temporal.hs
|
bsd-3-clause
| 844 | 0 | 8 | 152 | 210 | 118 | 92 | 16 | 1 |
module Phone where
import Data.Char
import Data.List
data DaPhone = DaPhone [(Digit, [Char])]
type Digit = Char
type Presses = Int
getCharDigitPresses :: Char -> [(Digit, [Char])] -> (Digit, Presses)
getCharDigitPresses c ((digit, chars) : digitsChars) =
case charElemIndex of
Nothing -> getCharDigitPresses c digitsChars
Just charIndex -> (digit, charIndex + 1)
where charElemIndex = elemIndex c chars
reverseTaps :: DaPhone -> Char -> [(Digit, Presses)]
reverseTaps (DaPhone digitsChars) c
| isAsciiUpper c = [getCharDigitPresses '^' digitsChars, getCharDigitPresses (toLower c) digitsChars]
| otherwise = [getCharDigitPresses c digitsChars]
cellPhonesDead :: DaPhone -> String -> [(Digit, Presses)]
cellPhonesDead daPhone = concatMap (reverseTaps daPhone)
fingerTaps :: [(Digit, Presses)] -> Presses
fingerTaps = sum . snd . unzip
charFingerTaps :: DaPhone -> Char -> Presses
charFingerTaps daPhone = fingerTaps . reverseTaps daPhone
mostPopularLetter :: String -> Char
mostPopularLetter = head . minimumBy (\s1 s2 -> compare (length s2) (length s1)) . group . sort
defaultPhone = DaPhone
[
('1', ""),
('2', "abc2"),
('3', "def3"),
('4', "ghi4"),
('5', "jkl5"),
('6', "mno6"),
('7', "pqrs7"),
('8', "tuv8"),
('9', "wxyz9"),
('*', "*^"),
('0', "+_ 0"),
('#', "#.,")
]
convo :: [String]
convo =
["Wanna play 20 questions",
"Ya",
"U 1st haha",
"Lol ok. Have u ever tasted alcohol lol",
"Lol ya",
"Wow ur cool haha. Ur turn",
"Ok. Do u think I am pretty Lol",
"Lol ya",
"Haha thanks just making sure rofl ur turn"]
|
abhean/phffp-examples
|
src/Phone.hs
|
bsd-3-clause
| 1,587 | 0 | 13 | 300 | 543 | 312 | 231 | 49 | 2 |
module Plunge.Parsers.PreprocessorOutput
( runCppParser
, Section(..)
) where
import Text.Parsec
import Plunge.Types.PreprocessorOutput
type CppParser = ParsecT String LineNumber IO
--------------------------------------------------------------------------------
manyTillWithEnd :: (Stream s m t) => ParsecT s u m a
-> ParsecT s u m end
-> ParsecT s u m ([a], end)
manyTillWithEnd p end = go []
where
p_end cont = do
e <- end
return (reverse cont, e)
p_next cont = do
p' <- p
go (p':cont)
go cont = (p_end cont) <|> (p_next cont)
--------------------------------------------------------------------------------
runCppParser :: FilePath -> String -> IO (Either ParseError [Section])
runCppParser path contents = runParserT aCppFile 1 path contents
aCppFile :: CppParser [Section]
aCppFile = many aSection
aSection :: CppParser Section
aSection = (try aSectionMiscDirective)
<|> (try aSectionExpansion)
<|> aSectionBlock
aSectionMiscDirective :: CppParser Section
aSectionMiscDirective = do
p0 <- getPosition
(lineNum, fileName) <- aDirectivePreamble
otherFlags <- optionMaybe aMiscFlags
_ <- newline
p1 <- getPosition
modifyState (\_ -> lineNum)
return $ MiscDirective
{ directive = CppDirective lineNum fileName (fromJustList otherFlags)
, lineRange = LineRange (sourceLine p0) (sourceLine p1)
}
where
fromJustList jlst = case jlst of
Nothing -> []
Just lst -> lst
aSectionExpansion :: CppParser Section
aSectionExpansion = do
p0 <- getPosition
num <- getState
ed <- aEnterFileDirective
(secs, rd) <- aSection `manyTillWithEnd` (try aReturnFileDirective)
let (CppDirective rdNum _ _) = rd
p1 <- getPosition
modifyState (\_ -> rdNum)
return $ Expansion
{ enterDirective = ed
, returnDirective = rd
, startLine = num
, sections = secs
, lineRange = LineRange (sourceLine p0) (sourceLine p1)
}
aSectionBlock :: CppParser Section
aSectionBlock = do
p0 <- getPosition
startLn <- getState
ls <- many1 plainLine
p1 <- getPosition
modifyState (\n -> n + (length ls))
return $ Block ls startLn $ LineRange (sourceLine p0) (sourceLine p1)
where
plainLine = do
_ <- lookAhead $ noneOf "#"
(l, nl) <- manyTillWithEnd anyChar (try newline)
return $ l ++ [nl]
aEnterFileDirective :: CppParser CppDirective
aEnterFileDirective = do
(lineNum, fileName) <- aDirectivePreamble
_ <- char ' '
enterFlag <- aEnterFile
otherFlags <- aMiscFlags
_ <- newline
return $ CppDirective lineNum fileName (enterFlag:otherFlags)
aReturnFileDirective :: CppParser CppDirective
aReturnFileDirective = do
(lineNum, fileName) <- aDirectivePreamble
_ <- char ' '
returnFlag <- aReturnFile
otherFlags <- aMiscFlags
_ <- newline
return $ CppDirective lineNum fileName (returnFlag:otherFlags)
aDirectivePreamble :: CppParser (Int, String)
aDirectivePreamble = do
_ <- string "# "
lineNumStr <- many1 digit
_ <- string " \""
fileNameStr <- many1 (noneOf "\"")
_ <- char '"'
return $ (read lineNumStr, fileNameStr)
aEnterFile, aReturnFile, aSystemHeader, aExternC :: CppParser DirectiveFlag
aEnterFile = char '1' >> return EnterFile
aReturnFile = char '2' >> return ReturnFile
aSystemHeader = char '3' >> return SystemHeader
aExternC = char '4' >> return ExternC
aMiscFlags :: CppParser [DirectiveFlag]
aMiscFlags = option [] someFlags
where
someFlags = do
sh <- optionMaybe (char ' ' >> aSystemHeader)
ec <- optionMaybe (char ' ' >> aExternC)
case (sh, ec) of
(Just sh', Just ec') -> return [sh', ec']
(Just sh', Nothing ) -> return [sh' ]
(Nothing, Just ec') -> return [ ec']
(Nothing, Nothing ) -> return [ ]
|
sw17ch/plunge
|
src/Plunge/Parsers/PreprocessorOutput.hs
|
bsd-3-clause
| 3,955 | 0 | 13 | 989 | 1,263 | 630 | 633 | 105 | 4 |
{-# LANGUAGE OverloadedStrings #-}
-- | Intero page.
module HL.Controller.Intero where
import HL.Controller
import HL.Controller.Html
import HL.View
-- | Intero page.
getInteroR :: C (Html ())
getInteroR =
htmlPage "Intero for Emacs" "intero.html"
|
haskell-lang/haskell-lang
|
src/HL/Controller/Intero.hs
|
bsd-3-clause
| 254 | 0 | 8 | 39 | 52 | 31 | 21 | 8 | 1 |
module System.TPFS.SuperBlock (
module System.TPFS.SolidArray,
SuperBlockState(..),
bitsToSBStates,
sbStatesToBits
) where
import Control.Applicative
import qualified Data.ByteString.Lazy as B
import System.TPFS.Bitmap
import System.TPFS.SolidArray
-- | Describes the three states a superblock can be in.
data SuperBlockState = SBEmpty
| SBSpaceAvailable
| SBFull
deriving (Show, Read, Eq)
instance SolidArray SuperBlockState where
arrRead h a (s,e) = bitsToSBStates <$> arrRead h a (s*2,e*2+1)
arrWrite h a o = arrWrite h a (o*2) . sbStatesToBits
-- | Converts a list of bits into the equivalent @['SuperBlockState']@. The
-- input list length must be even, and the output list length will
-- always be half that of the input list.
bitsToSBStates :: [Bool] -> [SuperBlockState]
bitsToSBStates (False : False : xs) = SBEmpty : bitsToSBStates xs
bitsToSBStates (True : False : xs) = SBSpaceAvailable : bitsToSBStates xs
bitsToSBStates (True : True : xs) = SBFull : bitsToSBStates xs
bitsToSBStates [] = []
-- | Converts @['SuperBlockState']@ into a list of bits. Dual of 'bitsToSBState'.
sbStatesToBits :: [SuperBlockState] -> [Bool]
sbStatesToBits (SBEmpty : xs) = False : False : sbStatesToBits xs
sbStatesToBits (SBSpaceAvailable : xs) = True : False : sbStatesToBits xs
sbStatesToBits (SBFull : xs) = True : True : sbStatesToBits xs
sbStatesToBits [] = []
|
devyn/TPFS
|
System/TPFS/SuperBlock.hs
|
bsd-3-clause
| 1,569 | 0 | 10 | 410 | 383 | 211 | 172 | 26 | 1 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Language.Elm.TH.BaseDecs where
--import AST.Annotation
import qualified AST.Module as Module
import qualified Data.Map as Map
import qualified Parse.Parse as Parse
import qualified Data.Text as Text
import qualified Text.PrettyPrint as Pretty
import Text.QuasiText
--import Data.FileEmbed
baseDecsElm :: Text.Text
baseDecsElm = [embed|
import Json
import Dict
import JsonUtils
getCtor = \(Json.Object d) -> case Dict.get "tag" d of
Just (Json.String c) -> c
varNamed = \(Json.Object d) n -> case Dict.get (show n) d of
Just val -> val
mapJson = \f (Json.Array l) -> map f l
makeList = \(Json.Array l) -> l
error = \s -> case True of False -> s
|]
infixes = Map.fromList . map (\(assoc,lvl,op) -> (op,(lvl,assoc))) . concatMap Module.iFixities $ []
--TODO add NthVar to unpack ADTs
baseDecs = case (Parse.program infixes $ Text.unpack baseDecsElm) of
Left doc -> error $ concatMap Pretty.render doc
Right modul -> Module.body modul
baseImports = case (Parse.program infixes $ Text.unpack baseDecsElm) of
Left doc -> error $ concatMap Pretty.render doc
Right modul -> Module.imports modul
jsonUtilModule = [embed|
module JsonUtils where
{-| General utility functions for working with JSON values.
Primarily intended working with values made or to be read by
Haskell's Aeson library.
Also contains some type definitions which act like ToJson
and FromJson typeclasses.
Note that there is an unenforced dependency on maxsnew/Error.
# Dict classes
@docs ToJson, FromJson
# ToJson and FromJson instances
@docs listToJson, listFromJson, maybeToJson, maybeFromJson,
intToJson, intFromJson, stringToJson, stringFromJson,
boolToJson, boolFromJson, floatToJson, floatFromJson, dictToJson, dictFromJson
# Helper functions
@docs packContents, unpackContents, getTag, varNamed
-}
import Json
import Dict
{-| Given the number of constructors a type has, a constructor name string,
and a list of JSON values to pack,
pack the values into a JSON object representing an ADT,
using the same format as Haskell's Aeson.
-}
packContents : Int -> String -> [Json.Value] -> Json.Value
packContents numCtors name contentList =
case contentList of
-- [] -> Json.Null TODO special case for only string
[item] -> let
dictList = [("tag", Json.String name), ("contents", item)]
in Json.Object <| Dict.fromList dictList
_ ->
if (numCtors == 0)
then Json.Array contentList
else
let
dictList = [("tag", Json.String name), ("contents", Json.Array contentList)]
in Json.Object <| Dict.fromList dictList
{-| Given the number of constructors a type has, and a JSON value,
get the sub-values wrapped up in that constructor,
assuming the values are packed using the same format as Haskell's Aeson.
-}
unpackContents : Int -> Json.Value -> [Json.Value]
unpackContents numCtors json = case (json, numCtors) of
(Json.Array contents, 0) -> contents
--Case when there are no values, just constructor
(Json.String s, _) -> []
(Json.Object valDict, _) -> case (Dict.get "contents" valDict) of
Just (Json.Array contents) -> contents
--any other case, means we had a single element for contents
Just json -> [json]
--_ -> Error.raise <| "No contents field of JSON " ++ (show json)
--_ -> Error.raise <| "No contents field of JSON. num: " ++ (show numCtors) ++ " json " ++ (show json)
{-| A value of type `ToJson a` is a function converting a value of type `a`` to a `Json.Value`.
This can be used similarly to typeclasses in Haskell, where a value of this type corresponds to an
instance of a typeclass.
-}
type ToJson a = (a -> Json.Value)
{-| A function converting from `a` to `Json.Value`. Similar to `ToJson`.
-}
type FromJson a = (Json.Value -> a)
{-| Given a ToJson instance for a type, generate a ToJson instance
for a list of that type.
-}
listToJson : ToJson a -> ToJson [a]
listToJson toJson = \values -> Json.Array (map toJson values)
{-| Given a ToJson instance for a type, generate a ToJson instance
for that type wrapped in `Maybe`.
-}
maybeToJson : ToJson a -> ToJson (Maybe a)
maybeToJson toJson = \mval -> case mval of
Nothing -> Json.Null
Just a -> toJson a
{-| Given a FromJson instance for a type, generate a FromJson instance
for a list of that type.
-}
listFromJson : FromJson a -> FromJson [a]
listFromJson fromJson = \(Json.Array elems) -> map fromJson elems
{-| Given a FromJson instance for a type, generate a FromJson instance
for that type wrapped in `Maybe`.
-}
maybeFromJson : FromJson a -> FromJson (Maybe a)
maybeFromJson fromJson = \json -> case json of
Json.Null -> Nothing
_ -> Just <| fromJson json
{-| Simple Int from JSON conversion, using `round` -}
intFromJson : FromJson Int
intFromJson (Json.Number f) = round f
{-| Simple Int to JSON conversion -}
intToJson : ToJson Int
intToJson i = Json.Number <| toFloat i
{-| Simple Float from JSON conversion -}
floatFromJson : FromJson Float
floatFromJson (Json.Number f) = f
{-| Simple Float to JSON conversion -}
floatToJson : ToJson Float
floatToJson = Json.Number
{-| Simple String from JSON conversion -}
stringFromJson : FromJson String
stringFromJson (Json.String s) = s
{-| Simple String to JSON conversion -}
stringToJson : ToJson String
stringToJson s = Json.String s
{-| Simple Bool from JSON conversion -}
boolFromJson : FromJson Bool
boolFromJson (Json.Boolean b) = b
{-| Simple Bool to JSON conversion -}
boolToJson : ToJson Bool
boolToJson b = Json.Boolean b
{-| Given FromJson instances for a comparable key type and some value type,
generate the conversion from a JSON object do a Dict mapping keys to values.
Assumes the JSON values represents a list of pairs.
-}
dictFromJson : FromJson comparable -> FromJson b -> FromJson (Dict.Dict comparable b)
dictFromJson keyFrom valueFrom = \(Json.Array tuples) ->
let unJsonTuples = map (\ (Json.Array [kj,vj]) -> (keyFrom kj, valueFrom vj)) tuples
in Dict.fromList unJsonTuples
{-| Given ToJson instances for a comparable key type and some value type,
generate the conversion from a Dict mapping keys to values to a JSON object.
Represents the Dict as a list of pairs.
-}
dictToJson : ToJson comparable -> ToJson b -> ToJson (Dict.Dict comparable b)
dictToJson keyTo valueTo = \dict ->
let
dictList = Dict.toList dict
tupleJson = map (\(k,v) -> Json.Array [keyTo k, valueTo v]) dictList
in Json.Array tupleJson
{-| From a Json Object, get a string from a field named "tag".
Fails using `Error.raise` if no such field exists.
Useful for extracting values from Haskell's Aeson instances.
-}
getTag : Json.Value -> String
getTag json = case json of
(Json.Object dict) -> case (Dict.get "tag" dict) of
Just (Json.String s) -> s
-- _ -> Error.raise <| "Couldn't get tag from JSON" ++ (show dict)
(Json.String s) -> s --Ctors with no contents get stored as strings
{-| From a Json Object, get a value from a field with the given name.
Fails using `Error.raise` if no such field exists.
Useful for extracting values from Haskell's Aeson instances.
-}
varNamed : Json.Value -> String -> Json.Value
varNamed (Json.Object dict) name = case (Dict.get name dict) of
Just j -> j
|]
|
JoeyEremondi/haskelm
|
src/Language/Elm/TH/BaseDecs.hs
|
bsd-3-clause
| 7,336 | 0 | 12 | 1,428 | 260 | 150 | 110 | 18 | 2 |
module Evolution
( EvolutionRules (..)
, evolution
) where
import Evolution.Internal
|
satai/FrozenBeagle
|
Simulation/Lib/src/Evolution.hs
|
bsd-3-clause
| 107 | 0 | 5 | 33 | 21 | 14 | 7 | 4 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Guesswork.Estimate.KNN where
import Data.List
import Data.Ord
import Data.Serialize
import Control.Arrow
import System.IO.Unsafe
--import GHC.Generics
import Guesswork.Types
import Guesswork.Math.Statistics
import qualified Guesswork.Transform as TRANSFORM
import Guesswork.Estimate
import qualified Debug.Trace as T
-- | KNN data type represents KNN estimator for type Sample a.
-- Serializing KNN requires also serializable Sample a type,
-- since KNN is merely the samples and the transform operation.
data (Sample a, Serialize a) => KNN a =
KNN [a] Int TRANSFORM.Operation Trace
deriving (Eq)
instance (Serialize a, Sample a) => Serialize (KNN a) where
get = do
samples <- get
k <- get
op <- get
t <- get
return $ KNN samples k op t
put (KNN samples k op t) = do
put samples
put k
put op
put t
instance (Sample a, Serialize a) => GuessworkEstimator (KNN a) where
guessWith (KNN samples k op _) = kNNEstimate samples k . TRANSFORM.apply op
type KNNFitness = (Sample a) => [a] -> Int -> Double
data KNNConfig = KNNConfig { ks :: [Int]
, fitness :: KNNFitness
}
-- | Default KNN configuration: test k values between 1 and 20.
defaultKNN = KNNConfig [1..20] splitFitness
-- | Perform KNN with defaultKNN configuration.
kNN :: (Sample a) => TRANSFORM.Transformed a -> Guesswork (Estimated a)
kNN [email protected]{..} = kNN' defaultKNN t
kNN [email protected]{..} = kNN' defaultKNN t
-- | Assumes scaled & prepared data.
kNN' :: (Sample a) => KNNConfig -> TRANSFORM.Transformed a -> Guesswork (Estimated a)
kNN' conf (TRANSFORM.Separated train test trace) = do
let
bestK = findBestK conf train
estimates = map (kNNEstimate train bestK . features) test
truths = map target test
return $ Estimated truths estimates test (trace ++ ",R=kNN("++show bestK++")")
kNN' conf (TRANSFORM.LeaveOneOut samples trace) = do
let
bestK = findBestK conf samples
indices = [0..(length samples - 1)]
pairs = map (takeBut samples) indices
estimates = map (\(x,xs) -> kNNEstimate xs bestK (features x)) pairs
truths = map target samples
return $ Estimated truths estimates samples (trace ++ ",R=kNN("++show bestK++")")
trainKNN = trainKNN' defaultKNN
trainKNN':: (Sample a, Serialize a) => KNNConfig -> TRANSFORM.Transformed a -> Guesswork (KNN a)
trainKNN' conf (TRANSFORM.OnlyTrain samples op trace) = do
let bestK = findBestK conf samples
return $ KNN samples bestK op (trace ++ ",R=kNN")
trainKNN' _ _ = error "Unsupported knn operation."
findBestK :: (Sample a) => KNNConfig -> [a] -> Int
findBestK KNNConfig{..} samples =
let paired = map (\k->(k, fitness samples k)) ks
bestK = fst . head . sortBy (comparing snd) $ paired
in bestK
-- FIXME: generalize
splitFitness :: KNNFitness
splitFitness samples k =
let (train,test) = splitAt (length samples `div` 2) samples
estimates = map (kNNEstimate train k . features) test
truths = map target test
in calcFitness truths estimates
-- FIXME: generalize
leaveOneOutFitness :: KNNFitness
leaveOneOutFitness samples k =
let indices = [0..(length samples - 1)]
pairs = map (takeBut samples) indices
estimates = map (\(x,xs) -> kNNEstimate xs k (features x)) pairs
truths = map target samples
in calcFitness truths estimates
kNNEstimate :: (Sample a) => [a] -> Int -> FeatureVector -> Double
kNNEstimate others k vec =
let f x = (x, euclidianNorm vec (features x))
byDistances = sortBy (comparing snd) . map f $ others
kNearest = map target . take k . map fst $ byDistances
in avg kNearest
flip' (a,b) = (b,a)
|
deggis/guesswork
|
src/Guesswork/Estimate/KNN.hs
|
bsd-3-clause
| 4,008 | 0 | 15 | 981 | 1,306 | 673 | 633 | 85 | 1 |
module Main where
import qualified Data.Map as M
import Morse
import WordNumber (digitToWord, digits, wordNumber)
import Test.Hspec
import Test.QuickCheck
allowedChars :: [Char]
allowedChars = M.keys letterToMorse
allowedMorse :: [String]
allowedMorse = M.elems letterToMorse
charGen :: Gen Char
charGen = elements allowedChars
morseGen :: Gen Morse
morseGen = elements allowedMorse
prop_thereAndBackAgain :: Property
prop_thereAndBackAgain =
forAll charGen
(\c -> ((charToMorse c) >>= morseToChar) == Just c)
main :: IO ()
main = hspec $ do
describe "digitToWord does what we want" $ do
it "returns zero for 0" $ do
digitToWord 0 `shouldBe` "zero"
it "returns one for 1" $ do
digitToWord 1 `shouldBe` "one"
describe "digits does what we want" $ do
it "returns [1] for 1" $ do
digits 1 `shouldBe` [1]
it "returns [1,0,0] for 100" $ do
digits 100 `shouldBe` [1,0,0]
describe "wordNumber does what we want" $ do
it "returns one-zero-zero for 100" $ do
wordNumber 100 `shouldBe` "one-zero-zero"
it "returns nine-zero-zero-one for 9001" $ do
wordNumber 9001 `shouldBe` "nine-zero-zero-one"
describe "Morse does what we want" $ do
it "Encodes the same string it encodes" $ do
prop_thereAndBackAgain
|
dmvianna/morse
|
tests/tests.hs
|
bsd-3-clause
| 1,289 | 0 | 15 | 277 | 366 | 184 | 182 | 38 | 1 |
{-# LANGUAGE BangPatterns #-}
module Tree.Load (mkBigTree, mkBigTrees) where
import Tree.Types
import Tree.ReadShow ()
mkBigTrees :: Int -> Int -> [Tree]
mkBigTrees n depth =
let !tree = mkBigTree depth
in replicate n tree
mkBigTree :: Int -> Tree
mkBigTree 0 = Leaf
mkBigTree depth =
let !subtree = mkBigTree (depth-1)
in Fork subtree subtree
|
thoughtpolice/binary-serialise-cbor
|
bench/Tree/Load.hs
|
bsd-3-clause
| 365 | 0 | 11 | 76 | 128 | 65 | 63 | 13 | 1 |
{-# LANGUAGE LambdaCase #-}
module TcTypeNats
( typeNatTyCons
, typeNatCoAxiomRules
, BuiltInSynFamily(..)
, typeNatAddTyCon
, typeNatMulTyCon
, typeNatExpTyCon
, typeNatLeqTyCon
, typeNatSubTyCon
, typeNatCmpTyCon
, typeSymbolCmpTyCon
, typeSymbolAppendTyCon
) where
import GhcPrelude
import Type
import Pair
import TcType ( TcType, tcEqType )
import TyCon ( TyCon, FamTyConFlav(..), mkFamilyTyCon
, Injectivity(..) )
import Coercion ( Role(..) )
import TcRnTypes ( Xi )
import CoAxiom ( CoAxiomRule(..), BuiltInSynFamily(..), TypeEqn )
import Name ( Name, BuiltInSyntax(..) )
import TysWiredIn
import TysPrim ( mkTemplateAnonTyConBinders )
import PrelNames ( gHC_TYPELITS
, gHC_TYPENATS
, typeNatAddTyFamNameKey
, typeNatMulTyFamNameKey
, typeNatExpTyFamNameKey
, typeNatLeqTyFamNameKey
, typeNatSubTyFamNameKey
, typeNatDivTyFamNameKey
, typeNatModTyFamNameKey
, typeNatLogTyFamNameKey
, typeNatCmpTyFamNameKey
, typeSymbolCmpTyFamNameKey
, typeSymbolAppendFamNameKey
)
import FastString ( FastString
, fsLit, nilFS, nullFS, unpackFS, mkFastString, appendFS
)
import qualified Data.Map as Map
import Data.Maybe ( isJust )
import Control.Monad ( guard )
import Data.List ( isPrefixOf, isSuffixOf )
{-------------------------------------------------------------------------------
Built-in type constructors for functions on type-level nats
-}
typeNatTyCons :: [TyCon]
typeNatTyCons =
[ typeNatAddTyCon
, typeNatMulTyCon
, typeNatExpTyCon
, typeNatLeqTyCon
, typeNatSubTyCon
, typeNatDivTyCon
, typeNatModTyCon
, typeNatLogTyCon
, typeNatCmpTyCon
, typeSymbolCmpTyCon
, typeSymbolAppendTyCon
]
typeNatAddTyCon :: TyCon
typeNatAddTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamAdd
, sfInteractTop = interactTopAdd
, sfInteractInert = interactInertAdd
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "+")
typeNatAddTyFamNameKey typeNatAddTyCon
typeNatSubTyCon :: TyCon
typeNatSubTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamSub
, sfInteractTop = interactTopSub
, sfInteractInert = interactInertSub
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "-")
typeNatSubTyFamNameKey typeNatSubTyCon
typeNatMulTyCon :: TyCon
typeNatMulTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamMul
, sfInteractTop = interactTopMul
, sfInteractInert = interactInertMul
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "*")
typeNatMulTyFamNameKey typeNatMulTyCon
typeNatDivTyCon :: TyCon
typeNatDivTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamDiv
, sfInteractTop = interactTopDiv
, sfInteractInert = interactInertDiv
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "Div")
typeNatDivTyFamNameKey typeNatDivTyCon
typeNatModTyCon :: TyCon
typeNatModTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamMod
, sfInteractTop = interactTopMod
, sfInteractInert = interactInertMod
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "Mod")
typeNatModTyFamNameKey typeNatModTyCon
typeNatExpTyCon :: TyCon
typeNatExpTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamExp
, sfInteractTop = interactTopExp
, sfInteractInert = interactInertExp
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "^")
typeNatExpTyFamNameKey typeNatExpTyCon
typeNatLogTyCon :: TyCon
typeNatLogTyCon = mkTypeNatFunTyCon1 name
BuiltInSynFamily
{ sfMatchFam = matchFamLog
, sfInteractTop = interactTopLog
, sfInteractInert = interactInertLog
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "Log2")
typeNatLogTyFamNameKey typeNatLogTyCon
typeNatLeqTyCon :: TyCon
typeNatLeqTyCon =
mkFamilyTyCon name
(mkTemplateAnonTyConBinders [ typeNatKind, typeNatKind ])
boolTy
Nothing
(BuiltInSynFamTyCon ops)
Nothing
NotInjective
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "<=?")
typeNatLeqTyFamNameKey typeNatLeqTyCon
ops = BuiltInSynFamily
{ sfMatchFam = matchFamLeq
, sfInteractTop = interactTopLeq
, sfInteractInert = interactInertLeq
}
typeNatCmpTyCon :: TyCon
typeNatCmpTyCon =
mkFamilyTyCon name
(mkTemplateAnonTyConBinders [ typeNatKind, typeNatKind ])
orderingKind
Nothing
(BuiltInSynFamTyCon ops)
Nothing
NotInjective
where
name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "CmpNat")
typeNatCmpTyFamNameKey typeNatCmpTyCon
ops = BuiltInSynFamily
{ sfMatchFam = matchFamCmpNat
, sfInteractTop = interactTopCmpNat
, sfInteractInert = \_ _ _ _ -> []
}
typeSymbolCmpTyCon :: TyCon
typeSymbolCmpTyCon =
mkFamilyTyCon name
(mkTemplateAnonTyConBinders [ typeSymbolKind, typeSymbolKind ])
orderingKind
Nothing
(BuiltInSynFamTyCon ops)
Nothing
NotInjective
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "CmpSymbol")
typeSymbolCmpTyFamNameKey typeSymbolCmpTyCon
ops = BuiltInSynFamily
{ sfMatchFam = matchFamCmpSymbol
, sfInteractTop = interactTopCmpSymbol
, sfInteractInert = \_ _ _ _ -> []
}
typeSymbolAppendTyCon :: TyCon
typeSymbolAppendTyCon = mkTypeSymbolFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamAppendSymbol
, sfInteractTop = interactTopAppendSymbol
, sfInteractInert = interactInertAppendSymbol
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "AppendSymbol")
typeSymbolAppendFamNameKey typeSymbolAppendTyCon
-- Make a unary built-in constructor of kind: Nat -> Nat
mkTypeNatFunTyCon1 :: Name -> BuiltInSynFamily -> TyCon
mkTypeNatFunTyCon1 op tcb =
mkFamilyTyCon op
(mkTemplateAnonTyConBinders [ typeNatKind ])
typeNatKind
Nothing
(BuiltInSynFamTyCon tcb)
Nothing
NotInjective
-- Make a binary built-in constructor of kind: Nat -> Nat -> Nat
mkTypeNatFunTyCon2 :: Name -> BuiltInSynFamily -> TyCon
mkTypeNatFunTyCon2 op tcb =
mkFamilyTyCon op
(mkTemplateAnonTyConBinders [ typeNatKind, typeNatKind ])
typeNatKind
Nothing
(BuiltInSynFamTyCon tcb)
Nothing
NotInjective
-- Make a binary built-in constructor of kind: Symbol -> Symbol -> Symbol
mkTypeSymbolFunTyCon2 :: Name -> BuiltInSynFamily -> TyCon
mkTypeSymbolFunTyCon2 op tcb =
mkFamilyTyCon op
(mkTemplateAnonTyConBinders [ typeSymbolKind, typeSymbolKind ])
typeSymbolKind
Nothing
(BuiltInSynFamTyCon tcb)
Nothing
NotInjective
{-------------------------------------------------------------------------------
Built-in rules axioms
-------------------------------------------------------------------------------}
-- If you add additional rules, please remember to add them to
-- `typeNatCoAxiomRules` also.
axAddDef
, axMulDef
, axExpDef
, axLeqDef
, axCmpNatDef
, axCmpSymbolDef
, axAppendSymbolDef
, axAdd0L
, axAdd0R
, axMul0L
, axMul0R
, axMul1L
, axMul1R
, axExp1L
, axExp0R
, axExp1R
, axLeqRefl
, axCmpNatRefl
, axCmpSymbolRefl
, axLeq0L
, axSubDef
, axSub0R
, axAppendSymbol0R
, axAppendSymbol0L
, axDivDef
, axDiv1
, axModDef
, axMod1
, axLogDef
:: CoAxiomRule
axAddDef = mkBinAxiom "AddDef" typeNatAddTyCon $
\x y -> Just $ num (x + y)
axMulDef = mkBinAxiom "MulDef" typeNatMulTyCon $
\x y -> Just $ num (x * y)
axExpDef = mkBinAxiom "ExpDef" typeNatExpTyCon $
\x y -> Just $ num (x ^ y)
axLeqDef = mkBinAxiom "LeqDef" typeNatLeqTyCon $
\x y -> Just $ bool (x <= y)
axCmpNatDef = mkBinAxiom "CmpNatDef" typeNatCmpTyCon
$ \x y -> Just $ ordering (compare x y)
axCmpSymbolDef =
CoAxiomRule
{ coaxrName = fsLit "CmpSymbolDef"
, coaxrAsmpRoles = [Nominal, Nominal]
, coaxrRole = Nominal
, coaxrProves = \cs ->
do [Pair s1 s2, Pair t1 t2] <- return cs
s2' <- isStrLitTy s2
t2' <- isStrLitTy t2
return (mkTyConApp typeSymbolCmpTyCon [s1,t1] ===
ordering (compare s2' t2')) }
axAppendSymbolDef = CoAxiomRule
{ coaxrName = fsLit "AppendSymbolDef"
, coaxrAsmpRoles = [Nominal, Nominal]
, coaxrRole = Nominal
, coaxrProves = \cs ->
do [Pair s1 s2, Pair t1 t2] <- return cs
s2' <- isStrLitTy s2
t2' <- isStrLitTy t2
let z = mkStrLitTy (appendFS s2' t2')
return (mkTyConApp typeSymbolAppendTyCon [s1, t1] === z)
}
axSubDef = mkBinAxiom "SubDef" typeNatSubTyCon $
\x y -> fmap num (minus x y)
axDivDef = mkBinAxiom "DivDef" typeNatDivTyCon $
\x y -> do guard (y /= 0)
return (num (div x y))
axModDef = mkBinAxiom "ModDef" typeNatModTyCon $
\x y -> do guard (y /= 0)
return (num (mod x y))
axLogDef = mkUnAxiom "LogDef" typeNatLogTyCon $
\x -> do (a,_) <- genLog x 2
return (num a)
axAdd0L = mkAxiom1 "Add0L" $ \(Pair s t) -> (num 0 .+. s) === t
axAdd0R = mkAxiom1 "Add0R" $ \(Pair s t) -> (s .+. num 0) === t
axSub0R = mkAxiom1 "Sub0R" $ \(Pair s t) -> (s .-. num 0) === t
axMul0L = mkAxiom1 "Mul0L" $ \(Pair s _) -> (num 0 .*. s) === num 0
axMul0R = mkAxiom1 "Mul0R" $ \(Pair s _) -> (s .*. num 0) === num 0
axMul1L = mkAxiom1 "Mul1L" $ \(Pair s t) -> (num 1 .*. s) === t
axMul1R = mkAxiom1 "Mul1R" $ \(Pair s t) -> (s .*. num 1) === t
axDiv1 = mkAxiom1 "Div1" $ \(Pair s t) -> (tDiv s (num 1) === t)
axMod1 = mkAxiom1 "Mod1" $ \(Pair s _) -> (tMod s (num 1) === num 0)
-- XXX: Shouldn't we check that _ is 0?
axExp1L = mkAxiom1 "Exp1L" $ \(Pair s _) -> (num 1 .^. s) === num 1
axExp0R = mkAxiom1 "Exp0R" $ \(Pair s _) -> (s .^. num 0) === num 1
axExp1R = mkAxiom1 "Exp1R" $ \(Pair s t) -> (s .^. num 1) === t
axLeqRefl = mkAxiom1 "LeqRefl" $ \(Pair s _) -> (s <== s) === bool True
axCmpNatRefl = mkAxiom1 "CmpNatRefl"
$ \(Pair s _) -> (cmpNat s s) === ordering EQ
axCmpSymbolRefl = mkAxiom1 "CmpSymbolRefl"
$ \(Pair s _) -> (cmpSymbol s s) === ordering EQ
axLeq0L = mkAxiom1 "Leq0L" $ \(Pair s _) -> (num 0 <== s) === bool True
axAppendSymbol0R = mkAxiom1 "Concat0R"
$ \(Pair s t) -> (mkStrLitTy nilFS `appendSymbol` s) === t
axAppendSymbol0L = mkAxiom1 "Concat0L"
$ \(Pair s t) -> (s `appendSymbol` mkStrLitTy nilFS) === t
typeNatCoAxiomRules :: Map.Map FastString CoAxiomRule
typeNatCoAxiomRules = Map.fromList $ map (\x -> (coaxrName x, x))
[ axAddDef
, axMulDef
, axExpDef
, axLeqDef
, axCmpNatDef
, axCmpSymbolDef
, axAppendSymbolDef
, axAdd0L
, axAdd0R
, axMul0L
, axMul0R
, axMul1L
, axMul1R
, axExp1L
, axExp0R
, axExp1R
, axLeqRefl
, axCmpNatRefl
, axCmpSymbolRefl
, axLeq0L
, axSubDef
, axAppendSymbol0R
, axAppendSymbol0L
, axDivDef
, axDiv1
, axModDef
, axMod1
, axLogDef
]
{-------------------------------------------------------------------------------
Various utilities for making axioms and types
-------------------------------------------------------------------------------}
(.+.) :: Type -> Type -> Type
s .+. t = mkTyConApp typeNatAddTyCon [s,t]
(.-.) :: Type -> Type -> Type
s .-. t = mkTyConApp typeNatSubTyCon [s,t]
(.*.) :: Type -> Type -> Type
s .*. t = mkTyConApp typeNatMulTyCon [s,t]
tDiv :: Type -> Type -> Type
tDiv s t = mkTyConApp typeNatDivTyCon [s,t]
tMod :: Type -> Type -> Type
tMod s t = mkTyConApp typeNatModTyCon [s,t]
(.^.) :: Type -> Type -> Type
s .^. t = mkTyConApp typeNatExpTyCon [s,t]
(<==) :: Type -> Type -> Type
s <== t = mkTyConApp typeNatLeqTyCon [s,t]
cmpNat :: Type -> Type -> Type
cmpNat s t = mkTyConApp typeNatCmpTyCon [s,t]
cmpSymbol :: Type -> Type -> Type
cmpSymbol s t = mkTyConApp typeSymbolCmpTyCon [s,t]
appendSymbol :: Type -> Type -> Type
appendSymbol s t = mkTyConApp typeSymbolAppendTyCon [s, t]
(===) :: Type -> Type -> Pair Type
x === y = Pair x y
num :: Integer -> Type
num = mkNumLitTy
bool :: Bool -> Type
bool b = if b then mkTyConApp promotedTrueDataCon []
else mkTyConApp promotedFalseDataCon []
isBoolLitTy :: Type -> Maybe Bool
isBoolLitTy tc =
do (tc,[]) <- splitTyConApp_maybe tc
case () of
_ | tc == promotedFalseDataCon -> return False
| tc == promotedTrueDataCon -> return True
| otherwise -> Nothing
orderingKind :: Kind
orderingKind = mkTyConApp orderingTyCon []
ordering :: Ordering -> Type
ordering o =
case o of
LT -> mkTyConApp promotedLTDataCon []
EQ -> mkTyConApp promotedEQDataCon []
GT -> mkTyConApp promotedGTDataCon []
isOrderingLitTy :: Type -> Maybe Ordering
isOrderingLitTy tc =
do (tc1,[]) <- splitTyConApp_maybe tc
case () of
_ | tc1 == promotedLTDataCon -> return LT
| tc1 == promotedEQDataCon -> return EQ
| tc1 == promotedGTDataCon -> return GT
| otherwise -> Nothing
known :: (Integer -> Bool) -> TcType -> Bool
known p x = case isNumLitTy x of
Just a -> p a
Nothing -> False
mkUnAxiom :: String -> TyCon -> (Integer -> Maybe Type) -> CoAxiomRule
mkUnAxiom str tc f =
CoAxiomRule
{ coaxrName = fsLit str
, coaxrAsmpRoles = [Nominal]
, coaxrRole = Nominal
, coaxrProves = \cs ->
do [Pair s1 s2] <- return cs
s2' <- isNumLitTy s2
z <- f s2'
return (mkTyConApp tc [s1] === z)
}
-- For the definitional axioms
mkBinAxiom :: String -> TyCon ->
(Integer -> Integer -> Maybe Type) -> CoAxiomRule
mkBinAxiom str tc f =
CoAxiomRule
{ coaxrName = fsLit str
, coaxrAsmpRoles = [Nominal, Nominal]
, coaxrRole = Nominal
, coaxrProves = \cs ->
do [Pair s1 s2, Pair t1 t2] <- return cs
s2' <- isNumLitTy s2
t2' <- isNumLitTy t2
z <- f s2' t2'
return (mkTyConApp tc [s1,t1] === z)
}
mkAxiom1 :: String -> (TypeEqn -> TypeEqn) -> CoAxiomRule
mkAxiom1 str f =
CoAxiomRule
{ coaxrName = fsLit str
, coaxrAsmpRoles = [Nominal]
, coaxrRole = Nominal
, coaxrProves = \case [eqn] -> Just (f eqn)
_ -> Nothing
}
{-------------------------------------------------------------------------------
Evaluation
-------------------------------------------------------------------------------}
matchFamAdd :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamAdd [s,t]
| Just 0 <- mbX = Just (axAdd0L, [t], t)
| Just 0 <- mbY = Just (axAdd0R, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axAddDef, [s,t], num (x + y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamAdd _ = Nothing
matchFamSub :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamSub [s,t]
| Just 0 <- mbY = Just (axSub0R, [s], s)
| Just x <- mbX, Just y <- mbY, Just z <- minus x y =
Just (axSubDef, [s,t], num z)
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamSub _ = Nothing
matchFamMul :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamMul [s,t]
| Just 0 <- mbX = Just (axMul0L, [t], num 0)
| Just 0 <- mbY = Just (axMul0R, [s], num 0)
| Just 1 <- mbX = Just (axMul1L, [t], t)
| Just 1 <- mbY = Just (axMul1R, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axMulDef, [s,t], num (x * y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamMul _ = Nothing
matchFamDiv :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamDiv [s,t]
| Just 1 <- mbY = Just (axDiv1, [s], s)
| Just x <- mbX, Just y <- mbY, y /= 0 = Just (axDivDef, [s,t], num (div x y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamDiv _ = Nothing
matchFamMod :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamMod [s,t]
| Just 1 <- mbY = Just (axMod1, [s], num 0)
| Just x <- mbX, Just y <- mbY, y /= 0 = Just (axModDef, [s,t], num (mod x y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamMod _ = Nothing
matchFamExp :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamExp [s,t]
| Just 0 <- mbY = Just (axExp0R, [s], num 1)
| Just 1 <- mbX = Just (axExp1L, [t], num 1)
| Just 1 <- mbY = Just (axExp1R, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axExpDef, [s,t], num (x ^ y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamExp _ = Nothing
matchFamLog :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamLog [s]
| Just x <- mbX, Just (n,_) <- genLog x 2 = Just (axLogDef, [s], num n)
where mbX = isNumLitTy s
matchFamLog _ = Nothing
matchFamLeq :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamLeq [s,t]
| Just 0 <- mbX = Just (axLeq0L, [t], bool True)
| Just x <- mbX, Just y <- mbY =
Just (axLeqDef, [s,t], bool (x <= y))
| tcEqType s t = Just (axLeqRefl, [s], bool True)
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamLeq _ = Nothing
matchFamCmpNat :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamCmpNat [s,t]
| Just x <- mbX, Just y <- mbY =
Just (axCmpNatDef, [s,t], ordering (compare x y))
| tcEqType s t = Just (axCmpNatRefl, [s], ordering EQ)
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamCmpNat _ = Nothing
matchFamCmpSymbol :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamCmpSymbol [s,t]
| Just x <- mbX, Just y <- mbY =
Just (axCmpSymbolDef, [s,t], ordering (compare x y))
| tcEqType s t = Just (axCmpSymbolRefl, [s], ordering EQ)
where mbX = isStrLitTy s
mbY = isStrLitTy t
matchFamCmpSymbol _ = Nothing
matchFamAppendSymbol :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamAppendSymbol [s,t]
| Just x <- mbX, nullFS x = Just (axAppendSymbol0R, [t], t)
| Just y <- mbY, nullFS y = Just (axAppendSymbol0L, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axAppendSymbolDef, [s,t], mkStrLitTy (appendFS x y))
where
mbX = isStrLitTy s
mbY = isStrLitTy t
matchFamAppendSymbol _ = Nothing
{-------------------------------------------------------------------------------
Interact with axioms
-------------------------------------------------------------------------------}
interactTopAdd :: [Xi] -> Xi -> [Pair Type]
interactTopAdd [s,t] r
| Just 0 <- mbZ = [ s === num 0, t === num 0 ] -- (s + t ~ 0) => (s ~ 0, t ~ 0)
| Just x <- mbX, Just z <- mbZ, Just y <- minus z x = [t === num y] -- (5 + t ~ 8) => (t ~ 3)
| Just y <- mbY, Just z <- mbZ, Just x <- minus z y = [s === num x] -- (s + 5 ~ 8) => (s ~ 3)
where
mbX = isNumLitTy s
mbY = isNumLitTy t
mbZ = isNumLitTy r
interactTopAdd _ _ = []
{-
Note [Weakened interaction rule for subtraction]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A simpler interaction here might be:
`s - t ~ r` --> `t + r ~ s`
This would enable us to reuse all the code for addition.
Unfortunately, this works a little too well at the moment.
Consider the following example:
0 - 5 ~ r --> 5 + r ~ 0 --> (5 = 0, r = 0)
This (correctly) spots that the constraint cannot be solved.
However, this may be a problem if the constraint did not
need to be solved in the first place! Consider the following example:
f :: Proxy (If (5 <=? 0) (0 - 5) (5 - 0)) -> Proxy 5
f = id
Currently, GHC is strict while evaluating functions, so this does not
work, because even though the `If` should evaluate to `5 - 0`, we
also evaluate the "then" branch which generates the constraint `0 - 5 ~ r`,
which fails.
So, for the time being, we only add an improvement when the RHS is a constant,
which happens to work OK for the moment, although clearly we need to do
something more general.
-}
interactTopSub :: [Xi] -> Xi -> [Pair Type]
interactTopSub [s,t] r
| Just z <- mbZ = [ s === (num z .+. t) ] -- (s - t ~ 5) => (5 + t ~ s)
where
mbZ = isNumLitTy r
interactTopSub _ _ = []
interactTopMul :: [Xi] -> Xi -> [Pair Type]
interactTopMul [s,t] r
| Just 1 <- mbZ = [ s === num 1, t === num 1 ] -- (s * t ~ 1) => (s ~ 1, t ~ 1)
| Just x <- mbX, Just z <- mbZ, Just y <- divide z x = [t === num y] -- (3 * t ~ 15) => (t ~ 5)
| Just y <- mbY, Just z <- mbZ, Just x <- divide z y = [s === num x] -- (s * 3 ~ 15) => (s ~ 5)
where
mbX = isNumLitTy s
mbY = isNumLitTy t
mbZ = isNumLitTy r
interactTopMul _ _ = []
interactTopDiv :: [Xi] -> Xi -> [Pair Type]
interactTopDiv _ _ = [] -- I can't think of anything...
interactTopMod :: [Xi] -> Xi -> [Pair Type]
interactTopMod _ _ = [] -- I can't think of anything...
interactTopExp :: [Xi] -> Xi -> [Pair Type]
interactTopExp [s,t] r
| Just 0 <- mbZ = [ s === num 0 ] -- (s ^ t ~ 0) => (s ~ 0)
| Just x <- mbX, Just z <- mbZ, Just y <- logExact z x = [t === num y] -- (2 ^ t ~ 8) => (t ~ 3)
| Just y <- mbY, Just z <- mbZ, Just x <- rootExact z y = [s === num x] -- (s ^ 2 ~ 9) => (s ~ 3)
where
mbX = isNumLitTy s
mbY = isNumLitTy t
mbZ = isNumLitTy r
interactTopExp _ _ = []
interactTopLog :: [Xi] -> Xi -> [Pair Type]
interactTopLog _ _ = [] -- I can't think of anything...
interactTopLeq :: [Xi] -> Xi -> [Pair Type]
interactTopLeq [s,t] r
| Just 0 <- mbY, Just True <- mbZ = [ s === num 0 ] -- (s <= 0) => (s ~ 0)
where
mbY = isNumLitTy t
mbZ = isBoolLitTy r
interactTopLeq _ _ = []
interactTopCmpNat :: [Xi] -> Xi -> [Pair Type]
interactTopCmpNat [s,t] r
| Just EQ <- isOrderingLitTy r = [ s === t ]
interactTopCmpNat _ _ = []
interactTopCmpSymbol :: [Xi] -> Xi -> [Pair Type]
interactTopCmpSymbol [s,t] r
| Just EQ <- isOrderingLitTy r = [ s === t ]
interactTopCmpSymbol _ _ = []
interactTopAppendSymbol :: [Xi] -> Xi -> [Pair Type]
interactTopAppendSymbol [s,t] r
-- (AppendSymbol a b ~ "") => (a ~ "", b ~ "")
| Just z <- mbZ, nullFS z =
[s === mkStrLitTy nilFS, t === mkStrLitTy nilFS ]
-- (AppendSymbol "foo" b ~ "foobar") => (b ~ "bar")
| Just x <- fmap unpackFS mbX, Just z <- fmap unpackFS mbZ, x `isPrefixOf` z =
[ t === mkStrLitTy (mkFastString $ drop (length x) z) ]
-- (AppendSymbol f "bar" ~ "foobar") => (f ~ "foo")
| Just y <- fmap unpackFS mbY, Just z <- fmap unpackFS mbZ, y `isSuffixOf` z =
[ t === mkStrLitTy (mkFastString $ take (length z - length y) z) ]
where
mbX = isStrLitTy s
mbY = isStrLitTy t
mbZ = isStrLitTy r
interactTopAppendSymbol _ _ = []
{-------------------------------------------------------------------------------
Interaction with inerts
-------------------------------------------------------------------------------}
interactInertAdd :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertAdd [x1,y1] z1 [x2,y2] z2
| sameZ && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertAdd _ _ _ _ = []
interactInertSub :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertSub [x1,y1] z1 [x2,y2] z2
| sameZ && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertSub _ _ _ _ = []
interactInertMul :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertMul [x1,y1] z1 [x2,y2] z2
| sameZ && known (/= 0) x1 && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && known (/= 0) y1 && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertMul _ _ _ _ = []
interactInertDiv :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertDiv _ _ _ _ = []
interactInertMod :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertMod _ _ _ _ = []
interactInertExp :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertExp [x1,y1] z1 [x2,y2] z2
| sameZ && known (> 1) x1 && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && known (> 0) y1 && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertExp _ _ _ _ = []
interactInertLog :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertLog _ _ _ _ = []
interactInertLeq :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertLeq [x1,y1] z1 [x2,y2] z2
| bothTrue && tcEqType x1 y2 && tcEqType y1 x2 = [ x1 === y1 ]
| bothTrue && tcEqType y1 x2 = [ (x1 <== y2) === bool True ]
| bothTrue && tcEqType y2 x1 = [ (x2 <== y1) === bool True ]
where bothTrue = isJust $ do True <- isBoolLitTy z1
True <- isBoolLitTy z2
return ()
interactInertLeq _ _ _ _ = []
interactInertAppendSymbol :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertAppendSymbol [x1,y1] z1 [x2,y2] z2
| sameZ && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertAppendSymbol _ _ _ _ = []
{- -----------------------------------------------------------------------------
These inverse functions are used for simplifying propositions using
concrete natural numbers.
----------------------------------------------------------------------------- -}
-- | Subtract two natural numbers.
minus :: Integer -> Integer -> Maybe Integer
minus x y = if x >= y then Just (x - y) else Nothing
-- | Compute the exact logarithm of a natural number.
-- The logarithm base is the second argument.
logExact :: Integer -> Integer -> Maybe Integer
logExact x y = do (z,True) <- genLog x y
return z
-- | Divide two natural numbers.
divide :: Integer -> Integer -> Maybe Integer
divide _ 0 = Nothing
divide x y = case divMod x y of
(a,0) -> Just a
_ -> Nothing
-- | Compute the exact root of a natural number.
-- The second argument specifies which root we are computing.
rootExact :: Integer -> Integer -> Maybe Integer
rootExact x y = do (z,True) <- genRoot x y
return z
{- | Compute the the n-th root of a natural number, rounded down to
the closest natural number. The boolean indicates if the result
is exact (i.e., True means no rounding was done, False means rounded down).
The second argument specifies which root we are computing. -}
genRoot :: Integer -> Integer -> Maybe (Integer, Bool)
genRoot _ 0 = Nothing
genRoot x0 1 = Just (x0, True)
genRoot x0 root = Just (search 0 (x0+1))
where
search from to = let x = from + div (to - from) 2
a = x ^ root
in case compare a x0 of
EQ -> (x, True)
LT | x /= from -> search x to
| otherwise -> (from, False)
GT | x /= to -> search from x
| otherwise -> (from, False)
{- | Compute the logarithm of a number in the given base, rounded down to the
closest integer. The boolean indicates if we the result is exact
(i.e., True means no rounding happened, False means we rounded down).
The logarithm base is the second argument. -}
genLog :: Integer -> Integer -> Maybe (Integer, Bool)
genLog x 0 = if x == 1 then Just (0, True) else Nothing
genLog _ 1 = Nothing
genLog 0 _ = Nothing
genLog x base = Just (exactLoop 0 x)
where
exactLoop s i
| i == 1 = (s,True)
| i < base = (s,False)
| otherwise =
let s1 = s + 1
in s1 `seq` case divMod i base of
(j,r)
| r == 0 -> exactLoop s1 j
| otherwise -> (underLoop s1 j, False)
underLoop s i
| i < base = s
| otherwise = let s1 = s + 1 in s1 `seq` underLoop s1 (div i base)
|
ezyang/ghc
|
compiler/typecheck/TcTypeNats.hs
|
bsd-3-clause
| 28,306 | 3 | 17 | 7,539 | 9,083 | 4,763 | 4,320 | 645 | 3 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Narradar.Constraints.Syntactic where
import Data.Foldable (Foldable)
import Data.Maybe (catMaybes, maybeToList)
import Narradar.Types
import qualified Data.Set as Set
isLeftLinear :: (Ord v, Foldable t, Functor t, HasRules t v trs) => trs -> Bool
isLeftLinear = null . nonLeftLinearRules
isOrthogonal p = isLeftLinear p && null (criticalPairs p)
isAlmostOrthogonal :: ( HasRules t v trs
, Eq (Term t v)
, Unify t
, Rename v, Enum v, Ord v
) => trs -> Bool
isAlmostOrthogonal p = isLeftLinear p && all isOverlay cps && and[ r1==r2 | (p,r1,r2) <- cps]
where cps = criticalPairs p
isOverlayTRS p = (all isOverlay . criticalPairs) p
isOverlay ([],r1,r2) = True
isOverlay _ = False
isNonOverlapping p = (null . criticalPairs) p
nonLeftLinearRules :: (Ord v, Foldable t, Functor t, HasRules t v trs) => trs -> [Rule t v]
nonLeftLinearRules trs = [ l:->r | l:->r <- rules trs, not (isLinear l)]
isConstructorBased :: (HasRules t v trs, HasSignature trs, HasId t, Foldable t, SignatureId trs ~ TermId t) => trs -> Bool
isConstructorBased trs = all (isConstructorRule trs) (rules trs)
isConstructorRule sig = Set.null
. Set.intersection (getDefinedSymbols sig)
. Set.fromList . catMaybes . map rootSymbol . properSubterms . lhs
criticalPairs :: (HasRules t v trs, Enum v, Ord v, Rename v, Unify t) =>
trs -> [(Position, Term t v, Term t v)]
criticalPairs trs
| null (rules trs) = []
| otherwise = -- Overlays between distinct rules
[ (p, updateAt p (const r') l \\ sigma, r \\ sigma)
| (l :-> r,rest) <- view (rules trs)
, l' :-> r' <- (`getVariant` (l:->r)) `map` rules rest
, l_p@Impure{} <- subterms $ annotateWithPos l
, let p = note l_p
, sigma <- maybeToList $ unify (dropNote l_p) l'
] ++
-- Overlays inside the same rule
[ (p, updateAt p (const r') l \\ sigma, r \\ sigma)
| l :-> r <- rules trs
, let l' :-> r' = getVariant (l:->r) (l:->r)
, l_p@Impure{} <- properSubterms $ annotateWithPos l
, let p = note l_p
, sigma <- maybeToList $ unify (dropNote l_p) l'
]
where
t \\ sigma = applySubst sigma t
-- comonadic map??? Need to learn about comonads
view = go [] where
go acc [x] = [(x,acc)]
go acc (x:xx) = (x, acc ++ xx) : go (x:acc) xx
|
pepeiborra/narradar
|
src/Narradar/Constraints/Syntactic.hs
|
bsd-3-clause
| 2,826 | 0 | 14 | 1,010 | 1,021 | 528 | 493 | 50 | 2 |
import Criterion.Main
import Criterion.Types
import SortBenchmarks
-- | This script runs the benchmarks, updating the HTML report on the
-- website.
main :: IO ()
main = sortBenchmarks
defaultConfig
{ reportFile = Just "../regex-uk/sort/sort-benchmarks.html"
}
|
cdornan/sort
|
benchmarks/src/update-sort-benchmarks.hs
|
bsd-3-clause
| 304 | 0 | 8 | 78 | 45 | 25 | 20 | 7 | 1 |
import System.Random
import Control.Monad.Identity
import Control.Monad.Random
import Control.Monad.Reader
import PIMC
main :: IO ()
main = do
let
params = testParams 1500 1.0 1.0
seed <- getStdGen
runMCSim params 100 1000
return ()
|
mstksg/pi-monte-carlo
|
src/Main.hs
|
bsd-3-clause
| 246 | 0 | 10 | 46 | 83 | 42 | 41 | 12 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.StorageGateway.UpdateChapCredentials
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation updates the Challenge-Handshake Authentication Protocol (CHAP)
-- credentials for a specified iSCSI target. By default, a gateway does not have
-- CHAP enabled; however, for added security, you might use it.
--
-- When you update CHAP credentials, all existing connections on the target
-- are closed and initiators must reconnect with the new credentials.
--
--
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateChapCredentials.html>
module Network.AWS.StorageGateway.UpdateChapCredentials
(
-- * Request
UpdateChapCredentials
-- ** Request constructor
, updateChapCredentials
-- ** Request lenses
, uccInitiatorName
, uccSecretToAuthenticateInitiator
, uccSecretToAuthenticateTarget
, uccTargetARN
-- * Response
, UpdateChapCredentialsResponse
-- ** Response constructor
, updateChapCredentialsResponse
-- ** Response lenses
, uccrInitiatorName
, uccrTargetARN
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
data UpdateChapCredentials = UpdateChapCredentials
{ _uccInitiatorName :: Text
, _uccSecretToAuthenticateInitiator :: Text
, _uccSecretToAuthenticateTarget :: Maybe Text
, _uccTargetARN :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'UpdateChapCredentials' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'uccInitiatorName' @::@ 'Text'
--
-- * 'uccSecretToAuthenticateInitiator' @::@ 'Text'
--
-- * 'uccSecretToAuthenticateTarget' @::@ 'Maybe' 'Text'
--
-- * 'uccTargetARN' @::@ 'Text'
--
updateChapCredentials :: Text -- ^ 'uccTargetARN'
-> Text -- ^ 'uccSecretToAuthenticateInitiator'
-> Text -- ^ 'uccInitiatorName'
-> UpdateChapCredentials
updateChapCredentials p1 p2 p3 = UpdateChapCredentials
{ _uccTargetARN = p1
, _uccSecretToAuthenticateInitiator = p2
, _uccInitiatorName = p3
, _uccSecretToAuthenticateTarget = Nothing
}
-- | The iSCSI initiator that connects to the target.
uccInitiatorName :: Lens' UpdateChapCredentials Text
uccInitiatorName = lens _uccInitiatorName (\s a -> s { _uccInitiatorName = a })
-- | The secret key that the initiator (e.g. Windows client) must provide to
-- participate in mutual CHAP with the target.
uccSecretToAuthenticateInitiator :: Lens' UpdateChapCredentials Text
uccSecretToAuthenticateInitiator =
lens _uccSecretToAuthenticateInitiator
(\s a -> s { _uccSecretToAuthenticateInitiator = a })
-- | The secret key that the target must provide to participate in mutual CHAP
-- with the initiator (e.g. Windows client).
uccSecretToAuthenticateTarget :: Lens' UpdateChapCredentials (Maybe Text)
uccSecretToAuthenticateTarget =
lens _uccSecretToAuthenticateTarget
(\s a -> s { _uccSecretToAuthenticateTarget = a })
-- | The Amazon Resource Name (ARN) of the iSCSI volume target. Use the 'DescribeStorediSCSIVolumes' operation to return to retrieve the TargetARN for specified VolumeARN.
uccTargetARN :: Lens' UpdateChapCredentials Text
uccTargetARN = lens _uccTargetARN (\s a -> s { _uccTargetARN = a })
data UpdateChapCredentialsResponse = UpdateChapCredentialsResponse
{ _uccrInitiatorName :: Maybe Text
, _uccrTargetARN :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'UpdateChapCredentialsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'uccrInitiatorName' @::@ 'Maybe' 'Text'
--
-- * 'uccrTargetARN' @::@ 'Maybe' 'Text'
--
updateChapCredentialsResponse :: UpdateChapCredentialsResponse
updateChapCredentialsResponse = UpdateChapCredentialsResponse
{ _uccrTargetARN = Nothing
, _uccrInitiatorName = Nothing
}
-- | The iSCSI initiator that connects to the target. This is the same initiator
-- name specified in the request.
uccrInitiatorName :: Lens' UpdateChapCredentialsResponse (Maybe Text)
uccrInitiatorName =
lens _uccrInitiatorName (\s a -> s { _uccrInitiatorName = a })
-- | The Amazon Resource Name (ARN) of the target. This is the same target
-- specified in the request.
uccrTargetARN :: Lens' UpdateChapCredentialsResponse (Maybe Text)
uccrTargetARN = lens _uccrTargetARN (\s a -> s { _uccrTargetARN = a })
instance ToPath UpdateChapCredentials where
toPath = const "/"
instance ToQuery UpdateChapCredentials where
toQuery = const mempty
instance ToHeaders UpdateChapCredentials
instance ToJSON UpdateChapCredentials where
toJSON UpdateChapCredentials{..} = object
[ "TargetARN" .= _uccTargetARN
, "SecretToAuthenticateInitiator" .= _uccSecretToAuthenticateInitiator
, "InitiatorName" .= _uccInitiatorName
, "SecretToAuthenticateTarget" .= _uccSecretToAuthenticateTarget
]
instance AWSRequest UpdateChapCredentials where
type Sv UpdateChapCredentials = StorageGateway
type Rs UpdateChapCredentials = UpdateChapCredentialsResponse
request = post "UpdateChapCredentials"
response = jsonResponse
instance FromJSON UpdateChapCredentialsResponse where
parseJSON = withObject "UpdateChapCredentialsResponse" $ \o -> UpdateChapCredentialsResponse
<$> o .:? "InitiatorName"
<*> o .:? "TargetARN"
|
kim/amazonka
|
amazonka-storagegateway/gen/Network/AWS/StorageGateway/UpdateChapCredentials.hs
|
mpl-2.0
| 6,519 | 0 | 11 | 1,359 | 745 | 450 | 295 | 87 | 1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest [
"-package"
, "ghc"
, "-XConstraintKinds", "-XFlexibleContexts"
, "-idist/build/autogen/"
, "-optP-include"
, "-optPdist/build/autogen/cabal_macros.h"
, "Language/Haskell/GhcMod.hs"
]
|
cabrera/ghc-mod
|
test/doctests.hs
|
bsd-3-clause
| 272 | 0 | 6 | 48 | 51 | 31 | 20 | 11 | 1 |
module Bead.Daemon.LDAP (
LDAPDaemon(..)
, LDAPDaemonConfig(..)
, startLDAPDaemon
, module Bead.Daemon.LDAP.Result
) where
import Prelude hiding (log)
import Control.Concurrent (forkIO)
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Monad (join)
import qualified Data.Map as Map
import Data.Maybe
import System.FilePath ((</>))
import Bead.Controller.Logging
import Bead.Daemon.LDAP.Result
import Bead.Daemon.LDAP.Query (QuerySettings(..))
import qualified Bead.Daemon.LDAP.Query as Query
import qualified Bead.Domain.Entities as Entity
type Username = String
type Password = String
data LDAPDaemon = LDAPDaemon {
query :: Username -> IO (IO LDAPResult)
-- ^ Queries the given username, and returns a computation that blocks
-- until the authentication result is not evaluated.
}
-- Configuration for the LDAPDaemon
data LDAPDaemonConfig = LDAPDaemonConfig {
timeout :: Int
, workers :: Int
, command :: String
, uidKey :: String
, nameKey :: String
, emailKey :: String
}
startLDAPDaemon :: Logger -> LDAPDaemonConfig -> IO LDAPDaemon
startLDAPDaemon logger config = do
queryQueue <- newTChanIO
noOfRequests <- newTVarIO (0 :: Int)
-- Every query tries to create an MTVar that blocks until
-- the final result is not calculated.
let query user = do
resultEnvelope <- newEmptyTMVarIO
atomically $ do
n <- modifyTVar add1 noOfRequests
writeTChan queryQueue (user,resultEnvelope)
return $ do
log logger INFO $ concat ["There are ", show n, " queries waiting in the LDAP queue."]
atomically $ readTMVar resultEnvelope
let uid_key = uidKey config
let name_key = nameKey config
let email_key = emailKey config
let queryOK attrs =
let attrMap = Map.fromList attrs
in fromMaybe LDAPAttrMapError $
do uid <- fmap Entity.Uid $ Map.lookup uid_key attrMap
name <- Map.lookup name_key attrMap
email <- fmap Entity.Email $ Map.lookup email_key attrMap
return $! LDAPUser (uid, email, name)
let queryInvalid = LDAPInvalidUser
let queryError msg = LDAPError msg
let attrs = [uid_key, name_key, email_key]
let loop daemon_id = do
log logger INFO $ concat ["LDAP Daemon ", daemon_id, " is waiting"]
join $ atomically $ do
modifyTVar sub1 noOfRequests
(user,resultEnvelope) <- readTChan queryQueue
return $ do
let querySettings = QuerySettings
{ queryTimeout = timeout config
, queryCommand = command config
}
queryResult <- waitCatch =<< async (Query.query querySettings user attrs)
log logger INFO $ concat ["LDAP Daemon ", daemon_id, " queries attributes for ", user]
atomically $ putTMVar resultEnvelope $ case queryResult of
Left someError -> LDAPError $ show someError
Right result -> Query.queryResult queryOK queryInvalid queryError result
loop daemon_id
-- Start the workers
sequence_ $ map (forkIO . loop . show) [1 .. workers config]
return $! LDAPDaemon query
where
sub1 x = x - 1
add1 x = x + 1
modifyTVar f var = do
x <- fmap f $ readTVar var
writeTVar var x
return x
|
andorp/bead
|
src/Bead/Daemon/LDAP.hs
|
bsd-3-clause
| 3,541 | 0 | 23 | 1,077 | 905 | 466 | 439 | 77 | 2 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
-- Create a source distribution tarball
module Stack.SDist
( getSDistTarball
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Codec.Compression.GZip as GZip
import Control.Applicative
import Control.Concurrent.Execute (ActionContext(..))
import Control.Monad (when, void)
import Control.Monad.Catch (MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Control (liftBaseWith)
import Control.Monad.Trans.Resource
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Data (Data, Typeable, cast, gmapT)
import Data.Either (partitionEithers)
import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import Distribution.Package (Dependency (..))
import Distribution.PackageDescription.PrettyPrint (showGenericPackageDescription)
import Distribution.Version (simplifyVersionRange, orLaterVersion, earlierVersion)
import Distribution.Version.Extra
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Path.IO
import Prelude -- Fix redundant import warnings
import Stack.Build (mkBaseConfigOpts)
import Stack.Build.Execute
import Stack.Build.Installed
import Stack.Build.Source (loadSourceMap, localFlags)
import Stack.Build.Target
import Stack.Constants
import Stack.Package
import Stack.Types
import Stack.Types.Internal
import qualified System.FilePath as FP
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env)
-- | Given the path to a local package, creates its source
-- distribution tarball.
--
-- While this yields a 'FilePath', the name of the tarball, this
-- tarball is not written to the disk and instead yielded as a lazy
-- bytestring.
getSDistTarball :: M env m
=> Maybe PvpBounds -- ^ override Config value
-> Path Abs Dir
-> m (FilePath, L.ByteString)
getSDistTarball mpvpBounds pkgDir = do
config <- asks getConfig
let pvpBounds = fromMaybe (configPvpBounds config) mpvpBounds
tweakCabal = pvpBounds /= PvpBoundsNone
pkgFp = toFilePath pkgDir
lp <- readLocalPackage pkgDir
$logInfo $ "Getting file list for " <> T.pack pkgFp
(fileList, cabalfp) <- getSDistFileList lp
$logInfo $ "Building sdist tarball for " <> T.pack pkgFp
files <- normalizeTarballPaths (lines fileList)
-- NOTE: Could make this use lazy I/O to only read files as needed
-- for upload (both GZip.compress and Tar.write are lazy).
-- However, it seems less error prone and more predictable to read
-- everything in at once, so that's what we're doing for now:
let tarPath isDir fp = either error id
(Tar.toTarPath isDir (pkgId FP.</> fp))
packWith f isDir fp =
liftIO $ f (pkgFp FP.</> fp)
(tarPath isDir fp)
packDir = packWith Tar.packDirectoryEntry True
packFile fp
| tweakCabal && isCabalFp fp = do
lbs <- getCabalLbs pvpBounds $ toFilePath cabalfp
return $ Tar.fileEntry (tarPath False fp) lbs
| otherwise = packWith Tar.packFileEntry False fp
isCabalFp fp = toFilePath pkgDir FP.</> fp == toFilePath cabalfp
tarName = pkgId FP.<.> "tar.gz"
pkgId = packageIdentifierString (packageIdentifier (lpPackage lp))
dirEntries <- mapM packDir (dirsFromFiles files)
fileEntries <- mapM packFile files
return (tarName, GZip.compress (Tar.write (dirEntries ++ fileEntries)))
-- | Get the PVP bounds-enabled version of the given cabal file
getCabalLbs :: M env m => PvpBounds -> FilePath -> m L.ByteString
getCabalLbs pvpBounds fp = do
bs <- liftIO $ S.readFile fp
(_warnings, gpd) <- readPackageUnresolvedBS Nothing bs
(_, _, _, _, sourceMap) <- loadSourceMap AllowNoTargets defaultBuildOpts
menv <- getMinimalEnvOverride
(installedMap, _, _) <- getInstalled menv GetInstalledOpts
{ getInstalledProfiling = False
, getInstalledHaddock = False
}
sourceMap
let gpd' = gtraverseT (addBounds sourceMap installedMap) gpd
return $ TLE.encodeUtf8 $ TL.pack $ showGenericPackageDescription gpd'
where
addBounds :: SourceMap -> InstalledMap -> Dependency -> Dependency
addBounds sourceMap installedMap dep@(Dependency cname range) =
case lookupVersion (fromCabalPackageName cname) of
Nothing -> dep
Just version -> Dependency cname $ simplifyVersionRange
$ (if toAddUpper && not (hasUpper range) then addUpper version else id)
$ (if toAddLower && not (hasLower range) then addLower version else id)
range
where
lookupVersion name =
case Map.lookup name sourceMap of
Just (PSLocal lp) -> Just $ packageVersion $ lpPackage lp
Just (PSUpstream version _ _) -> Just version
Nothing ->
case Map.lookup name installedMap of
Just (_, installed) -> Just (installedVersion installed)
Nothing -> Nothing
addUpper version = intersectVersionRanges
(earlierVersion $ toCabalVersion $ nextMajorVersion version)
addLower version = intersectVersionRanges
(orLaterVersion (toCabalVersion version))
(toAddLower, toAddUpper) =
case pvpBounds of
PvpBoundsNone -> (False, False)
PvpBoundsUpper -> (False, True)
PvpBoundsLower -> (True, False)
PvpBoundsBoth -> (True, True)
-- | Traverse a data type.
gtraverseT :: (Data a,Typeable b) => (Typeable b => b -> b) -> a -> a
gtraverseT f =
gmapT (\x -> case cast x of
Nothing -> gtraverseT f x
Just b -> fromMaybe x (cast (f b)))
-- Read in a 'LocalPackage' config. This makes some default decisions
-- about 'LocalPackage' fields that might not be appropriate for other
-- usecases.
--
-- TODO: Dedupe with similar code in "Stack.Build.Source".
readLocalPackage :: M env m => Path Abs Dir -> m LocalPackage
readLocalPackage pkgDir = do
econfig <- asks getEnvConfig
bconfig <- asks getBuildConfig
cabalfp <- getCabalFileName pkgDir
name <- parsePackageNameFromFilePath cabalfp
let config = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = localFlags Map.empty bconfig name
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform $ getConfig bconfig
}
(warnings,package) <- readPackage config cabalfp
mapM_ (printCabalFileWarning cabalfp) warnings
return LocalPackage
{ lpPackage = package
, lpExeComponents = Nothing -- HACK: makes it so that sdist output goes to a log instead of a file.
, lpDir = pkgDir
, lpCabalFile = cabalfp
-- NOTE: these aren't the 'correct values, but aren't used in
-- the usage of this function in this module.
, lpTestDeps = Map.empty
, lpBenchDeps = Map.empty
, lpTestBench = Nothing
, lpDirtyFiles = Just Set.empty
, lpNewBuildCache = Map.empty
, lpFiles = Set.empty
, lpComponents = Set.empty
}
-- | Returns a newline-separate list of paths, and the absolute path to the .cabal file.
getSDistFileList :: M env m => LocalPackage -> m (String, Path Abs File)
getSDistFileList lp =
withCanonicalizedSystemTempDirectory (stackProgName <> "-sdist") $ \tmpdir -> do
menv <- getMinimalEnvOverride
let bopts = defaultBuildOpts
baseConfigOpts <- mkBaseConfigOpts bopts
(_, _mbp, locals, _extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts
runInBase <- liftBaseWith $ \run -> return (void . run)
withExecuteEnv menv bopts baseConfigOpts locals
[] -- provide empty list of globals. This is a hack around custom Setup.hs files
sourceMap $ \ee -> do
withSingleContext runInBase ac ee task Nothing (Just "sdist") $ \_package cabalfp _pkgDir cabal _announce _console _mlogFile -> do
let outFile = toFilePath tmpdir FP.</> "source-files-list"
cabal False ["sdist", "--list-sources", outFile]
contents <- liftIO (readFile outFile)
return (contents, cabalfp)
where
package = lpPackage lp
ac = ActionContext Set.empty
task = Task
{ taskProvides = PackageIdentifier (packageName package) (packageVersion package)
, taskType = TTLocal lp
, taskConfigOpts = TaskConfigOpts
{ tcoMissing = Set.empty
, tcoOpts = \_ -> ConfigureOpts [] []
}
, taskPresent = Map.empty
}
normalizeTarballPaths :: M env m => [FilePath] -> m [FilePath]
normalizeTarballPaths fps = do
--TODO: consider whether erroring out is better - otherwise the
--user might upload an incomplete tar?
when (not (null outsideDir)) $
$logWarn $ T.concat
[ "Warning: These files are outside of the package directory, and will be omitted from the tarball: "
, T.pack (show outsideDir)]
return files
where
(outsideDir, files) = partitionEithers (map pathToEither fps)
pathToEither fp = maybe (Left fp) Right (normalizePath fp)
normalizePath :: FilePath -> (Maybe FilePath)
normalizePath = fmap FP.joinPath . go . FP.splitDirectories . FP.normalise
where
go [] = Just []
go ("..":_) = Nothing
go (_:"..":xs) = go xs
go (x:xs) = (x :) <$> go xs
dirsFromFiles :: [FilePath] -> [FilePath]
dirsFromFiles dirs = Set.toAscList (Set.delete "." results)
where
results = foldl' (\s -> go s . FP.takeDirectory) Set.empty dirs
go s x
| Set.member x s = s
| otherwise = go (Set.insert x s) (FP.takeDirectory x)
|
lukexi/stack
|
src/Stack/SDist.hs
|
bsd-3-clause
| 10,849 | 0 | 21 | 2,925 | 2,624 | 1,391 | 1,233 | 197 | 10 |
{-# LANGUAGE MagicHash #-}
module Stack.Types.StringError where
import Control.Exception
import Control.Monad.Catch
import Data.Typeable
import GHC.Prim
newtype StringError = StringError String
deriving (Typeable)
instance Exception StringError
instance Show StringError where show (StringError str) = str
throwString :: MonadThrow m => String -> m a
throwString = throwM . StringError
errorString :: String -> a
errorString = raise# . toException . StringError
|
mrkkrp/stack
|
src/Stack/Types/StringError.hs
|
bsd-3-clause
| 472 | 0 | 8 | 70 | 123 | 68 | 55 | 14 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module BenchmarkUtils where
import Feldspar.Compiler.Plugin (pack)
import Control.Exception (evaluate)
import Criterion.Main
import Criterion.Types
import Data.List (intercalate)
mkConfig report = defaultConfig { forceGC = True
, reportFile = Just report
}
dimToString ls = intercalate "x" (map show ls)
mkData ds ls = do putStrLn $ unwords ["Alloc array with", dimToString ls, "elements"]
evaluate =<< pack (take (fromIntegral $ product ls) ds)
mkData2 ds ls = do putStrLn $ unwords ["Alloc array with", dimToString ls, "elements"]
evaluate =<< pack (ls,take (fromIntegral $ product ls) ds)
mkBench name ls fun = bench (name ++ "_" ++ dimToString ls) fun
|
emwap/feldspar-compiler
|
benchs/BenchmarkUtils.hs
|
bsd-3-clause
| 801 | 0 | 13 | 212 | 246 | 128 | 118 | 15 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Internal.Http.Parser.Tests
( tests ) where
import qualified Control.Exception as E
import Control.Exception hiding (try, assert)
import Control.Monad
import Control.Parallel.Strategies
import Data.Attoparsec hiding (Result(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Internal (c2w)
import Data.List
import qualified Data.Map as Map
import Data.Maybe (isNothing)
import Data.Monoid
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import qualified Test.QuickCheck.Monadic as QC
import Test.QuickCheck.Monadic hiding (run, assert)
import Test.HUnit hiding (Test, path)
import Text.Printf
import Snap.Internal.Http.Parser
import Snap.Internal.Http.Types
import Snap.Internal.Debug
import Snap.Iteratee hiding (map, sequence)
import qualified Snap.Iteratee as I
import Snap.Test.Common()
tests :: [Test]
tests = [ testShow
, testCookie
, testChunked
, testP2I
, testNull
, testPartial
, testParseError
, testFormEncoded ]
emptyParser :: Parser ByteString
emptyParser = option "foo" $ string "bar"
testShow :: Test
testShow = testCase "parser/show" $ do
let i = IRequest GET "/" (1,1) []
let !b = show i `using` rdeepseq
return $ b `seq` ()
testP2I :: Test
testP2I = testCase "parser/iterParser" $ do
i <- liftM (enumBS "z") $ runIteratee (iterParser emptyParser)
l <- run_ i
assertEqual "should be foo" "foo" l
forceErr :: SomeException -> IO ()
forceErr e = f `seq` (return ())
where
!f = show e
testNull :: Test
testNull = testCase "parser/shortParse" $ do
f <- run_ (parseRequest)
assertBool "should be Nothing" $ isNothing f
testPartial :: Test
testPartial = testCase "parser/partial" $ do
i <- liftM (enumBS "GET / ") $ runIteratee parseRequest
f <- E.try $ run_ i
case f of (Left e) -> forceErr e
(Right x) -> assertFailure $ "expected exception, got " ++ show x
testParseError :: Test
testParseError = testCase "parser/error" $ do
step <- runIteratee parseRequest
let i = enumBS "ZZZZZZZZZZ" step
f <- E.try $ run_ i
case f of (Left e) -> forceErr e
(Right x) -> assertFailure $ "expected exception, got " ++ show x
-- | convert a bytestring to chunked transfer encoding
transferEncodingChunked :: L.ByteString -> L.ByteString
transferEncodingChunked = f . L.toChunks
where
toChunk s = L.concat [ len, "\r\n", L.fromChunks [s], "\r\n" ]
where
len = L.pack $ map c2w $ printf "%x" $ S.length s
f l = L.concat $ (map toChunk l ++ ["0\r\n\r\n"])
-- | ensure that running the 'readChunkedTransferEncoding' iteratee against
-- 'transferEncodingChunked' returns the original string
testChunked :: Test
testChunked = testProperty "parser/chunkedTransferEncoding" $
monadicIO $ forAllM arbitrary prop_chunked
where
prop_chunked s = do
QC.run $ debug "=============================="
QC.run $ debug $ "input is " ++ show s
QC.run $ debug $ "chunked is " ++ show chunked
QC.run $ debug "------------------------------"
sstep <- QC.run $ runIteratee $ stream2stream
step <- QC.run $ runIteratee $
joinI $ readChunkedTransferEncoding sstep
out <- QC.run $ run_ $ enum step
QC.assert $ s == out
QC.run $ debug "==============================\n"
where
chunked = (transferEncodingChunked s)
enum = enumLBS chunked
testCookie :: Test
testCookie =
testCase "parser/parseCookie" $ do
assertEqual "cookie parsing" (Just [cv]) cv2
where
cv = Cookie nm v Nothing Nothing Nothing False False
cv2 = parseCookie ct
nm = "foo"
v = "bar"
ct = S.concat [ nm , "=" , v ]
testFormEncoded :: Test
testFormEncoded = testCase "parser/formEncoded" $ do
let bs = "foo1=bar1&foo2=bar2+baz2;foo3=foo%20bar"
let mp = parseUrlEncoded bs
assertEqual "foo1" (Just ["bar1"] ) $ Map.lookup "foo1" mp
assertEqual "foo2" (Just ["bar2 baz2"]) $ Map.lookup "foo2" mp
assertEqual "foo3" (Just ["foo bar"] ) $ Map.lookup "foo3" mp
copyingStream2Stream :: (Monad m) => Iteratee ByteString m ByteString
copyingStream2Stream = go []
where
go l = do
mbx <- I.head
maybe (return $ S.concat $ reverse l)
(\x -> let !z = S.copy x in go (z:l))
mbx
stream2stream :: (Monad m) => Iteratee ByteString m L.ByteString
stream2stream = liftM L.fromChunks consume
|
beni55/snap-server
|
test/suite/Snap/Internal/Http/Parser/Tests.hs
|
bsd-3-clause
| 4,977 | 0 | 17 | 1,309 | 1,441 | 751 | 690 | 119 | 2 |
{-# LANGUAGE CPP #-}
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 704
{-# LANGUAGE Trustworthy #-}
#endif
{-# LANGUAGE Rank2Types #-}
#ifndef MIN_VERSION_template_haskell
#define MIN_VERSION_template_haskell(x,y,z) 1
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.TH.Lens
-- Copyright : (C) 2012-2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : TemplateHaskell
--
-- Lenses, Prisms, and Traversals for working with Template Haskell
----------------------------------------------------------------------------
module Language.Haskell.TH.Lens
(
-- * Traversals
HasName(..)
, HasTypeVars(..)
, SubstType(..)
, typeVars -- :: HasTypeVars t => Traversal' t Name
, substTypeVars -- :: HasTypeVars t => Map Name Name -> t -> t
, conFields
, conNamedFields
-- * Lenses
-- ** Loc Lenses
, locFileName
, locPackage
, locModule
, locStart
, locEnd
-- ** FunDep Lenses
, funDepInputs
, funDepOutputs
-- ** Match Lenses
, matchPattern
, matchBody
, matchDeclarations
-- ** Fixity Lenses
, fixityPrecedence
, fixityDirection
-- ** Clause Lenses
, clausePattern
, clauseBody
, clauseDecs
-- ** FieldExp Lenses
, fieldExpName
, fieldExpExpression
-- ** FieldPat Lenses
, fieldPatName
, fieldPatPattern
#if MIN_VERSION_template_haskell(2,9,0)
-- ** TySynEqn Lenses
, tySynEqnPatterns
, tySynEqnResult
#endif
-- * Prisms
-- ** Info Prisms
, _ClassI
, _ClassOpI
, _TyConI
, _FamilyI
, _PrimTyConI
, _DataConI
, _VarI
, _TyVarI
-- ** Dec Prisms
, _FunD
, _ValD
, _DataD
, _NewtypeD
, _TySynD
, _ClassD
, _InstanceD
, _SigD
, _ForeignD
#if MIN_VERSION_template_haskell(2,8,0)
, _InfixD
#endif
, _PragmaD
, _FamilyD
, _DataInstD
, _NewtypeInstD
, _TySynInstD
#if MIN_VERSION_template_haskell(2,9,0)
, _ClosedTypeFamilyD
, _RoleAnnotD
#endif
-- ** Con Prisms
, _NormalC
, _RecC
, _InfixC
, _ForallC
-- ** Strict Prisms
, _IsStrict
, _NotStrict
, _Unpacked
-- ** Foreign Prisms
, _ImportF
, _ExportF
-- ** Callconv Prisms
, _CCall
, _StdCall
-- ** Safety Prisms
, _Unsafe
, _Safe
, _Interruptible
-- ** Pragma Prisms
, _InlineP
, _SpecialiseP
#if MIN_VERSION_template_haskell(2,8,0)
, _SpecialiseInstP
, _RuleP
#if MIN_VERSION_template_haskell(2,9,0)
, _AnnP
#endif
-- ** Inline Prisms
, _NoInline
, _Inline
, _Inlinable
-- ** RuleMatch Prisms
, _ConLike
, _FunLike
-- ** Phases Prisms
, _AllPhases
, _FromPhase
, _BeforePhase
-- ** RuleBndr Prisms
, _RuleVar
, _TypedRuleVar
#endif
#if MIN_VERSION_template_haskell(2,9,0)
-- ** AnnTarget Prisms
, _ModuleAnnotation
, _TypeAnnotation
, _ValueAnnotation
#endif
-- ** FunDep Prisms TODO make a lens
, _FunDep
-- ** FamFlavour Prisms
, _TypeFam
, _DataFam
-- ** FixityDirection Prisms
, _InfixL
, _InfixR
, _InfixN
-- ** Exp Prisms
, _VarE
, _ConE
, _LitE
, _AppE
, _InfixE
, _UInfixE
, _ParensE
, _LamE
#if MIN_VERSION_template_haskell(2,8,0)
, _LamCaseE
#endif
, _TupE
, _UnboxedTupE
, _CondE
#if MIN_VERSION_template_haskell(2,8,0)
, _MultiIfE
#endif
, _LetE
, _CaseE
, _DoE
, _CompE
, _ArithSeqE
, _ListE
, _SigE
, _RecConE
, _RecUpdE
-- ** Body Prisms
, _GuardedB
, _NormalB
-- ** Guard Prisms
, _NormalG
, _PatG
-- ** Stmt Prisms
, _BindS
, _LetS
, _NoBindS
, _ParS
-- ** Range Prisms
, _FromR
, _FromThenR
, _FromToR
, _FromThenToR
-- ** Lit Prisms
, _CharL
, _StringL
, _IntegerL
, _RationalL
, _IntPrimL
, _WordPrimL
, _FloatPrimL
, _DoublePrimL
, _StringPrimL
-- ** Pat Prisms
, _LitP
, _VarP
, _TupP
, _UnboxedTupP
, _ConP
, _InfixP
, _UInfixP
, _ParensP
, _TildeP
, _BangP
, _AsP
, _WildP
, _RecP
, _ListP
, _SigP
, _ViewP
-- ** Type Prisms
, _ForallT
, _AppT
, _SigT
, _VarT
, _ConT
#if MIN_VERSION_template_haskell(2,8,0)
, _PromotedT
#endif
, _TupleT
, _UnboxedTupleT
, _ArrowT
, _ListT
#if MIN_VERSION_template_haskell(2,8,0)
, _PromotedTupleT
, _PromotedNilT
, _PromotedConsT
, _StarT
, _ConstraintT
, _LitT
#endif
-- ** TyVarBndr Prisms
, _PlainTV
, _KindedTV
#if MIN_VERSION_template_haskell(2,8,0)
-- ** TyLit Prisms
, _NumTyLit
, _StrTyLit
#endif
#if !MIN_VERSION_template_haskell(2,10,0)
-- ** Pred Prisms
, _ClassP
, _EqualP
#endif
#if MIN_VERSION_template_haskell(2,9,0)
-- ** Role Prisms
, _NominalR
, _RepresentationalR
#endif
) where
import Control.Applicative
import Control.Lens.At
import Control.Lens.Getter
import Control.Lens.Setter
import Control.Lens.Fold
import Control.Lens.Lens
import Control.Lens.Prism
import Control.Lens.Tuple
import Control.Lens.Traversal
import Data.Map as Map hiding (toList,map)
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Set as Set hiding (toList,map)
import Data.Set.Lens
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
#if MIN_VERSION_template_haskell(2,8,0)
import Data.Word
#endif
import Prelude
-- | Has a 'Name'
class HasName t where
-- | Extract (or modify) the 'Name' of something
name :: Lens' t Name
instance HasName TyVarBndr where
name f (PlainTV n) = PlainTV <$> f n
name f (KindedTV n k) = (`KindedTV` k) <$> f n
instance HasName Name where
name = id
instance HasName Con where
name f (NormalC n tys) = (`NormalC` tys) <$> f n
name f (RecC n tys) = (`RecC` tys) <$> f n
name f (InfixC l n r) = (\n' -> InfixC l n' r) <$> f n
name f (ForallC bds ctx con) = ForallC bds ctx <$> name f con
-- | Contains some amount of `Type`s inside
class HasTypes t where
-- | Traverse all the types
types :: Traversal' t Type
instance HasTypes Type where
types = id
instance HasTypes Con where
types f (NormalC n t) = NormalC n <$> traverse (_2 (types f)) t
types f (RecC n t) = RecC n <$> traverse (_3 (types f)) t
types f (InfixC t1 n t2) = InfixC <$> _2 (types f) t1
<*> pure n <*> _2 (types f) t2
types f (ForallC vb ctx con) = ForallC vb ctx <$> types f con
instance HasTypes t => HasTypes [t] where
types = traverse . types
-- | Provides for the extraction of free type variables, and alpha renaming.
class HasTypeVars t where
-- | When performing substitution into this traversal you're not allowed
-- to substitute in a name that is bound internally or you'll violate
-- the 'Traversal' laws, when in doubt generate your names with 'newName'.
typeVarsEx :: Set Name -> Traversal' t Name
instance HasTypeVars TyVarBndr where
typeVarsEx s f b
| s^.contains (b^.name) = pure b
| otherwise = name f b
instance HasTypeVars Name where
typeVarsEx s f n
| s^.contains n = pure n
| otherwise = f n
instance HasTypeVars Type where
typeVarsEx s f (VarT n) = VarT <$> typeVarsEx s f n
typeVarsEx s f (AppT l r) = AppT <$> typeVarsEx s f l <*> typeVarsEx s f r
typeVarsEx s f (SigT t k) = (`SigT` k) <$> typeVarsEx s f t
typeVarsEx s f (ForallT bs ctx ty) = ForallT bs <$> typeVarsEx s' f ctx <*> typeVarsEx s' f ty
where s' = s `Set.union` setOf typeVars bs
typeVarsEx _ _ t = pure t
#if !MIN_VERSION_template_haskell(2,10,0)
instance HasTypeVars Pred where
typeVarsEx s f (ClassP n ts) = ClassP n <$> typeVarsEx s f ts
typeVarsEx s f (EqualP l r) = EqualP <$> typeVarsEx s f l <*> typeVarsEx s f r
#endif
instance HasTypeVars Con where
typeVarsEx s f (NormalC n ts) = NormalC n <$> traverseOf (traverse . _2) (typeVarsEx s f) ts
typeVarsEx s f (RecC n ts) = RecC n <$> traverseOf (traverse . _3) (typeVarsEx s f) ts
typeVarsEx s f (InfixC l n r) = InfixC <$> g l <*> pure n <*> g r
where g (i, t) = (,) i <$> typeVarsEx s f t
typeVarsEx s f (ForallC bs ctx c) = ForallC bs <$> typeVarsEx s' f ctx <*> typeVarsEx s' f c
where s' = s `Set.union` setOf typeVars bs
instance HasTypeVars t => HasTypeVars [t] where
typeVarsEx s = traverse . typeVarsEx s
instance HasTypeVars t => HasTypeVars (Maybe t) where
typeVarsEx s = traverse . typeVarsEx s
-- | Traverse /free/ type variables
typeVars :: HasTypeVars t => Traversal' t Name
typeVars = typeVarsEx mempty
-- | Substitute using a map of names in for /free/ type variables
substTypeVars :: HasTypeVars t => Map Name Name -> t -> t
substTypeVars m = over typeVars $ \n -> fromMaybe n (m^.at n)
-- | Provides substitution for types
class SubstType t where
-- | Perform substitution for types
substType :: Map Name Type -> t -> t
instance SubstType Type where
substType m t@(VarT n) = fromMaybe t (m^.at n)
substType m (ForallT bs ctx ty) = ForallT bs (substType m' ctx) (substType m' ty)
where m' = foldrOf typeVars Map.delete m bs
substType m (SigT t k) = SigT (substType m t) k
substType m (AppT l r) = AppT (substType m l) (substType m r)
substType _ t = t
instance SubstType t => SubstType [t] where
substType = map . substType
#if !MIN_VERSION_template_haskell(2,10,0)
instance SubstType Pred where
substType m (ClassP n ts) = ClassP n (substType m ts)
substType m (EqualP l r) = substType m (EqualP l r)
#endif
-- | Provides a 'Traversal' of the types of each field of a constructor.
conFields :: Traversal' Con StrictType
conFields f (NormalC n fs) = NormalC n <$> traverse f fs
conFields f (RecC n fs) = RecC n <$> traverse sans_var fs
where sans_var (fn,s,t) = (\(s', t') -> (fn,s',t')) <$> f (s, t)
conFields f (InfixC l n r) = InfixC <$> f l <*> pure n <*> f r
conFields f (ForallC bds ctx c) = ForallC bds ctx <$> conFields f c
-- | 'Traversal' of the types of the /named/ fields of a constructor.
conNamedFields :: Traversal' Con VarStrictType
conNamedFields f (RecC n fs) = RecC n <$> traverse f fs
conNamedFields f (ForallC a b fs) = ForallC a b <$> conNamedFields f fs
conNamedFields _ c = pure c
-- Lenses and Prisms
locFileName :: Lens' Loc String
locFileName = lens loc_filename
$ \loc fn -> loc { loc_filename = fn }
locPackage :: Lens' Loc String
locPackage = lens loc_package
$ \loc fn -> loc { loc_package = fn }
locModule :: Lens' Loc String
locModule = lens loc_module
$ \loc fn -> loc { loc_module = fn }
locStart :: Lens' Loc CharPos
locStart = lens loc_start
$ \loc fn -> loc { loc_start = fn }
locEnd :: Lens' Loc CharPos
locEnd = lens loc_end
$ \loc fn -> loc { loc_end = fn }
funDepInputs :: Lens' FunDep [Name]
funDepInputs = lens g s where
g (FunDep xs _) = xs
s (FunDep _ ys) xs = FunDep xs ys
funDepOutputs :: Lens' FunDep [Name]
funDepOutputs = lens g s where
g (FunDep _ xs) = xs
s (FunDep ys _) = FunDep ys
fieldExpName :: Lens' FieldExp Name
fieldExpName = _1
fieldExpExpression :: Lens' FieldExp Exp
fieldExpExpression = _2
fieldPatName :: Lens' FieldPat Name
fieldPatName = _1
fieldPatPattern :: Lens' FieldPat Pat
fieldPatPattern = _2
matchPattern :: Lens' Match Pat
matchPattern = lens g s where
g (Match p _ _) = p
s (Match _ x y) p = Match p x y
matchBody :: Lens' Match Body
matchBody = lens g s where
g (Match _ b _) = b
s (Match x _ y) b = Match x b y
matchDeclarations :: Lens' Match [Dec]
matchDeclarations = lens g s where
g (Match _ _ ds) = ds
s (Match x y _ ) = Match x y
fixityPrecedence :: Lens' Fixity Int
fixityPrecedence = lens g s where
g (Fixity i _) = i
s (Fixity _ x) i = Fixity i x
fixityDirection :: Lens' Fixity FixityDirection
fixityDirection = lens g s where
g (Fixity _ d) = d
s (Fixity i _) = Fixity i
clausePattern :: Lens' Clause [Pat]
clausePattern = lens g s where
g (Clause ps _ _) = ps
s (Clause _ x y) ps = Clause ps x y
clauseBody :: Lens' Clause Body
clauseBody = lens g s where
g (Clause _ b _) = b
s (Clause x _ y) b = Clause x b y
clauseDecs :: Lens' Clause [Dec]
clauseDecs = lens g s where
g (Clause _ _ ds) = ds
s (Clause x y _ ) = Clause x y
#if MIN_VERSION_template_haskell(2,8,0)
_ClassI :: Prism' Info (Dec, [InstanceDec])
_ClassI
= prism remitter reviewer
where
remitter (x, y) = ClassI x y
reviewer (ClassI x y) = Right (x, y)
reviewer x = Left x
_ClassOpI :: Prism' Info (Name, Type, ParentName, Fixity)
_ClassOpI
= prism remitter reviewer
where
remitter (x, y, z, w) = ClassOpI x y z w
reviewer (ClassOpI x y z w) = Right (x, y, z, w)
reviewer x = Left x
#else
_ClassI :: Prism' Info (Dec, [Dec])
_ClassI
= prism remitter reviewer
where
remitter (x, y) = ClassI x y
reviewer (ClassI x y) = Right (x, y)
reviewer x = Left x
_ClassOpI :: Prism' Info (Name, Type, Name, Fixity)
_ClassOpI
= prism remitter reviewer
where
remitter (x, y, z, w) = ClassOpI x y z w
reviewer (ClassOpI x y z w) = Right (x, y, z, w)
reviewer x = Left x
#endif
_TyConI :: Prism' Info Dec
_TyConI
= prism remitter reviewer
where
remitter = TyConI
reviewer (TyConI x) = Right x
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_FamilyI :: Prism' Info (Dec, [InstanceDec])
_FamilyI
= prism remitter reviewer
where
remitter (x, y) = FamilyI x y
reviewer (FamilyI x y) = Right (x, y)
reviewer x = Left x
_PrimTyConI :: Prism' Info (Name, Arity, Unlifted)
_PrimTyConI
= prism remitter reviewer
where
remitter (x, y, z) = PrimTyConI x y z
reviewer (PrimTyConI x y z) = Right (x, y, z)
reviewer x = Left x
_DataConI :: Prism' Info (Name, Type, ParentName, Fixity)
_DataConI
= prism remitter reviewer
where
remitter (x, y, z, w) = DataConI x y z w
reviewer (DataConI x y z w) = Right (x, y, z, w)
reviewer x = Left x
#else
_FamilyI :: Prism' Info (Dec, [Dec])
_FamilyI
= prism remitter reviewer
where
remitter (x, y) = FamilyI x y
reviewer (FamilyI x y) = Right (x, y)
reviewer x = Left x
_PrimTyConI :: Prism' Info (Name, Int, Bool)
_PrimTyConI
= prism remitter reviewer
where
remitter (x, y, z) = PrimTyConI x y z
reviewer (PrimTyConI x y z) = Right (x, y, z)
reviewer x = Left x
_DataConI :: Prism' Info (Name, Type, Name, Fixity)
_DataConI
= prism remitter reviewer
where
remitter (x, y, z, w) = DataConI x y z w
reviewer (DataConI x y z w) = Right (x, y, z, w)
reviewer x = Left x
#endif
_VarI :: Prism' Info (Name, Type, Maybe Dec, Fixity)
_VarI
= prism remitter reviewer
where
remitter (x, y, z, w) = VarI x y z w
reviewer (VarI x y z w) = Right (x, y, z, w)
reviewer x = Left x
_TyVarI :: Prism' Info (Name, Type)
_TyVarI
= prism remitter reviewer
where
remitter (x, y) = TyVarI x y
reviewer (TyVarI x y) = Right (x, y)
reviewer x = Left x
_FunD :: Prism' Dec (Name, [Clause])
_FunD
= prism remitter reviewer
where
remitter (x, y) = FunD x y
reviewer (FunD x y) = Right (x, y)
reviewer x = Left x
_ValD :: Prism' Dec (Pat, Body, [Dec])
_ValD
= prism remitter reviewer
where
remitter (x, y, z) = ValD x y z
reviewer (ValD x y z) = Right (x, y, z)
reviewer x = Left x
_DataD :: Prism' Dec (Cxt, Name, [TyVarBndr], [Con], [Name])
_DataD
= prism remitter reviewer
where
remitter (x, y, z, w, u) = DataD x y z w u
reviewer (DataD x y z w u) = Right (x, y, z, w, u)
reviewer x = Left x
_NewtypeD :: Prism' Dec (Cxt, Name, [TyVarBndr], Con, [Name])
_NewtypeD
= prism remitter reviewer
where
remitter (x, y, z, w, u) = NewtypeD x y z w u
reviewer (NewtypeD x y z w u) = Right (x, y, z, w, u)
reviewer x = Left x
_TySynD :: Prism' Dec (Name, [TyVarBndr], Type)
_TySynD
= prism remitter reviewer
where
remitter (x, y, z) = TySynD x y z
reviewer (TySynD x y z) = Right (x, y, z)
reviewer x = Left x
_ClassD :: Prism' Dec (Cxt, Name, [TyVarBndr], [FunDep], [Dec])
_ClassD
= prism remitter reviewer
where
remitter (x, y, z, w, u) = ClassD x y z w u
reviewer (ClassD x y z w u) = Right (x, y, z, w, u)
reviewer x = Left x
_InstanceD :: Prism' Dec (Cxt, Type, [Dec])
_InstanceD
= prism remitter reviewer
where
remitter (x, y, z) = InstanceD x y z
reviewer (InstanceD x y z) = Right (x, y, z)
reviewer x = Left x
_SigD :: Prism' Dec (Name, Type)
_SigD
= prism remitter reviewer
where
remitter (x, y) = SigD x y
reviewer (SigD x y) = Right (x, y)
reviewer x = Left x
_ForeignD :: Prism' Dec Foreign
_ForeignD
= prism remitter reviewer
where
remitter = ForeignD
reviewer (ForeignD x) = Right x
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_InfixD :: Prism' Dec (Fixity, Name)
_InfixD
= prism remitter reviewer
where
remitter (x, y) = InfixD x y
reviewer (InfixD x y) = Right (x, y)
reviewer x = Left x
#endif
_PragmaD :: Prism' Dec Pragma
_PragmaD
= prism remitter reviewer
where
remitter = PragmaD
reviewer (PragmaD x) = Right x
reviewer x = Left x
_FamilyD :: Prism' Dec (FamFlavour, Name, [TyVarBndr], Maybe Kind)
_FamilyD
= prism remitter reviewer
where
remitter (x, y, z, w) = FamilyD x y z w
reviewer (FamilyD x y z w) = Right (x, y, z, w)
reviewer x = Left x
_DataInstD :: Prism' Dec (Cxt, Name, [Type], [Con], [Name])
_DataInstD
= prism remitter reviewer
where
remitter (x, y, z, w, u) = DataInstD x y z w u
reviewer (DataInstD x y z w u) = Right (x, y, z, w, u)
reviewer x = Left x
_NewtypeInstD :: Prism' Dec (Cxt, Name, [Type], Con, [Name])
_NewtypeInstD
= prism remitter reviewer
where
remitter (x, y, z, w, u) = NewtypeInstD x y z w u
reviewer (NewtypeInstD x y z w u) = Right (x, y, z, w, u)
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,9,0)
_TySynInstD :: Prism' Dec (Name, TySynEqn)
_TySynInstD
= prism remitter reviewer
where
remitter (x, y) = TySynInstD x y
reviewer (TySynInstD x y) = Right (x, y)
reviewer x = Left x
_ClosedTypeFamilyD :: Prism' Dec (Name, [TyVarBndr], Maybe Kind, [TySynEqn])
_ClosedTypeFamilyD
= prism remitter reviewer
where
remitter (x, y, z, w) = ClosedTypeFamilyD x y z w
reviewer (ClosedTypeFamilyD x y z w) = Right (x, y, z, w)
reviewer x = Left x
_RoleAnnotD :: Prism' Dec (Name, [Role])
_RoleAnnotD
= prism remitter reviewer
where
remitter (x, y) = RoleAnnotD x y
reviewer (RoleAnnotD x y) = Right (x, y)
reviewer x = Left x
#else
_TySynInstD :: Prism' Dec (Name, [Type], Type)
_TySynInstD
= prism remitter reviewer
where
remitter (x, y, z) = TySynInstD x y z
reviewer (TySynInstD x y z) = Right (x, y, z)
reviewer x = Left x
#endif
_NormalC ::
Prism' Con (Name, [StrictType])
_NormalC
= prism remitter reviewer
where
remitter (x, y) = NormalC x y
reviewer (NormalC x y) = Right (x, y)
reviewer x = Left x
_RecC ::
Prism' Con (Name, [VarStrictType])
_RecC
= prism remitter reviewer
where
remitter (x, y) = RecC x y
reviewer (RecC x y) = Right (x, y)
reviewer x = Left x
_InfixC ::
Prism' Con (StrictType,
Name,
StrictType)
_InfixC
= prism remitter reviewer
where
remitter (x, y, z)
= InfixC x y z
reviewer (InfixC x y z)
= Right (x, y, z)
reviewer x = Left x
_ForallC :: Prism' Con ([TyVarBndr], Cxt, Con)
_ForallC
= prism remitter reviewer
where
remitter (x, y, z)
= ForallC x y z
reviewer (ForallC x y z)
= Right (x, y, z)
reviewer x = Left x
_IsStrict :: Prism' Strict ()
_IsStrict
= prism remitter reviewer
where
remitter () = IsStrict
reviewer IsStrict = Right ()
reviewer x = Left x
_NotStrict :: Prism' Strict ()
_NotStrict
= prism remitter reviewer
where
remitter () = NotStrict
reviewer NotStrict = Right ()
reviewer x = Left x
_Unpacked :: Prism' Strict ()
_Unpacked
= prism remitter reviewer
where
remitter () = Unpacked
reviewer Unpacked = Right ()
reviewer x = Left x
_ImportF :: Prism' Foreign (Callconv, Safety, String, Name, Type)
_ImportF
= prism remitter reviewer
where
remitter (x, y, z, w, u)
= ImportF x y z w u
reviewer (ImportF x y z w u)
= Right (x, y, z, w, u)
reviewer x = Left x
_ExportF :: Prism' Foreign (Callconv, String, Name, Type)
_ExportF
= prism remitter reviewer
where
remitter (x, y, z, w)
= ExportF x y z w
reviewer (ExportF x y z w)
= Right (x, y, z, w)
reviewer x = Left x
_CCall :: Prism' Callconv ()
_CCall
= prism remitter reviewer
where
remitter () = CCall
reviewer CCall = Right ()
reviewer x = Left x
_StdCall :: Prism' Callconv ()
_StdCall
= prism remitter reviewer
where
remitter () = StdCall
reviewer StdCall = Right ()
reviewer x = Left x
_Unsafe :: Prism' Safety ()
_Unsafe
= prism remitter reviewer
where
remitter () = Unsafe
reviewer Unsafe = Right ()
reviewer x = Left x
_Safe :: Prism' Safety ()
_Safe
= prism remitter reviewer
where
remitter () = Safe
reviewer Safe = Right ()
reviewer x = Left x
_Interruptible :: Prism' Safety ()
_Interruptible
= prism remitter reviewer
where
remitter () = Interruptible
reviewer Interruptible = Right ()
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_InlineP :: Prism' Pragma (Name, Inline, RuleMatch, Phases)
_InlineP
= prism remitter reviewer
where
remitter (x, y, z, w)
= InlineP x y z w
reviewer (InlineP x y z w)
= Right (x, y, z, w)
reviewer x = Left x
_SpecialiseP :: Prism' Pragma (Name, Type, Maybe Inline, Phases)
_SpecialiseP
= prism remitter reviewer
where
remitter (x, y, z, w)
= SpecialiseP x y z w
reviewer (SpecialiseP x y z w)
= Right (x, y, z, w)
reviewer x = Left x
#else
_InlineP :: Prism' Pragma (Name, InlineSpec)
_InlineP
= prism remitter reviewer
where
remitter (x, y)
= InlineP x y
reviewer (InlineP x y)
= Right (x, y)
reviewer x = Left x
_SpecialiseP :: Prism' Pragma (Name, Type, Maybe InlineSpec)
_SpecialiseP
= prism remitter reviewer
where
remitter (x, y, z)
= SpecialiseP x y z
reviewer (SpecialiseP x y z)
= Right (x, y, z)
reviewer x = Left x
-- TODO add lenses for InlineSpec
#endif
#if MIN_VERSION_template_haskell(2,8,0)
_SpecialiseInstP :: Prism' Pragma Type
_SpecialiseInstP
= prism remitter reviewer
where
remitter = SpecialiseInstP
reviewer (SpecialiseInstP x) = Right x
reviewer x = Left x
_RuleP :: Prism' Pragma (String, [RuleBndr], Exp, Exp, Phases)
_RuleP
= prism remitter reviewer
where
remitter (x, y, z, w, u)
= RuleP x y z w u
reviewer (RuleP x y z w u)
= Right (x, y, z, w, u)
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,9,0)
_AnnP :: Prism' Pragma (AnnTarget, Exp)
_AnnP
= prism remitter reviewer
where
remitter (x, y) = AnnP x y
reviewer (AnnP x y) = Right (x, y)
reviewer x = Left x
#endif
_NoInline :: Prism' Inline ()
_NoInline
= prism remitter reviewer
where
remitter () = NoInline
reviewer NoInline = Right ()
reviewer x = Left x
_Inline :: Prism' Inline ()
_Inline
= prism remitter reviewer
where
remitter () = Inline
reviewer Inline = Right ()
reviewer x = Left x
_Inlinable :: Prism' Inline ()
_Inlinable
= prism remitter reviewer
where
remitter () = Inlinable
reviewer Inlinable = Right ()
reviewer x = Left x
_ConLike :: Prism' RuleMatch ()
_ConLike
= prism remitter reviewer
where
remitter () = ConLike
reviewer ConLike = Right ()
reviewer x = Left x
_FunLike :: Prism' RuleMatch ()
_FunLike
= prism remitter reviewer
where
remitter () = FunLike
reviewer FunLike = Right ()
reviewer x = Left x
_AllPhases :: Prism' Phases ()
_AllPhases
= prism remitter reviewer
where
remitter () = AllPhases
reviewer AllPhases = Right ()
reviewer x = Left x
_FromPhase :: Prism' Phases Int
_FromPhase
= prism remitter reviewer
where
remitter = FromPhase
reviewer (FromPhase x) = Right x
reviewer x = Left x
_BeforePhase :: Prism' Phases Int
_BeforePhase
= prism remitter reviewer
where
remitter = BeforePhase
reviewer (BeforePhase x) = Right x
reviewer x = Left x
_RuleVar :: Prism' RuleBndr Name
_RuleVar
= prism remitter reviewer
where
remitter = RuleVar
reviewer (RuleVar x) = Right x
reviewer x = Left x
_TypedRuleVar :: Prism' RuleBndr (Name, Type)
_TypedRuleVar
= prism remitter reviewer
where
remitter (x, y) = TypedRuleVar x y
reviewer (TypedRuleVar x y) = Right (x, y)
reviewer x = Left x
#endif
#if MIN_VERSION_template_haskell(2,9,0)
_ModuleAnnotation :: Prism' AnnTarget ()
_ModuleAnnotation
= prism remitter reviewer
where
remitter () = ModuleAnnotation
reviewer ModuleAnnotation
= Right ()
reviewer x = Left x
_TypeAnnotation :: Prism' AnnTarget Name
_TypeAnnotation
= prism remitter reviewer
where
remitter = TypeAnnotation
reviewer (TypeAnnotation x)
= Right x
reviewer x = Left x
_ValueAnnotation :: Prism' AnnTarget Name
_ValueAnnotation
= prism remitter reviewer
where
remitter = ValueAnnotation
reviewer (ValueAnnotation x) = Right x
reviewer x = Left x
#endif
_FunDep :: Prism' FunDep ([Name], [Name])
_FunDep
= prism remitter reviewer
where
remitter (x, y) = FunDep x y
reviewer (FunDep x y) = Right (x, y)
_TypeFam :: Prism' FamFlavour ()
_TypeFam
= prism remitter reviewer
where
remitter () = TypeFam
reviewer TypeFam = Right ()
reviewer x = Left x
_DataFam :: Prism' FamFlavour ()
_DataFam
= prism remitter reviewer
where
remitter () = DataFam
reviewer DataFam = Right ()
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,9,0)
tySynEqnPatterns :: Lens' TySynEqn [Type]
tySynEqnPatterns = lens g s where
g (TySynEqn xs _) = xs
s (TySynEqn _ y) xs = TySynEqn xs y
tySynEqnResult :: Lens' TySynEqn Type
tySynEqnResult = lens g s where
g (TySynEqn _ x) = x
s (TySynEqn xs _) = TySynEqn xs
#endif
_InfixL :: Prism' FixityDirection ()
_InfixL
= prism remitter reviewer
where
remitter () = InfixL
reviewer InfixL = Right ()
reviewer x = Left x
_InfixR :: Prism' FixityDirection ()
_InfixR
= prism remitter reviewer
where
remitter () = InfixR
reviewer InfixR = Right ()
reviewer x = Left x
_InfixN :: Prism' FixityDirection ()
_InfixN
= prism remitter reviewer
where
remitter () = InfixN
reviewer InfixN = Right ()
reviewer x = Left x
_VarE :: Prism' Exp Name
_VarE
= prism remitter reviewer
where
remitter = VarE
reviewer (VarE x) = Right x
reviewer x = Left x
_ConE :: Prism' Exp Name
_ConE
= prism remitter reviewer
where
remitter = ConE
reviewer (ConE x) = Right x
reviewer x = Left x
_LitE :: Prism' Exp Lit
_LitE
= prism remitter reviewer
where
remitter = LitE
reviewer (LitE x) = Right x
reviewer x = Left x
_AppE :: Prism' Exp (Exp, Exp)
_AppE
= prism remitter reviewer
where
remitter (x, y) = AppE x y
reviewer (AppE x y) = Right (x, y)
reviewer x = Left x
_InfixE :: Prism' Exp (Maybe Exp, Exp, Maybe Exp)
_InfixE
= prism remitter reviewer
where
remitter (x, y, z)
= InfixE x y z
reviewer (InfixE x y z)
= Right (x, y, z)
reviewer x = Left x
_UInfixE :: Prism' Exp (Exp, Exp, Exp)
_UInfixE
= prism remitter reviewer
where
remitter (x, y, z)
= UInfixE x y z
reviewer (UInfixE x y z)
= Right (x, y, z)
reviewer x = Left x
_ParensE :: Prism' Exp Exp
_ParensE
= prism remitter reviewer
where
remitter = ParensE
reviewer (ParensE x) = Right x
reviewer x = Left x
_LamE :: Prism' Exp ([Pat], Exp)
_LamE
= prism remitter reviewer
where
remitter (x, y) = LamE x y
reviewer (LamE x y) = Right (x, y)
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_LamCaseE :: Prism' Exp [Match]
_LamCaseE
= prism remitter reviewer
where
remitter = LamCaseE
reviewer (LamCaseE x) = Right x
reviewer x = Left x
#endif
_TupE :: Prism' Exp [Exp]
_TupE
= prism remitter reviewer
where
remitter = TupE
reviewer (TupE x) = Right x
reviewer x = Left x
_UnboxedTupE :: Prism' Exp [Exp]
_UnboxedTupE
= prism remitter reviewer
where
remitter = UnboxedTupE
reviewer (UnboxedTupE x) = Right x
reviewer x = Left x
_CondE :: Prism' Exp (Exp, Exp, Exp)
_CondE
= prism remitter reviewer
where
remitter (x, y, z)
= CondE x y z
reviewer (CondE x y z)
= Right (x, y, z)
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_MultiIfE :: Prism' Exp [(Guard, Exp)]
_MultiIfE
= prism remitter reviewer
where
remitter = MultiIfE
reviewer (MultiIfE x) = Right x
reviewer x = Left x
#endif
_LetE :: Prism' Exp ([Dec], Exp)
_LetE
= prism remitter reviewer
where
remitter (x, y) = LetE x y
reviewer (LetE x y) = Right (x, y)
reviewer x = Left x
_CaseE :: Prism' Exp (Exp, [Match])
_CaseE
= prism remitter reviewer
where
remitter (x, y) = CaseE x y
reviewer (CaseE x y) = Right (x, y)
reviewer x = Left x
_DoE :: Prism' Exp [Stmt]
_DoE
= prism remitter reviewer
where
remitter = DoE
reviewer (DoE x) = Right x
reviewer x = Left x
_CompE :: Prism' Exp [Stmt]
_CompE
= prism remitter reviewer
where
remitter = CompE
reviewer (CompE x) = Right x
reviewer x = Left x
_ArithSeqE :: Prism' Exp Range
_ArithSeqE
= prism remitter reviewer
where
remitter = ArithSeqE
reviewer (ArithSeqE x) = Right x
reviewer x = Left x
_ListE :: Prism' Exp [Exp]
_ListE
= prism remitter reviewer
where
remitter = ListE
reviewer (ListE x) = Right x
reviewer x = Left x
_SigE :: Prism' Exp (Exp, Type)
_SigE
= prism remitter reviewer
where
remitter (x, y) = SigE x y
reviewer (SigE x y) = Right (x, y)
reviewer x = Left x
_RecConE :: Prism' Exp (Name, [FieldExp])
_RecConE
= prism remitter reviewer
where
remitter (x, y) = RecConE x y
reviewer (RecConE x y) = Right (x, y)
reviewer x = Left x
_RecUpdE :: Prism' Exp (Exp, [FieldExp])
_RecUpdE
= prism remitter reviewer
where
remitter (x, y) = RecUpdE x y
reviewer (RecUpdE x y) = Right (x, y)
reviewer x = Left x
_GuardedB :: Prism' Body [(Guard, Exp)]
_GuardedB
= prism remitter reviewer
where
remitter = GuardedB
reviewer (GuardedB x) = Right x
reviewer x = Left x
_NormalB :: Prism' Body Exp
_NormalB
= prism remitter reviewer
where
remitter = NormalB
reviewer (NormalB x) = Right x
reviewer x = Left x
_NormalG :: Prism' Guard Exp
_NormalG
= prism remitter reviewer
where
remitter = NormalG
reviewer (NormalG x) = Right x
reviewer x = Left x
_PatG :: Prism' Guard [Stmt]
_PatG
= prism remitter reviewer
where
remitter = PatG
reviewer (PatG x) = Right x
reviewer x = Left x
_BindS :: Prism' Stmt (Pat, Exp)
_BindS
= prism remitter reviewer
where
remitter (x, y) = BindS x y
reviewer (BindS x y) = Right (x, y)
reviewer x = Left x
_LetS :: Prism' Stmt [Dec]
_LetS
= prism remitter reviewer
where
remitter = LetS
reviewer (LetS x) = Right x
reviewer x = Left x
_NoBindS :: Prism' Stmt Exp
_NoBindS
= prism remitter reviewer
where
remitter = NoBindS
reviewer (NoBindS x) = Right x
reviewer x = Left x
_ParS :: Prism' Stmt [[Stmt]]
_ParS
= prism remitter reviewer
where
remitter = ParS
reviewer (ParS x) = Right x
reviewer x = Left x
_FromR :: Prism' Range Exp
_FromR
= prism remitter reviewer
where
remitter = FromR
reviewer (FromR x) = Right x
reviewer x = Left x
_FromThenR :: Prism' Range (Exp, Exp)
_FromThenR
= prism remitter reviewer
where
remitter (x, y) = FromThenR x y
reviewer (FromThenR x y)
= Right (x, y)
reviewer x = Left x
_FromToR :: Prism' Range (Exp, Exp)
_FromToR
= prism remitter reviewer
where
remitter (x, y) = FromToR x y
reviewer (FromToR x y) = Right (x, y)
reviewer x = Left x
_FromThenToR :: Prism' Range (Exp, Exp, Exp)
_FromThenToR
= prism remitter reviewer
where
remitter (x, y, z)
= FromThenToR x y z
reviewer (FromThenToR x y z)
= Right (x, y, z)
reviewer x = Left x
_CharL :: Prism' Lit Char
_CharL
= prism remitter reviewer
where
remitter = CharL
reviewer (CharL x) = Right x
reviewer x = Left x
_StringL :: Prism' Lit String
_StringL
= prism remitter reviewer
where
remitter = StringL
reviewer (StringL x) = Right x
reviewer x = Left x
_IntegerL :: Prism' Lit Integer
_IntegerL
= prism remitter reviewer
where
remitter = IntegerL
reviewer (IntegerL x) = Right x
reviewer x = Left x
_RationalL :: Prism' Lit Rational
_RationalL
= prism remitter reviewer
where
remitter = RationalL
reviewer (RationalL x) = Right x
reviewer x = Left x
_IntPrimL :: Prism' Lit Integer
_IntPrimL
= prism remitter reviewer
where
remitter = IntPrimL
reviewer (IntPrimL x) = Right x
reviewer x = Left x
_WordPrimL :: Prism' Lit Integer
_WordPrimL
= prism remitter reviewer
where
remitter = WordPrimL
reviewer (WordPrimL x) = Right x
reviewer x = Left x
_FloatPrimL :: Prism' Lit Rational
_FloatPrimL
= prism remitter reviewer
where
remitter = FloatPrimL
reviewer (FloatPrimL x) = Right x
reviewer x = Left x
_DoublePrimL :: Prism' Lit Rational
_DoublePrimL
= prism remitter reviewer
where
remitter = DoublePrimL
reviewer (DoublePrimL x) = Right x
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_StringPrimL :: Prism' Lit [Word8]
_StringPrimL
= prism remitter reviewer
where
remitter = StringPrimL
reviewer (StringPrimL x) = Right x
reviewer x = Left x
#else
_StringPrimL :: Prism' Lit String
_StringPrimL
= prism remitter reviewer
where
remitter = StringPrimL
reviewer (StringPrimL x) = Right x
reviewer x = Left x
#endif
_LitP :: Prism' Pat Lit
_LitP
= prism remitter reviewer
where
remitter = LitP
reviewer (LitP x) = Right x
reviewer x = Left x
_VarP :: Prism' Pat Name
_VarP
= prism remitter reviewer
where
remitter = VarP
reviewer (VarP x) = Right x
reviewer x = Left x
_TupP :: Prism' Pat [Pat]
_TupP
= prism remitter reviewer
where
remitter = TupP
reviewer (TupP x) = Right x
reviewer x = Left x
_UnboxedTupP :: Prism' Pat [Pat]
_UnboxedTupP
= prism remitter reviewer
where
remitter = UnboxedTupP
reviewer (UnboxedTupP x) = Right x
reviewer x = Left x
_ConP :: Prism' Pat (Name, [Pat])
_ConP
= prism remitter reviewer
where
remitter (x, y) = ConP x y
reviewer (ConP x y) = Right (x, y)
reviewer x = Left x
_InfixP :: Prism' Pat (Pat, Name, Pat)
_InfixP
= prism remitter reviewer
where
remitter (x, y, z)
= InfixP x y z
reviewer (InfixP x y z)
= Right (x, y, z)
reviewer x = Left x
_UInfixP :: Prism' Pat (Pat, Name, Pat)
_UInfixP
= prism remitter reviewer
where
remitter (x, y, z)
= UInfixP x y z
reviewer (UInfixP x y z)
= Right (x, y, z)
reviewer x = Left x
_ParensP :: Prism' Pat Pat
_ParensP
= prism remitter reviewer
where
remitter = ParensP
reviewer (ParensP x) = Right x
reviewer x = Left x
_TildeP :: Prism' Pat Pat
_TildeP
= prism remitter reviewer
where
remitter = TildeP
reviewer (TildeP x) = Right x
reviewer x = Left x
_BangP :: Prism' Pat Pat
_BangP
= prism remitter reviewer
where
remitter = BangP
reviewer (BangP x) = Right x
reviewer x = Left x
_AsP :: Prism' Pat (Name, Pat)
_AsP
= prism remitter reviewer
where
remitter (x, y) = AsP x y
reviewer (AsP x y) = Right (x, y)
reviewer x = Left x
_WildP :: Prism' Pat ()
_WildP
= prism remitter reviewer
where
remitter () = WildP
reviewer WildP = Right ()
reviewer x = Left x
_RecP :: Prism' Pat (Name, [FieldPat])
_RecP
= prism remitter reviewer
where
remitter (x, y) = RecP x y
reviewer (RecP x y) = Right (x, y)
reviewer x = Left x
_ListP :: Prism' Pat [Pat]
_ListP
= prism remitter reviewer
where
remitter = ListP
reviewer (ListP x) = Right x
reviewer x = Left x
_SigP :: Prism' Pat (Pat, Type)
_SigP
= prism remitter reviewer
where
remitter (x, y) = SigP x y
reviewer (SigP x y) = Right (x, y)
reviewer x = Left x
_ViewP :: Prism' Pat (Exp, Pat)
_ViewP
= prism remitter reviewer
where
remitter (x, y) = ViewP x y
reviewer (ViewP x y) = Right (x, y)
reviewer x = Left x
_ForallT :: Prism' Type ([TyVarBndr], Cxt, Type)
_ForallT
= prism remitter reviewer
where
remitter (x, y, z)
= ForallT x y z
reviewer (ForallT x y z)
= Right (x, y, z)
reviewer x = Left x
_AppT :: Prism' Type (Type, Type)
_AppT
= prism remitter reviewer
where
remitter (x, y) = AppT x y
reviewer (AppT x y) = Right (x, y)
reviewer x = Left x
_SigT :: Prism' Type (Type, Kind)
_SigT
= prism remitter reviewer
where
remitter (x, y) = SigT x y
reviewer (SigT x y) = Right (x, y)
reviewer x = Left x
_VarT :: Prism' Type Name
_VarT
= prism remitter reviewer
where
remitter = VarT
reviewer (VarT x) = Right x
reviewer x = Left x
_ConT :: Prism' Type Name
_ConT
= prism remitter reviewer
where
remitter = ConT
reviewer (ConT x) = Right x
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_PromotedT :: Prism' Type Name
_PromotedT
= prism remitter reviewer
where
remitter = PromotedT
reviewer (PromotedT x) = Right x
reviewer x = Left x
#endif
_TupleT :: Prism' Type Int
_TupleT
= prism remitter reviewer
where
remitter = TupleT
reviewer (TupleT x) = Right x
reviewer x = Left x
_UnboxedTupleT :: Prism' Type Int
_UnboxedTupleT
= prism remitter reviewer
where
remitter = UnboxedTupleT
reviewer (UnboxedTupleT x) = Right x
reviewer x = Left x
_ArrowT :: Prism' Type ()
_ArrowT
= prism remitter reviewer
where
remitter () = ArrowT
reviewer ArrowT = Right ()
reviewer x = Left x
_ListT :: Prism' Type ()
_ListT
= prism remitter reviewer
where
remitter () = ListT
reviewer ListT = Right ()
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_PromotedTupleT :: Prism' Type Int
_PromotedTupleT
= prism remitter reviewer
where
remitter = PromotedTupleT
reviewer (PromotedTupleT x) = Right x
reviewer x = Left x
_PromotedNilT :: Prism' Type ()
_PromotedNilT
= prism remitter reviewer
where
remitter () = PromotedNilT
reviewer PromotedNilT = Right ()
reviewer x = Left x
_PromotedConsT :: Prism' Type ()
_PromotedConsT
= prism remitter reviewer
where
remitter () = PromotedConsT
reviewer PromotedConsT = Right ()
reviewer x = Left x
_StarT :: Prism' Type ()
_StarT
= prism remitter reviewer
where
remitter () = StarT
reviewer StarT = Right ()
reviewer x = Left x
_ConstraintT :: Prism' Type ()
_ConstraintT
= prism remitter reviewer
where
remitter () = ConstraintT
reviewer ConstraintT = Right ()
reviewer x = Left x
_LitT :: Prism' Type TyLit
_LitT
= prism remitter reviewer
where
remitter = LitT
reviewer (LitT x) = Right x
reviewer x = Left x
#endif
_PlainTV :: Prism' TyVarBndr Name
_PlainTV
= prism remitter reviewer
where
remitter = PlainTV
reviewer (PlainTV x) = Right x
reviewer x = Left x
_KindedTV :: Prism' TyVarBndr (Name, Kind)
_KindedTV
= prism remitter reviewer
where
remitter (x, y) = KindedTV x y
reviewer (KindedTV x y) = Right (x, y)
reviewer x = Left x
#if MIN_VERSION_template_haskell(2,8,0)
_NumTyLit :: Prism' TyLit Integer
_NumTyLit
= prism remitter reviewer
where
remitter = NumTyLit
reviewer (NumTyLit x) = Right x
reviewer x = Left x
_StrTyLit :: Prism' TyLit String
_StrTyLit
= prism remitter reviewer
where
remitter = StrTyLit
reviewer (StrTyLit x) = Right x
reviewer x = Left x
#endif
#if !MIN_VERSION_template_haskell(2,10,0)
_ClassP :: Prism' Pred (Name, [Type])
_ClassP
= prism remitter reviewer
where
remitter (x, y) = ClassP x y
reviewer (ClassP x y) = Right (x, y)
reviewer x = Left x
_EqualP :: Prism' Pred (Type, Type)
_EqualP
= prism remitter reviewer
where
remitter (x, y) = EqualP x y
reviewer (EqualP x y) = Right (x, y)
reviewer x = Left x
#endif
#if MIN_VERSION_template_haskell(2,9,0)
_NominalR :: Prism' Role ()
_NominalR
= prism remitter reviewer
where
remitter () = NominalR
reviewer NominalR = Right ()
reviewer x = Left x
_RepresentationalR :: Prism' Role ()
_RepresentationalR
= prism remitter reviewer
where
remitter () = RepresentationalR
reviewer RepresentationalR = Right ()
reviewer x = Left x
_PhantomR :: Prism' Role ()
_PhantomR
= prism remitter reviewer
where
remitter () = PhantomR
reviewer PhantomR = Right ()
reviewer x = Left x
_InferR :: Prism' Role ()
_InferR
= prism remitter reviewer
where
remitter () = InferR
reviewer InferR = Right ()
reviewer x = Left x
#endif
|
rpglover64/lens
|
src/Language/Haskell/TH/Lens.hs
|
bsd-3-clause
| 42,470 | 0 | 12 | 11,693 | 14,492 | 7,552 | 6,940 | 1,253 | 2 |
{-# LANGUAGE BangPatterns #-}
-----------------------------------------------------------------------------
-- | Separate module for HTTP actions, using a proxy server if one exists.
-----------------------------------------------------------------------------
module Distribution.Client.HttpUtils (
DownloadResult(..),
configureTransport,
HttpTransport(..),
HttpCode,
downloadURI,
transportCheckHttps,
remoteRepoCheckHttps,
remoteRepoTryUpgradeToHttps,
isOldHackageURI
) where
import Prelude ()
import Distribution.Client.Compat.Prelude
import Network.HTTP
( Request (..), Response (..), RequestMethod (..)
, Header(..), HeaderName(..), lookupHeader )
import Network.HTTP.Proxy ( Proxy(..), fetchProxy)
import Network.URI
( URI (..), URIAuth (..), uriToString )
import Network.Browser
( browse, setOutHandler, setErrHandler, setProxy
, setAuthorityGen, request, setAllowBasicAuth, setUserAgent )
import qualified Control.Exception as Exception
import Control.Exception
( evaluate )
import Control.DeepSeq
( force )
import Control.Monad
( guard )
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Paths_cabal_install (version)
import Distribution.Verbosity (Verbosity)
import Distribution.Simple.Utils
( die', info, warn, debug, notice, writeFileAtomic
, copyFileVerbose, withTempFile )
import Distribution.Client.Utils
( withTempFileName )
import Distribution.Client.Types
( RemoteRepo(..) )
import Distribution.System
( buildOS, buildArch )
import Distribution.Text
( display )
import qualified System.FilePath.Posix as FilePath.Posix
( splitDirectories )
import System.FilePath
( (<.>), takeFileName, takeDirectory )
import System.Directory
( doesFileExist, renameFile, canonicalizePath )
import System.IO
( withFile, IOMode(ReadMode), hGetContents, hClose )
import System.IO.Error
( isDoesNotExistError )
import Distribution.Simple.Program
( Program, simpleProgram, ConfiguredProgram, programPath
, ProgramInvocation(..), programInvocation
, getProgramInvocationOutput )
import Distribution.Simple.Program.Db
( ProgramDb, emptyProgramDb, addKnownPrograms
, configureAllKnownPrograms
, requireProgram, lookupProgram )
import Distribution.Simple.Program.Run
( getProgramInvocationOutputAndErrors )
import Numeric (showHex)
import System.Random (randomRIO)
import System.Exit (ExitCode(..))
------------------------------------------------------------------------------
-- Downloading a URI, given an HttpTransport
--
data DownloadResult = FileAlreadyInCache
| FileDownloaded FilePath
deriving (Eq)
downloadURI :: HttpTransport
-> Verbosity
-> URI -- ^ What to download
-> FilePath -- ^ Where to put it
-> IO DownloadResult
downloadURI _transport verbosity uri path | uriScheme uri == "file:" = do
copyFileVerbose verbosity (uriPath uri) path
return (FileDownloaded path)
-- Can we store the hash of the file so we can safely return path when the
-- hash matches to avoid unnecessary computation?
downloadURI transport verbosity uri path = do
let etagPath = path <.> "etag"
targetExists <- doesFileExist path
etagPathExists <- doesFileExist etagPath
-- In rare cases the target file doesn't exist, but the etag does.
etag <- if targetExists && etagPathExists
then Just <$> readFile etagPath
else return Nothing
-- Only use the external http transports if we actually have to
-- (or have been told to do so)
let transport'
| uriScheme uri == "http:"
, not (transportManuallySelected transport)
= plainHttpTransport
| otherwise
= transport
withTempFileName (takeDirectory path) (takeFileName path) $ \tmpFile -> do
result <- getHttp transport' verbosity uri etag tmpFile []
-- Only write the etag if we get a 200 response code.
-- A 304 still sends us an etag header.
case result of
(200, Just newEtag) -> writeFile etagPath newEtag
_ -> return ()
case fst result of
200 -> do
info verbosity ("Downloaded to " ++ path)
renameFile tmpFile path
return (FileDownloaded path)
304 -> do
notice verbosity "Skipping download: local and remote files match."
return FileAlreadyInCache
errCode -> die' verbosity $ "Failed to download " ++ show uri
++ " : HTTP code " ++ show errCode
------------------------------------------------------------------------------
-- Utilities for repo url management
--
remoteRepoCheckHttps :: Verbosity -> HttpTransport -> RemoteRepo -> IO ()
remoteRepoCheckHttps verbosity transport repo
| uriScheme (remoteRepoURI repo) == "https:"
, not (transportSupportsHttps transport)
= die' verbosity $ "The remote repository '" ++ remoteRepoName repo
++ "' specifies a URL that " ++ requiresHttpsErrorMessage
| otherwise = return ()
transportCheckHttps :: Verbosity -> HttpTransport -> URI -> IO ()
transportCheckHttps verbosity transport uri
| uriScheme uri == "https:"
, not (transportSupportsHttps transport)
= die' verbosity $ "The URL " ++ show uri
++ " " ++ requiresHttpsErrorMessage
| otherwise = return ()
requiresHttpsErrorMessage :: String
requiresHttpsErrorMessage =
"requires HTTPS however the built-in HTTP implementation "
++ "does not support HTTPS. The transport implementations with HTTPS "
++ "support are " ++ intercalate ", "
[ name | (name, _, True, _ ) <- supportedTransports ]
++ ". One of these will be selected automatically if the corresponding "
++ "external program is available, or one can be selected specifically "
++ "with the global flag --http-transport="
remoteRepoTryUpgradeToHttps :: Verbosity -> HttpTransport -> RemoteRepo -> IO RemoteRepo
remoteRepoTryUpgradeToHttps verbosity transport repo
| remoteRepoShouldTryHttps repo
, uriScheme (remoteRepoURI repo) == "http:"
, not (transportSupportsHttps transport)
, not (transportManuallySelected transport)
= die' verbosity $ "The builtin HTTP implementation does not support HTTPS, but using "
++ "HTTPS for authenticated uploads is recommended. "
++ "The transport implementations with HTTPS support are "
++ intercalate ", " [ name | (name, _, True, _ ) <- supportedTransports ]
++ "but they require the corresponding external program to be "
++ "available. You can either make one available or use plain HTTP by "
++ "using the global flag --http-transport=plain-http (or putting the "
++ "equivalent in the config file). With plain HTTP, your password "
++ "is sent using HTTP digest authentication so it cannot be easily "
++ "intercepted, but it is not as secure as using HTTPS."
| remoteRepoShouldTryHttps repo
, uriScheme (remoteRepoURI repo) == "http:"
, transportSupportsHttps transport
= return repo {
remoteRepoURI = (remoteRepoURI repo) { uriScheme = "https:" }
}
| otherwise
= return repo
-- | Utility function for legacy support.
isOldHackageURI :: URI -> Bool
isOldHackageURI uri
= case uriAuthority uri of
Just (URIAuth {uriRegName = "hackage.haskell.org"}) ->
FilePath.Posix.splitDirectories (uriPath uri)
== ["/","packages","archive"]
_ -> False
------------------------------------------------------------------------------
-- Setting up a HttpTransport
--
data HttpTransport = HttpTransport {
-- | GET a URI, with an optional ETag (to do a conditional fetch),
-- write the resource to the given file and return the HTTP status code,
-- and optional ETag.
getHttp :: Verbosity -> URI -> Maybe ETag -> FilePath -> [Header]
-> IO (HttpCode, Maybe ETag),
-- | POST a resource to a URI, with optional auth (username, password)
-- and return the HTTP status code and any redirect URL.
postHttp :: Verbosity -> URI -> String -> Maybe Auth
-> IO (HttpCode, String),
-- | POST a file resource to a URI using multipart\/form-data encoding,
-- with optional auth (username, password) and return the HTTP status
-- code and any error string.
postHttpFile :: Verbosity -> URI -> FilePath -> Maybe Auth
-> IO (HttpCode, String),
-- | PUT a file resource to a URI, with optional auth
-- (username, password), extra headers and return the HTTP status code
-- and any error string.
putHttpFile :: Verbosity -> URI -> FilePath -> Maybe Auth -> [Header]
-> IO (HttpCode, String),
-- | Whether this transport supports https or just http.
transportSupportsHttps :: Bool,
-- | Whether this transport implementation was specifically chosen by
-- the user via configuration, or whether it was automatically selected.
-- Strictly speaking this is not a property of the transport itself but
-- about how it was chosen. Nevertheless it's convenient to keep here.
transportManuallySelected :: Bool
}
--TODO: why does postHttp return a redirect, but postHttpFile return errors?
type HttpCode = Int
type ETag = String
type Auth = (String, String)
noPostYet :: Verbosity -> URI -> String -> Maybe (String, String)
-> IO (Int, String)
noPostYet verbosity _ _ _ = die' verbosity "Posting (for report upload) is not implemented yet"
supportedTransports :: [(String, Maybe Program, Bool,
ProgramDb -> Maybe HttpTransport)]
supportedTransports =
[ let prog = simpleProgram "curl" in
( "curl", Just prog, True
, \db -> curlTransport <$> lookupProgram prog db )
, let prog = simpleProgram "wget" in
( "wget", Just prog, True
, \db -> wgetTransport <$> lookupProgram prog db )
, let prog = simpleProgram "powershell" in
( "powershell", Just prog, True
, \db -> powershellTransport <$> lookupProgram prog db )
, ( "plain-http", Nothing, False
, \_ -> Just plainHttpTransport )
]
configureTransport :: Verbosity -> Maybe String -> IO HttpTransport
configureTransport verbosity (Just name) =
-- the user secifically selected a transport by name so we'll try and
-- configure that one
case find (\(name',_,_,_) -> name' == name) supportedTransports of
Just (_, mprog, _tls, mkTrans) -> do
progdb <- case mprog of
Nothing -> return emptyProgramDb
Just prog -> snd <$> requireProgram verbosity prog emptyProgramDb
-- ^^ if it fails, it'll fail here
let Just transport = mkTrans progdb
return transport { transportManuallySelected = True }
Nothing -> die' verbosity $ "Unknown HTTP transport specified: " ++ name
++ ". The supported transports are "
++ intercalate ", "
[ name' | (name', _, _, _ ) <- supportedTransports ]
configureTransport verbosity Nothing = do
-- the user hasn't selected a transport, so we'll pick the first one we
-- can configure successfully, provided that it supports tls
-- for all the transports except plain-http we need to try and find
-- their external executable
progdb <- configureAllKnownPrograms verbosity $
addKnownPrograms
[ prog | (_, Just prog, _, _) <- supportedTransports ]
emptyProgramDb
let availableTransports =
[ (name, transport)
| (name, _, _, mkTrans) <- supportedTransports
, transport <- maybeToList (mkTrans progdb) ]
-- there's always one because the plain one is last and never fails
let (name, transport) = head availableTransports
debug verbosity $ "Selected http transport implementation: " ++ name
return transport { transportManuallySelected = False }
------------------------------------------------------------------------------
-- The HttpTransports based on external programs
--
curlTransport :: ConfiguredProgram -> HttpTransport
curlTransport prog =
HttpTransport gethttp posthttp posthttpfile puthttpfile True False
where
gethttp verbosity uri etag destPath reqHeaders = do
withTempFile (takeDirectory destPath)
"curl-headers.txt" $ \tmpFile tmpHandle -> do
hClose tmpHandle
let args = [ show uri
, "--output", destPath
, "--location"
, "--write-out", "%{http_code}"
, "--user-agent", userAgent
, "--silent", "--show-error"
, "--dump-header", tmpFile ]
++ concat
[ ["--header", "If-None-Match: " ++ t]
| t <- maybeToList etag ]
++ concat
[ ["--header", show name ++ ": " ++ value]
| Header name value <- reqHeaders ]
resp <- getProgramInvocationOutput verbosity
(programInvocation prog args)
withFile tmpFile ReadMode $ \hnd -> do
headers <- hGetContents hnd
(code, _err, etag') <- parseResponse verbosity uri resp headers
evaluate $ force (code, etag')
posthttp = noPostYet
addAuthConfig auth progInvocation = progInvocation
{ progInvokeInput = do
(uname, passwd) <- auth
return $ unlines
[ "--digest"
, "--user " ++ uname ++ ":" ++ passwd
]
, progInvokeArgs = ["--config", "-"] ++ progInvokeArgs progInvocation
}
posthttpfile verbosity uri path auth = do
let args = [ show uri
, "--form", "package=@"++path
, "--write-out", "\n%{http_code}"
, "--user-agent", userAgent
, "--silent", "--show-error"
, "--header", "Accept: text/plain"
, "--location"
]
resp <- getProgramInvocationOutput verbosity $ addAuthConfig auth
(programInvocation prog args)
(code, err, _etag) <- parseResponse verbosity uri resp ""
return (code, err)
puthttpfile verbosity uri path auth headers = do
let args = [ show uri
, "--request", "PUT", "--data-binary", "@"++path
, "--write-out", "\n%{http_code}"
, "--user-agent", userAgent
, "--silent", "--show-error"
, "--location"
, "--header", "Accept: text/plain"
]
++ concat
[ ["--header", show name ++ ": " ++ value]
| Header name value <- headers ]
resp <- getProgramInvocationOutput verbosity $ addAuthConfig auth
(programInvocation prog args)
(code, err, _etag) <- parseResponse verbosity uri resp ""
return (code, err)
-- on success these curl invocations produces an output like "200"
-- and on failure it has the server error response first
parseResponse :: Verbosity -> URI -> String -> String -> IO (Int, String, Maybe ETag)
parseResponse verbosity uri resp headers =
let codeerr =
case reverse (lines resp) of
(codeLine:rerrLines) ->
case readMaybe (trim codeLine) of
Just i -> let errstr = mkErrstr rerrLines
in Just (i, errstr)
Nothing -> Nothing
[] -> Nothing
mkErrstr = unlines . reverse . dropWhile (all isSpace)
mb_etag :: Maybe ETag
mb_etag = listToMaybe $ reverse
[ etag
| ["ETag:", etag] <- map words (lines headers) ]
in case codeerr of
Just (i, err) -> return (i, err, mb_etag)
_ -> statusParseFail verbosity uri resp
wgetTransport :: ConfiguredProgram -> HttpTransport
wgetTransport prog =
HttpTransport gethttp posthttp posthttpfile puthttpfile True False
where
gethttp verbosity uri etag destPath reqHeaders = do
resp <- runWGet verbosity uri args
-- wget doesn't support range requests.
-- so, we not only ignore range request headers,
-- but we also dispay a warning message when we see them.
let hasRangeHeader = any isRangeHeader reqHeaders
warningMsg = "the 'wget' transport currently doesn't support"
++ " range requests, which wastes network bandwidth."
++ " To fix this, set 'http-transport' to 'curl' or"
++ " 'plain-http' in '~/.cabal/config'."
++ " Note that the 'plain-http' transport doesn't"
++ " support HTTPS.\n"
when (hasRangeHeader) $ warn verbosity warningMsg
(code, etag') <- parseOutput verbosity uri resp
return (code, etag')
where
args = [ "--output-document=" ++ destPath
, "--user-agent=" ++ userAgent
, "--tries=5"
, "--timeout=15"
, "--server-response" ]
++ concat
[ ["--header", "If-None-Match: " ++ t]
| t <- maybeToList etag ]
++ [ "--header=" ++ show name ++ ": " ++ value
| hdr@(Header name value) <- reqHeaders
, (not (isRangeHeader hdr)) ]
-- wget doesn't support range requests.
-- so, we ignore range request headers, lest we get errors.
isRangeHeader :: Header -> Bool
isRangeHeader (Header HdrRange _) = True
isRangeHeader _ = False
posthttp = noPostYet
posthttpfile verbosity uri path auth =
withTempFile (takeDirectory path)
(takeFileName path) $ \tmpFile tmpHandle ->
withTempFile (takeDirectory path) "response" $
\responseFile responseHandle -> do
hClose responseHandle
(body, boundary) <- generateMultipartBody path
BS.hPut tmpHandle body
hClose tmpHandle
let args = [ "--post-file=" ++ tmpFile
, "--user-agent=" ++ userAgent
, "--server-response"
, "--output-document=" ++ responseFile
, "--header=Accept: text/plain"
, "--header=Content-type: multipart/form-data; " ++
"boundary=" ++ boundary ]
out <- runWGet verbosity (addUriAuth auth uri) args
(code, _etag) <- parseOutput verbosity uri out
withFile responseFile ReadMode $ \hnd -> do
resp <- hGetContents hnd
evaluate $ force (code, resp)
puthttpfile verbosity uri path auth headers =
withTempFile (takeDirectory path) "response" $
\responseFile responseHandle -> do
hClose responseHandle
let args = [ "--method=PUT", "--body-file="++path
, "--user-agent=" ++ userAgent
, "--server-response"
, "--output-document=" ++ responseFile
, "--header=Accept: text/plain" ]
++ [ "--header=" ++ show name ++ ": " ++ value
| Header name value <- headers ]
out <- runWGet verbosity (addUriAuth auth uri) args
(code, _etag) <- parseOutput verbosity uri out
withFile responseFile ReadMode $ \hnd -> do
resp <- hGetContents hnd
evaluate $ force (code, resp)
addUriAuth Nothing uri = uri
addUriAuth (Just (user, pass)) uri = uri
{ uriAuthority = Just a { uriUserInfo = user ++ ":" ++ pass ++ "@" }
}
where
a = fromMaybe (URIAuth "" "" "") (uriAuthority uri)
runWGet verbosity uri args = do
-- We pass the URI via STDIN because it contains the users' credentials
-- and sensitive data should not be passed via command line arguments.
let
invocation = (programInvocation prog ("--input-file=-" : args))
{ progInvokeInput = Just (uriToString id uri "")
}
-- wget returns its output on stderr rather than stdout
(_, resp, exitCode) <- getProgramInvocationOutputAndErrors verbosity
invocation
-- wget returns exit code 8 for server "errors" like "304 not modified"
if exitCode == ExitSuccess || exitCode == ExitFailure 8
then return resp
else die' verbosity $ "'" ++ programPath prog
++ "' exited with an error:\n" ++ resp
-- With the --server-response flag, wget produces output with the full
-- http server response with all headers, we want to find a line like
-- "HTTP/1.1 200 OK", but only the last one, since we can have multiple
-- requests due to redirects.
parseOutput verbosity uri resp =
let parsedCode = listToMaybe
[ code
| (protocol:codestr:_err) <- map words (reverse (lines resp))
, "HTTP/" `isPrefixOf` protocol
, code <- maybeToList (readMaybe codestr) ]
mb_etag :: Maybe ETag
mb_etag = listToMaybe
[ etag
| ["ETag:", etag] <- map words (reverse (lines resp)) ]
in case parsedCode of
Just i -> return (i, mb_etag)
_ -> statusParseFail verbosity uri resp
powershellTransport :: ConfiguredProgram -> HttpTransport
powershellTransport prog =
HttpTransport gethttp posthttp posthttpfile puthttpfile True False
where
gethttp verbosity uri etag destPath reqHeaders = do
resp <- runPowershellScript verbosity $
webclientScript
(setupHeaders ((useragentHeader : etagHeader) ++ reqHeaders))
[ "$wc.DownloadFile(" ++ escape (show uri)
++ "," ++ escape destPath ++ ");"
, "Write-Host \"200\";"
, "Write-Host $wc.ResponseHeaders.Item(\"ETag\");"
]
parseResponse resp
where
parseResponse x = case readMaybe . unlines . take 1 . lines $ trim x of
Just i -> return (i, Nothing) -- TODO extract real etag
Nothing -> statusParseFail verbosity uri x
etagHeader = [ Header HdrIfNoneMatch t | t <- maybeToList etag ]
posthttp = noPostYet
posthttpfile verbosity uri path auth =
withTempFile (takeDirectory path)
(takeFileName path) $ \tmpFile tmpHandle -> do
(body, boundary) <- generateMultipartBody path
BS.hPut tmpHandle body
hClose tmpHandle
fullPath <- canonicalizePath tmpFile
let contentHeader = Header HdrContentType
("multipart/form-data; boundary=" ++ boundary)
resp <- runPowershellScript verbosity $ webclientScript
(setupHeaders (contentHeader : extraHeaders) ++ setupAuth auth)
(uploadFileAction "POST" uri fullPath)
parseUploadResponse verbosity uri resp
puthttpfile verbosity uri path auth headers = do
fullPath <- canonicalizePath path
resp <- runPowershellScript verbosity $ webclientScript
(setupHeaders (extraHeaders ++ headers) ++ setupAuth auth)
(uploadFileAction "PUT" uri fullPath)
parseUploadResponse verbosity uri resp
runPowershellScript verbosity script = do
let args =
[ "-InputFormat", "None"
-- the default execution policy doesn't allow running
-- unsigned scripts, so we need to tell powershell to bypass it
, "-ExecutionPolicy", "bypass"
, "-NoProfile", "-NonInteractive"
, "-Command", "-"
]
getProgramInvocationOutput verbosity (programInvocation prog args)
{ progInvokeInput = Just (script ++ "\nExit(0);")
}
escape = show
useragentHeader = Header HdrUserAgent userAgent
extraHeaders = [Header HdrAccept "text/plain", useragentHeader]
setupHeaders headers =
[ "$wc.Headers.Add(" ++ escape (show name) ++ "," ++ escape value ++ ");"
| Header name value <- headers
]
setupAuth auth =
[ "$wc.Credentials = new-object System.Net.NetworkCredential("
++ escape uname ++ "," ++ escape passwd ++ ",\"\");"
| (uname,passwd) <- maybeToList auth
]
uploadFileAction method uri fullPath =
[ "$fileBytes = [System.IO.File]::ReadAllBytes(" ++ escape fullPath ++ ");"
, "$bodyBytes = $wc.UploadData(" ++ escape (show uri) ++ ","
++ show method ++ ", $fileBytes);"
, "Write-Host \"200\";"
, "Write-Host (-join [System.Text.Encoding]::UTF8.GetChars($bodyBytes));"
]
parseUploadResponse verbosity uri resp = case lines (trim resp) of
(codeStr : message)
| Just code <- readMaybe codeStr -> return (code, unlines message)
_ -> statusParseFail verbosity uri resp
webclientScript setup action = unlines
[ "$wc = new-object system.net.webclient;"
, unlines setup
, "Try {"
, unlines (map (" " ++) action)
, "} Catch [System.Net.WebException] {"
, " $exception = $_.Exception;"
, " If ($exception.Status -eq "
++ "[System.Net.WebExceptionStatus]::ProtocolError) {"
, " $response = $exception.Response -as [System.Net.HttpWebResponse];"
, " $reader = new-object "
++ "System.IO.StreamReader($response.GetResponseStream());"
, " Write-Host ($response.StatusCode -as [int]);"
, " Write-Host $reader.ReadToEnd();"
, " } Else {"
, " Write-Host $exception.Message;"
, " }"
, "} Catch {"
, " Write-Host $_.Exception.Message;"
, "}"
]
------------------------------------------------------------------------------
-- The builtin plain HttpTransport
--
plainHttpTransport :: HttpTransport
plainHttpTransport =
HttpTransport gethttp posthttp posthttpfile puthttpfile False False
where
gethttp verbosity uri etag destPath reqHeaders = do
let req = Request{
rqURI = uri,
rqMethod = GET,
rqHeaders = [ Header HdrIfNoneMatch t
| t <- maybeToList etag ]
++ reqHeaders,
rqBody = BS.empty
}
(_, resp) <- cabalBrowse verbosity Nothing (request req)
let code = convertRspCode (rspCode resp)
etag' = lookupHeader HdrETag (rspHeaders resp)
-- 206 Partial Content is a normal response to a range request; see #3385.
when (code==200 || code==206) $
writeFileAtomic destPath $ rspBody resp
return (code, etag')
posthttp = noPostYet
posthttpfile verbosity uri path auth = do
(body, boundary) <- generateMultipartBody path
let headers = [ Header HdrContentType
("multipart/form-data; boundary="++boundary)
, Header HdrContentLength (show (BS.length body))
, Header HdrAccept ("text/plain")
]
req = Request {
rqURI = uri,
rqMethod = POST,
rqHeaders = headers,
rqBody = body
}
(_, resp) <- cabalBrowse verbosity auth (request req)
return (convertRspCode (rspCode resp), rspErrorString resp)
puthttpfile verbosity uri path auth headers = do
body <- BS.readFile path
let req = Request {
rqURI = uri,
rqMethod = PUT,
rqHeaders = Header HdrContentLength (show (BS.length body))
: Header HdrAccept "text/plain"
: headers,
rqBody = body
}
(_, resp) <- cabalBrowse verbosity auth (request req)
return (convertRspCode (rspCode resp), rspErrorString resp)
convertRspCode (a,b,c) = a*100 + b*10 + c
rspErrorString resp =
case lookupHeader HdrContentType (rspHeaders resp) of
Just contenttype
| takeWhile (/= ';') contenttype == "text/plain"
-> BS.unpack (rspBody resp)
_ -> rspReason resp
cabalBrowse verbosity auth act = do
p <- fixupEmptyProxy <$> fetchProxy True
Exception.handleJust
(guard . isDoesNotExistError)
(const . die' verbosity $ "Couldn't establish HTTP connection. "
++ "Possible cause: HTTP proxy server is down.") $
browse $ do
setProxy p
setErrHandler (warn verbosity . ("http error: "++))
setOutHandler (debug verbosity)
setUserAgent userAgent
setAllowBasicAuth False
setAuthorityGen (\_ _ -> return auth)
act
fixupEmptyProxy (Proxy uri _) | null uri = NoProxy
fixupEmptyProxy p = p
------------------------------------------------------------------------------
-- Common stuff used by multiple transport impls
--
userAgent :: String
userAgent = concat [ "cabal-install/", display Paths_cabal_install.version
, " (", display buildOS, "; ", display buildArch, ")"
]
statusParseFail :: Verbosity -> URI -> String -> IO a
statusParseFail verbosity uri r =
die' verbosity $ "Failed to download " ++ show uri ++ " : "
++ "No Status Code could be parsed from response: " ++ r
-- Trim
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
------------------------------------------------------------------------------
-- Multipart stuff partially taken from cgi package.
--
generateMultipartBody :: FilePath -> IO (BS.ByteString, String)
generateMultipartBody path = do
content <- BS.readFile path
boundary <- genBoundary
let !body = formatBody content (BS.pack boundary)
return (body, boundary)
where
formatBody content boundary =
BS.concat $
[ crlf, dd, boundary, crlf ]
++ [ BS.pack (show header) | header <- headers ]
++ [ crlf
, content
, crlf, dd, boundary, dd, crlf ]
headers =
[ Header (HdrCustom "Content-disposition")
("form-data; name=package; " ++
"filename=\"" ++ takeFileName path ++ "\"")
, Header HdrContentType "application/x-gzip"
]
crlf = BS.pack "\r\n"
dd = BS.pack "--"
genBoundary :: IO String
genBoundary = do
i <- randomRIO (0x10000000000000,0xFFFFFFFFFFFFFF) :: IO Integer
return $ showHex i ""
|
themoritz/cabal
|
cabal-install/Distribution/Client/HttpUtils.hs
|
bsd-3-clause
| 31,004 | 0 | 22 | 9,397 | 6,595 | 3,435 | 3,160 | 570 | 5 |
{-# LANGUAGE DuplicateRecordFields, TemplateHaskell, NoMonomorphismRestriction #-}
data S = MkS { x :: Int }
data T = MkT { x :: Int }
-- This tests what happens when an ambiguous record update is used in
-- a splice: since it can't be represented in TH, it should error
-- cleanly, rather than panicking or silently using one field.
foo = [e| (MkS 3) { x = 3 } |]
main = return ()
|
sdiehl/ghc
|
testsuite/tests/overloadedrecflds/should_fail/overloadedrecfldsfail09.hs
|
bsd-3-clause
| 385 | 0 | 8 | 78 | 54 | 34 | 20 | 5 | 1 |
module SubPatternIn2 where
-- allow the user to select 'x' on the LHS of
-- g. Should introduce 2 new equations for f:
-- g z (C1 x b c@[]) = x
-- g z (C1 x b c@(b_1 : b_2)) = x
data T = C1 [Int] Int [Float]| C2 Int
g :: Int -> T -> Int
g z (C1 x b c)
= case x of
x@[] -> b
x@(b_1 : b_2) -> b
g z (C1 x b c) = b
g z (C2 x) = x
f :: [Int] -> Int
f x@[] = hd x + hd (tl x)
f x@(y:ys) = hd x + hd (tl x)
hd x = head x
tl x = tail x
|
kmate/HaRe
|
old/testing/introCase/SubPatternIn2_TokOut.hs
|
bsd-3-clause
| 468 | 0 | 10 | 163 | 229 | 121 | 108 | 14 | 2 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Lazyfoo.Lesson20 (main) where
import Prelude hiding (any, mapM_)
import Control.Applicative
import Control.Monad hiding (mapM_)
import Data.Foldable
import Data.Maybe
import Data.Monoid
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import qualified Data.Vector as V
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
format <- SDL.surfaceFormat surface
key <- SDL.mapRGB format (V3 0 maxBound maxBound)
SDL.colorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> Maybe CDouble -> Maybe (Point V2 CInt) -> Maybe (V2 Bool) -> IO ()
renderTexture r (Texture t size) xy clip theta center flips =
let dstSize =
maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.renderCopyEx r
t
clip
(Just (SDL.Rectangle xy dstSize))
(fromMaybe 0 theta)
center
(fromMaybe (pure False) flips)
getJoystick :: IO (SDL.Joystick)
getJoystick = do
joysticks <- SDL.availableJoysticks
joystick <- if V.length joysticks == 0
then error "No joysticks connected!"
else return (joysticks V.! 0)
SDL.openJoystick joystick
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo, SDL.InitJoystick, SDL.InitHaptic]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererType = SDL.AcceleratedVSyncRenderer
, SDL.rendererTargetTexture = False
})
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
rumbleTexture <- loadTexture renderer "examples/lazyfoo/rumble.bmp"
joystick <- getJoystick
hapticDevice <- SDL.openHaptic (SDL.OpenHapticJoystick joystick)
SDL.hapticRumbleInit hapticDevice
let loop = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let (Any quit, Any buttonDown) =
foldMap (\case
SDL.QuitEvent -> (Any True, mempty)
SDL.KeyboardEvent e ->
if | SDL.keyboardEventKeyMotion e == SDL.Pressed ->
let scancode = SDL.keysymScancode (SDL.keyboardEventKeysym e)
in if | scancode == SDL.ScancodeEscape -> (Any True, mempty)
| otherwise -> mempty
| otherwise -> mempty
SDL.JoyButtonEvent e ->
if | SDL.joyButtonEventState e /= 0 -> (mempty, Any True)
| otherwise -> mempty
_ -> mempty) $
map SDL.eventPayload events
if buttonDown
then SDL.hapticRumblePlay hapticDevice 0.75 500
else return ()
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.renderClear renderer
renderTexture renderer rumbleTexture (P $ V2 0 0) Nothing Nothing Nothing Nothing
SDL.renderPresent renderer
unless quit $ loop
loop
SDL.closeHaptic hapticDevice
SDL.closeJoystick joystick
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
|
dalaing/sdl2
|
examples/lazyfoo/Lesson20.hs
|
bsd-3-clause
| 4,329 | 12 | 20 | 1,281 | 1,181 | 591 | 590 | 108 | 9 |
import Numeric
import GHC.Natural
main = do
-- test that GHC correctly compiles big Natural literals
let x = 0xffffffffffffffffffffffff :: Natural
print (showHex x "" == "ffffffffffffffffffffffff")
|
sdiehl/ghc
|
testsuite/tests/numeric/should_run/T15301.hs
|
bsd-3-clause
| 208 | 1 | 10 | 38 | 48 | 23 | 25 | 5 | 1 |
{-# LANGUAGE CPP #-}
module Options.Applicative.Help.Chunk
( mappendWith
, Chunk(..)
, chunked
, listToChunk
, (<<+>>)
, (<</>>)
, vcatChunks
, vsepChunks
, isEmpty
, stringChunk
, paragraph
, extractChunk
, tabulate
) where
import Control.Applicative
import Control.Monad
import Data.Maybe
import Data.Monoid
import Options.Applicative.Help.Pretty
mappendWith :: Monoid a => a -> a -> a -> a
mappendWith s x y = mconcat [x, s, y]
-- | The free monoid on a semigroup 'a'.
newtype Chunk a = Chunk
{ unChunk :: Maybe a }
deriving (Eq, Show)
instance Functor Chunk where
fmap f = Chunk . fmap f . unChunk
instance Applicative Chunk where
pure = Chunk . pure
Chunk f <*> Chunk x = Chunk (f <*> x)
instance Alternative Chunk where
empty = Chunk Control.Applicative.empty
a <|> b = Chunk $ unChunk a <|> unChunk b
instance Monad Chunk where
return = pure
m >>= f = Chunk $ unChunk m >>= unChunk . f
instance MonadPlus Chunk where
mzero = Chunk mzero
mplus m1 m2 = Chunk $ mplus (unChunk m1) (unChunk m2)
-- | Given a semigroup structure on 'a', return a monoid structure on 'Chunk a'.
--
-- Note that this is /not/ the same as 'liftA2'.
chunked :: (a -> a -> a)
-> Chunk a -> Chunk a -> Chunk a
chunked _ (Chunk Nothing) y = y
chunked _ x (Chunk Nothing) = x
chunked f (Chunk (Just x)) (Chunk (Just y)) = Chunk (Just (f x y))
-- | Concatenate a list into a Chunk. 'listToChunk' satisfies:
--
-- > isEmpty . listToChunk = null
-- > listToChunk = mconcat . fmap pure
listToChunk :: Monoid a => [a] -> Chunk a
listToChunk [] = mempty
listToChunk xs = pure (mconcat xs)
instance Monoid a => Monoid (Chunk a) where
mempty = Chunk Nothing
mappend = chunked mappend
-- | Part of a constrained comonad instance.
--
-- This is the counit of the adjunction between 'Chunk' and the forgetful
-- functor from monoids to semigroups. It satisfies:
--
-- > extractChunk . pure = id
-- > extractChunk . fmap pure = id
extractChunk :: Monoid a => Chunk a -> a
extractChunk = fromMaybe mempty . unChunk
-- we could also define:
-- duplicate :: Monoid a => Chunk a -> Chunk (Chunk a)
-- duplicate = fmap pure
-- | Concatenate two 'Chunk's with a space in between. If one is empty, this
-- just returns the other one.
--
-- Unlike '<+>' for 'Doc', this operation has a unit element, namely the empty
-- 'Chunk'.
(<<+>>) :: Chunk Doc -> Chunk Doc -> Chunk Doc
(<<+>>) = chunked (<+>)
-- | Concatenate two 'Chunk's with a softline in between. This is exactly like
-- '<<+>>', but uses a softline instead of a space.
(<</>>) :: Chunk Doc -> Chunk Doc -> Chunk Doc
(<</>>) = chunked (</>)
-- | Concatenate 'Chunk's vertically.
vcatChunks :: [Chunk Doc] -> Chunk Doc
vcatChunks = foldr (chunked (.$.)) mempty
-- | Concatenate 'Chunk's vertically separated by empty lines.
vsepChunks :: [Chunk Doc] -> Chunk Doc
vsepChunks = foldr (chunked (\x y -> x .$. mempty .$. y)) mempty
-- | Whether a 'Chunk' is empty. Note that something like 'pure mempty' is not
-- considered an empty chunk, even though the underlying 'Doc' is empty.
isEmpty :: Chunk a -> Bool
isEmpty = isNothing . unChunk
-- | Convert a 'String' into a 'Chunk'. This satisfies:
--
-- > isEmpty . stringChunk = null
-- > extractChunk . stringChunk = string
stringChunk :: String -> Chunk Doc
stringChunk "" = mempty
stringChunk s = pure (string s)
-- | Convert a paragraph into a 'Chunk'. The resulting chunk is composed by the
-- words of the original paragraph separated by softlines, so it will be
-- automatically word-wrapped when rendering the underlying document.
--
-- This satisfies:
--
-- > isEmpty . paragraph = null . words
paragraph :: String -> Chunk Doc
paragraph = foldr (chunked (</>) . stringChunk) mempty
. words
tabulate' :: Int -> [(Doc, Doc)] -> Chunk Doc
tabulate' _ [] = mempty
tabulate' size table = pure $ vcat
[ indent 2 (fillBreak size key <+> value)
| (key, value) <- table ]
-- | Display pairs of strings in a table.
tabulate :: [(Doc, Doc)] -> Chunk Doc
tabulate = tabulate' 24
|
begriffs/optparse-applicative
|
Options/Applicative/Help/Chunk.hs
|
bsd-3-clause
| 4,045 | 6 | 12 | 833 | 1,022 | 554 | 468 | 75 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, MagicHash
, GeneralizedNewtypeDeriving
#-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
#ifdef __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
-- XXX -fno-warn-unused-binds stops us warning about unused constructors,
-- but really we should just remove them if we don't want them
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.C.Types
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Mapping of C types to corresponding Haskell types.
--
-----------------------------------------------------------------------------
module Foreign.C.Types
( -- * Representations of C types
-- $ctypes
-- ** Integral types
-- | These types are are represented as @newtype@s of
-- types in "Data.Int" and "Data.Word", and are instances of
-- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',
-- 'Prelude.Show', 'Prelude.Enum', 'Typeable', 'Storable',
-- 'Prelude.Bounded', 'Prelude.Real', 'Prelude.Integral' and
-- 'Bits'.
CChar(..), CSChar(..), CUChar(..)
, CShort(..), CUShort(..), CInt(..), CUInt(..)
, CLong(..), CULong(..)
, CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..)
, CLLong(..), CULLong(..)
, CIntPtr(..), CUIntPtr(..), CIntMax(..), CUIntMax(..)
-- ** Numeric types
-- | These types are are represented as @newtype@s of basic
-- foreign types, and are instances of
-- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',
-- 'Prelude.Show', 'Prelude.Enum', 'Typeable' and 'Storable'.
, CClock(..), CTime(..), CUSeconds(..), CSUSeconds(..)
-- extracted from CTime, because we don't want this comment in
-- the Haskell 2010 report:
-- | To convert 'CTime' to 'Data.Time.UTCTime', use the following formula:
--
-- > posixSecondsToUTCTime (realToFrac :: POSIXTime)
--
-- ** Floating types
-- | These types are are represented as @newtype@s of
-- 'Prelude.Float' and 'Prelude.Double', and are instances of
-- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',
-- 'Prelude.Show', 'Prelude.Enum', 'Typeable', 'Storable',
-- 'Prelude.Real', 'Prelude.Fractional', 'Prelude.Floating',
-- 'Prelude.RealFrac' and 'Prelude.RealFloat'.
, CFloat(..), CDouble(..)
-- GHC doesn't support CLDouble yet
#ifndef __GLASGOW_HASKELL__
, CLDouble(..)
#endif
-- ** Other types
-- Instances of: Eq and Storable
, CFile, CFpos, CJmpBuf
) where
#ifndef __NHC__
import Foreign.Storable
import Data.Bits ( Bits(..) )
import Data.Int ( Int8, Int16, Int32, Int64 )
import Data.Word ( Word8, Word16, Word32, Word64 )
import Data.Typeable
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Float
import GHC.Enum
import GHC.Real
import GHC.Show
import GHC.Read
import GHC.Num
#else
import Control.Monad ( liftM )
#endif
#ifdef __HUGS__
import Hugs.Ptr ( castPtr )
#endif
#include "HsBaseConfig.h"
#include "CTypes.h"
-- | Haskell type representing the C @char@ type.
INTEGRAL_TYPE(CChar,tyConCChar,"CChar",HTYPE_CHAR)
-- | Haskell type representing the C @signed char@ type.
INTEGRAL_TYPE(CSChar,tyConCSChar,"CSChar",HTYPE_SIGNED_CHAR)
-- | Haskell type representing the C @unsigned char@ type.
INTEGRAL_TYPE(CUChar,tyConCUChar,"CUChar",HTYPE_UNSIGNED_CHAR)
-- | Haskell type representing the C @short@ type.
INTEGRAL_TYPE(CShort,tyConCShort,"CShort",HTYPE_SHORT)
-- | Haskell type representing the C @unsigned short@ type.
INTEGRAL_TYPE(CUShort,tyConCUShort,"CUShort",HTYPE_UNSIGNED_SHORT)
-- | Haskell type representing the C @int@ type.
INTEGRAL_TYPE(CInt,tyConCInt,"CInt",HTYPE_INT)
-- | Haskell type representing the C @unsigned int@ type.
INTEGRAL_TYPE(CUInt,tyConCUInt,"CUInt",HTYPE_UNSIGNED_INT)
-- | Haskell type representing the C @long@ type.
INTEGRAL_TYPE(CLong,tyConCLong,"CLong",HTYPE_LONG)
-- | Haskell type representing the C @unsigned long@ type.
INTEGRAL_TYPE(CULong,tyConCULong,"CULong",HTYPE_UNSIGNED_LONG)
-- | Haskell type representing the C @long long@ type.
INTEGRAL_TYPE(CLLong,tyConCLLong,"CLLong",HTYPE_LONG_LONG)
-- | Haskell type representing the C @unsigned long long@ type.
INTEGRAL_TYPE(CULLong,tyConCULLong,"CULLong",HTYPE_UNSIGNED_LONG_LONG)
{-# RULES
"fromIntegral/a->CChar" fromIntegral = \x -> CChar (fromIntegral x)
"fromIntegral/a->CSChar" fromIntegral = \x -> CSChar (fromIntegral x)
"fromIntegral/a->CUChar" fromIntegral = \x -> CUChar (fromIntegral x)
"fromIntegral/a->CShort" fromIntegral = \x -> CShort (fromIntegral x)
"fromIntegral/a->CUShort" fromIntegral = \x -> CUShort (fromIntegral x)
"fromIntegral/a->CInt" fromIntegral = \x -> CInt (fromIntegral x)
"fromIntegral/a->CUInt" fromIntegral = \x -> CUInt (fromIntegral x)
"fromIntegral/a->CLong" fromIntegral = \x -> CLong (fromIntegral x)
"fromIntegral/a->CULong" fromIntegral = \x -> CULong (fromIntegral x)
"fromIntegral/a->CLLong" fromIntegral = \x -> CLLong (fromIntegral x)
"fromIntegral/a->CULLong" fromIntegral = \x -> CULLong (fromIntegral x)
"fromIntegral/CChar->a" fromIntegral = \(CChar x) -> fromIntegral x
"fromIntegral/CSChar->a" fromIntegral = \(CSChar x) -> fromIntegral x
"fromIntegral/CUChar->a" fromIntegral = \(CUChar x) -> fromIntegral x
"fromIntegral/CShort->a" fromIntegral = \(CShort x) -> fromIntegral x
"fromIntegral/CUShort->a" fromIntegral = \(CUShort x) -> fromIntegral x
"fromIntegral/CInt->a" fromIntegral = \(CInt x) -> fromIntegral x
"fromIntegral/CUInt->a" fromIntegral = \(CUInt x) -> fromIntegral x
"fromIntegral/CLong->a" fromIntegral = \(CLong x) -> fromIntegral x
"fromIntegral/CULong->a" fromIntegral = \(CULong x) -> fromIntegral x
"fromIntegral/CLLong->a" fromIntegral = \(CLLong x) -> fromIntegral x
"fromIntegral/CULLong->a" fromIntegral = \(CULLong x) -> fromIntegral x
#-}
-- | Haskell type representing the C @float@ type.
FLOATING_TYPE(CFloat,tyConCFloat,"CFloat",HTYPE_FLOAT)
-- | Haskell type representing the C @double@ type.
FLOATING_TYPE(CDouble,tyConCDouble,"CDouble",HTYPE_DOUBLE)
-- GHC doesn't support CLDouble yet
#ifndef __GLASGOW_HASKELL__
-- HACK: Currently no long double in the FFI, so we simply re-use double
-- | Haskell type representing the C @long double@ type.
FLOATING_TYPE(CLDouble,tyConCLDouble,"CLDouble",HTYPE_DOUBLE)
#endif
{-# RULES
"realToFrac/a->CFloat" realToFrac = \x -> CFloat (realToFrac x)
"realToFrac/a->CDouble" realToFrac = \x -> CDouble (realToFrac x)
"realToFrac/CFloat->a" realToFrac = \(CFloat x) -> realToFrac x
"realToFrac/CDouble->a" realToFrac = \(CDouble x) -> realToFrac x
#-}
-- GHC doesn't support CLDouble yet
-- "realToFrac/a->CLDouble" realToFrac = \x -> CLDouble (realToFrac x)
-- "realToFrac/CLDouble->a" realToFrac = \(CLDouble x) -> realToFrac x
-- | Haskell type representing the C @ptrdiff_t@ type.
INTEGRAL_TYPE(CPtrdiff,tyConCPtrdiff,"CPtrdiff",HTYPE_PTRDIFF_T)
-- | Haskell type representing the C @size_t@ type.
INTEGRAL_TYPE(CSize,tyConCSize,"CSize",HTYPE_SIZE_T)
-- | Haskell type representing the C @wchar_t@ type.
INTEGRAL_TYPE(CWchar,tyConCWchar,"CWchar",HTYPE_WCHAR_T)
-- | Haskell type representing the C @sig_atomic_t@ type.
INTEGRAL_TYPE(CSigAtomic,tyConCSigAtomic,"CSigAtomic",HTYPE_SIG_ATOMIC_T)
{-# RULES
"fromIntegral/a->CPtrdiff" fromIntegral = \x -> CPtrdiff (fromIntegral x)
"fromIntegral/a->CSize" fromIntegral = \x -> CSize (fromIntegral x)
"fromIntegral/a->CWchar" fromIntegral = \x -> CWchar (fromIntegral x)
"fromIntegral/a->CSigAtomic" fromIntegral = \x -> CSigAtomic (fromIntegral x)
"fromIntegral/CPtrdiff->a" fromIntegral = \(CPtrdiff x) -> fromIntegral x
"fromIntegral/CSize->a" fromIntegral = \(CSize x) -> fromIntegral x
"fromIntegral/CWchar->a" fromIntegral = \(CWchar x) -> fromIntegral x
"fromIntegral/CSigAtomic->a" fromIntegral = \(CSigAtomic x) -> fromIntegral x
#-}
-- | Haskell type representing the C @clock_t@ type.
ARITHMETIC_TYPE(CClock,tyConCClock,"CClock",HTYPE_CLOCK_T)
-- | Haskell type representing the C @time_t@ type.
ARITHMETIC_TYPE(CTime,tyConCTime,"CTime",HTYPE_TIME_T)
-- | Haskell type representing the C @useconds_t@ type.
ARITHMETIC_TYPE(CUSeconds,tyConCUSeconds,"CUSeconds",HTYPE_USECONDS_T)
-- | Haskell type representing the C @suseconds_t@ type.
ARITHMETIC_TYPE(CSUSeconds,tyConCSUSeconds,"CSUSeconds",HTYPE_SUSECONDS_T)
-- FIXME: Implement and provide instances for Eq and Storable
-- | Haskell type representing the C @FILE@ type.
data CFile = CFile
-- | Haskell type representing the C @fpos_t@ type.
data CFpos = CFpos
-- | Haskell type representing the C @jmp_buf@ type.
data CJmpBuf = CJmpBuf
INTEGRAL_TYPE(CIntPtr,tyConCIntPtr,"CIntPtr",HTYPE_INTPTR_T)
INTEGRAL_TYPE(CUIntPtr,tyConCUIntPtr,"CUIntPtr",HTYPE_UINTPTR_T)
INTEGRAL_TYPE(CIntMax,tyConCIntMax,"CIntMax",HTYPE_INTMAX_T)
INTEGRAL_TYPE(CUIntMax,tyConCUIntMax,"CUIntMax",HTYPE_UINTMAX_T)
{-# RULES
"fromIntegral/a->CIntPtr" fromIntegral = \x -> CIntPtr (fromIntegral x)
"fromIntegral/a->CUIntPtr" fromIntegral = \x -> CUIntPtr (fromIntegral x)
"fromIntegral/a->CIntMax" fromIntegral = \x -> CIntMax (fromIntegral x)
"fromIntegral/a->CUIntMax" fromIntegral = \x -> CUIntMax (fromIntegral x)
#-}
-- C99 types which are still missing include:
-- wint_t, wctrans_t, wctype_t
{- $ctypes
These types are needed to accurately represent C function prototypes,
in order to access C library interfaces in Haskell. The Haskell system
is not required to represent those types exactly as C does, but the
following guarantees are provided concerning a Haskell type @CT@
representing a C type @t@:
* If a C function prototype has @t@ as an argument or result type, the
use of @CT@ in the corresponding position in a foreign declaration
permits the Haskell program to access the full range of values encoded
by the C type; and conversely, any Haskell value for @CT@ has a valid
representation in C.
* @'sizeOf' ('Prelude.undefined' :: CT)@ will yield the same value as
@sizeof (t)@ in C.
* @'alignment' ('Prelude.undefined' :: CT)@ matches the alignment
constraint enforced by the C implementation for @t@.
* The members 'peek' and 'poke' of the 'Storable' class map all values
of @CT@ to the corresponding value of @t@ and vice versa.
* When an instance of 'Prelude.Bounded' is defined for @CT@, the values
of 'Prelude.minBound' and 'Prelude.maxBound' coincide with @t_MIN@
and @t_MAX@ in C.
* When an instance of 'Prelude.Eq' or 'Prelude.Ord' is defined for @CT@,
the predicates defined by the type class implement the same relation
as the corresponding predicate in C on @t@.
* When an instance of 'Prelude.Num', 'Prelude.Read', 'Prelude.Integral',
'Prelude.Fractional', 'Prelude.Floating', 'Prelude.RealFrac', or
'Prelude.RealFloat' is defined for @CT@, the arithmetic operations
defined by the type class implement the same function as the
corresponding arithmetic operations (if available) in C on @t@.
* When an instance of 'Bits' is defined for @CT@, the bitwise operation
defined by the type class implement the same function as the
corresponding bitwise operation in C on @t@.
-}
#else /* __NHC__ */
import NHC.FFI
( CChar(..), CSChar(..), CUChar(..)
, CShort(..), CUShort(..), CInt(..), CUInt(..)
, CLong(..), CULong(..), CLLong(..), CULLong(..)
, CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..)
, CClock(..), CTime(..), CUSeconds(..), CSUSeconds(..)
, CFloat(..), CDouble(..), CLDouble(..)
, CIntPtr(..), CUIntPtr(..), CIntMax(..), CUIntMax(..)
, CFile, CFpos, CJmpBuf
, Storable(..)
)
import Data.Bits
import NHC.SizedTypes
#define INSTANCE_BITS(T) \
instance Bits T where { \
(T x) .&. (T y) = T (x .&. y) ; \
(T x) .|. (T y) = T (x .|. y) ; \
(T x) `xor` (T y) = T (x `xor` y) ; \
complement (T x) = T (complement x) ; \
shift (T x) n = T (shift x n) ; \
rotate (T x) n = T (rotate x n) ; \
bit n = T (bit n) ; \
setBit (T x) n = T (setBit x n) ; \
clearBit (T x) n = T (clearBit x n) ; \
complementBit (T x) n = T (complementBit x n) ; \
testBit (T x) n = testBit x n ; \
bitSize (T x) = bitSize x ; \
isSigned (T x) = isSigned x ; \
popCount (T x) = popCount x }
INSTANCE_BITS(CChar)
INSTANCE_BITS(CSChar)
INSTANCE_BITS(CUChar)
INSTANCE_BITS(CShort)
INSTANCE_BITS(CUShort)
INSTANCE_BITS(CInt)
INSTANCE_BITS(CUInt)
INSTANCE_BITS(CLong)
INSTANCE_BITS(CULong)
INSTANCE_BITS(CLLong)
INSTANCE_BITS(CULLong)
INSTANCE_BITS(CPtrdiff)
INSTANCE_BITS(CWchar)
INSTANCE_BITS(CSigAtomic)
INSTANCE_BITS(CSize)
INSTANCE_BITS(CIntPtr)
INSTANCE_BITS(CUIntPtr)
INSTANCE_BITS(CIntMax)
INSTANCE_BITS(CUIntMax)
#endif
|
beni55/haste-compiler
|
libraries/ghc-7.8/base/Foreign/C/Types.hs
|
bsd-3-clause
| 13,342 | 0 | 6 | 2,455 | 899 | 583 | 316 | -1 | -1 |
module C5 where
import D5
instance SameOrNot Double
where
isSame a b = a == b
isNotSame a b = a /= b
myFringe :: (Tree a) -> [a]
myFringe (Leaf x) = [x]
myFringe (Branch left right) = myFringe left
mySumSq = D5.sum
|
kmate/HaRe
|
old/testing/renaming/C5_AstOut.hs
|
bsd-3-clause
| 236 | 1 | 8 | 65 | 105 | 55 | 50 | 9 | 1 |
module ShouldSucceed where
x = 'a'
(y:ys) = ['a','b','c'] where p = x
|
siddhanathan/ghc
|
testsuite/tests/typecheck/should_compile/tc069.hs
|
bsd-3-clause
| 71 | 0 | 6 | 14 | 38 | 23 | 15 | 3 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Haarss.Main where
import Control.Concurrent
import Control.Exception
import Control.Lens
import Control.Monad
import Data.Time
import Data.Typeable
import FRP.Sodium
import FRP.Sodium.IO
import qualified Graphics.Vty as Vty
import System.Exit
import System.Process
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
import Data.Monoid (mconcat)
#endif
import Haarss.Config
import Haarss.Fetching
import Haarss.Interface
import Haarss.Model
import Haarss.Model.Window
import Haarss.View
------------------------------------------------------------------------
main :: IO ()
main = do
cfg <- loadConfig
vty <- Vty.mkVty =<< Vty.standardIOConfig
sz <- Vty.displayBounds $ Vty.outputIface vty
model <- resizeModel sz <$> loadModel cfg
(eEvent, pushEvent) <- sync newEvent
tid <- myThreadId
sync $ setupReactive cfg vty sz model eEvent tid
forever (Vty.nextEvent vty >>= sync . pushEvent)
`catches` [ Handler (\Shutdown -> do
Vty.shutdown vty
exitSuccess)
, Handler (\e -> do
Vty.shutdown vty
putStrLn $ "Unexpected error: " ++
show (e :: SomeException)
exitFailure)
]
data Shutdown = Shutdown
deriving (Show, Typeable)
instance Exception Shutdown where
------------------------------------------------------------------------
setupReactive :: Config -> Vty.Vty -> Vty.DisplayRegion -> Model ->
Event Vty.Event -> ThreadId -> Reactive ()
setupReactive cfg vty sz initModel eEvent tid = do
(eFeedback, pushFeedback) <- newEvent
:: Reactive (Event Feedback,
Feedback -> Reactive ())
eSize <- fmap updates $ hold sz $ filterJust $ fmap
(\e -> case e of
Vty.EvResize h w -> Just (h, w)
_ -> Nothing) eEvent
:: Reactive (Event Vty.DisplayRegion)
rec
eCmd <- filterJust <$>
collectE (uncurry cmd) Normal (snapshot (,) eEvent bModel)
:: Reactive (Event ExCmd)
let eResp :: Event ExResp
eResp = executeAsyncIO $ fmap
(\(ExCmd o p) -> ExResp o p <$> resp o p) eCmd
where
resp :: Op o -> Cmd o -> IO (Resp o)
resp UpdateFeeds us = do
sync $ pushFeedback $ Downloading (length us)
time <- getCurrentTime
fs <- download us (sync $ pushFeedback FeedDownloaded)
(cfg^.proxy)
return (time, fs)
resp Move _ = return ()
resp OpenUrl mu = case mu of
Nothing -> return ()
Just u -> do
-- We use createProcess, rather than say rawSystem, so we
-- can redirect stderr and thus avoid having the terminal
-- flooded by warnings from the browser.
_ <- createProcess (proc (cfg^.browser) [u])
{ std_err = CreatePipe }
return ()
resp MarkAllAsRead fs = do
-- This will save the /previous/ state of the feeds, because
-- we haven't yet marked them as read -- if we mark as read
-- twice in a row we save the current state though.
updateConfig cfg fs
saveModel fs
return ()
resp MarkAsRead () = return ()
resp OpenPrompt _ = return ()
resp PutPrompt _ = return ()
resp DelPrompt () = return ()
resp CancelPrompt () = return ()
resp ClosePrompt () = return ()
resp Quit fs = do
updateConfig cfg fs
saveModel fs
throwTo tid Shutdown
threadDelay 1000000 -- Wait for main thread to shut down...
resp RemoveFeed () = return ()
resp Rearrange _ = return ()
resp Search _ = return ()
resp Scroll _ = return ()
resp Resize _ = return ()
bModel <- accum initModel $ mconcat
[ (\(ExResp o p a) -> update o p a) <$> eResp
, feedback <$> eFeedback
, resizeModel <$> eSize
]
:: Reactive (Behavior Model)
_ <- listen (value bModel) (viewModel vty)
return ()
------------------------------------------------------------------------
cmd :: Vty.Event -> Model -> Mode -> (Maybe ExCmd, Mode)
cmd _ m Normal | m^.downloading > 0 = (Nothing, Normal)
cmd e _ Normal | key 'K' == e = normal Move Top
cmd e _ Normal | key 'k' == e = normal Move Up
cmd e _ Normal | key 'j' == e = normal Move Down
cmd e _ Normal | key 'J' == e = normal Move Bot
cmd e _ Normal | key 'l' == e = normal Move In
cmd e _ Normal | enter == e = normal Move In
cmd e _ Normal | arrowUp == e = normal Move Up
cmd e _ Normal | arrowDown == e = normal Move Down
cmd e m Normal | key 'q' == e = if browsingFeeds m
then normal Quit
(m^.feeds.to closeWindow)
else normal Move Out
cmd e m Normal | key 'R' == e = normal UpdateFeeds
[getFeedUrl m]
cmd e m Normal | key 'r' == e = normal UpdateFeeds (getFeedUrls m)
cmd e m Normal | key 'o' == e = normal OpenUrl (getItemUrl m)
cmd e m Normal | key 'm' == e = normal MarkAllAsRead
(m^.feeds.to closeWindow)
cmd e _ Normal | key 'M' == e = normal MarkAsRead ()
cmd e _ Normal | key 'D' == e = normal RemoveFeed ()
cmd e m Normal | key 'c' == e &&
browsingFeeds m = input OpenPrompt RenameFeed
cmd e m Normal | key 'a' == e &&
browsingFeeds m = input OpenPrompt AddFeed
cmd e m Normal | key 'P' == e &&
browsingFeeds m = normal Rearrange Up
cmd e m Normal | key 'N' == e &&
browsingFeeds m = normal Rearrange Down
cmd e _ Normal | key '/' == e = input OpenPrompt SearchPrompt
cmd e _ Normal | key '\t' == e = input OpenPrompt SearchPrompt
cmd e _ Normal | key ' ' == e = normal Scroll DownFull
cmd e _ Normal | key 'd' == e = normal Scroll DownHalf
cmd e _ Normal | key 'b' == e = normal Scroll UpFull
cmd e _ Normal | key 'u' == e = normal Scroll UpHalf
cmd _ _ Normal = (Nothing, Normal)
cmd e _ Input | isKey e = input PutPrompt (getKey e)
cmd e _ Input | backspace == e = input DelPrompt ()
cmd e _ Input | esc == e = normal CancelPrompt ()
cmd e _ Input | enter == e = normal ClosePrompt ()
cmd e _ Input | ctrl 'g' == e = normal CancelPrompt ()
cmd _ _ Input = (Nothing, Input)
------------------------------------------------------------------------
normal, input :: Op o -> Cmd o -> (Maybe ExCmd, Mode)
normal o c = (Just $ ExCmd o c, Normal)
input o c = (Just $ ExCmd o c, Input)
key, ctrl :: Char -> Vty.Event
key c = Vty.EvKey (Vty.KChar c) []
ctrl c = Vty.EvKey (Vty.KChar c) [Vty.MCtrl]
arrowUp, arrowDown :: Vty.Event
arrowUp = Vty.EvKey Vty.KUp []
arrowDown = Vty.EvKey Vty.KDown []
enter, backspace, esc :: Vty.Event
enter = Vty.EvKey Vty.KEnter []
backspace = Vty.EvKey Vty.KBS []
esc = Vty.EvKey Vty.KEsc []
isKey :: Vty.Event -> Bool
isKey (Vty.EvKey (Vty.KChar _) []) = True
isKey _ = False
getKey :: Vty.Event -> Char
getKey (Vty.EvKey (Vty.KChar c) []) = c
getKey _ = error "getKey"
|
stevana/haarss
|
src/Haarss/Main.hs
|
isc
| 8,262 | 2 | 26 | 3,153 | 2,604 | 1,253 | 1,351 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Control.Applicative (liftA2)
import Control.Logging (log', withStderrLogging)
import Control.Monad
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Binary.Builder (Builder)
import qualified Data.Binary.Builder as Builder
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import qualified Data.HashTable.IO as H
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (catMaybes, fromMaybe, isJust,
listToMaybe)
import Data.Monoid ((<>))
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Database.PostgreSQL.Simple as PG
import qualified Database.SQLite.Simple as SQLITE
import qualified HTMLEntities.Text as HE
import Magic (MagicFlag (MagicMimeType),
magicCString, magicLoadDefault,
magicOpen)
import Network.HTTP.Types (hContentType)
import Network.HTTP.Types.Status (status200)
import Network.Wai (Response, rawPathInfo,
requestMethod, responseBuilder,
responseLBS)
import Network.Wai.Handler.Warp (runEnv)
import System.Environment (getEnv, lookupEnv)
import System.FilePath (takeExtension)
import Text.RE.Replace
import Text.RE.TDFA.Text
import Web.Fn
import qualified Web.Larceny as L
import qualified Shed.Blob.Email as Email
import qualified Shed.Blob.File as File
import qualified Shed.Blob.Permanode as Permanode
import Shed.BlobServer
import Shed.BlobServer.Directory
import Shed.BlobServer.Memory
import Shed.Images
import Shed.Importer
import Shed.Indexer
import Shed.IndexServer
import Shed.IndexServer.Postgresql
import Shed.IndexServer.Sqlite
import Shed.Signing
import Shed.Types
import Shed.Util
type Fill = L.Fill ()
type Library = L.Library ()
type Substitutions = L.Substitutions ()
data Ctxt = Ctxt { _req :: FnRequest
, _store :: SomeBlobServer
, _db :: SomeIndexServer
, _library :: Library
, _key :: Key
}
instance RequestContext Ctxt where
getRequest = _req
setRequest c r = c { _req = r }
render :: Ctxt -> Text -> IO (Maybe Response)
render ctxt = renderWith ctxt mempty
renderWith :: Ctxt -> Substitutions -> Text -> IO (Maybe Response)
renderWith ctxt subs tpl =
do t <- L.renderWith (_library ctxt) subs () (T.splitOn "/" tpl)
case t of
Nothing -> return Nothing
Just t' -> okHtml t'
initializer :: IO Ctxt
initializer = do
lib <- L.loadTemplates "templates" L.defaultOverrides
pth' <- fmap T.pack <$> (lookupEnv "BLOBS")
(store, pth) <- case pth' of
Just pth'' -> return (SomeBlobServer (FileStore pth''), pth'')
Nothing -> do
ht <- H.new
return (SomeBlobServer (MemoryStore ht), ":memory:")
db' <- fmap T.pack <$> lookupEnv "INDEX"
(serv, nm) <- case db' of
Just db -> do c <- PG.connectPostgreSQL $ T.encodeUtf8 $ "dbname='" <> db <> "'"
return (SomeIndexServer (PG c), db)
Nothing -> do sql <- readFile "migrations/sqlite.sql"
c <- SQLITE.open ":memory:"
SQLITE.execute_ c (fromString sql)
let serv = SomeIndexServer (SL c)
log' "Running indexer to populate :memory: index."
-- NOTE(dbp 2017-05-29): Run many times because
-- we need permanodes in DB before files stored
-- in them are indexed
index store serv
index store serv
index store serv
return (serv, ":memory:")
keyid <- T.pack <$> getEnv "KEY"
keyblob <- getPubKey keyid
ref <- writeBlob store keyblob
let key = Key keyid ref
log' $ "Opening the Shed [Blobs " <> pth <> " Index " <> nm <> "]"
return (Ctxt defaultFnRequest store serv lib key)
main :: IO ()
main = withStderrLogging $
do ctxt <- initializer
runEnv 3000 $ toWAI ctxt site
instance FromParam SHA1 where
fromParam [x] | "sha1-" `T.isPrefixOf` x = Right $ SHA1 x
fromParam [] = Left ParamMissing
fromParam _ = Left ParamTooMany
site :: Ctxt -> IO Response
site ctxt = do
log' $ T.decodeUtf8 (requestMethod (fst $ _req ctxt)) <> " " <> T.decodeUtf8 (rawPathInfo (fst $ _req ctxt))
route ctxt [ end // param "page" ==> indexH
, path "static" ==> staticServe "static"
, segment // path "thumb" ==> thumbH
, segment ==> renderH
, path "blob" // segment ==> blobH
, path "file" // segment ==> \ctxt sha -> File.serve (_store ctxt) sha
, path "raw" // segment ==> rawH
, path "upload" // file "file" !=> uploadH
, path "search" // param "q" ==> searchH
, path "reindex" ==> reindexH
, path "wipe" ==> wipeH
]
`fallthrough` do r <- render ctxt "404"
case r of
Just r' -> return r'
Nothing -> notFoundText "Page not found"
permanodeSubs :: Permanode -> Substitutions
permanodeSubs (Permanode (SHA1 sha) attrs thumb prev) =
L.subs [("permanodeRef", L.textFill sha)
,("contentRef", L.textFill $ attrs M.! "camliContent")
,("has-thumbnail", justFill thumb)
,("no-thumbnail", nothingFill thumb)
,("has-preview", justFill prev)
,("preview", L.rawTextFill $ maybe "" (T.replace "\n" "</p><p>" . HE.text) prev)]
where
justFill m = if isJust m then L.fillChildren else L.textFill ""
nothingFill m = if isJust m then L.textFill "" else L.fillChildren
indexH :: Ctxt -> Maybe Int -> IO (Maybe Response)
indexH ctxt page = do
ps <- getPermanodes (_db ctxt) (fromMaybe 0 page)
renderWith ctxt
(L.subs [("has-more", L.fillChildren)
,("next-page", L.textFill $ maybe "1" (T.pack . show . (+1)) page)
,("permanodes", L.mapSubs permanodeSubs ps)
,("q", L.textFill "")])
"index"
searchH :: Ctxt -> Text -> IO (Maybe Response)
searchH ctxt q = do
if T.strip q == "" then redirect "/" else do
ps <- search (_db ctxt) q
if length ps == 0 then redirect "/" else
renderWith ctxt
(L.subs [("has-more", L.textFill "")
,("q", L.textFill q)
,("permanodes", L.mapSubs permanodeSubs ps)])
"index"
reindexH :: Ctxt -> IO (Maybe Response)
reindexH ctxt = do
index (_store ctxt) (_db ctxt)
okText "OK."
wipeH :: Ctxt -> IO (Maybe Response)
wipeH ctxt = do
wipe (_db ctxt)
redirect "/"
mmsum :: (Monad f, MonadPlus m, Foldable t) => t (f (m a)) -> f (m a)
mmsum = foldl (liftA2 mplus) (return mzero)
renderH :: Ctxt -> SHA1 -> IO (Maybe Response)
renderH ctxt sha = do
res' <- readBlob (_store ctxt) sha
case res' of
Nothing -> return Nothing
Just bs ->
liftA2 mplus
(mmsum $ map (\f -> f (_store ctxt) (_db ctxt) (renderWith ctxt) sha bs)
[File.toHtml
,Email.toHtml
])
(blobH ctxt sha)
blobH :: Ctxt -> SHA1 -> IO (Maybe Response)
blobH ctxt sha = do
res' <- readBlob (_store ctxt) sha
case res' of
Nothing -> return Nothing
Just bs ->
route ctxt [anything ==> \_ -> Permanode.toHtml (_store ctxt) (_db ctxt) (renderWith ctxt) sha bs
,anything ==> \_ -> do
m <- magicOpen [MagicMimeType]
magicLoadDefault m
let b = BL.toStrict bs
mime <- unsafeUseAsCStringLen b (magicCString m)
let display = renderWith ctxt (L.subs [("content", L.rawTextFill (hyperLinkEscape (T.decodeUtf8 b)))]) "blob"
case mime of
"text/plain" -> display
"text/html" -> display
_ -> rawH ctxt sha]
rawH :: Ctxt -> SHA1 -> IO (Maybe Response)
rawH ctxt sha@(SHA1 s) =
do res' <- readBlob (_store ctxt) sha
case res' of
Nothing -> return Nothing
Just res -> return $ Just $ responseLBS status200 [] res
renderIcon :: IO (Maybe Response)
renderIcon = sendFile "static/icon.png"
thumbH :: Ctxt -> SHA1 -> IO (Maybe Response)
thumbH ctxt sha =
do res <- getThumbnail (_db ctxt) sha
case res of
Nothing -> renderIcon
Just jpg -> return $ Just $ responseBuilder status200 [(hContentType, "image/jpeg")] (Builder.fromByteString jpg)
uploadH :: Ctxt -> File -> IO (Maybe Response)
uploadH ctxt f = do log' $ "Uploading " <> fileName f <> "..."
process (_store ctxt) (_db ctxt) (_key ctxt) f
okText "OK"
|
dbp/shed
|
app/Main.hs
|
isc
| 10,086 | 0 | 29 | 3,672 | 2,931 | 1,514 | 1,417 | 216 | 4 |
{-
Module : Reopt.Semantics.Implementation
Copyright : (c) Galois, Inc 2015-2016
This defines a template haskell function for creating storable records.
-}
{-# OPTIONS_GHC -Werror #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
module System.Linux.Ptrace.GenStruct where
import Control.Monad
import Foreign
import Language.Haskell.TH
-- | This creates a storable structure containing a list of fields each with the same type.
genStruct :: String -> [String] -> Q Type -> Q [Dec]
genStruct name ctors elemType = do
let name' = mkName name
elemType' <- elemType
#if MIN_VERSION_template_haskell(2,11,0)
let strictness = Bang NoSourceUnpackedness NoSourceStrictness
let varsAndTypes = (\nm -> (mkName nm, strictness, elemType')) <$> ctors
let typeDecl :: Dec
typeDecl = DataD [{-context-}]
name'
[{-tyvars-}]
Nothing
[RecC name' varsAndTypes]
#if MIN_VERSION_template_haskell(2,12,0)
[DerivClause Nothing [ConT ''Show]]
#else
[ConT ''Show]
#endif
#else
varsAndTypes <- mapM (\n -> varStrictType (mkName n) (strictType notStrict elemType)) ctors
let typeDecl :: Dec
typeDecl = DataD [{-context-}]
name'
[{-tyvars-}]
[RecC name' varsAndTypes]
[''Show]
#endif
-- Could evaluate this now, but what happens if we're cross-compiling? Is CInt the target's size, or ours?
let elemSize = [|sizeOf (undefined :: $(elemType))|]
-- This exposes at least two GHC bugs:
-- 1) It's rejected because GHC thinks $(conT name') is a type variable
-- 2) The error message reverses the order of member definitions
--storableInst <-
-- [d|instance Storable $(conT name') where
-- sizeOf _ = $(litP . integerL $ length ctors) * $(elemSize)
-- alignment _ = alignment (undefined :: $(elemType))
-- peek p = foldl (\e k -> [| $e `ap` peekByteOff p (k * $(elemSize)) |]) [|return $(conE name')|] [0..length ctors-1]
-- |]
-- This exposes another GHC bug:
-- 3) We can't capture Storable in a type quotation since it's a class name.
--storableInst <- instanceD (cxt []) [t|Storable $(conT name')|] ...
-- Work around instanceD's nasty interface
let fixDecs :: Q [Dec] -> Q [DecQ]
fixDecs decs = (fmap.fmap) return decs
-- Eek, can't substitute this below: TH lifting is not referentially transparent
let numCtors = length ctors
storableInst : [] <- [d| instance Storable $(return $ ConT name') where
sizeOf _ = numCtors * $(elemSize)
alignment _ = alignment (undefined :: $(elemType))
peek p = $(foldl (\e k -> [| $(e) `ap` peekByteOff p (k * $(elemSize)) |]) [|return $(conE name')|] [0..length ctors-1])
poke p v = sequence_ $(listE $ map (\(n,c) -> [| pokeByteOff p (n * $(elemSize)) ($(varE (mkName c)) v) |]) $ zip [0::Int ..] ctors)
|]
return [typeDecl, storableInst]
|
GaloisInc/linux-ptrace
|
System/Linux/Ptrace/GenStruct.hs
|
mit
| 3,146 | 9 | 15 | 899 | 347 | 215 | 132 | 28 | 1 |
module Main where
import Data.Bits
import Data.Word
import ZMachine
import ZMachine.ZTypes
word :: Word16
word = 0xBEEF
main :: IO ()
main = do
print . show $ (word `shiftR` 12) .&. complement (-1 `shiftL` 4)
print . show $ fetchBits bit15 size4 word
|
RaphMad/ZMachine
|
src/main/Main.hs
|
mit
| 260 | 0 | 11 | 53 | 103 | 57 | 46 | 11 | 1 |
module Zeno.Flags (
ZenoFlags (..), readFlags, defaultFlags
) where
import Prelude ()
import Zeno.Prelude
import System.Console.GetOpt
defaultIsabelleDir :: String
defaultIsabelleDir = "isa"
data ZenoFlags
= ZenoFlags { flagVerboseProof :: !Bool,
flagPrintCore :: !Bool,
flagKeepModuleNames :: !Bool,
flagSkipChecker :: !Bool,
flagSkipSolver :: !Bool,
flagSkipIsabelle :: !Bool,
flagIsabelleAll :: !Bool,
flagWebMode :: !Bool,
flagIncludeDirs :: ![String],
flagIsabelleDir :: !String,
flagMatchWith :: ![String],
flagHaskellFiles :: ![String],
flagTimeout :: !Int }
defaultFlags :: ZenoFlags
defaultFlags
= ZenoFlags { flagVerboseProof = False,
flagPrintCore = False,
flagKeepModuleNames = False,
flagSkipChecker = False,
flagSkipSolver = False,
flagSkipIsabelle = False,
flagIsabelleAll = False,
flagWebMode = False,
flagIncludeDirs = [],
flagIsabelleDir = defaultIsabelleDir,
flagMatchWith = [],
flagHaskellFiles = [],
flagTimeout = 0 }
readFlags :: [String] -> ZenoFlags
readFlags args
| not (null errors) = error (concat errors ++ usage)
| null (flagHaskellFiles flags) =
error ("No Haskell filenames specified!\n\n" ++ usage)
| otherwise = flags
where
header = "Usage: zeno [OPTION] [FILENAME]"
examples = "\n\nExamples:"
++ "\n\nzeno *"
++ "\n Attempts to prove or disprove every property in every file "
++ "(ending in .hs or .lhs) in the current directory."
++ "\n\nzeno -m prop Test.hs"
++ "\n Attempts to prove or disprove every property "
++ "with the text \"prop\" in its name in the file \"Test.hs\" or its imports."
++ "\n\nzeno -S Test.hs"
++ "\n Disables the solver and hence runs Zeno as just a "
++ "counter-example finder on every property in \"Test.hs\"."
++ "\n\nzeno -CSa -o test Test.hs Test2.hs"
++ "\n Uses Zeno as a Haskell-to-Isabelle conversion tool on the code in "
++ "\"Test.hs\" and \"Test2.hs\", outputting it to the directory \"test\""
++ "\n"
usage = usageInfo (header ++ examples) options
(flag_funs, [], errors) =
getOpt (ReturnInOrder hsFile) options args
hsFile n f
| ".hs" `isSuffixOf` n || ".lhs" `isSuffixOf` n =
f { flagHaskellFiles = n : flagHaskellFiles f }
| otherwise = f
flags = foldl' (flip ($)) defaultFlags flag_funs
options :: [OptDescr (ZenoFlags -> ZenoFlags)]
options = [
Option ['m'] ["match"]
(ReqArg (\m f -> f { flagMatchWith = m : flagMatchWith f }) "TEXT")
$ "Only consider properties which contain this string. "
++ "This argument may be given multiple times, in which case Zeno considers "
++ "properties containing any of the given strings.",
{-
Option ['v'] ["verbose"] (NoArg $ \f -> f { flagVerboseProof = True })
$ "Enables verbose Isabelle proof output, adding a "
++ "comment to every step that Zeno has made in constructing a proof.",
-}
Option ['c'] ["print-core"] (NoArg $ \f -> f { flagPrintCore = True })
$ "Prints the internal representation of any Haskell code that Zeno has loaded "
++ "along with any properties defined, then terminates Zeno. "
++ "This code Zeno uses has been through the GHC simplifier so may be "
++ "slightly different to the code you originally wrote. "
++ "If you are wondering why Zeno cannot work with a certain "
++ "function definition it might be worth checking how it came out here.",
{-
Option ['q'] ["qualify"] (NoArg $ \f -> f { flagKeepModuleNames = True })
$ "Stops Zeno from stripping modules from the beginning of names within your "
++ "program. Module names are removed by default for clarity, and will not affect "
++ "the Zeno system itself, but may cause naming clashes in the "
++ "Isabelle code that Zeno outputs.",
-}
Option ['C'] ["no-check"] (NoArg $ \f -> f { flagSkipChecker = True })
$ "Stops Zeno from running its counter-example finder (think SmallCheck but "
++ "worse) on properties. Not sure why you'd want to turn this off but "
++ "who am I to judge.",
Option ['S'] ["no-solve"] (NoArg $ \f -> f { flagSkipSolver = True })
$ "Stops Zeno from attempting to prove properties. Might be useful if you "
++ "just wanted to run the counter-example finder.",
Option ['I'] ["no-isa"] (NoArg $ \f -> f { flagSkipIsabelle = True })
$ "Stops Zeno from automatically invoking Isabelle on any programs or proofs that "
++ "it outputs. Maybe Isabelle is hanging (Zeno could probably put the simplifier "
++ "into a loop with the right input), maybe you'd rather just fire up Emacs "
++ "and run through the proofs yourself, or maybe you were too lazy to install "
++ "Isabelle in the first place.",
Option ['a'] ["isa-all"] (NoArg $ \f -> f { flagIsabelleAll = True })
$ "Normally Zeno will only output functions to Isabelle if they are used "
++ "within proven properties. If you specify this option your entire program "
++ "will be printed to the Isabelle output file instead. "
++ "This feature is very experimental and the Isabelle output will often need "
++ "to be manually tweaked.",
Option ['i'] ["include-dir"]
(ReqArg (\d f -> f { flagIncludeDirs = d : flagIncludeDirs f }) "DIR")
$ "Specify a directory to be included when loading Haskell code. "
++ "Essentially this is just passed as an -i parameter to GHC.",
Option ['o'] ["isa-dir"] (ReqArg (\d f -> f { flagIsabelleDir = d }) "DIR")
$ "Specify the directory where Zeno will output its generated Isabelle code. "
++ "Defaults to \"" ++ defaultIsabelleDir ++ "\"",
Option ['t'] ["timeout"] (ReqArg (\t f -> f { flagTimeout = read t }) "SECS")
$ "Specify a timeout for Zeno to run within; any number less than one is ignored.",
Option [] ["tryzeno"] (NoArg $ \f -> f { flagWebMode = True })
$ "Formats the output for the TryZeno interface."
]
|
Gurmeet-Singh/Zeno
|
src/Zeno/Flags.hs
|
mit
| 6,227 | 0 | 19 | 1,622 | 1,078 | 601 | 477 | 135 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.GDAX.Implicit.MarketData where
import Control.Lens
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Reader
import Data.Time
import Data.Vector
import Network.GDAX.Core
import qualified Network.GDAX.Explicit.MarketData as Explicit
import Network.GDAX.Types.MarketData
import Network.GDAX.Types.Shared
getProducts :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => m (Vector Product)
getProducts = do
g <- (^. gdax) <$> ask
Explicit.getProducts g
getProductTopOfBook :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> m AggrigateBook
getProductTopOfBook pid = do
g <- (^. gdax) <$> ask
Explicit.getProductTopOfBook g pid
getProductTop50OfBook :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> m AggrigateBook
getProductTop50OfBook pid = do
g <- (^. gdax) <$> ask
Explicit.getProductTop50OfBook g pid
getProductOrderBook :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> m Book
getProductOrderBook pid = do
g <- (^. gdax) <$> ask
Explicit.getProductOrderBook g pid
getProductTicker :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> m Tick
getProductTicker pid = do
g <- (^. gdax) <$> ask
Explicit.getProductTicker g pid
getProductTrades :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> m (Vector Trade)
getProductTrades pid = do
g <- (^. gdax) <$> ask
Explicit.getProductTrades g pid
getProductHistory :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> Maybe StartTime -> Maybe EndTime -> Maybe Granularity -> m (Vector Candle)
getProductHistory pid mst met mg = do
g <- (^. gdax) <$> ask
Explicit.getProductHistory g pid mst met mg
getProductStats :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => ProductId -> m Stats
getProductStats pid = do
g <- (^. gdax) <$> ask
Explicit.getProductStats g pid
getCurrencies :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => m (Vector Currency)
getCurrencies = do
g <- (^. gdax) <$> ask
Explicit.getCurrencies g
getTime :: (MonadIO m, MonadThrow m, MonadReader e m, HasGdax e) => m UTCTime
getTime = do
g <- (^. gdax) <$> ask
Explicit.getTime g
|
AndrewRademacher/gdax
|
lib/Network/GDAX/Implicit/MarketData.hs
|
mit
| 2,450 | 0 | 12 | 517 | 844 | 437 | 407 | 53 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
module Data.Apiary.Method
( Method(..)
, renderMethod
, dispatchMethod
, parseMethod
) where
import Data.Hashable(Hashable(..))
import Data.String(IsString(..))
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Unsafe as U
data Method
= GET
| POST
| HEAD
| PUT
| DELETE
| TRACE
| CONNECT
| OPTIONS
| PATCH
| NonStandard S.ByteString
deriving (Eq, Ord, Read, Show)
instance Hashable Method where
hash GET = 0
hash POST = 1
hash HEAD = 2
hash PUT = 3
hash DELETE = 4
hash TRACE = 5
hash CONNECT = 6
hash OPTIONS = 7
hash PATCH = 8
hash (NonStandard s) = hash s
hashWithSalt salt x = salt `hashWithSalt` hash x
renderMethod :: Method -> S.ByteString
renderMethod = \case
GET -> "GET"
POST -> "POST"
HEAD -> "HEAD"
PUT -> "PUT"
DELETE -> "DELETE"
TRACE -> "TRACE"
CONNECT -> "CONNECT"
OPTIONS -> "OPTIONS"
PATCH -> "PATCH"
NonStandard a -> a
{-# INLINE renderMethod #-}
dispatchMethod :: a -> a -> a -> a -> a -> a -> a -> a -> a -> (S.ByteString -> a) -> S.ByteString -> a
dispatchMethod get post head_ put delete trace connect options patch ns s
| S.length s < 2 = ns s
| otherwise = case U.unsafeHead s of
71 -> if S.length s == 3 && cc 1 69 && cc 2 84 then get else ns s
80 -> case U.unsafeIndex s 1 of
79 -> if S.length s == 4 && cc 2 83 && cc 3 84 then post else ns s
85 -> if S.length s == 3 && cc 2 84 then put else ns s
65 -> if S.length s == 5 && cc 2 84 && cc 3 67 && cc 4 72 then patch else ns s
_ -> ns s
72 -> if S.length s == 4 && cc 1 69 && cc 2 65 && cc 3 68 then head_ else ns s
68 -> if S.length s == 6 && cc 1 69 && cc 2 76 && cc 3 69 && cc 4 84 && cc 5 69 then delete else ns s
84 -> if S.length s == 5 && cc 1 82 && cc 2 65 && cc 3 67 && cc 4 69 then trace else ns s
67 -> if S.length s == 7 && cc 1 79 && cc 2 78 && cc 3 78 && cc 4 69 && cc 5 67 && cc 6 84 then connect else ns s
79 -> if S.length s == 7 && cc 1 80 && cc 2 84 && cc 3 73 && cc 4 79 && cc 5 78 && cc 6 83 then options else ns s
_ -> ns s
where
cc i c = U.unsafeIndex s i == c
parseMethod :: S.ByteString -> Method
parseMethod = dispatchMethod GET POST HEAD PUT DELETE TRACE CONNECT OPTIONS PATCH NonStandard
instance IsString Method where
fromString = parseMethod . S.pack
|
philopon/apiary
|
src/Data/Apiary/Method.hs
|
mit
| 2,714 | 0 | 18 | 967 | 1,088 | 546 | 542 | 69 | 20 |
-- |
-- This module provides
-- Template Haskell based derivers for typical newtype instances,
-- which the @GeneralizedNewtypeDeriving@ extension refuses to handle.
--
-- Here is what it allows you to do:
--
-- >{-# LANGUAGE UndecidableInstances, TypeFamilies, FlexibleInstances,
-- > TemplateHaskell, GeneralizedNewtypeDeriving,
-- > MultiParamTypeClasses #-}
-- >
-- >import NewtypeDeriving
-- >import Control.Monad.Base
-- >import Control.Monad.Trans.Control
-- >import Control.Monad.Trans.Class
-- >import Control.Monad.Trans.Either
-- >import Control.Monad.Trans.Maybe
-- >import Control.Monad.Trans.State
-- >import Control.Monad.Trans.Reader
-- >import Control.Monad.Trans.Writer
-- >
-- >newtype T m a =
-- > T (ReaderT Int (StateT Char (WriterT [Int] (EitherT String (MaybeT m)))) a)
-- > deriving (Functor, Applicative, Monad)
-- >
-- >monadTransInstance ''T
-- >monadTransControlInstance ''T
-- >monadBaseTransformerInstance ''T
-- >monadBaseControlTransformerInstance ''T
module NewtypeDeriving where
import BasePrelude
import Language.Haskell.TH
import qualified NewtypeDeriving.Reification as Reification
import qualified NewtypeDeriving.Rendering as Rendering
-- |
-- Given a name of a newtype wrapper
-- produce an instance of
-- @Control.Monad.Trans.Class.'Control.Monad.Trans.Class.MonadTrans'@.
monadTransInstance :: Name -> Q [Dec]
monadTransInstance n =
do
Reification.Newtype typeName conName innerType <-
join $ fmap (either fail return) $
Reification.reifyNewtype n
let
layers =
unfoldr Reification.peelTransformer $
case innerType of AppT m _ -> m
return $ pure $
Rendering.monadTransInstance (ConT typeName) conName (length layers)
-- |
-- Given a name of a newtype wrapper
-- produce an instance of
-- @Control.Monad.Base.'Control.Monad.Base.MonadBase'@,
-- which is specialised for monad transformers.
monadBaseTransformerInstance :: Name -> Q [Dec]
monadBaseTransformerInstance n =
do
Reification.Newtype typeName conName innerType <-
join $ fmap (either fail return) $
Reification.reifyNewtype n
return $ pure $
Rendering.monadBaseTransformerInstance (ConT typeName) conName
-- |
-- Given a name of a newtype wrapper
-- produce an instance of
-- @Control.Monad.Trans.Control.'Control.Monad.Trans.Control.MonadTransControl'@.
monadTransControlInstance :: Name -> Q [Dec]
monadTransControlInstance n =
do
Reification.Newtype typeName conName innerType <-
join $ fmap (either fail return) $
Reification.reifyNewtype n
let
layers =
unfoldr Reification.peelTransformer $
case innerType of AppT m _ -> m
return $ pure $
Rendering.monadTransControlInstance (ConT typeName) conName layers
-- |
-- Given a name of a newtype wrapper
-- produce an instance of
-- @Control.Monad.Trans.Control.'Control.Monad.Trans.Control.MonadBaseControl'@,
-- which is specialised for monad transformers.
monadBaseControlTransformerInstance :: Name -> Q [Dec]
monadBaseControlTransformerInstance n =
return $ pure $
Rendering.monadBaseControlTransformerInstance (ConT n)
|
nikita-volkov/newtype-deriving
|
library/NewtypeDeriving.hs
|
mit
| 3,160 | 0 | 14 | 546 | 455 | 247 | 208 | 41 | 1 |
import System.Environment -- access to arguments etc.
import Data.Bits
import Data.List
import Debug.Trace
import System.IO.Unsafe -- be careful!
import System.Random
import Helpers
------------------------------------
--- Scan Inclusive and Exclusive ---
--- and Segmented Scan Inclusive ---
------------------------------------
scanInc :: (a->a->a) -> a -> [a] -> [a]
scanInc myop ne arr = tail $ scanl myop ne arr
scanExc :: (a->a->a) -> a -> [a] -> [a]
scanExc myop ne arr = let n = length arr
r = scanl myop ne arr
in take n r
segmScanInc :: (a->a->a) -> a -> [Int] -> [a] -> [a]
segmScanInc myop ne flags arr =
let fvs = zip flags arr
(_,a) = unzip $
scanl (\(f1,v1) (f2,v2) ->
let f = f1 .|. f2
in if f2 == 0
then (f, v1 `myop` v2)
else (f, v2)
) (0,ne) fvs
in tail a
segmScanExc :: (a->a->a) -> a -> [Int] -> [a] -> [a]
segmScanExc myop ne flags arr =
let inds = iota (length arr)
adj_arr= zipWith (\i f -> if f>0 then ne
else (arr !! (i-1)))
inds flags
in segmScanInc myop ne flags adj_arr
-----------------------------------
--- Filter and Segmented Filter ---
-----------------------------------
parFilter :: (a->Bool) -> [a] -> ([a], [Int])
parFilter cond arr =
let n = length arr
cs = map cond arr
tfs = map (\f -> if f then 1
else 0) cs
isT = scanInc (+) 0 tfs
i = last isT
ffs = map (\f->if f then 0
else 1) cs
isF = (map (+ i) . scanInc (+) 0) ffs
inds= map (\(c,iT,iF) ->
if c then iT-1 else iF-1)
(zip3 cs isT isF)
flags = write [0,i] [i,n-i] (replicate n 0)
in (permute inds arr, flags)
-----------------------------------
--- Computing the prime numbers ---
--- up to and including N ---
-----------------------------------
primes :: Int -> [Int]
primes n =
let a = map (\i -> if i==0 || i==1
then 0
else 1 ) [0..n]
sqrtN = floor (sqrt (fromIntegral n))
-- sqrtN1 = trace (show sqrtN) sqrtN
in primesHelp 2 n sqrtN a
where
primesHelp :: Int -> Int -> Int -> [Int] -> [Int]
primesHelp i n sqrtN a =
if i > sqrtN
then a
else let m = (n `div` i) - 1
inds = map (\k -> (k+2)*i) (iota m)
vals = replicate m 0
a' = write inds vals a
-- a'' = trace (show inds ++ " " ++ show vals ++ " " ++ show a') a'
in primesHelp (i+1) n sqrtN a'
primesOpt :: Int -> [Int]
primesOpt n =
if n <= 2 then [2]
else let sqrtN = floor (sqrt (fromIntegral n))
sqrt_primes = primesOpt sqrtN
composite = map (\ p -> let m = (n `div` p)
in map (\ j -> j * p ) (drop 2 (iota (m+1)))
) sqrt_primes
not_primes = reduce (++) [] composite
zero_array = replicate (length not_primes) False
prime_flags= write not_primes zero_array (replicate (n+1) True)
(primes,_)= ( unzip . filter (\(i,f) -> f) ) (zip (iota (n+1)) prime_flags)
primes' = trace (show n ++ " " ++ show sqrt_primes ++ " " ++
show composite ++ " "++ show primes) primes
in drop 2 primes
primesFlat :: Int -> [Int]
primesFlat n =
if n <= 2 then [2]
else let sqrtN = floor (sqrt (fromIntegral n))
sqrt_primes = primesFlat sqrtN
num_primes = length sqrt_primes
mult_lens = map (\p -> (n `div` p) - 1) sqrt_primes
mult_scan = scanExc (+) 0 mult_lens
mult_tot_len= (last mult_scan) + (last mult_lens)
flags = write mult_scan (replicate num_primes 1) (replicate mult_tot_len 0)
ps = write mult_scan sqrt_primes (replicate mult_tot_len 0)
prime_vals= segmScanInc (+) 0 flags ps
prime_inds= segmScanInc (+) 0 flags (replicate mult_tot_len 1)
not_primes= zipWith (\i v->(i+1)*v) prime_inds prime_vals
zero_array = replicate (length not_primes) False
prime_flags= write not_primes zero_array (replicate (n+1) True)
(primes,_)= ( unzip . filter (\(i,f) -> f) ) (zip (iota (n+1)) prime_flags)
primes' = trace (show n ++ " " ++ show sqrt_primes ++ " " ++
show not_primes ++ " "++ show primes) primes
in drop 2 primes
-----------------
--- QuickSort ---
-----------------
nestedQuicksort :: (Ord a, Show a) => [a] -> [a]
nestedQuicksort arr =
if (length arr) <= 1 then arr
else let i :: Int
i = unsafePerformIO (getStdRandom (randomR (0, (length arr) - 1)))
a = arr !! i
s1 = filter (\x -> (x < a)) arr
s2 = filter (\x -> (x >= a)) arr
rs = map nestedQuicksort [s1, s2]
-- rs'= trace (show rs) rs
in (rs !! 0) ++ (rs !! 1)
-------------------------------------------------------
--- The flat version receives as input a
--- (semantically) two-dimensional array,
--- whose representation is a 1D array of
--- 1. flags: [3,0,0,2,0,5,0,0,0,0,1] and
--- 2. data : [9,8,7,5,6,4,3,2,1,0,9], meaning:
--- the first row has 3 elements: [9,8,7]
--- the second row has 2 elements: [5,6]
--- the third row has 5 elements: [4,3,2,1,0] and
--- the fourth row has 1 element : [9]
-------------------------------------------------------
flatQuicksort :: (Ord a, Show a, Num a) => a -> [Int] -> [a] -> [a]
flatQuicksort ne sizes arr =
if reduce (&&) True $ map (\s->(s<2)) sizes then arr
else let si = scanInc (+) 0 sizes
r_inds= map (\(l,u,s)-> if s<1 then ne
else let i :: Int
i = unsafePerformIO (getStdRandom (randomR (l,u-1)))
in (arr !! i)
) (zip3 (0:si) si sizes)
rands = segmScanInc (+) ne sizes r_inds
(sizes', arr_rands) = segmSpecialFilter (\(r,x) -> (x < r)) sizes (zip rands arr)
(_,arr') = unzip arr_rands
-- arr'' = trace (show arr ++ " " ++ show sizes ++ " " ++ " " ++ show rands ++ " " ++ show arr' ++ " " ++ show sizes') arr'
in flatQuicksort ne sizes' arr'
-----------------------------------------------------
--- ASSIGNMENT 1: implement this function (below) ---
--- TASK 3. (the current implementation is ---
--- bogus, i.e., just to compile) ---
--- ---
--- Intuitive Semantics: ---
--- segmSpecialFilter odd [2,0,2,0] [4,1,3,3] ---
--- gives ([1,1,2,0],[1,4,3,3]) ---
--- [2,0,2,0] are the flags
--- [4,1,3,3] are the data
--- The first segment consists of elements ---
--- [4,1] and filtering with odd will ---
--- break it into two segments, one of ---
--- odd numbers, occuring first, and one ---
--- for even numbers. Hence the flag is ---
--- modified to [1,1] and data is ---
--- permuted to [1,4]! ---
--- The second segment consist of elements ---
--- [3,3], which are both odd, hence their--
--- flags and data remain as provided, ---
--- i.e., [2,0] and [3,3], respectivelly.---
---
--- It follows the final result should be: ---
--- (flags,data): ([1,1,2,0], [1,4,3,3]) ---
--- ---
--- IF YOU GET IT RIGHT flatQuicksort should WORK!---
-----------------------------------------------------
segmSpecialFilter :: (a->Bool) -> [Int] -> [a] -> ([Int],[a])
segmSpecialFilter cond sizes arr =
let n = length arr
cs = map cond arr
tfs = map (\f -> if f then 1
else 0) cs
ffs = map (\f->if f then 0
else 1) cs
isT = segmScanInc (+) 0 sizes tfs
isF = segmScanInc (+) 0 sizes ffs
acc_sizes = scanInc (+) 0 sizes
is = map (\s -> isT !! (s - 1)) acc_sizes
si = segmScanInc (+) 0 sizes sizes
offsets = zipWith (-) acc_sizes si
inds = map (\ (c,i,o,iT,iF) -> if c then iT+o-1 else iF+i+o-1 )
(zip5 cs is offsets isT isF)
tmp1 = map (\m -> iota m) sizes
iotas = map (+1) $ reduce (++) [] tmp1
flags = map (\(f,i,s,ri) -> if f > 0
then (if ri > 0
then ri
else f)
else (if (i-1) == ri
then s-ri
else 0)) (zip4 sizes iotas si is)
in (flags, permute inds arr)
-----------------------------------------------------
--- ASSIGNMENT 1: implement sparse matrix-vector ---
--- TASK 4a. multiplication with nested ---
--- parallelism \& test it! ---
--- Matrix: ---
--- [ 2.0, -1.0, 0.0, 0.0] ---
--- [-1.0, 2.0, -1.0, 0.0] ---
--- [ 0.0, -1.0, 2.0,-1.0] ---
--- [ 0.0, 0.0, -1.0, 2.0] ---
--- ---
--- IS REPRESENTED AS a list of lists---
--- in which the outer list has the---
--- same number of elements as the ---
--- number of rows of the matrix. ---
--- However, each row is represented--
--- as a sparse list that pairs up ---
--- each non-zero element with its ---
--- column index, as below: ---
--- ---
--- [ [(0,2.0), (1,-1.0)], ---
--- [(0,-1.0), (1, 2.0), (2,-1.0)],---
--- [(1,-1.0), (2, 2.0), (3,-1.0)],---
--- [(2,-1.0), (3, 2.0)] ---
--- ] ---
--- The vector is full and matches ---
--- the matrix number of columns, ---
--- e.g., x = [2.0, 1.0, 0.0, 3.0] ---
--- (transposed) ---
--- ALSO LOOK WHERE IT IS FUNCTION IS CALLED ---
-----------------------------------------------------
nestSparseMatVctMult :: [[(Int,Double)]] -> [Double] -> [Double]
nestSparseMatVctMult mat x =
map (\row -> sum $ (map (\(i,n) -> n*(x!!i)) row) ) mat
-----------------------------------------------------------
--- ASSIGNMENT 1: implement sparse matrix-vector ---
--- TASK 4b. multiplication with flat parallelism! ---
--- Same matrix as before has a flat ---
--- representation: flag vector (flags) & ---
--- data vector (mat ) ---
--- ALSO LOOK WHERE IT IS FUNCTION IS CALLED ---
-----------------------------------------------------------
flatSparseMatVctMult :: [Int] -> [(Int,Double)] -> [Double] -> [Double]
flatSparseMatVctMult flags mat x =
let comps = map (\(a,b) -> b*(x!!a)) mat
sums = segmScanInc (+) 0 flags comps
end_flags = tail flags ++ [head flags] -- flags now marks ends of segments.
foo = zip end_flags sums
(vals, ff) = parFilter (\(a,b) -> a == 1) foo
(_, res) = unzip $ take (head ff) vals
in res
----------------------------------------
--- MAIN ---
----------------------------------------
-- runhaskell PrimeQuicksort.hs
main :: IO()
main = do args <- getArgs
let inp = if null args then [8,14,0,12,4,10,6,2] else read (head args)
inpL = length inp
sizes= [2,0,1,4,0,0,0,1]
pinp = permute [7, 6, 5, 4, 3, 2, 1, 0] inp
vals :: [Int]
vals = [33,33,33,33]
inds = [0,2,4,6]
winp = write inds vals inp
matrix_nest = [ [(0,2.0), (1,-1.0)],
[(0,-1.0), (1, 2.0), (2,-1.0)],
[(1,-1.0), (2, 2.0), (3,-1.0)],
[(2,-1.0), (3, 2.0)]
]
matrix_flag = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]
matrix_flat = [(0,2.0), (1,-1.0), (0,-1.0), (1, 2.0), (2,-1.0), (1,-1.0), (2, 2.0), (3,-1.0), (2,-1.0), (3, 2.0)]
x_vector = [2.0, 1.0, 0.0, 3.0]
putStrLn ("Input list: "++show inp)
putStrLn ("Input flags:"++show sizes)
putStrLn ("SegmScanIncl: "++ show (segmScanInc (+) 0 sizes inp))
putStrLn ("SegmScanExcl: "++ show (segmScanExc (+) 0 sizes inp))
putStrLn ("Permuted list: "++show pinp)
putStrLn ("Written list: " ++show winp)
putStrLn (" ParFilterOdd(a/2):"++show ( parFilter (\x->odd (x `div` 2)) inp))
putStrLn ("SegmFilterOdd(a/2):"++show (segmSpecialFilter (\x->odd (x `div` 2)) sizes inp))
putStrLn ("Primes 32: " ++ show (primes 32))
putStrLn ("PrimesOpt 49: " ++ show (primesOpt 49))
putStrLn ("PrimesOpt 9: " ++ show (primesOpt 9))
putStrLn ("PrimesFlat 49: " ++ show (primesFlat 49))
putStrLn ("PrimesFlat 9: " ++ show (primesFlat 9))
putStrLn ("NestQuicksort inp: " ++ show (nestedQuicksort inp))
putStrLn ("FlatQuicksort inp: " ++ show (flatQuicksort 0 (inpL:(replicate (inpL-1) 0)) inp))
putStrLn ("Nested SparseMatrixMult: " ++ show (nestSparseMatVctMult matrix_nest x_vector))
putStrLn ("Flat SparseMatrixMult: " ++ show (flatSparseMatVctMult matrix_flag matrix_flat x_vector))
|
martinnj/PMPH2015
|
Assignment2/src/matrixmul/PrimesQuicksort.hs
|
mit
| 14,305 | 0 | 24 | 5,435 | 4,008 | 2,228 | 1,780 | 193 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module View.User where
import CMark
import Data.Monoid
import Data.Time.Clock ()
import Lucid
import Model
import Static
import View.Utils
userPage :: SessionInfo -> SUser -> [Snippet] -> Html ()
userPage u u' ss = doctypehtml_ . html_ $ do
pageTitle $ sUserName u' <> " | jsm"
body_ $ do
topBar u
div_ [class_ "Content"] $ do
h1_ $ do
span_ "Email: "
let email = sUserEmail u'
a_ [href_ $ "mailto:" <> email] $ toHtml email
toHtmlRaw $ commonmarkToHtml [] (sUserDesc u')
div_ [class_ "Content"] $ do
h1_ . toHtml $ sUserName u' <> "'s snippets:"
ul_ $ mapM_ (li_ [class_ "Code"] . codePreview) ss
script_ userPageScript
|
winterland1989/jsmServer
|
src/View/User.hs
|
mit
| 868 | 0 | 21 | 323 | 263 | 126 | 137 | 24 | 1 |
{-# LANGUAGE RankNTypes #-}
module Universe.Worker where
import Control.Lens hiding (universe)
import Data.Map
import Data.Maybe
import Universe
import Player
import Worker
import Workplace
getWorkers :: Universe -> PlayerId -> [WorkerId]
getWorkers universe player = toListOf (players . ix player . workers . folding keys) universe
getWorkerWorkplace :: Universe -> WorkerId -> Maybe WorkplaceId
getWorkerWorkplace universe workerId = universe ^? (players . traverse . workers . ix workerId . currentWorkplace . traverse)
getWorkerStrength :: Universe -> WorkerId -> WorkerStrength
getWorkerStrength universe workerId = fromMaybe 0 $ universe ^? (players . traverse . workers . ix workerId . workerStrength)
workerWorking :: WorkerState -> Bool
workerWorking = isJust . view currentWorkplace
inWorkplace :: (Choice p, Applicative f) => WorkplaceId -> Optic' p f WorkerState WorkerState
inWorkplace workplaceId = filtered (has $ currentWorkplace . filtered (== Just workplaceId))
newWorkerId :: Universe -> WorkerId
newWorkerId universe = WorkerId (maximum workerNumbers + 1)
where getNumberFromId (WorkerId number) = number
workerNumbers = toListOf (players . traverse . workers . to keys . traverse . to getNumberFromId) universe
|
martin-kolinek/some-board-game-rules
|
src/Universe/Worker.hs
|
mit
| 1,250 | 0 | 13 | 188 | 375 | 194 | 181 | 23 | 1 |
module GHCJS.DOM.SVGGlyphRefElement (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/SVGGlyphRefElement.hs
|
mit
| 48 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
module SemanticSpec where
import Text.Parsec.Pos
import Test.Hspec
import Data.List hiding(find)
import qualified Data.Map as M
import Control.Monad.State.Strict
import Control.Exception
import AST
import Parser
import Environment
import AnalyzedAST
import Semantic
u :: SourcePos
u = newPos "test" 0 0
run :: String -> IO A_Program
run test = do
ast <- parseProgram ("SemanticTest/" ++ test)
return $ fst (runEnv (analyze ast) M.empty)
spec :: Spec
spec = do
describe "Environment" $ do
it "detect duplicate decralations" $ do
run "test_0.c" `shouldThrow` anyException
run "test_1.c" `shouldThrow` anyException
run "test_2.c" `shouldThrow` anyException
run "test_3.c" `shouldThrow` anyException
it "detect invalid reference" $ do
run "test_4.c" `shouldThrow` anyException
run "test_5.c" `shouldThrow` anyException
it "detect type error" $ do
run "test_6.c" `shouldThrow` anyException
run "test_7.c" `shouldThrow` anyException
run "test_8.c" `shouldThrow` anyException
run "test_9.c" `shouldThrow` anyException
run "test_10.c" `shouldThrow` anyException
run "test_11.c" `shouldThrow` anyException
run "test_12.c" `shouldThrow` anyException
run "test_13.c" `shouldThrow` anyException
run "test_14.c" `shouldThrow` anyException
run "test_15.c" `shouldThrow` anyException
run "test_16.c" `shouldThrow` anyException
|
yu-i9/HaSC
|
test/SemanticSpec.hs
|
mit
| 1,439 | 0 | 14 | 284 | 395 | 204 | 191 | 41 | 1 |
{-# LANGUAGE CPP, NoImplicitPrelude, PackageImports #-}
module Foreign.Compat (
module Base
) where
import "base-compat" Foreign.Compat as Base
|
haskell-compat/base-compat
|
base-compat-batteries/src/Foreign/Compat.hs
|
mit
| 147 | 0 | 4 | 21 | 21 | 15 | 6 | 4 | 0 |
{-# LANGUAGE
OverloadedStrings
, LambdaCase
#-}
module Main
( main
) where
import Data.List
import System.Environment
import System.Exit
import qualified Data.Map.Strict as M
import CommandClean
import CommandInstall
import CommandSwitch
-- succeed as long as the given key matches exactly one result (by prefix)
uniqueLookup :: Eq ke => [ke] -> M.Map [ke] v -> Maybe v
uniqueLookup k m = case filter ((k `isPrefixOf`) . fst) $ M.toList m of
[(_,v)] -> Just v
_ -> Nothing
subCmds :: M.Map String (IO ())
subCmds = M.fromList
[ ("switch", cmdSwitch)
, ("install", cmdInstall)
, ("clean", cmdClean)
]
{-
TODO: update this tool to only deal with grub2, which can simplify the workflow a little.
This is not to say that grub2 is in any way good,
a garbage is still a garbage, just that it's less convenient avoiding using it.
-}
main :: IO ()
main = getArgs >>= \case
[cmd] | Just action <- uniqueLookup cmd subCmds -> action
_ -> do
putStrLn $ "kernel-tool <" <> intercalate "|" (M.keys subCmds) <> ">"
exitFailure
|
Javran/misc
|
kernel-tool/src/Main.hs
|
mit
| 1,064 | 0 | 16 | 225 | 286 | 156 | 130 | 27 | 2 |
module P003 where
import Euler
solution :: EulerType
solution = Left . last $ factors 600851475143
main = printEuler solution
|
Undeterminant/euler-haskell
|
P003.hs
|
cc0-1.0
| 126 | 0 | 6 | 20 | 36 | 20 | 16 | 5 | 1 |
module Stl.StlFileWriter(writeStlToFile, writeStlDebugToFile)
where
import Stl.StlBase(stlShapeToText, StlShape(..))
import CornerPoints.Debug((+++^?), (++^?), CubeName(..), CubeDebug(..), CubeDebugs(..), showDebugMsg)
import System.IO
{-
Writes the temp.stl file to /src/Data/temp.stl folder when run from emacs repl.
Should have a config file in which this can be set.
given:
shape: an StlShape generated form a file such as HeelGenerators, or Sockets
return:
null as it is an IO() action.
temp.stl file with the stlShape written to it. Will overrite whatever was in the file.
Fails if file does not already exist.
Known uses:
All code which outputs the final stl, uses this to write the stl file.
-}
writeStlToFile :: StlShape -> IO()
writeStlToFile shape = writeFile "src/Data/temp.stl" $ stlShapeToText shape
{-
Writes the debug.txt file to src/Data/debug.txt folder when run from emacs repl.
Should have a config file in which this can be set.
given:
shape: an [CubeDebug] generated from a file such as HeelGenerators, or Sockets
return:
null as it is an IO() action.
debug.txt file with the CubeDebug written to it. Will overrite whatever was in the file.
Fails if file does not already exist.
Needs to be formatted with /n. Should it be done here or in the CornerPointsDebug module?
Known uses:
BlackRunnerHeel uses this to write of the stl file.
-}
writeStlDebugToFile :: [CubeDebug] -> IO()
writeStlDebugToFile debugs = writeFile "src/Data/debug.txt" $ show debugs
|
heathweiss/Tricad
|
src/Stl/StlFileWriter.hs
|
gpl-2.0
| 1,499 | 0 | 7 | 245 | 146 | 86 | 60 | 8 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
{- |
Module : ./GUI/HTkUtils.hs
Copyright : (c) K. Luettich, Rene Wagner, Uni Bremen 2002-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports HTk)
Utilities on top of HTk
-}
module GUI.HTkUtils
( LBGoalView (..)
, LBStatusIndicator (..)
, EnableWid (..)
, GUIMVar
, listBox
, errorMess
, confirmMess
, messageMess
, askFileNameAndSave
, createTextSaveDisplay
, newFileDialogStr
, fileDialogStr
, displayTheoryWithWarning
, populateGoalsListBox
, indicatorFromProofStatus
, indicatorFromBasicProof
, indicatorString
, enableWids
, disableWids
, enableWidsUponSelection
, module X
) where
import System.Directory
import Util.Messages
import HTk.Toplevel.HTk as X hiding (x, y)
import HTk.Toolkit.ScrollBox as X
import HTk.Toolkit.SimpleForm as X
import HTk.Toolkit.TextDisplay as X
import HTk.Toolkit.FileDialog
import Logic.Prover
import Static.GTheory
import Common.DocUtils
import Control.Concurrent.MVar
-- ** some types
-- | Type for storing the proof management window
type GUIMVar = MVar (Maybe Toplevel)
-- | create a window with title and list of options, return selected option
listBox :: String -> [String] -> IO (Maybe Int)
listBox title entries =
do
main <- createToplevel [text title]
lb <- newListBox main [value entries, bg "white", size (100, 39)] ::
IO (ListBox String)
pack lb [Side AtLeft, Expand On, Fill Both]
scb <- newScrollBar main []
pack scb [Side AtRight, Fill Y]
lb # scrollbar Vertical scb
(press, _) <- bindSimple lb (ButtonPress (Just 1))
(closeWindow, _) <- bindSimple main Destroy
sync ( (press >>> do
sel <- getSelection lb
destroy main
return (case sel of
Just [i] -> Just i
_ -> Nothing) )
+> (closeWindow >>> do
destroy main
return Nothing ))
{- |
Display some (longish) text in an uneditable, scrollable editor.
Returns immediately-- the display is forked off to separate thread. -}
createTextSaveDisplayExt :: String -- ^ title of the window
-> String -- ^ default filename for saving the text
-> String -- ^ text to be displayed
-> [Config Editor] {- ^ configuration options for
the text editor -}
-> IO () {- ^ action to be executed when
the window is closed -}
-> IO (Toplevel, Editor) {- ^ the window in which
the text is displayed -}
createTextSaveDisplayExt title fname txt conf upost =
do win <- createToplevel [text title]
b <- newFrame win [relief Groove, borderwidth (cm 0.05)]
t <- newLabel b [text title, font (Helvetica, Roman, 18 :: Int)]
q <- newButton b [text "Close", width 12]
s <- newButton b [text "Save", width 12]
(sb, ed) <- newScrollBox b (`newEditor` conf) []
ed # state Disabled
pack b [Side AtTop, Fill Both, Expand On]
pack t [Side AtTop, Expand Off, PadY 10]
pack sb [Side AtTop, Expand On, Fill Both]
pack ed [Side AtTop, Expand On, Fill Both]
pack q [Side AtRight, PadX 8, PadY 5]
pack s [Side AtLeft, PadX 5, PadY 5]
ed # state Normal
ed # value txt
ed # state Disabled
forceFocus ed
(editClicked, _) <- bindSimple ed (ButtonPress (Just 1))
quit <- clicked q
save <- clicked s
_ <- spawnEvent $ forever $ quit >>> (destroy win >> upost)
+> save >>> do
disableButs q s
askFileNameAndSave fname txt
enableButs q s
done
+> editClicked >>> forceFocus ed
return (win, ed)
where disableButs b1 b2 = disable b1 >> disable b2
enableButs b1 b2 = enable b1 >> enable b2
{- |
Display some (longish) text in an uneditable, scrollable editor.
Simplified version of createTextSaveDisplayExt -}
createTextSaveDisplay :: String -- ^ title of the window
-> String -- ^ default filename for saving the text
-> String -- ^ text to be displayed
-> IO ()
createTextSaveDisplay t f txt = do
createTextSaveDisplayExt t f txt [size (100, 44)] done
done
{- - added by KL
opens a FileDialog and saves to the selected file if OK is clicked
otherwise nothing happens -}
askFileNameAndSave :: String -- ^ default filename for saving the text
-> String -- ^ text to be saved
-> IO ()
askFileNameAndSave defFN txt =
do curDir <- getCurrentDirectory
selev <- newFileDialogStr "Save file" (curDir ++ '/' : defFN)
mfile <- sync selev
maybe done saveFile mfile
where saveFile fp = writeFile fp txt
{- | returns a window displaying the given theory and the given
warning text.
-}
displayTheoryWithWarning :: String -- ^ kind of theory
-> String -- ^ name of theory
-> String -- ^ warning text
-> G_theory -- ^ to be shown theory
-> IO ()
displayTheoryWithWarning kind thname warningTxt gth =
let str = warningTxt ++ showDoc gth "\n"
title = kind ++ " of " ++ thname
in createTextSaveDisplay title (thname ++ ".het") str
{- - added by RW
Represents the state of a goal in a 'ListBox' that uses 'populateGoalsListBox'
-}
data LBStatusIndicator = LBIndicatorProved
| LBIndicatorProvedInconsistent
| LBIndicatorDisproved
| LBIndicatorOpen
| LBIndicatorGuessed
| LBIndicatorConjectured
| LBIndicatorHandwritten
{- |
Converts a 'LBStatusIndicator' into a short 'String' representing it in
a 'ListBox' -}
indicatorString :: LBStatusIndicator
-> String
indicatorString i = case i of
LBIndicatorProved -> "[+]"
LBIndicatorProvedInconsistent -> "[*]"
LBIndicatorDisproved -> "[-]"
LBIndicatorOpen -> "[ ]"
LBIndicatorGuessed -> "[.]"
LBIndicatorConjectured -> "[:]"
LBIndicatorHandwritten -> "[/]"
{- |
Represents a goal in a 'ListBox' that uses 'populateGoalsListBox' -}
data LBGoalView = LBGoalView { -- | status indicator
statIndicator :: LBStatusIndicator,
-- | description
goalDescription :: String
}
{- |
Populates a 'ListBox' with goals. After the initial call to this function
the number of goals is assumed to remain constant in ensuing calls. -}
populateGoalsListBox :: ListBox String -- ^ listbox
-> [LBGoalView] {- ^ list of goals
length must remain constant after the first call -}
-> IO ()
populateGoalsListBox lb v = do
selectedOld <- getSelection lb :: IO (Maybe [Int])
lb # value (toString v)
maybe (return ()) (mapM_ (`selection` lb)) selectedOld
where
toString = map (\ LBGoalView {statIndicator = i, goalDescription = d} ->
indicatorString i ++ ' ' : d)
-- | Converts a 'Logic.Prover.ProofStatus' into a 'LBStatusIndicator'
indicatorFromProofStatus :: ProofStatus a
-> LBStatusIndicator
indicatorFromProofStatus st = case goalStatus st of
Proved c -> if c then LBIndicatorProved else LBIndicatorProvedInconsistent
Disproved -> LBIndicatorDisproved
Open _ -> LBIndicatorOpen
-- | Converts a 'BasicProof' into a 'LBStatusIndicator'
indicatorFromBasicProof :: BasicProof
-> LBStatusIndicator
indicatorFromBasicProof p = case p of
BasicProof _ st -> indicatorFromProofStatus st
Guessed -> LBIndicatorGuessed
Conjectured -> LBIndicatorConjectured
Handwritten -> LBIndicatorHandwritten
-- | existential type for widgets that can be enabled and disabled
data EnableWid = forall wid . HasEnable wid => EnW wid
enableWids :: [EnableWid] -> IO ()
enableWids = mapM_ $ \ ew -> case ew of
EnW w -> enable w >> return ()
disableWids :: [EnableWid] -> IO ()
disableWids = mapM_ $ \ ew -> case ew of
EnW w -> disable w >> return ()
{- | enables widgets only if at least one entry is selected in the listbox,
otherwise the widgets are disabled -}
enableWidsUponSelection :: ListBox String -> [EnableWid] -> IO ()
enableWidsUponSelection lb goalSpecificWids =
(getSelection lb :: IO (Maybe [Int])) >>=
maybe (disableWids goalSpecificWids)
(const $ enableWids goalSpecificWids)
|
gnn/Hets
|
GUI/HTkUtils.hs
|
gpl-2.0
| 8,693 | 0 | 20 | 2,509 | 1,947 | 995 | 952 | 172 | 7 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE ScopedTypeVariables, RankNTypes, FlexibleInstances #-}
module UnfoldSpec(main, spec) where
import Test.Hspec
import Test.QuickCheck
import Control.Applicative
import Data.Monoid
import Data.Functor.Identity
import Data.Function(on)
import Unfold
main :: IO ()
main = hspec spec
instance Arbitrary a => Arbitrary (Unfold a) where
arbitrary = unfold <$> (vector 10 :: Gen [a]) <*> pure unfoldList
shrink = fmap (\l -> unfold l unfoldList) . shrink . toList
instance (Arbitrary a) => Arbitrary (UnfoldT Identity a) where
arbitrary = (UnfoldT . return) <$> arbitrary
shrink = fmap (UnfoldT . Identity) . shrink . runIdentity . runUnfoldT
instance Show a => Show (UnfoldT Identity a) where
show = show . runIdentity . runUnfoldT
instance Eq a => Eq (UnfoldT Identity a) where
(==) = (==) `on` (runIdentity . runUnfoldT)
spec :: Spec
spec = do
describe "An Unfold" $ do
it "can be unfolded step by step" $ do
let u0 = unfold [1..10 :: Int] unfoldList
Yield a1 u1 = next u0
a1 `shouldBe` 1
let Yield a2 _ = next u1
a2 `shouldBe` 2
functorProperty fromList toList
applicativeProperty fromList toList
monadProperty fromList toList
monoidProperty fromList toList
describe "An UnfoldT" $ do
let fromListT = UnfoldT . Identity . fromList
toListT = toList . runIdentity . runUnfoldT
functorProperty fromListT toListT
applicativeProperty fromListT toListT
monadProperty fromListT toListT
monoidProperty fromListT toListT
functorProperty :: forall f. (Show (f Int), Eq (f Int), Functor f, Arbitrary (f Int))
=> (forall a. [a] -> f a) -> (forall a. f a -> [a]) -> Spec
functorProperty fromList' toList' =
context "when used as a Functor" $ do
it "mappes the values correctly" $
property $ \(l :: [Int]) -> toList' (fmap (*2) (fromList' l)) == [2*x | x <- l]
it "preserves identity" $
property $ \(u :: f Int) -> fmap id u == u
it "is a homomorphism" $
property $ \(i :: Int) (j :: Int) (u :: f Int) ->
let f = (*i)
g = (+j)
in fmap (f . g) u == fmap f (fmap g u)
applicativeProperty :: forall f. (Show (f Int), Eq (f Int), Applicative f, Arbitrary (f Int))
=> (forall a. [a] -> f a) -> (forall a. f a -> [a]) -> Spec
applicativeProperty fromList' toList' =
context "when used as an Applicative" $ do
it "mappes the values correctly" $
property $ \(l :: [Int]) ->
let u = fromList' l
in toList' ((*) <$> pure 2 <*> u) == [2*x | x <- l]
it "preserves identity" $
property $ \(u :: f Int) -> toList' (pure id <*> u) == toList' u
it "is closed under composition" $
property $ \(i :: Int) (j :: Int) (u :: f Int) ->
let f = pure (*i)
g = pure (+j)
in (pure (.) <*> f <*> g <*> u) == (f <*> (g <*> u))
it "is an homomorphism" $
property $ \(i :: Int) (x :: Int) ->
let f = (*i)
in (pure f <*> pure x :: f Int) == pure (f x)
it "can interchange function and argument" $
property $ \(i :: Int) (x :: Int) ->
let f = pure (*i)
in (f <*> pure x :: f Int) == (pure ($ x) <*> f)
monadProperty :: forall f. (Show (f Int), Eq (f Int), Monad f, Arbitrary (f Int))
=> (forall a. [a] -> f a) -> (forall a. f a -> [a]) -> Spec
monadProperty fromList' toList' =
context "when used as a monad" $ do
it "binds correctly" $
property $ \(l :: [Int]) ->
let u = fromList' l
in toList' (u >>= (\a -> return $ 2 * a)) == [2*x | x <- l]
it "preserves left application" $
property $ \(i :: Int) (x :: Int) ->
let f = return . (*i)
in (return x >>= f :: f Int) == f x
it "preserves right identity" $
property $ \(u :: f Int) ->
(u >>= return) == u
it "preserves associativity" $
property $ \(i :: Int) (j :: Int) (u :: f Int) ->
let f = return . (*i)
g = return . (+j)
in (u >>= (\x -> f x >>= g)) == ((u >>= f) >>= g)
monoidProperty :: forall f. (Show (f Int), Eq (f Int), Monoid (f Int), Arbitrary (f Int))
=> (forall a. [a] -> f a) -> (forall a. f a -> [a]) -> Spec
monoidProperty fromList' toList' =
context "when used as a Monoid" $ do
it "appends the values correctly" $
property $ \(l :: [Int]) (k :: [Int]) ->
let list l' = fromList' l'
in toList' (list l `mappend` list k) == l `mappend` k
it "preserves right identity" $
property $ \(u :: f Int) ->
u `mappend` mempty == u
it "preserves left identity" $
property $ \(u :: f Int) ->
mempty `mappend` u == u
it "preserves associativity" $
property $ \(u :: f Int) (v :: f Int) (w :: f Int)->
(u `mappend` v) `mappend` w == u `mappend` (v `mappend` w)
|
svenkeidel/gnome-citadel
|
test/UnfoldSpec.hs
|
gpl-3.0
| 4,887 | 0 | 19 | 1,417 | 2,173 | 1,119 | 1,054 | 115 | 1 |
{-
Author: Ka Wai
License: GPL 3.0
File: OutputModel.hs
Description: outputs a graph representing the given model
-}
module OutputModel where
import Data.List
import qualified Data.Map as Map
import System.Cmd
import System.Directory
import Signature
import Model
import ProofSearch
-- Creates visual graph of model in specified format
outputModel :: Model -> FilePath -> String -> IO ()
outputModel model filename format
= do writeModel (filename ++ ".dot") model
rawSystem "dot" ["-T" ++ format, filename ++ ".dot", "-o", filename ++ "." ++ format]
removeFile (filename ++ ".dot")
return ()
{-
Output string of DOT language that draws model
WARNING: assumes the model is already checked & correct
-}
modelToGraph :: Model -> String
modelToGraph ([], _, _)
= "digraph {\n label = \"Domain is empty, no model to draw\" ;\n}"
modelToGraph (dom, us, bs)
| length dom /= length (nub dom) =
begin ++ "label = \"Domain contains duplicated individuals\" ;\n" ++ end
| not $ isUnique us =
begin ++ "label = \"Duplicated unary relation names exist\" ;\n" ++ end
| not $ isUnique bs =
begin ++ "label = \"Duplicated binary relation names exist\" ;\n" ++ end
| otherwise =
begin ++ concat ulabels ++ domOnlyToGraph (dom \\ unodes) ++
concatMap drawEdges bs ++ end
where (unodes, ulabels) = unaryToGraph $ mapUnary us Map.empty
begin = "digraph {\n "
end = "}"
-- Returns true if there is only 1 occurrence of the fst of the pairs in the list
isUnique :: [(String, a)] -> Bool
isUnique xs = length xs == length (nub . fst $ unzip xs)
-- Draws edges for a binary relation
drawEdges :: (String, [(Individual, Individual)]) -> String
drawEdges (_, []) = []
drawEdges (r, (p,c):es)
= concat [show p, " -> ", show c, " [label=\"", r, "\"] ;\n ",
drawEdges (r, nub es \\ [(p,c)])]
-- Returns string that draws all individuals that are not in unary relations
domOnlyToGraph :: [Individual] -> String
domOnlyToGraph ds
= concat [show i ++ " [label=\"" ++ show i ++ "\"] ;\n " | i <- ds]
-- Returns string to label every unary in the
unaryToGraph :: Map.Map Individual [String] -> ([Individual], [String])
unaryToGraph m
= unzip [(k, show k ++ " [label=\"" ++ show k ++ ": " ++
intercalate ", " (addnewlines a) ++ "\"] ;\n ")
| (k, a) <- Map.toList m ]
-- Ensures node is not too large
-- Adds a newline after every 8 characters (specified by max's assigned value)
addnewlines :: [String] -> [String]
addnewlines [] = []
addnewlines (c:cs)
| index == 0 = (pre ++ "-\\n" ++ newsuf) : newtail
| rest == [] = c:cs
| otherwise = line ++ (("\\n" ++ head newrest) : tail newrest)
where (line, rest) = splitAt index (c:cs)
acculength = scanl1 ((+) . (+2)) $ map length (c:cs)
-- acculength = zipWith (+) [2,4..] $ scanl1 (+) $ map length (c:cs)
index = length $ takeWhile (<=max) acculength
(pre, suf) = splitAt (max-1) c
max = 8
(newsuf:newtail) = addnewlines (suf:cs)
newrest = addnewlines rest
-- Collects all dot labels
mapUnary :: [UnaryRelation] -> Map.Map Individual [String]
-> Map.Map Individual [String]
mapUnary [] m = m
mapUnary ((u,is):xs) m = mapUnary xs $ addToIndividual u is m
-- Add unary to all individuals satisfying
addToIndividual :: String -> [Individual] -> Map.Map Individual [String]
-> Map.Map Individual [String]
addToIndividual u [] m = m
addToIndividual u (i:is) m = Map.insertWith (++) i [u] $ addToIndividual u is m
-- Writes graph to file.
writeModel :: FilePath -> Model -> IO()
writeModel filename = writeFile (filename) . modelToGraph
|
j5b/ps-pc
|
OutputModel.hs
|
gpl-3.0
| 3,710 | 0 | 13 | 863 | 1,165 | 617 | 548 | 68 | 1 |
fmap f ma = ma >>= \a -> return (f a)
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.4/code/haskell/snippet15.hs
|
gpl-3.0
| 37 | 0 | 9 | 10 | 29 | 14 | 15 | 1 | 1 |
module Response.Loading
(loadingResponse) where
import qualified Data.Text as T
import Happstack.Server
import MasterTemplate
import Text.Blaze ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
loadingResponse :: T.Text -> ServerPart Response
loadingResponse size =
ok $ toResponse $
masterTemplate "Courseography - Loading..."
[]
(do
header "Loading..."
if size == "small"
then smallLoadingIcon
else largeLoadingIcon
)
""
{- Insert a large loading icon into the page -}
largeLoadingIcon :: H.Html
largeLoadingIcon = H.div ! A.id "loading-icon" $ do
H.img ! A.id "c-logo" ! A.src "/static/res/img/C-logo.png"
H.img ! A.id "compass" ! A.class_ "spinner" ! A.src "/static/res/img/compass.png"
{- Insert a small loading icon into the page -}
smallLoadingIcon :: H.Html
smallLoadingIcon = H.div ! A.id "loading-icon" $ do
H.img ! A.id "c-logo-small" ! A.src "/static/res/img/C-logo-small.png"
H.img ! A.id "compass-small" ! A.class_ "spinner" ! A.src "/static/res/img/compass-small.png"
|
Courseography/courseography
|
app/Response/Loading.hs
|
gpl-3.0
| 1,251 | 0 | 12 | 356 | 289 | 151 | 138 | 27 | 2 |
{-# LANGUAGE DeriveGeneric #-}
module Estuary.Tidal.Types where
import Data.List as List (intercalate, zip)
import Data.Map.Strict as Map
import Data.Ratio
import GHC.Generics
import Data.Aeson
import Estuary.Types.Live
data RepOrDiv = Once | Rep Int | Div Int deriving (Eq,Generic)
instance ToJSON RepOrDiv where
toEncoding = genericToEncoding defaultOptions
instance FromJSON RepOrDiv
instance Show RepOrDiv where
show Once = ""
show (Rep n) = "*" ++ (show n)
show (Div n) = "/" ++ (show n)
data Potential a = Potential a | PotentialDelete
| PotentialMakeGroup | PotentialMakeLayer | PotentialLiveness Liveness
| Inert | PotentialRepOrDiv| Potentials [Potential a] deriving (Eq,Show,Generic)
instance ToJSON a => ToJSON (Potential a) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON a => FromJSON (Potential a)
data GeneralPattern a =
Atom a (Potential a) RepOrDiv |
Blank (Potential a) |
Group (Live ([GeneralPattern a],RepOrDiv)) (Potential a) |
Layers (Live ([GeneralPattern a],RepOrDiv)) (Potential a) |
TextPattern String
deriving (Eq,Generic)
instance ToJSON a => ToJSON (GeneralPattern a) where
toEncoding = genericToEncoding defaultOptions
instance FromJSON a => FromJSON (GeneralPattern a)
isGroup :: GeneralPattern a -> Bool
isGroup (Group _ _)= True
isGroup _ = False
isLayers :: GeneralPattern a -> Bool
isLayers (Layers _ _) = True
isLayers _ = False
isAtom :: GeneralPattern a -> Bool
isAtom (Atom _ _ _) = True
isAtom _ = False
isBlank :: GeneralPattern a -> Bool
isBlank (Blank _) = True
isBlank _ = False
generalPatternIsEmptyFuture :: GeneralPattern a -> Bool
generalPatternIsEmptyFuture (Atom _ _ _) = False
generalPatternIsEmptyFuture (Blank _) = True
generalPatternIsEmptyFuture (Group (Live (xs,_) _) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyFuture (Group (Edited _ (xs,_)) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyFuture (Layers (Live (xs,_) _) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyFuture (Layers (Edited _ (xs,_)) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyFuture (TextPattern x) = length x == 0
generalPatternIsEmptyPast :: GeneralPattern a -> Bool
generalPatternIsEmptyPast (Atom _ _ _) = False
generalPatternIsEmptyPast (Blank _) = True
generalPatternIsEmptyPast (Group (Live (xs,_) _) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyPast (Group (Edited (xs,_) _) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyPast (Layers (Live (xs,_) _) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyPast (Layers (Edited (xs,_) _) _) = and $ fmap generalPatternIsEmptyFuture xs
generalPatternIsEmptyPast (TextPattern x) = length x == 0
showNoQuotes :: (Show a) => a -> String
showNoQuotes x = if ((head x'=='"' && (last x')=='"') || (head x'== '\'' && last x'=='\'')) then if x''=="" then "~" else x'' else show x
where x' = show x
x''=(tail (init x'))
instance Show a => Show (GeneralPattern a) where
show (Atom a _ r) = (showNoQuotes a) ++ (show r)
show (Blank _) = "~"
show (Group (Live ([],r) _) _) = ""
show (Group (Live (xs,r) _) _) = "[" ++ (intercalate " " $ Prelude.map (show) xs) ++ "]" ++ (show r)
show (Group (Edited ([],r) _) _) = ""
show (Group (Edited (xs,r) _) _) = "[" ++ (intercalate " " $ Prelude.map (show) xs) ++ "]" ++ (show r)
show (Layers (Live ([],r) _) _) = ""
show (Layers (Live (xs,r) _) _) = "[" ++ (intercalate ", " $ Prelude.map (show) xs) ++ "]" ++ (show r)
show (Layers (Edited ([],r) _) _) = ""
show (Layers (Edited (xs,r) _) _) = "[" ++ (intercalate ", " $ Prelude.map (show) xs) ++ "]" ++ (show r)
show (TextPattern x) = Prelude.filter (not . (`elem` "?")) x
type SampleName = String
newtype Sample = Sample (SampleName,Int) deriving (Eq,Generic)
instance ToJSON Sample where
toEncoding = genericToEncoding defaultOptions
instance FromJSON Sample
instance Show Sample where
show (Sample (x,0)) = showNoQuotes x
show (Sample (x,y)) = (showNoQuotes x) ++ ":" ++ (show y)
data SpecificPattern = Accelerate (GeneralPattern Double) | Bandf (GeneralPattern Int)
| Bandq (GeneralPattern Double) | Begin (GeneralPattern Double) | Coarse (GeneralPattern Int)
| Crush (GeneralPattern Int) | Cut (GeneralPattern Int) | Cutoff (GeneralPattern Int)
| Delay (GeneralPattern Double) | Delayfeedback (GeneralPattern Double) | Delaytime (GeneralPattern Double)
| End (GeneralPattern Double) | Gain (GeneralPattern Double) | Hcutoff (GeneralPattern Int)
| Hresonance (GeneralPattern Double) | Loop (GeneralPattern Int) | N (GeneralPattern Int)
| Pan (GeneralPattern Double)
| Resonance (GeneralPattern Double) | S (GeneralPattern SampleName) | Shape (GeneralPattern Double)
| Sound (GeneralPattern Sample) | Speed (GeneralPattern Double) | Unit (GeneralPattern Char)
| Up (GeneralPattern Double) | Vowel (GeneralPattern Char) deriving (Eq,Generic)
instance Show SpecificPattern where
show (Accelerate x) = "accelerate \"" ++ (show x) ++ "\""
show (Bandf x) = "bandf \"" ++ (show x) ++ "\""
show (Bandq x) = "bandq \"" ++ (show x) ++ "\""
show (Begin x) = "begin \"" ++ (show x) ++ "\""
show (Coarse x) = "coarse \"" ++ (show x) ++ "\""
show (Crush x) = "crush \"" ++ (show x) ++ "\""
show (Cut x) = "cut \"" ++ (show x) ++ "\""
show (Cutoff x) = "cutoff \"" ++ (show x) ++ "\""
show (Delay x) = "delay \"" ++ (show x) ++ "\""
show (Delayfeedback x) = "delayfeedback \"" ++ (show x) ++ "\""
show (Delaytime x) = "delaytime \"" ++ (show x) ++ "\""
show (End x) = "end \"" ++ (show x) ++ "\""
show (Gain x) = "gain \"" ++ (show x) ++ "\""
show (Hcutoff x) = "hcutoff \"" ++ (show x) ++ "\""
show (Hresonance x) = "hresonane \"" ++ (show x) ++ "\""
show (Loop x) = "loop \"" ++ (show x) ++ "\""
show (N x) = "n \"" ++ (show x) ++ "\""
show (Pan x) = "pan \"" ++ (show x) ++ "\""
show (Resonance x) = "resonance \"" ++ (show x) ++ "\""
show (S x) = "s \"" ++ (show x) ++ "\""
show (Shape x) = "shape \"" ++ (show x) ++ "\""
show (Sound x) = "sound \"" ++ (show x) ++ "\""
show (Speed x) = "speed \"" ++ (show x) ++ "\""
show (Unit x) = "unit \"" ++ (show x) ++ "\""
show (Up x) = "up \"" ++ (show x) ++ "\""
show (Vowel x) = "vowel \"" ++ (show x) ++ "\""
instance ToJSON SpecificPattern where
toEncoding = genericToEncoding defaultOptions
instance FromJSON SpecificPattern
emptySPattern :: SpecificPattern
emptySPattern = S (Blank Inert)
data PatternCombinator = Merge | Add | Subtract | Multiply | Divide deriving (Eq,Read,Generic)
instance ToJSON PatternCombinator where
toEncoding = genericToEncoding defaultOptions
instance FromJSON PatternCombinator
instance Show PatternCombinator where
show (Merge) = "|=|"
show (Add) = "|+|"
show (Subtract) = "|-|"
show (Multiply) = "|*|"
show (Divide) = "|/|"
data PatternTransformer =
NoTransformer |
Rev |
Slow Rational |
Density Rational |
Degrade |
DegradeBy Double |
Every Int PatternTransformer |
Brak |
Jux PatternTransformer |
Chop Int |
Combine SpecificPattern PatternCombinator
deriving (Eq,Generic)
instance Show PatternTransformer where
show NoTransformer = ""
show Rev = "rev"
show (Slow f) = "slow " ++ (show f)
show (Density f) = "density " ++ (show f)
show Degrade = "degrade"
show (DegradeBy f) = "degradeBy " ++ (show f)
show (Every n t) = "every " ++ (show n) ++ "(" ++ show t ++ ")"
show (Brak) = "brak"
show (Jux f) = "jux (" ++ (show f) ++ ")"
show (Chop i) = "chop (" ++ (show i) ++ ")"
show (Combine p c) = (show p) ++ " " ++ (show c) ++ " "
instance ToJSON PatternTransformer where
toEncoding = genericToEncoding defaultOptions
instance FromJSON PatternTransformer
data TransformedPattern =
TransformedPattern PatternTransformer TransformedPattern |
UntransformedPattern SpecificPattern |
EmptyTransformedPattern
deriving (Eq,Generic)
instance Show TransformedPattern where
show (TransformedPattern t p) = (show t) ++ " " ++ (show p)
show (UntransformedPattern u) = (show u)
show (EmptyTransformedPattern) = ""
instance ToJSON TransformedPattern where
toEncoding = genericToEncoding defaultOptions
instance FromJSON TransformedPattern
data StackedPatterns = StackedPatterns [TransformedPattern] deriving (Eq,Generic)
instance ToJSON StackedPatterns where
toEncoding = genericToEncoding defaultOptions
instance FromJSON StackedPatterns
instance Show StackedPatterns where
show (StackedPatterns xs) = "stack [" ++ (intercalate ", " (Prelude.map show xs)) ++ "]"
|
d0kt0r0/estuary
|
common/src/Estuary/Tidal/Types.hs
|
gpl-3.0
| 8,625 | 0 | 12 | 1,588 | 3,534 | 1,832 | 1,702 | 182 | 3 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Language.Slicer.Primitives
( -- * Built-in primitive operators and functions
Primitive(..), isInfixOp, acceptsExns
) where
import Control.DeepSeq ( NFData )
import GHC.Generics ( Generic )
import Text.PrettyPrint.HughesPJClass
data Primitive
-- Arithmetic operators
= OpPlus | OpMinus | OpTimes | OpDiv | OpMod
-- Integer and boolean comparisons
| OpEq | OpNeq
-- Integer comparisons
| OpLt | OpGt | OpLeq | OpGeq
-- Logical operators
| OpAnd | OpOr | OpNot
-- Builtin functions
| PrimBwdSlice | PrimTraceSlice | PrimVal
deriving (Eq, Ord, Generic, NFData)
instance Show Primitive where
-- Arithmetic operators
show OpPlus = "+"
show OpMinus = "-"
show OpTimes = "*"
show OpDiv = "/"
show OpMod = "%"
-- Integer and boolean comparisons
show OpEq = "=="
show OpNeq = "/="
-- Integer comparisons
show OpLt = "<"
show OpGt = ">"
show OpLeq = "<="
show OpGeq = ">="
-- Logical operators
show OpAnd = "&&"
show OpOr = "||"
show OpNot = "not"
-- Builtin functions
show PrimBwdSlice = "bwdSlice"
show PrimTraceSlice = "traceSlice"
show PrimVal = "read"
instance Pretty Primitive where
pPrint op = text (show op)
isInfixOp :: Primitive -> Bool
isInfixOp OpPlus = True
isInfixOp OpMinus = True
isInfixOp OpTimes = True
isInfixOp OpDiv = True
isInfixOp OpMod = True
-- Integer and boolean comparisons
isInfixOp OpEq = True
isInfixOp OpNeq = True
-- Integer comparisons
isInfixOp OpLt = True
isInfixOp OpGt = True
isInfixOp OpLeq = True
isInfixOp OpGeq = True
-- Logical operators
isInfixOp OpAnd = True
isInfixOp OpOr = True
-- Logical negation and builtin functions
isInfixOp _ = False
-- | Does operator accept exception values as arguments?
acceptsExns :: Primitive -> Bool
acceptsExns PrimBwdSlice = True
acceptsExns PrimTraceSlice = True
acceptsExns PrimVal = True
acceptsExns _ = False
|
jstolarek/slicer
|
lib/Language/Slicer/Primitives.hs
|
gpl-3.0
| 2,298 | 0 | 8 | 746 | 471 | 261 | 210 | 55 | 1 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback is free software: you can redistribute it and/or modify it under |
| the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Fallback is distributed in the hope that it will be useful, but WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for |
| more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.Test.Pathfind (pathfindTests) where
import Control.Applicative ((<$>))
import Data.Array
import Data.List (transpose, unfoldr)
import Data.Maybe (listToMaybe)
import Test.HUnit ((~:), Test(TestList))
import Fallback.Data.Point
import Fallback.State.Pathfind
import Fallback.Test.Base (insistEq)
-------------------------------------------------------------------------------
pathfindTests :: Test
pathfindTests = "pathfind" ~: TestList [
pathfindTest 10
"OOOOOOO\n\
\O e gO\n\
\O . O\n\
\OOO. O\n\
\O . O\n\
\Os O\n\
\OOOOOOO",
pathfindFail 3
"OOOOOOO\n\
\O g gO\n\
\O O\n\
\OOO O\n\
\O O\n\
\Os O\n\
\OOOOOOO",
pathfindTest 20
"OOOOOOOO\n\
\O e O\n\
\O . O\n\
\O . O\n\
\O . O\n\
\O . O\n\
\O . O\n\
\O sO\n\
\OOOOOOOO",
pathfindTest 20
"OOOOOOOO\n\
\Oe O\n\
\O.OOOO O\n\
\O. O\n\
\Os O\n\
\O O\n\
\O O\n\
\O gO\n\
\OOOOOOOO",
pathfindTest 20
"OOOOOOOO\n\
\Og O\n\
\OOOOOO O\n\
\O O\n\
\Os O\n\
\O . O\n\
\O ... O\n\
\O eO\n\
\OOOOOOOO",
pathfindTest 20
"OOOOOOOO\n\
\O eO O\n\
\O.OO O\n\
\O.O . O\n\
\O.O.O. O\n\
\O.O.O. O\n\
\O . O. O\n\
\O O sO\n\
\OOOOOOOO",
pathfindTest 20
"OOOOOOOO\n\
\O e O\n\
\O ... O\n\
\O.OOOOOO\n\
\O .. O\n\
\OOOO. O\n\
\O .. O\n\
\Os O\n\
\OOOOOOOO",
pathfindTest 20
"OOOOOOOO\n\
\O ..e O\n\
\O .O O\n\
\O.OOOOOO\n\
\O .. O\n\
\OOOO. O\n\
\O .. O\n\
\Os O\n\
\OOOOOOOO"]
-------------------------------------------------------------------------------
pathfindTest :: Int -> String -> Test
pathfindTest limit terrain =
let strings = lines terrain
width = length (head strings)
height = length strings
arr = listArray ((0, 0), (width - 1, height - 1)) $ concat $
transpose strings
get (Point x y) = arr ! (x, y)
allPoints = range (Point 0 0, Point (width - 1) (height - 1))
isBlocked = ('O' ==) . get
isGoal pt = let c = get pt in c == 'e' || c == 'g'
goals = filter isGoal allPoints
heuristic pos = minimum $ flip map goals $ \goal ->
pDist (fromIntegral <$> pos) (fromIntegral <$> goal)
start = head $ filter (('s' ==) . get) $ allPoints
path = pathfind isBlocked isGoal heuristic limit start
expected = Just $
let fn (mbCurrent, prev) =
case mbCurrent of
Nothing -> Nothing
Just current ->
let mbNext = listToMaybe $ filter (ok prev) $
map (current `plusDir`) allDirections
in Just (current, (mbNext, current))
ok prev next =
next /= prev && (let c = get next in c == '.' || c == 'e')
in tail $ unfoldr fn (Just start, start)
in insistEq expected path
pathfindFail :: Int -> String -> Test
pathfindFail limit terrain =
let strings = lines terrain
width = length (head strings)
height = length strings
arr = listArray ((0, 0), (width - 1, height - 1)) $ concat $
transpose strings
get (Point x y) = arr ! (x, y)
allPoints = range (Point 0 0, Point (width - 1) (height - 1))
isBlocked = ('O' ==) . get
isGoal pt = let c = get pt in c == 'e' || c == 'g'
goals = filter isGoal allPoints
heuristic pos = minimum $ flip map goals $ \goal ->
pDist (fromIntegral <$> pos) (fromIntegral <$> goal)
start = head $ filter (('s' ==) . get) $ allPoints
path = pathfind isBlocked isGoal heuristic limit start
in insistEq Nothing path
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/Test/Pathfind.hs
|
gpl-3.0
| 5,386 | 0 | 25 | 1,999 | 982 | 521 | 461 | 72 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Schema.UnknownPredictions.V0 where
import Database.Persist.TH (persistUpperCase)
import qualified Database.Persist.TH as TH
import Schema.Model (PredictionModelId)
import Schema.Implementation (ImplementationId)
TH.share [TH.mkPersist TH.sqlSettings, TH.mkSave "schema"] [persistUpperCase|
UnknownPrediction
modelId PredictionModelId
count Int
deriving Eq Show
UnknownSet
unknownPredId UnknownPredictionId
implId ImplementationId
Primary unknownPredId implId
deriving Eq Show
|]
|
merijn/GPU-benchmarks
|
benchmark-analysis/src/Schema/UnknownPredictions/V0.hs
|
gpl-3.0
| 953 | 0 | 8 | 127 | 92 | 61 | 31 | 19 | 0 |
module Colors where
import Clay hiding (header)
colors :: (Color, Color) -> Css
colors (bg, fg) = backgroundColor bg >> color fg
darkMain :: Color
darkMain = "#282828"
midDarkMain :: Color
midDarkMain = "#555555"
midMain :: Color
midMain = "#777777"
midLightMain :: Color
midLightMain = "#DDDDDD"
lightMain :: Color
lightMain = "#E8E8E8"
noteTitle = colors (white, darkMain)
noteBody = colors (white, darkMain)
noteButton = colors (transparent, darkMain)
noteButtonHover = colors (darkMain, white)
leftColumn = colors (white, darkMain)
rightColumn = colors (white, darkMain)
header = colors (midDarkMain, white)
headerButton = header
headerButtonHover = colors (white, midDarkMain)
background = colors (lightMain, darkMain)
|
ktvoelker/KB
|
clay/Colors.hs
|
gpl-3.0
| 734 | 0 | 6 | 110 | 233 | 135 | 98 | 24 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.LiveBroadcasts.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing broadcast for the authenticated user.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.liveBroadcasts.update@.
module Network.Google.Resource.YouTube.LiveBroadcasts.Update
(
-- * REST Resource
LiveBroadcastsUpdateResource
-- * Creating a Request
, liveBroadcastsUpdate
, LiveBroadcastsUpdate
-- * Request Lenses
, lbuXgafv
, lbuPart
, lbuUploadProtocol
, lbuAccessToken
, lbuUploadType
, lbuPayload
, lbuOnBehalfOfContentOwner
, lbuOnBehalfOfContentOwnerChannel
, lbuCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.liveBroadcasts.update@ method which the
-- 'LiveBroadcastsUpdate' request conforms to.
type LiveBroadcastsUpdateResource =
"youtube" :>
"v3" :>
"liveBroadcasts" :>
QueryParams "part" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "onBehalfOfContentOwnerChannel" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] LiveBroadcast :>
Put '[JSON] LiveBroadcast
-- | Updates an existing broadcast for the authenticated user.
--
-- /See:/ 'liveBroadcastsUpdate' smart constructor.
data LiveBroadcastsUpdate =
LiveBroadcastsUpdate'
{ _lbuXgafv :: !(Maybe Xgafv)
, _lbuPart :: ![Text]
, _lbuUploadProtocol :: !(Maybe Text)
, _lbuAccessToken :: !(Maybe Text)
, _lbuUploadType :: !(Maybe Text)
, _lbuPayload :: !LiveBroadcast
, _lbuOnBehalfOfContentOwner :: !(Maybe Text)
, _lbuOnBehalfOfContentOwnerChannel :: !(Maybe Text)
, _lbuCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LiveBroadcastsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbuXgafv'
--
-- * 'lbuPart'
--
-- * 'lbuUploadProtocol'
--
-- * 'lbuAccessToken'
--
-- * 'lbuUploadType'
--
-- * 'lbuPayload'
--
-- * 'lbuOnBehalfOfContentOwner'
--
-- * 'lbuOnBehalfOfContentOwnerChannel'
--
-- * 'lbuCallback'
liveBroadcastsUpdate
:: [Text] -- ^ 'lbuPart'
-> LiveBroadcast -- ^ 'lbuPayload'
-> LiveBroadcastsUpdate
liveBroadcastsUpdate pLbuPart_ pLbuPayload_ =
LiveBroadcastsUpdate'
{ _lbuXgafv = Nothing
, _lbuPart = _Coerce # pLbuPart_
, _lbuUploadProtocol = Nothing
, _lbuAccessToken = Nothing
, _lbuUploadType = Nothing
, _lbuPayload = pLbuPayload_
, _lbuOnBehalfOfContentOwner = Nothing
, _lbuOnBehalfOfContentOwnerChannel = Nothing
, _lbuCallback = Nothing
}
-- | V1 error format.
lbuXgafv :: Lens' LiveBroadcastsUpdate (Maybe Xgafv)
lbuXgafv = lens _lbuXgafv (\ s a -> s{_lbuXgafv = a})
-- | The *part* parameter serves two purposes in this operation. It
-- identifies the properties that the write operation will set as well as
-- the properties that the API response will include. The part properties
-- that you can include in the parameter value are id, snippet,
-- contentDetails, and status. Note that this method will override the
-- existing values for all of the mutable properties that are contained in
-- any parts that the parameter value specifies. For example, a
-- broadcast\'s privacy status is defined in the status part. As such, if
-- your request is updating a private or unlisted broadcast, and the
-- request\'s part parameter value includes the status part, the
-- broadcast\'s privacy setting will be updated to whatever value the
-- request body specifies. If the request body does not specify a value,
-- the existing privacy setting will be removed and the broadcast will
-- revert to the default privacy setting.
lbuPart :: Lens' LiveBroadcastsUpdate [Text]
lbuPart
= lens _lbuPart (\ s a -> s{_lbuPart = a}) . _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
lbuUploadProtocol :: Lens' LiveBroadcastsUpdate (Maybe Text)
lbuUploadProtocol
= lens _lbuUploadProtocol
(\ s a -> s{_lbuUploadProtocol = a})
-- | OAuth access token.
lbuAccessToken :: Lens' LiveBroadcastsUpdate (Maybe Text)
lbuAccessToken
= lens _lbuAccessToken
(\ s a -> s{_lbuAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
lbuUploadType :: Lens' LiveBroadcastsUpdate (Maybe Text)
lbuUploadType
= lens _lbuUploadType
(\ s a -> s{_lbuUploadType = a})
-- | Multipart request metadata.
lbuPayload :: Lens' LiveBroadcastsUpdate LiveBroadcast
lbuPayload
= lens _lbuPayload (\ s a -> s{_lbuPayload = a})
-- | *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwner* parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
lbuOnBehalfOfContentOwner :: Lens' LiveBroadcastsUpdate (Maybe Text)
lbuOnBehalfOfContentOwner
= lens _lbuOnBehalfOfContentOwner
(\ s a -> s{_lbuOnBehalfOfContentOwner = a})
-- | This parameter can only be used in a properly authorized request.
-- *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwnerChannel* parameter specifies the
-- YouTube channel ID of the channel to which a video is being added. This
-- parameter is required when a request specifies a value for the
-- onBehalfOfContentOwner parameter, and it can only be used in conjunction
-- with that parameter. In addition, the request must be authorized using a
-- CMS account that is linked to the content owner that the
-- onBehalfOfContentOwner parameter specifies. Finally, the channel that
-- the onBehalfOfContentOwnerChannel parameter value specifies must be
-- linked to the content owner that the onBehalfOfContentOwner parameter
-- specifies. This parameter is intended for YouTube content partners that
-- own and manage many different YouTube channels. It allows content owners
-- to authenticate once and perform actions on behalf of the channel
-- specified in the parameter value, without having to provide
-- authentication credentials for each separate channel.
lbuOnBehalfOfContentOwnerChannel :: Lens' LiveBroadcastsUpdate (Maybe Text)
lbuOnBehalfOfContentOwnerChannel
= lens _lbuOnBehalfOfContentOwnerChannel
(\ s a -> s{_lbuOnBehalfOfContentOwnerChannel = a})
-- | JSONP
lbuCallback :: Lens' LiveBroadcastsUpdate (Maybe Text)
lbuCallback
= lens _lbuCallback (\ s a -> s{_lbuCallback = a})
instance GoogleRequest LiveBroadcastsUpdate where
type Rs LiveBroadcastsUpdate = LiveBroadcast
type Scopes LiveBroadcastsUpdate =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl"]
requestClient LiveBroadcastsUpdate'{..}
= go _lbuPart _lbuXgafv _lbuUploadProtocol
_lbuAccessToken
_lbuUploadType
_lbuOnBehalfOfContentOwner
_lbuOnBehalfOfContentOwnerChannel
_lbuCallback
(Just AltJSON)
_lbuPayload
youTubeService
where go
= buildClient
(Proxy :: Proxy LiveBroadcastsUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/LiveBroadcasts/Update.hs
|
mpl-2.0
| 8,857 | 0 | 20 | 1,868 | 999 | 594 | 405 | 138 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Classroom.Courses.Students.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a student of a course. This method returns the following error
-- codes: * \`PERMISSION_DENIED\` if the requesting user is not permitted
-- to delete students of this course or for access errors. * \`NOT_FOUND\`
-- if no student of this course has the requested ID or if the course does
-- not exist.
--
-- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.courses.students.delete@.
module Network.Google.Resource.Classroom.Courses.Students.Delete
(
-- * REST Resource
CoursesStudentsDeleteResource
-- * Creating a Request
, coursesStudentsDelete
, CoursesStudentsDelete
-- * Request Lenses
, csdXgafv
, csdUploadProtocol
, csdCourseId
, csdAccessToken
, csdUploadType
, csdUserId
, csdCallback
) where
import Network.Google.Classroom.Types
import Network.Google.Prelude
-- | A resource alias for @classroom.courses.students.delete@ method which the
-- 'CoursesStudentsDelete' request conforms to.
type CoursesStudentsDeleteResource =
"v1" :>
"courses" :>
Capture "courseId" Text :>
"students" :>
Capture "userId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes a student of a course. This method returns the following error
-- codes: * \`PERMISSION_DENIED\` if the requesting user is not permitted
-- to delete students of this course or for access errors. * \`NOT_FOUND\`
-- if no student of this course has the requested ID or if the course does
-- not exist.
--
-- /See:/ 'coursesStudentsDelete' smart constructor.
data CoursesStudentsDelete =
CoursesStudentsDelete'
{ _csdXgafv :: !(Maybe Xgafv)
, _csdUploadProtocol :: !(Maybe Text)
, _csdCourseId :: !Text
, _csdAccessToken :: !(Maybe Text)
, _csdUploadType :: !(Maybe Text)
, _csdUserId :: !Text
, _csdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CoursesStudentsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csdXgafv'
--
-- * 'csdUploadProtocol'
--
-- * 'csdCourseId'
--
-- * 'csdAccessToken'
--
-- * 'csdUploadType'
--
-- * 'csdUserId'
--
-- * 'csdCallback'
coursesStudentsDelete
:: Text -- ^ 'csdCourseId'
-> Text -- ^ 'csdUserId'
-> CoursesStudentsDelete
coursesStudentsDelete pCsdCourseId_ pCsdUserId_ =
CoursesStudentsDelete'
{ _csdXgafv = Nothing
, _csdUploadProtocol = Nothing
, _csdCourseId = pCsdCourseId_
, _csdAccessToken = Nothing
, _csdUploadType = Nothing
, _csdUserId = pCsdUserId_
, _csdCallback = Nothing
}
-- | V1 error format.
csdXgafv :: Lens' CoursesStudentsDelete (Maybe Xgafv)
csdXgafv = lens _csdXgafv (\ s a -> s{_csdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
csdUploadProtocol :: Lens' CoursesStudentsDelete (Maybe Text)
csdUploadProtocol
= lens _csdUploadProtocol
(\ s a -> s{_csdUploadProtocol = a})
-- | Identifier of the course. This identifier can be either the
-- Classroom-assigned identifier or an alias.
csdCourseId :: Lens' CoursesStudentsDelete Text
csdCourseId
= lens _csdCourseId (\ s a -> s{_csdCourseId = a})
-- | OAuth access token.
csdAccessToken :: Lens' CoursesStudentsDelete (Maybe Text)
csdAccessToken
= lens _csdAccessToken
(\ s a -> s{_csdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
csdUploadType :: Lens' CoursesStudentsDelete (Maybe Text)
csdUploadType
= lens _csdUploadType
(\ s a -> s{_csdUploadType = a})
-- | Identifier of the student to delete. The identifier can be one of the
-- following: * the numeric identifier for the user * the email address of
-- the user * the string literal \`\"me\"\`, indicating the requesting user
csdUserId :: Lens' CoursesStudentsDelete Text
csdUserId
= lens _csdUserId (\ s a -> s{_csdUserId = a})
-- | JSONP
csdCallback :: Lens' CoursesStudentsDelete (Maybe Text)
csdCallback
= lens _csdCallback (\ s a -> s{_csdCallback = a})
instance GoogleRequest CoursesStudentsDelete where
type Rs CoursesStudentsDelete = Empty
type Scopes CoursesStudentsDelete =
'["https://www.googleapis.com/auth/classroom.rosters"]
requestClient CoursesStudentsDelete'{..}
= go _csdCourseId _csdUserId _csdXgafv
_csdUploadProtocol
_csdAccessToken
_csdUploadType
_csdCallback
(Just AltJSON)
classroomService
where go
= buildClient
(Proxy :: Proxy CoursesStudentsDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-classroom/gen/Network/Google/Resource/Classroom/Courses/Students/Delete.hs
|
mpl-2.0
| 5,812 | 0 | 18 | 1,322 | 789 | 464 | 325 | 114 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.URLMaps.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the specified UrlMap resource with the data included in the
-- request. This method supports patch semantics.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.urlMaps.patch@.
module Network.Google.Resource.Compute.URLMaps.Patch
(
-- * REST Resource
URLMapsPatchResource
-- * Creating a Request
, urlMapsPatch
, URLMapsPatch
-- * Request Lenses
, umpURLMap
, umpProject
, umpPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.urlMaps.patch@ method which the
-- 'URLMapsPatch' request conforms to.
type URLMapsPatchResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"urlMaps" :>
Capture "urlMap" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] URLMap :> Patch '[JSON] Operation
-- | Updates the specified UrlMap resource with the data included in the
-- request. This method supports patch semantics.
--
-- /See:/ 'urlMapsPatch' smart constructor.
data URLMapsPatch = URLMapsPatch'
{ _umpURLMap :: !Text
, _umpProject :: !Text
, _umpPayload :: !URLMap
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'URLMapsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'umpURLMap'
--
-- * 'umpProject'
--
-- * 'umpPayload'
urlMapsPatch
:: Text -- ^ 'umpURLMap'
-> Text -- ^ 'umpProject'
-> URLMap -- ^ 'umpPayload'
-> URLMapsPatch
urlMapsPatch pUmpURLMap_ pUmpProject_ pUmpPayload_ =
URLMapsPatch'
{ _umpURLMap = pUmpURLMap_
, _umpProject = pUmpProject_
, _umpPayload = pUmpPayload_
}
-- | Name of the UrlMap resource to update.
umpURLMap :: Lens' URLMapsPatch Text
umpURLMap
= lens _umpURLMap (\ s a -> s{_umpURLMap = a})
-- | Project ID for this request.
umpProject :: Lens' URLMapsPatch Text
umpProject
= lens _umpProject (\ s a -> s{_umpProject = a})
-- | Multipart request metadata.
umpPayload :: Lens' URLMapsPatch URLMap
umpPayload
= lens _umpPayload (\ s a -> s{_umpPayload = a})
instance GoogleRequest URLMapsPatch where
type Rs URLMapsPatch = Operation
type Scopes URLMapsPatch =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient URLMapsPatch'{..}
= go _umpProject _umpURLMap (Just AltJSON)
_umpPayload
computeService
where go
= buildClient (Proxy :: Proxy URLMapsPatchResource)
mempty
|
rueshyna/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/URLMaps/Patch.hs
|
mpl-2.0
| 3,593 | 0 | 16 | 869 | 470 | 281 | 189 | 74 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdExchangeBuyer.Proposals.Search
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Search for proposals using pql query
--
-- /See:/ <https://developers.google.com/ad-exchange/buyer-rest Ad Exchange Buyer API Reference> for @adexchangebuyer.proposals.search@.
module Network.Google.Resource.AdExchangeBuyer.Proposals.Search
(
-- * REST Resource
ProposalsSearchResource
-- * Creating a Request
, proposalsSearch
, ProposalsSearch
-- * Request Lenses
, pPqlQuery
) where
import Network.Google.AdExchangeBuyer.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangebuyer.proposals.search@ method which the
-- 'ProposalsSearch' request conforms to.
type ProposalsSearchResource =
"adexchangebuyer" :>
"v1.4" :>
"proposals" :>
"search" :>
QueryParam "pqlQuery" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GetOrdersResponse
-- | Search for proposals using pql query
--
-- /See:/ 'proposalsSearch' smart constructor.
newtype ProposalsSearch = ProposalsSearch'
{ _pPqlQuery :: Maybe Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProposalsSearch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pPqlQuery'
proposalsSearch
:: ProposalsSearch
proposalsSearch =
ProposalsSearch'
{ _pPqlQuery = Nothing
}
-- | Query string to retrieve specific proposals.
pPqlQuery :: Lens' ProposalsSearch (Maybe Text)
pPqlQuery
= lens _pPqlQuery (\ s a -> s{_pPqlQuery = a})
instance GoogleRequest ProposalsSearch where
type Rs ProposalsSearch = GetOrdersResponse
type Scopes ProposalsSearch =
'["https://www.googleapis.com/auth/adexchange.buyer"]
requestClient ProposalsSearch'{..}
= go _pPqlQuery (Just AltJSON) adExchangeBuyerService
where go
= buildClient
(Proxy :: Proxy ProposalsSearchResource)
mempty
|
rueshyna/gogol
|
gogol-adexchange-buyer/gen/Network/Google/Resource/AdExchangeBuyer/Proposals/Search.hs
|
mpl-2.0
| 2,801 | 0 | 13 | 640 | 304 | 186 | 118 | 49 | 1 |
module Types.Agent.Dummy where
import Types.World
-- |A mind that always does the same thing and can optionally storage messages
-- sent to it.
data DummyMind = DummyMind {
-- |The action which the mind will always perform.
_dummyMindAction :: Action,
-- |Indicates whether the agent should store incoming messages.
_dummyMindStoreMessages :: Bool,
-- |The agent's message store.
_dummyMindMessageSpace :: [Message]
}
|
jtapolczai/wumpus
|
Types/Agent/Dummy.hs
|
apache-2.0
| 442 | 0 | 9 | 85 | 47 | 32 | 15 | 6 | 0 |
module ListsAndTuples where
sorted :: [Integer] -> Bool
sorted [] = True
sorted [_] = True
sorted (x:r@(y:_)) = x < y && sorted r
|
zer/BeginningHaskell
|
src/Chapter2/ListsAndTuples.hs
|
apache-2.0
| 148 | 0 | 10 | 43 | 73 | 40 | 33 | 5 | 1 |
module Main where
import Prelude (IO)
import Yesod.Default.Config (fromArgs)
import Yesod.Default.Main (defaultMain)
import Settings (parseExtra)
import Application (makeApplication)
main :: IO ()
main = defaultMain (fromArgs parseExtra) makeApplication
|
dtekcth/DtekPortalen
|
src/main.hs
|
bsd-2-clause
| 293 | 0 | 7 | 67 | 76 | 45 | 31 | 8 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionToolBoxV2.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionToolBoxV2 (
QqStyleOptionToolBoxV2(..)
,QqStyleOptionToolBoxV2_nf(..)
,qStyleOptionToolBoxV2_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QStyleOptionToolBoxV2
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionToolBoxV2 x1 where
qStyleOptionToolBoxV2 :: x1 -> IO (QStyleOptionToolBoxV2 ())
instance QqStyleOptionToolBoxV2 (()) where
qStyleOptionToolBoxV2 ()
= withQStyleOptionToolBoxV2Result $
qtc_QStyleOptionToolBoxV2
foreign import ccall "qtc_QStyleOptionToolBoxV2" qtc_QStyleOptionToolBoxV2 :: IO (Ptr (TQStyleOptionToolBoxV2 ()))
instance QqStyleOptionToolBoxV2 ((QStyleOptionToolBoxV2 t1)) where
qStyleOptionToolBoxV2 (x1)
= withQStyleOptionToolBoxV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBoxV21 cobj_x1
foreign import ccall "qtc_QStyleOptionToolBoxV21" qtc_QStyleOptionToolBoxV21 :: Ptr (TQStyleOptionToolBoxV2 t1) -> IO (Ptr (TQStyleOptionToolBoxV2 ()))
instance QqStyleOptionToolBoxV2 ((QStyleOptionToolBox t1)) where
qStyleOptionToolBoxV2 (x1)
= withQStyleOptionToolBoxV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBoxV22 cobj_x1
foreign import ccall "qtc_QStyleOptionToolBoxV22" qtc_QStyleOptionToolBoxV22 :: Ptr (TQStyleOptionToolBox t1) -> IO (Ptr (TQStyleOptionToolBoxV2 ()))
class QqStyleOptionToolBoxV2_nf x1 where
qStyleOptionToolBoxV2_nf :: x1 -> IO (QStyleOptionToolBoxV2 ())
instance QqStyleOptionToolBoxV2_nf (()) where
qStyleOptionToolBoxV2_nf ()
= withObjectRefResult $
qtc_QStyleOptionToolBoxV2
instance QqStyleOptionToolBoxV2_nf ((QStyleOptionToolBoxV2 t1)) where
qStyleOptionToolBoxV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBoxV21 cobj_x1
instance QqStyleOptionToolBoxV2_nf ((QStyleOptionToolBox t1)) where
qStyleOptionToolBoxV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionToolBoxV22 cobj_x1
instance Qposition (QStyleOptionToolBoxV2 a) (()) (IO (Int)) where
position x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBoxV2_position cobj_x0
foreign import ccall "qtc_QStyleOptionToolBoxV2_position" qtc_QStyleOptionToolBoxV2_position :: Ptr (TQStyleOptionToolBoxV2 a) -> IO CInt
instance QselectedPosition (QStyleOptionToolBoxV2 a) (()) where
selectedPosition x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBoxV2_selectedPosition cobj_x0
foreign import ccall "qtc_QStyleOptionToolBoxV2_selectedPosition" qtc_QStyleOptionToolBoxV2_selectedPosition :: Ptr (TQStyleOptionToolBoxV2 a) -> IO CInt
instance QsetPosition (QStyleOptionToolBoxV2 a) ((QStyleOptionToolBoxV2TabPosition)) where
setPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBoxV2_setPosition cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QStyleOptionToolBoxV2_setPosition" qtc_QStyleOptionToolBoxV2_setPosition :: Ptr (TQStyleOptionToolBoxV2 a) -> CLong -> IO ()
instance QsetSelectedPosition (QStyleOptionToolBoxV2 a) ((QStyleOptionToolBoxV2SelectedPosition)) where
setSelectedPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBoxV2_setSelectedPosition cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QStyleOptionToolBoxV2_setSelectedPosition" qtc_QStyleOptionToolBoxV2_setSelectedPosition :: Ptr (TQStyleOptionToolBoxV2 a) -> CLong -> IO ()
qStyleOptionToolBoxV2_delete :: QStyleOptionToolBoxV2 a -> IO ()
qStyleOptionToolBoxV2_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionToolBoxV2_delete cobj_x0
foreign import ccall "qtc_QStyleOptionToolBoxV2_delete" qtc_QStyleOptionToolBoxV2_delete :: Ptr (TQStyleOptionToolBoxV2 a) -> IO ()
|
keera-studios/hsQt
|
Qtc/Gui/QStyleOptionToolBoxV2.hs
|
bsd-2-clause
| 4,367 | 0 | 12 | 553 | 943 | 494 | 449 | -1 | -1 |
import Data.List
import qualified Data.Map as M
import Data.Maybe
import System.IO
import Text.ParserCombinators.ReadP
import System.IO.Unsafe
data Arg = Reg String | IReg String | Const Int | Addr Int | Lbl String deriving (Show, Eq, Ord)
data Op = Op (Maybe String) String [Arg] deriving (Show, Eq, Ord)
p_oneof = choice . (char `map`)
p_whitespace = p_oneof [' ', '\t', '\r']
p_ws = many1 p_whitespace
p_ows = optional p_ws
p_eol = char '\n'
p_comment = do
char ';'
many $ satisfy (/= '\n')
return ()
p_indir = (char '[' >> p_ows) `between` (char ']' >> p_ows)
p_gpreg = do
id <- p_oneof ['a' .. 'h']
p_ows
return (Reg [id])
p_igpreg = do
(Reg id) <- p_indir p_gpreg
return (IReg id)
p_pc = do
id <- string "pc"
p_ows
return (Reg id)
p_ipc = do
(Reg id) <- p_indir p_pc
return (IReg id)
p_reg = choice [p_gpreg, p_pc]
p_ireg = choice [p_igpreg, p_ipc]
p_num = do
num <- many1 $ p_oneof ['0' .. '9']
let n = read num
p_ows
if n >= 0 && n <= 255
then return (Const n)
else pfail
p_addr = do
(Const n) <- p_indir p_num
return (Addr n)
p_lblid = many1 $ p_oneof $ concat [['a' .. 'z'], ['A' .. 'Z'], ['0' .. '9'], ['_']]
p_lblref = do
char '$'
id <- p_lblid
p_ows
return (Lbl id)
p_xlabel = do
lbl <- p_lblid
char ':'
p_ows
return lbl
p_label = choice [p_xlabel >>= (return . Just), return Nothing]
p_pcaddr = choice [p_num, p_lblref]
p_ramorreg = choice [p_reg, p_ireg, p_addr]
p_nonpcramorreg = choice [p_gpreg, p_igpreg, p_addr]
p_val = choice [p_ramorreg, p_num]
p_opmov = do
lbl <- p_label
string "mov"
p_ws
dest <- p_ramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "mov" [dest, src])
p_opinc = do
lbl <- p_label
string "inc"
p_ws
dest <- p_nonpcramorreg
return (Op lbl "inc" [dest])
p_opdec = do
lbl <- p_label
string "dec"
p_ws
dest <- p_nonpcramorreg
return (Op lbl "dec" [dest])
p_opadd = do
lbl <- p_label
string "add"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "add" [dest, src])
p_opsub = do
lbl <- p_label
string "sub"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "sub" [dest, src])
p_opmul = do
lbl <- p_label
string "mul"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "mul" [dest, src])
p_opdiv = do
lbl <- p_label
string "div"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "div" [dest, src])
p_opand = do
lbl <- p_label
string "and"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "and" [dest, src])
p_opor = do
lbl <- p_label
string "or"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "or" [dest, src])
p_opxor = do
lbl <- p_label
string "xor"
p_ws
dest <- p_nonpcramorreg
p_ows
char ','
p_ows
src <- p_val
return (Op lbl "xor" [dest, src])
p_opjlt = do
lbl <- p_label
string "jlt"
p_ws
targ <- p_pcaddr
p_ows
char ','
p_ows
x <- p_val
p_ows
char ','
p_ows
y <- p_val
return (Op lbl "jlt" [targ, x, y])
p_opjeq = do
lbl <- p_label
string "jeq"
p_ws
targ <- p_pcaddr
p_ows
char ','
p_ows
x <- p_val
p_ows
char ','
p_ows
y <- p_val
return (Op lbl "jeq" [targ, x, y])
p_opjgt = do
lbl <- p_label
string "jgt"
p_ws
targ <- p_pcaddr
p_ows
char ','
p_ows
x <- p_val
p_ows
char ','
p_ows
y <- p_val
return (Op lbl "jgt" [targ, x, y])
p_opint tag intnum = do
lbl <- p_label
string tag
p_ows
return (Op lbl "int" [Const intnum])
p_opset_dir = p_opint "set_dir" 0
p_opget_lm_1_pos = p_opint "get_lm_1_pos" 1
p_opget_lm_2_pos = p_opint "get_lm_2_pos" 2
p_opget_my_ix = p_opint "get_my_ix" 3
p_opget_gh_st_pos = p_opint "get_gh_st_pos" 4
p_opget_gh_cur_pos = p_opint "get_gh_cur_pos" 5
p_opget_gh_cur_st = p_opint "get_gh_cur_st" 6
p_opget_map_sq = p_opint "get_map_sq" 7
p_opdebug = p_opint "debug" 8
p_ophlt = do
lbl <- p_label
string "hlt"
p_ows
return (Op lbl "hlt" [])
p_op = choice [p_opmov, p_opinc, p_opdec, p_opadd, p_opsub, p_opmul, p_opdiv, p_opand, p_opor, p_opxor, p_opjlt, p_opjeq, p_opjgt,
p_opset_dir, p_opget_lm_1_pos, p_opget_lm_2_pos, p_opget_my_ix, p_opget_gh_st_pos, p_opget_gh_cur_pos, p_opget_gh_cur_st,
p_opget_map_sq, p_opdebug, p_ophlt]
p_linenop = do
p_ows
optional p_comment
p_eol
return []
p_lineop = do
p_ows
op <- p_op
optional p_comment
p_eol
return [op]
p_program = do
ops <- many $ choice [p_lineop, p_linenop]
let opl = concat ops
eof
return opl
outlbl Nothing = ""
outlbl (Just lbl) = "\t; " ++ lbl ++ ":"
--data Arg = Reg String | IReg String | Const Int | Addr Int | Lbl String deriving (Show, Eq, Ord)
outarg _ (Reg n) = n
outarg lbls (IReg n) = "[" ++ outarg lbls (Reg n) ++ "]"
outarg _ (Const n) = show n
outarg lbls (Addr n) = "[" ++ outarg lbls (Const n) ++ "]"
outarg lbls (Lbl n) = show $ fromJust $ n `M.lookup` lbls
out lbls (Op lbl name args) = "\t" ++ name ++ "\t" ++ (", " `intercalate` ((outarg lbls) `map` args)) ++ outlbl lbl
codegen lines = "\n" `intercalate` ((out labels) `map` lines)
where
f m (_, (Op Nothing _ _)) = m
f m (ix, (Op (Just lbl) _ _)) = M.insert lbl ix m
labels = foldl f M.empty ([0 ..] `zip` lines)
main = do
hPutStrLn stderr "GHC80 v0.0"
input <- getContents
let ast = p_program `readP_to_S` input
if length ast /= 1
then hPutStrLn stderr $ "No parse or multiple parses -- " ++ show (length ast) ++ " found."
else
if length (fst $ head ast) > 256
then hPutStrLn stderr $ "Program too long -- " ++ show (length (fst $ head ast)) ++ " line(s)."
else do
putStrLn $ codegen (fst $ head ast)
hPutStrLn stderr "Task complete."
hPutStrLn stderr ""
|
pbl64k/icfpc2014
|
code/ghc80.hs
|
bsd-2-clause
| 6,348 | 0 | 16 | 1,897 | 2,509 | 1,211 | 1,298 | 256 | 3 |
module Life.Scenes where
import Life.Types
-- Pre-plotted Scenes
glider :: [Pos]
glider = [(2,3),(3,4),(4,2),(4,3),(4,4)]
gliderGun :: [Pos]
gliderGun = [(2,6), (2,7), (3,6), (3,7), (12,6),
(12,7), (12,8), (13,5), (13,9), (14,4),
(14,10), (15,4), (15,10), (16,7), (17,5),
(17,9), (18,6), (18,7), (18,8), (19,7),
(22,4), (22,5), (22,6), (23,4), (23,5),
(23,6), (24,3), (24,7), (26,2), (26,3),
(26,7), (26,8), (36,4), (36,5), (37,4), (37,5)]
acorn :: [Pos]
acorn = [(20,15), (21,13), (22, 10), (22, 11), (22, 12), (22, 15), (22,16)]
|
ku-fpg/better-life
|
Life/Scenes.hs
|
bsd-2-clause
| 548 | 12 | 6 | 88 | 495 | 326 | 169 | 14 | 1 |
{-# OPTIONS -XCPP #-}
module Radio ( radio) where
-- #define ALONE -- to execute it alone, uncomment this
#ifdef ALONE
import MFlow.Wai.Blaze.Html.All
main= runNavigation "" $ transientNav grid
#else
import MFlow.Wai.Blaze.Html.All hiding(retry, page)
import Menu
#endif
radio = do
r <- page $ p << b << "Radio buttons"
++> getRadio [\n -> fromStr v ++> setRadioActive v n | v <- ["red","green","blue"]]
page $ p << ( show r ++ " selected") ++> wlink () << p << " menu"
-- to run it alone, change page by ask and uncomment this:
--main= runNavigation "" $ transientNav radio
|
agocorona/MFlow
|
Demos/Radio.hs
|
bsd-3-clause
| 604 | 0 | 13 | 129 | 145 | 79 | 66 | 8 | 1 |
{-# LANGUAGE CPP #-}
#if WITH_TEMPLATE_HASKELL
{-# LANGUAGE TemplateHaskell #-}
#endif
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK hide #-}
module Network.Xmpp.Types
( NonemptyText(..)
, nonEmpty
, text
, IQError(..)
, IQRequest(..)
, IQRequestType(..)
, IQResponse(..)
, IQResult(..)
, LangTag (..)
#if WITH_TEMPLATE_HASKELL
, langTagQ
#endif
, langTagFromText
, langTagToText
, parseLangTag
, ExtendedAttribute
, Message(..)
, message
, MessageError(..)
, messageError
, MessageType(..)
, Presence(..)
, presence
, PresenceError(..)
, PresenceType(..)
, SaslError(..)
, SaslFailure(..)
, StreamFeatures(..)
, Stanza(..)
, messageS
, messageErrorS
, presenceS
, StanzaError(..)
, StanzaErrorCondition(..)
, StanzaErrorType(..)
, XmppFailure(..)
, XmppTlsError(..)
, StreamErrorCondition(..)
, Version(..)
, versionFromText
, StreamHandle(..)
, Stream(..)
, StreamState(..)
, ConnectionState(..)
, StreamErrorInfo(..)
, ConnectionDetails(..)
, StreamConfiguration(..)
, xmppDefaultParams
, xmppDefaultParamsStrong
, Jid(..)
#if WITH_TEMPLATE_HASKELL
, jidQ
, jid
#endif
, isBare
, isFull
, jidFromText
, jidFromTexts
, (<~)
, nodeprepProfile
, resourceprepProfile
, jidToText
, jidToTexts
, toBare
, localpart
, domainpart
, resourcepart
, parseJid
, TlsBehaviour(..)
, AuthFailure(..)
) where
import Control.Applicative ((<$>), (<|>), many)
import Control.Concurrent.STM
import Control.Exception
import Control.Monad.Error
import qualified Data.Attoparsec.Text as AP
import qualified Data.ByteString as BS
import Data.Char (isSpace)
import Data.Conduit
import Data.Default
import qualified Data.Set as Set
import Data.String (IsString, fromString)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Typeable(Typeable)
import Data.XML.Types as XML
import qualified Data.Text.Encoding as Text
#if WITH_TEMPLATE_HASKELL
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import qualified Language.Haskell.TH.Syntax as TH
#endif
import Network
import Network.DNS
import Network.TLS hiding (Version)
import Network.TLS.Extra
import qualified Text.StringPrep as SP
import qualified Text.StringPrep.Profiles as SP
-- $setup
-- :set -itests
-- >>> :add tests/Tests/Arbitrary.hs
-- >>> import Network.Xmpp.Types
-- >>> import Control.Applicative((<$>))
-- | Type of Texts that contain at least on non-space character
newtype NonemptyText = Nonempty {fromNonempty :: Text}
deriving (Show, Read, Eq, Ord)
instance IsString NonemptyText where
fromString str = case nonEmpty (Text.pack str) of
Nothing -> error $ "NonemptyText fromString called on empty or " ++
"all-whitespace string"
Just r -> r
-- | Check that Text contains at least one non-space character and wrap it
nonEmpty :: Text -> Maybe NonemptyText
nonEmpty txt = if Text.all isSpace txt then Nothing else Just (Nonempty txt)
-- | Same as 'fromNonempty'
text :: NonemptyText -> Text
text (Nonempty txt) = txt
-- | The Xmpp communication primities (Message, Presence and Info/Query) are
-- called stanzas.
data Stanza = IQRequestS !IQRequest
| IQResultS !IQResult
| IQErrorS !IQError
| MessageS !Message
| MessageErrorS !MessageError
| PresenceS !Presence
| PresenceErrorS !PresenceError
deriving (Eq, Show)
type ExtendedAttribute = (XML.Name, Text)
-- | A "request" Info/Query (IQ) stanza is one with either "get" or "set" as
-- type. It always contains an xml payload.
data IQRequest = IQRequest { iqRequestID :: !Text
, iqRequestFrom :: !(Maybe Jid)
, iqRequestTo :: !(Maybe Jid)
, iqRequestLangTag :: !(Maybe LangTag)
, iqRequestType :: !IQRequestType
, iqRequestPayload :: !Element
, iqRequestAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
-- | The type of IQ request that is made.
data IQRequestType = Get | Set deriving (Eq, Ord, Read, Show)
-- | A "response" Info/Query (IQ) stanza is either an 'IQError', an IQ stanza
-- of type "result" ('IQResult')
data IQResponse = IQResponseError IQError
| IQResponseResult IQResult
deriving (Eq, Show)
-- | The (non-error) answer to an IQ request.
data IQResult = IQResult { iqResultID :: !Text
, iqResultFrom :: !(Maybe Jid)
, iqResultTo :: !(Maybe Jid)
, iqResultLangTag :: !(Maybe LangTag)
, iqResultPayload :: !(Maybe Element)
, iqResultAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
-- | The answer to an IQ request that generated an error.
data IQError = IQError { iqErrorID :: !Text
, iqErrorFrom :: !(Maybe Jid)
, iqErrorTo :: !(Maybe Jid)
, iqErrorLangTag :: !(Maybe LangTag)
, iqErrorStanzaError :: !StanzaError
, iqErrorPayload :: !(Maybe Element) -- should this be []?
, iqErrorAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
-- | The message stanza. Used for /push/ type communication.
data Message = Message { messageID :: !(Maybe Text)
, messageFrom :: !(Maybe Jid)
, messageTo :: !(Maybe Jid)
, messageLangTag :: !(Maybe LangTag)
, messageType :: !MessageType
, messagePayload :: ![Element]
, messageAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
-- | An empty message
--
-- @
-- message = Message { messageID = Nothing
-- , messageFrom = Nothing
-- , messageTo = Nothing
-- , messageLangTag = Nothing
-- , messageType = Normal
-- , messagePayload = []
-- }
-- @
message :: Message
message = Message { messageID = Nothing
, messageFrom = Nothing
, messageTo = Nothing
, messageLangTag = Nothing
, messageType = Normal
, messagePayload = []
, messageAttributes = []
}
-- | Empty message stanza
--
-- @messageS = 'MessageS' 'message'@
messageS :: Stanza
messageS = MessageS message
instance Default Message where
def = message
-- | An error stanza generated in response to a 'Message'.
data MessageError = MessageError { messageErrorID :: !(Maybe Text)
, messageErrorFrom :: !(Maybe Jid)
, messageErrorTo :: !(Maybe Jid)
, messageErrorLangTag :: !(Maybe LangTag)
, messageErrorStanzaError :: !StanzaError
, messageErrorPayload :: ![Element]
, messageErrorAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
messageError :: MessageError
messageError = MessageError { messageErrorID = Nothing
, messageErrorFrom = Nothing
, messageErrorTo = Nothing
, messageErrorLangTag = Nothing
, messageErrorStanzaError =
StanzaError { stanzaErrorType = Cancel
, stanzaErrorCondition =
ServiceUnavailable
, stanzaErrorText = Nothing
, stanzaErrorApplicationSpecificCondition = Nothing
}
, messageErrorPayload = []
, messageErrorAttributes = []
}
instance Default MessageError where
def = messageError
messageErrorS :: Stanza
messageErrorS = MessageErrorS def
-- | The type of a Message being sent
-- (<http://xmpp.org/rfcs/rfc6121.html#message-syntax-type>)
data MessageType = -- | The message is sent in the context of a one-to-one chat
-- session. Typically an interactive client will present a
-- message of type /chat/ in an interface that enables
-- one-to-one chat between the two parties, including an
-- appropriate conversation history.
Chat
-- | The message is sent in the context of a multi-user chat
-- environment (similar to that of @IRC@). Typically a
-- receiving client will present a message of type
-- /groupchat/ in an interface that enables many-to-many
-- chat between the parties, including a roster of parties
-- in the chatroom and an appropriate conversation history.
| GroupChat
-- | The message provides an alert, a notification, or other
-- transient information to which no reply is expected
-- (e.g., news headlines, sports updates, near-real-time
-- market data, or syndicated content). Because no reply to
-- the message is expected, typically a receiving client
-- will present a message of type /headline/ in an interface
-- that appropriately differentiates the message from
-- standalone messages, chat messages, and groupchat
-- messages (e.g., by not providing the recipient with the
-- ability to reply).
| Headline
-- | The message is a standalone message that is sent outside
-- the context of a one-to-one conversation or groupchat, and
-- to which it is expected that the recipient will reply.
-- Typically a receiving client will present a message of
-- type /normal/ in an interface that enables the recipient
-- to reply, but without a conversation history.
--
-- This is the /default/ value.
| Normal
deriving (Eq, Read, Show)
-- | The presence stanza. Used for communicating status updates.
data Presence = Presence { presenceID :: !(Maybe Text)
, presenceFrom :: !(Maybe Jid)
, presenceTo :: !(Maybe Jid)
, presenceLangTag :: !(Maybe LangTag)
, presenceType :: !PresenceType
, presencePayload :: ![Element]
, presenceAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
-- | An empty presence.
presence :: Presence
presence = Presence { presenceID = Nothing
, presenceFrom = Nothing
, presenceTo = Nothing
, presenceLangTag = Nothing
, presenceType = Available
, presencePayload = []
, presenceAttributes = []
}
-- | Empty presence stanza
presenceS :: Stanza
presenceS = PresenceS presence
instance Default Presence where
def = presence
-- | An error stanza generated in response to a 'Presence'.
data PresenceError = PresenceError { presenceErrorID :: !(Maybe Text)
, presenceErrorFrom :: !(Maybe Jid)
, presenceErrorTo :: !(Maybe Jid)
, presenceErrorLangTag :: !(Maybe LangTag)
, presenceErrorStanzaError :: !StanzaError
, presenceErrorPayload :: ![Element]
, presenceErrorAttributes :: ![ExtendedAttribute]
} deriving (Eq, Show)
-- | @PresenceType@ holds Xmpp presence types. The "error" message type is left
-- out as errors are using @PresenceError@.
data PresenceType = Subscribe | -- ^ Sender wants to subscribe to presence
Subscribed | -- ^ Sender has approved the subscription
Unsubscribe | -- ^ Sender is unsubscribing from presence
Unsubscribed | -- ^ Sender has denied or cancelled a
-- subscription
Probe | -- ^ Sender requests current presence;
-- should only be used by servers
Available | -- ^ Sender wants to express availability
-- (no type attribute is defined)
Unavailable deriving (Eq, Read, Show)
-- | All stanzas (IQ, message, presence) can cause errors, which in the Xmpp
-- stream looks like @\<stanza-kind to=\'sender\' type=\'error\'\>@ . These
-- errors are wrapped in the @StanzaError@ type. TODO: Sender XML is (optional
-- and is) not yet included.
data StanzaError = StanzaError
{ stanzaErrorType :: StanzaErrorType
, stanzaErrorCondition :: StanzaErrorCondition
, stanzaErrorText :: Maybe (Maybe LangTag, NonemptyText)
, stanzaErrorApplicationSpecificCondition :: Maybe Element
} deriving (Eq, Show)
-- | @StanzaError@s always have one of these types.
data StanzaErrorType = Cancel | -- ^ Error is unrecoverable - do not retry
Continue | -- ^ Conditition was a warning - proceed
Modify | -- ^ Change the data and retry
Auth | -- ^ Provide credentials and retry
Wait -- ^ Error is temporary - wait and retry
deriving (Eq, Read, Show)
-- | Stanza errors are accommodated with one of the error conditions listed
-- below.
data StanzaErrorCondition = BadRequest -- ^ Malformed XML.
| Conflict -- ^ Resource or session with
-- name already exists.
| FeatureNotImplemented
| Forbidden -- ^ Insufficient permissions.
| Gone (Maybe NonemptyText) -- ^ Entity can no longer
-- be contacted at this
-- address.
| InternalServerError
| ItemNotFound
| JidMalformed
| NotAcceptable -- ^ Does not meet policy
-- criteria.
| NotAllowed -- ^ No entity may perform
-- this action.
| NotAuthorized -- ^ Must provide proper
-- credentials.
| PolicyViolation -- ^ The entity has violated
-- some local service policy
-- (e.g., a message contains
-- words that are prohibited
-- by the service)
| RecipientUnavailable -- ^ Temporarily unavailable.
| Redirect (Maybe NonemptyText) -- ^ Redirecting to
-- other entity,
-- usually
-- temporarily.
| RegistrationRequired
| RemoteServerNotFound
| RemoteServerTimeout
| ResourceConstraint -- ^ Entity lacks the
-- necessary system
-- resources.
| ServiceUnavailable
| SubscriptionRequired
| UndefinedCondition -- ^ Application-specific
-- condition.
| UnexpectedRequest -- ^ Badly timed request.
deriving (Eq, Read, Show)
-- =============================================================================
-- OTHER STUFF
-- =============================================================================
data SaslFailure = SaslFailure { saslFailureCondition :: SaslError
, saslFailureText :: Maybe ( Maybe LangTag
, Text
)
} deriving (Eq, Show)
data SaslError = SaslAborted -- ^ Client aborted.
| SaslAccountDisabled -- ^ The account has been temporarily
-- disabled.
| SaslCredentialsExpired -- ^ The authentication failed because
-- the credentials have expired.
| SaslEncryptionRequired -- ^ The mechanism requested cannot be
-- used the confidentiality and
-- integrity of the underlying
-- stream is protected (typically
-- with TLS).
| SaslIncorrectEncoding -- ^ The base64 encoding is incorrect.
| SaslInvalidAuthzid -- ^ The authzid has an incorrect
-- format or the initiating entity
-- does not have the appropriate
-- permissions to authorize that ID.
| SaslInvalidMechanism -- ^ The mechanism is not supported by
-- the receiving entity.
| SaslMalformedRequest -- ^ Invalid syntax.
| SaslMechanismTooWeak -- ^ The receiving entity policy
-- requires a stronger mechanism.
| SaslNotAuthorized -- ^ Invalid credentials provided, or
-- some generic authentication
-- failure has occurred.
| SaslTemporaryAuthFailure -- ^ There receiving entity reported a
-- temporary error condition; the
-- initiating entity is recommended
-- to try again later.
deriving (Eq, Read, Show)
-- The documentation of StreamErrorConditions is copied from
-- http://xmpp.org/rfcs/rfc6120.html#streams-error-conditions
data StreamErrorCondition
= StreamBadFormat -- ^ The entity has sent XML that cannot be processed.
| StreamBadNamespacePrefix -- ^ The entity has sent a namespace prefix that
-- is unsupported, or has sent no namespace
-- prefix on an element that needs such a prefix
| StreamConflict -- ^ The server either (1) is closing the existing stream
-- for this entity because a new stream has been initiated
-- that conflicts with the existing stream, or (2) is
-- refusing a new stream for this entity because allowing
-- the new stream would conflict with an existing stream
-- (e.g., because the server allows only a certain number
-- of connections from the same IP address or allows only
-- one server-to-server stream for a given domain pair as a
-- way of helping to ensure in-order processing
| StreamConnectionTimeout -- ^ One party is closing the stream because it
-- has reason to believe that the other party has
-- permanently lost the ability to communicate
-- over the stream.
| StreamHostGone -- ^ The value of the 'to' attribute provided in the
-- initial stream header corresponds to an FQDN that is no
-- longer serviced by the receiving entity
| StreamHostUnknown -- ^ The value of the 'to' attribute provided in the
-- initial stream header does not correspond to an FQDN
-- that is serviced by the receiving entity.
| StreamImproperAddressing -- ^ A stanza sent between two servers lacks a
-- 'to' or 'from' attribute, the 'from' or 'to'
-- attribute has no value, or the value violates
-- the rules for XMPP addresses
| StreamInternalServerError -- ^ The server has experienced a
-- misconfiguration or other internal error that
-- prevents it from servicing the stream.
| StreamInvalidFrom -- ^ The data provided in a 'from' attribute does not
-- match an authorized JID or validated domain as
-- negotiated (1) between two servers using SASL or
-- Server Dialback, or (2) between a client and a server
-- via SASL authentication and resource binding.
| StreamInvalidNamespace -- ^ The stream namespace name is something other
-- than \"http://etherx.jabber.org/streams\" (see
-- Section 11.2) or the content namespace declared
-- as the default namespace is not supported (e.g.,
-- something other than \"jabber:client\" or
-- \"jabber:server\").
| StreamInvalidXml -- ^ The entity has sent invalid XML over the stream to a
-- server that performs validation
| StreamNotAuthorized -- ^ The entity has attempted to send XML stanzas or
-- other outbound data before the stream has been
-- authenticated, or otherwise is not authorized to
-- perform an action related to stream negotiation;
-- the receiving entity MUST NOT process the offending
-- data before sending the stream error.
| StreamNotWellFormed -- ^ The initiating entity has sent XML that violates
-- the well-formedness rules of [XML] or [XML‑NAMES].
| StreamPolicyViolation -- ^ The entity has violated some local service
-- policy (e.g., a stanza exceeds a configured size
-- limit); the server MAY choose to specify the
-- policy in the \<text/\> element or in an
-- application-specific condition element.
| StreamRemoteConnectionFailed -- ^ The server is unable to properly connect
-- to a remote entity that is needed for
-- authentication or authorization (e.g., in
-- certain scenarios related to Server
-- Dialback [XEP‑0220]); this condition is
-- not to be used when the cause of the error
-- is within the administrative domain of the
-- XMPP service provider, in which case the
-- \<internal-server-error /\> condition is
-- more appropriate.
| StreamReset -- ^ The server is closing the stream because it has new
-- (typically security-critical) features to offer, because
-- the keys or certificates used to establish a secure context
-- for the stream have expired or have been revoked during the
-- life of the stream , because the TLS sequence number has
-- wrapped, etc. The reset applies to the stream and to any
-- security context established for that stream (e.g., via TLS
-- and SASL), which means that encryption and authentication
-- need to be negotiated again for the new stream (e.g., TLS
-- session resumption cannot be used)
| StreamResourceConstraint -- ^ The server lacks the system resources
-- necessary to service the stream.
| StreamRestrictedXml -- ^ he entity has attempted to send restricted XML
-- features such as a comment, processing instruction,
-- DTD subset, or XML entity reference
| StreamSeeOtherHost -- ^ The server will not provide service to the
-- initiating entity but is redirecting traffic to
-- another host under the administrative control of the
-- same service provider.
| StreamSystemShutdown -- ^ The server is being shut down and all active
-- streams are being closed.
| StreamUndefinedCondition -- ^ The error condition is not one of those
-- defined by the other conditions in this list
| StreamUnsupportedEncoding -- ^ The initiating entity has encoded the
-- stream in an encoding that is not supported
-- by the server or has otherwise improperly
-- encoded the stream (e.g., by violating the
-- rules of the [UTF‑8] encoding).
| StreamUnsupportedFeature -- ^ The receiving entity has advertised a
-- mandatory-to-negotiate stream feature that the
-- initiating entity does not support, and has
-- offered no other mandatory-to-negotiate
-- feature alongside the unsupported feature.
| StreamUnsupportedStanzaType -- ^ The initiating entity has sent a
-- first-level child of the stream that is not
-- supported by the server, either because the
-- receiving entity does not understand the
-- namespace or because the receiving entity
-- does not understand the element name for
-- the applicable namespace (which might be
-- the content namespace declared as the
-- default namespace)
| StreamUnsupportedVersion -- ^ The 'version' attribute provided by the
-- initiating entity in the stream header
-- specifies a version of XMPP that is not
-- supported by the server.
deriving (Eq, Read, Show)
-- | Encapsulates information about an XMPP stream error.
data StreamErrorInfo = StreamErrorInfo
{ errorCondition :: !StreamErrorCondition
, errorText :: !(Maybe (Maybe LangTag, NonemptyText))
, errorXml :: !(Maybe Element)
} deriving (Show, Eq)
data XmppTlsError = XmppTlsError TLSError
| XmppTlsException TLSException
deriving (Show, Eq, Typeable)
-- | Signals an XMPP stream error or another unpredicted stream-related
-- situation. This error is fatal, and closes the XMPP stream.
data XmppFailure = StreamErrorFailure StreamErrorInfo -- ^ An error XML stream
-- element has been
-- encountered.
| StreamEndFailure -- ^ The stream has been closed.
-- This exception is caught by the
-- concurrent implementation, and
-- will thus not be visible
-- through use of 'Session'.
| StreamCloseError ([Element], XmppFailure) -- ^ When an XmppFailure
-- is encountered in
-- closeStreams, this
-- constructor wraps the
-- elements collected so
-- far.
| TcpConnectionFailure -- ^ All attempts to TCP
-- connect to the server
-- failed.
| XmppIllegalTcpDetails -- ^ The TCP details provided did not
-- validate.
| TlsError XmppTlsError -- ^ An error occurred in the
-- TLS layer
| TlsNoServerSupport -- ^ The server does not support
-- the use of TLS
| XmppNoStream -- ^ An action that required an active
-- stream were performed when the
-- 'StreamState' was 'Closed'
| XmppAuthFailure AuthFailure -- ^ Authentication with the
-- server failed (unrecoverably)
| TlsStreamSecured -- ^ Connection already secured
| XmppOtherFailure -- ^ Undefined condition. More
-- information should be available in
-- the log.
| XmppIOException IOException -- ^ An 'IOException'
-- occurred
| XmppInvalidXml String -- ^ Received data is not valid XML
deriving (Show, Eq, Typeable)
instance Exception XmppFailure
instance Error XmppFailure where noMsg = XmppOtherFailure
-- | Signals a SASL authentication error condition.
data AuthFailure = -- | No mechanism offered by the server was matched
-- by the provided acceptable mechanisms; wraps the
-- mechanisms offered by the server
AuthNoAcceptableMechanism [Text.Text]
| AuthStreamFailure XmppFailure -- TODO: Remove
-- | A SASL failure element was encountered
| AuthSaslFailure SaslFailure
-- | The credentials provided did not conform to
-- the SASLprep Stringprep profile
| AuthIllegalCredentials
-- | Other failure; more information is available
-- in the log
| AuthOtherFailure
deriving (Eq, Show)
instance Error AuthFailure where
noMsg = AuthOtherFailure
-- =============================================================================
-- XML TYPES
-- =============================================================================
-- | XMPP version number. Displayed as "\<major\>.\<minor\>". 2.4 is lesser than
-- 2.13, which in turn is lesser than 12.3.
data Version = Version { majorVersion :: !Integer
, minorVersion :: !Integer } deriving (Eq, Read, Show)
-- If the major version numbers are not equal, compare them. Otherwise, compare
-- the minor version numbers.
instance Ord Version where
compare (Version amajor aminor) (Version bmajor bminor)
| amajor /= bmajor = compare amajor bmajor
| otherwise = compare aminor bminor
-- instance Read Version where
-- readsPrec _ txt = (,"") <$> maybeToList (versionFromText $ Text.pack txt)
-- instance Show Version where
-- show (Version major minor) = (show major) ++ "." ++ (show minor)
-- Converts a "<major>.<minor>" numeric version number to a @Version@ object.
versionFromText :: Text.Text -> Maybe Version
versionFromText s = case AP.parseOnly versionParser s of
Right version -> Just version
Left _ -> Nothing
-- Read numbers, a dot, more numbers, and end-of-file.
versionParser :: AP.Parser Version
versionParser = do
major <- AP.many1 AP.digit
AP.skip (== '.')
minor <- AP.many1 AP.digit
AP.endOfInput
return $ Version (read major) (read minor)
-- | The language tag in accordance with RFC 5646 (in the form of "en-US"). It
-- has a primary tag and a number of subtags. Two language tags are considered
-- equal if and only if they contain the same tags (case-insensitive).
data LangTag = LangTag { primaryTag :: !Text
, subtags :: ![Text] }
-- Equals for language tags is not case-sensitive.
instance Eq LangTag where
LangTag p s == LangTag q t = Text.toLower p == Text.toLower q &&
map Text.toLower s == map Text.toLower t
-- | Parses, validates, and possibly constructs a "LangTag" object.
langTagFromText :: Text.Text -> Maybe LangTag
langTagFromText s = case AP.parseOnly langTagParser s of
Right tag -> Just tag
Left _ -> Nothing
langTagToText :: LangTag -> Text.Text
langTagToText (LangTag p []) = p
langTagToText (LangTag p s) = Text.concat $ [p, "-", Text.intercalate "-" s]
-- Parses a language tag as defined by RFC 1766 and constructs a LangTag object.
langTagParser :: AP.Parser LangTag
langTagParser = do
-- Read until we reach a '-' character, or EOF. This is the `primary tag'.
primTag <- tag
-- Read zero or more subtags.
subTags <- many subtag
AP.endOfInput
return $ LangTag primTag subTags
where
tag :: AP.Parser Text.Text
tag = do
t <- AP.takeWhile1 $ AP.inClass tagChars
return t
subtag :: AP.Parser Text.Text
subtag = do
AP.skip (== '-')
tag
tagChars :: [Char]
tagChars = ['a'..'z'] ++ ['A'..'Z']
data StreamFeatures = StreamFeatures
{ streamFeaturesTls :: !(Maybe Bool)
, streamFeaturesMechanisms :: ![Text.Text]
, streamFeaturesRosterVer :: !(Maybe Bool)
-- ^ @Nothing@ for no roster versioning, @Just False@ for roster
-- versioning and @Just True@ when the server sends the non-standard
-- "optional" element (observed with prosody).
, streamFeaturesPreApproval :: !Bool -- ^ Does the server support pre-approval
, streamFeaturesSession :: !(Maybe Bool)
-- ^ Does this server allow the stream elelemt? (See
-- https://tools.ietf.org/html/draft-cridland-xmpp-session-01)
, streamFeaturesOther :: ![Element]
-- TODO: All feature elements instead?
} deriving (Eq, Show)
instance Monoid StreamFeatures where
mempty = StreamFeatures
{ streamFeaturesTls = Nothing
, streamFeaturesMechanisms = []
, streamFeaturesRosterVer = Nothing
, streamFeaturesPreApproval = False
, streamFeaturesSession = Nothing
, streamFeaturesOther = []
}
mappend sf1 sf2 =
StreamFeatures
{ streamFeaturesTls = mplusOn streamFeaturesTls
, streamFeaturesMechanisms = mplusOn streamFeaturesMechanisms
, streamFeaturesRosterVer = mplusOn streamFeaturesRosterVer
, streamFeaturesPreApproval =
streamFeaturesPreApproval sf1
|| streamFeaturesPreApproval sf2
, streamFeaturesSession = mplusOn streamFeaturesSession
, streamFeaturesOther = mplusOn streamFeaturesOther
}
where
mplusOn f = f sf1 `mplus` f sf2
-- | Signals the state of the stream connection.
data ConnectionState
= Closed -- ^ Stream has not been established yet
| Plain -- ^ Stream established, but not secured via TLS
| Secured -- ^ Stream established and secured via TLS
| Finished -- ^ Stream was closed
deriving (Show, Eq, Typeable)
-- | Defines operations for sending, receiving, flushing, and closing on a
-- stream.
data StreamHandle =
StreamHandle { streamSend :: BS.ByteString
-> IO (Either XmppFailure ()) -- ^ Sends may not
-- interleave
, streamReceive :: Int -> IO (Either XmppFailure BS.ByteString)
-- This is to hold the state of the XML parser (otherwise we
-- will receive EventBeginDocument events and forget about
-- name prefixes). (TODO: Clarify)
, streamFlush :: IO ()
, streamClose :: IO ()
}
data StreamState = StreamState
{ -- | State of the stream - 'Closed', 'Plain', or 'Secured'
streamConnectionState :: !ConnectionState
-- | Functions to send, receive, flush, and close the stream
, streamHandle :: StreamHandle
-- | Event conduit source, and its associated finalizer
, streamEventSource :: Source (ErrorT XmppFailure IO) Event
-- | Stream features advertised by the server
, streamFeatures :: !StreamFeatures -- TODO: Maybe?
-- | The hostname or IP specified for the connection
, streamAddress :: !(Maybe Text)
-- | The hostname specified in the server's stream element's
-- `from' attribute
, streamFrom :: !(Maybe Jid)
-- | The identifier specified in the server's stream element's
-- `id' attribute
, streamId :: !(Maybe Text)
-- | The language tag value specified in the server's stream
-- element's `langtag' attribute; will be a `Just' value once
-- connected to the server
-- TODO: Verify
, streamLang :: !(Maybe LangTag)
-- | Our JID as assigned by the server
, streamJid :: !(Maybe Jid)
-- | Configuration settings for the stream
, streamConfiguration :: StreamConfiguration
}
newtype Stream = Stream { unStream :: TMVar StreamState }
---------------
-- JID
---------------
-- | A JID is XMPP\'s native format for addressing entities in the network. It
-- is somewhat similar to an e-mail address but contains three parts instead of
-- two: localpart, domainpart, and resourcepart.
--
-- The @localpart@ of a JID is an optional identifier placed
-- before the domainpart and separated from the latter by a
-- \'\@\' character. Typically a localpart uniquely identifies
-- the entity requesting and using network access provided by a
-- server (i.e., a local account), although it can also
-- represent other kinds of entities (e.g., a chat room
-- associated with a multi-user chat service). The entity
-- represented by an XMPP localpart is addressed within the
-- context of a specific domain (i.e.,
-- @localpart\@domainpart@).
--
-- The domainpart typically identifies the /home/ server to
-- which clients connect for XML routing and data management
-- functionality. However, it is not necessary for an XMPP
-- domainpart to identify an entity that provides core XMPP
-- server functionality (e.g., a domainpart can identify an
-- entity such as a multi-user chat service, a
-- publish-subscribe service, or a user directory).
--
-- The resourcepart of a JID is an optional identifier placed
-- after the domainpart and separated from the latter by the
-- \'\/\' character. A resourcepart can modify either a
-- @localpart\@domainpart@ address or a mere @domainpart@
-- address. Typically a resourcepart uniquely identifies a
-- specific connection (e.g., a device or location) or object
-- (e.g., an occupant in a multi-user chat room) belonging to
-- the entity associated with an XMPP localpart at a domain
-- (i.e., @localpart\@domainpart/resourcepart@).
--
-- For more details see RFC 6122 <http://xmpp.org/rfcs/rfc6122.html>
data Jid = Jid { localpart_ :: !(Maybe NonemptyText)
, domainpart_ :: !NonemptyText
, resourcepart_ :: !(Maybe NonemptyText)
} deriving (Eq, Ord)
-- | Converts a JID to a Text.
jidToText :: Jid -> Text
jidToText (Jid nd dmn res) = Text.concat . concat $
[ maybe [] (:["@"]) (text <$> nd)
, [text dmn]
, maybe [] (\r -> ["/",r]) (text <$> res)
]
-- | Converts a JID to up to three Text values: (the optional) localpart, the
-- domainpart, and (the optional) resourcepart.
--
-- >>> jidToTexts [jid|foo@bar/quux|]
-- (Just "foo","bar",Just "quux")
--
-- >>> jidToTexts [jid|bar/quux|]
-- (Nothing,"bar",Just "quux")
--
-- >>> jidToTexts [jid|foo@bar|]
-- (Just "foo","bar",Nothing)
--
-- prop> jidToTexts j == (localpart j, domainpart j, resourcepart j)
jidToTexts :: Jid -> (Maybe Text, Text, Maybe Text)
jidToTexts (Jid nd dmn res) = (text <$> nd, text dmn, text <$> res)
-- Produces a Jid value in the format "parseJid \"<jid>\"".
instance Show Jid where
show j = "parseJid " ++ show (jidToText j)
-- The string must be in the format "parseJid \"<jid>\"".
-- TODO: This function should produce its error values in a uniform way.
-- TODO: Do we need to care about precedence here?
instance Read Jid where
readsPrec _ s = do
-- Verifies that the first word is "parseJid", parses the second word and
-- the remainder, if any, and produces these two values or fails.
let (s', r) = case lex s of
[] -> error "Expected `parseJid \"<jid>\"'"
[("parseJid", r')] -> case lex r' of
[] -> error "Expected `parseJid \"<jid>\"'"
[(s'', r'')] -> (s'', r'')
_ -> error "Expected `parseJid \"<jid>\"'"
_ -> error "Expected `parseJid \"<jid>\"'"
-- Read the JID string (removes the quotes), validate, and return.
[(parseJid (read s' :: String), r)] -- May fail with "Prelude.read: no parse"
-- or the `parseJid' error message (see below)
#if WITH_TEMPLATE_HASKELL
instance TH.Lift Jid where
lift (Jid lp dp rp) = [| Jid $(mbTextE $ text <$> lp)
$(textE $ text dp)
$(mbTextE $ text <$> rp)
|]
where
textE t = [| Nonempty $ Text.pack $(stringE $ Text.unpack t) |]
mbTextE Nothing = [| Nothing |]
mbTextE (Just s) = [| Just $(textE s) |]
-- | Constructs and validates a @Jid@ at compile time.
--
-- Syntax:
-- @
-- [jid|localpart\@domainpart/resourcepart|]
-- @
--
-- >>> [jid|foo@bar/quux|]
-- parseJid "foo@bar/quux"
--
-- >>> Just [jid|foo@bar/quux|] == jidFromTexts (Just "foo") "bar" (Just "quux")
-- True
--
-- >>> Just [jid|foo@bar/quux|] == jidFromText "foo@bar/quux"
-- True
--
-- See also 'jidFromText'
jid :: QuasiQuoter
jid = QuasiQuoter { quoteExp = \s -> do
when (head s == ' ') . fail $ "Leading whitespaces in JID" ++ show s
let t = Text.pack s
when (Text.last t == ' ') . reportWarning $ "Trailing whitespace in JID " ++ show s
case jidFromText t of
Nothing -> fail $ "Could not parse JID " ++ s
Just j -> TH.lift j
, quotePat = fail "Jid patterns aren't implemented"
, quoteType = fail "jid QQ can't be used in type context"
, quoteDec = fail "jid QQ can't be used in declaration context"
}
-- | Synonym for 'jid'
jidQ :: QuasiQuoter
jidQ = jidQ
#endif
-- | The partial order of "definiteness". JID1 is less than or equal JID2 iff
-- the domain parts are equal and JID1's local part and resource part each are
-- either Nothing or equal to Jid2's
(<~) :: Jid -> Jid -> Bool
(Jid lp1 dp1 rp1) <~ (Jid lp2 dp2 rp2) =
dp1 == dp2 &&
lp1 ~<~ lp2 &&
rp1 ~<~ rp2
where
Nothing ~<~ _ = True
Just x ~<~ Just y = x == y
_ ~<~ _ = False
-- Produces a LangTag value in the format "parseLangTag \"<jid>\"".
instance Show LangTag where
show l = "parseLangTag " ++ show (langTagToText l)
-- The string must be in the format "parseLangTag \"<LangTag>\"". This is based
-- on parseJid, and suffers the same problems.
instance Read LangTag where
readsPrec _ s = do
let (s', r) = case lex s of
[] -> error "Expected `parseLangTag \"<LangTag>\"'"
[("parseLangTag", r')] -> case lex r' of
[] -> error "Expected `parseLangTag \"<LangTag>\"'"
[(s'', r'')] -> (s'', r'')
_ -> error "Expected `parseLangTag \"<LangTag>\"'"
_ -> error "Expected `parseLangTag \"<LangTag>\"'"
[(parseLangTag (read s' :: String), r)]
parseLangTag :: String -> LangTag
parseLangTag s = case langTagFromText $ Text.pack s of
Just l -> l
Nothing -> error $ "Language tag value (" ++ s ++ ") did not validate"
#if WITH_TEMPLATE_HASKELL
langTagQ :: QuasiQuoter
langTagQ = QuasiQuoter {quoteExp = \s -> case langTagFromText $ Text.pack s of
Nothing -> fail $ "Not a valid language tag: "
++ s
Just lt -> [|LangTag $(textE $ primaryTag lt)
$(listE $
map textE (subtags lt))
|]
, quotePat = fail $ "LanguageTag patterns aren't"
++ " implemented"
, quoteType = fail $ "LanguageTag QQ can't be used"
++ " in type context"
, quoteDec = fail $ "LanguageTag QQ can't be used"
++ " in declaration context"
}
where
textE t = [| Text.pack $(stringE $ Text.unpack t) |]
#endif
-- | Parses a JID string.
--
-- Note: This function is only meant to be used to reverse @Jid@ Show
-- operations; it will produce an 'undefined' value if the JID does not
-- validate; please refer to @jidFromText@ for a safe equivalent.
parseJid :: String -> Jid
parseJid s = case jidFromText $ Text.pack s of
Just j -> j
Nothing -> error $ "Jid value (" ++ s ++ ") did not validate"
-- | Parse a JID
--
-- >>> localpart <$> jidFromText "foo@bar/quux"
-- Just (Just "foo")
--
-- >>> domainpart <$> jidFromText "foo@bar/quux"
-- Just "bar"
--
-- >>> resourcepart <$> jidFromText "foo@bar/quux"
-- Just (Just "quux")
--
-- * Counterexamples
--
-- A JID must only have one \'\@\':
--
-- >>> jidFromText "foo@bar@quux"
-- Nothing
--
-- \'\@\' must come before \'/\':
--
-- >>> jidFromText "foo/bar@quux"
-- Nothing
--
-- The domain part can\'t be empty:
--
-- >>> jidFromText "foo@/quux"
-- Nothing
--
-- Both the local part and the resource part can be omitted (but the
-- \'\@\' and \'\/\', must also be removed):
--
-- >>> jidToTexts <$> jidFromText "bar"
-- Just (Nothing,"bar",Nothing)
--
-- >>> jidToTexts <$> jidFromText "@bar"
-- Nothing
--
-- >>> jidToTexts <$> jidFromText "bar/"
-- Nothing
jidFromText :: Text -> Maybe Jid
jidFromText t = do
(l, d, r) <- eitherToMaybe $ AP.parseOnly jidParts t
jidFromTexts l d r
where
eitherToMaybe = either (const Nothing) Just
-- | Convert localpart, domainpart, and resourcepart to a JID. Runs the
-- appropriate stringprep profiles and validates the parts.
--
-- >>> jidFromTexts (Just "foo") "bar" (Just "baz") == jidFromText "foo@bar/baz"
-- True
--
-- prop> jidFromTexts (localpart j) (domainpart j) (resourcepart j) == Just j
jidFromTexts :: Maybe Text -> Text -> Maybe Text -> Maybe Jid
jidFromTexts l d r = do
localPart <- case l of
Nothing -> return Nothing
Just l'-> do
l'' <- SP.runStringPrep nodeprepProfile l'
guard $ validPartLength l''
let prohibMap = Set.fromList nodeprepExtraProhibitedCharacters
guard $ Text.all (`Set.notMember` prohibMap) l''
l''' <- nonEmpty l''
return $ Just l'''
domainPart' <- SP.runStringPrep (SP.namePrepProfile False) (stripSuffix d)
guard $ validDomainPart domainPart'
guard $ validPartLength domainPart'
domainPart <- nonEmpty domainPart'
resourcePart <- case r of
Nothing -> return Nothing
Just r' -> do
r'' <- SP.runStringPrep resourceprepProfile r'
guard $ validPartLength r''
r''' <- nonEmpty r''
return $ Just r'''
return $ Jid localPart domainPart resourcePart
where
validDomainPart :: Text -> Bool
validDomainPart s = not $ Text.null s -- TODO: implement more stringent
-- checks
validPartLength :: Text -> Bool
validPartLength p = Text.length p > 0
&& BS.length (Text.encodeUtf8 p) < 1024
-- RFC6122 §2.2
stripSuffix t = if Text.last t == '.' then Text.init t else t
-- | Returns 'True' if the JID is /bare/, that is, it doesn't have a resource
-- part, and 'False' otherwise.
--
-- >>> isBare [jid|foo@bar|]
-- True
--
-- >>> isBare [jid|foo@bar/quux|]
-- False
isBare :: Jid -> Bool
isBare j | resourcepart j == Nothing = True
| otherwise = False
-- | Returns 'True' if the JID is /full/, and 'False' otherwise.
--
-- @isFull = not . isBare@
--
-- >>> isBare [jid|foo@bar|]
-- True
--
-- >>> isBare [jid|foo@bar/quux|]
-- False
isFull :: Jid -> Bool
isFull = not . isBare
-- | Returns the @Jid@ without the resourcepart (if any).
--
-- >>> toBare [jid|foo@bar/quux|] == [jid|foo@bar|]
-- True
toBare :: Jid -> Jid
toBare j = j{resourcepart_ = Nothing}
-- | Returns the localpart of the @Jid@ (if any).
--
-- >>> localpart [jid|foo@bar/quux|]
-- Just "foo"
localpart :: Jid -> Maybe Text
localpart = fmap text . localpart_
-- | Returns the domainpart of the @Jid@.
--
-- >>> domainpart [jid|foo@bar/quux|]
-- "bar"
domainpart :: Jid -> Text
domainpart = text . domainpart_
-- | Returns the resourcepart of the @Jid@ (if any).
--
-- >>> resourcepart [jid|foo@bar/quux|]
-- Just "quux"
resourcepart :: Jid -> Maybe Text
resourcepart = fmap text . resourcepart_
-- | Parse the parts of a JID. The parts need to be validated with stringprep
-- before the JID can be constructed
jidParts :: AP.Parser (Maybe Text, Text, Maybe Text)
jidParts = do
maybeLocalPart <- Just <$> localPart <|> return Nothing
domainPart <- AP.takeWhile1 (AP.notInClass ['@', '/'])
maybeResourcePart <- Just <$> resourcePart <|> return Nothing
AP.endOfInput
return (maybeLocalPart, domainPart, maybeResourcePart)
where
localPart = do
bytes <- AP.takeWhile1 (AP.notInClass ['@', '/'])
_ <- AP.char '@'
return bytes
resourcePart = do
_ <- AP.char '/'
AP.takeWhile1 (AP.notInClass ['@', '/'])
-- | The `nodeprep' StringPrep profile.
nodeprepProfile :: SP.StringPrepProfile
nodeprepProfile = SP.Profile { SP.maps = [SP.b1, SP.b2]
, SP.shouldNormalize = True
, SP.prohibited = [ SP.a1
, SP.c11
, SP.c12
, SP.c21
, SP.c22
, SP.c3
, SP.c4
, SP.c5
, SP.c6
, SP.c7
, SP.c8
, SP.c9
]
, SP.shouldCheckBidi = True
}
-- | These characters needs to be checked for after normalization.
nodeprepExtraProhibitedCharacters :: [Char]
nodeprepExtraProhibitedCharacters = ['\x22', '\x26', '\x27', '\x2F', '\x3A',
'\x3C', '\x3E', '\x40']
-- | The `resourceprep' StringPrep profile.
resourceprepProfile :: SP.StringPrepProfile
resourceprepProfile = SP.Profile { SP.maps = [SP.b1]
, SP.shouldNormalize = True
, SP.prohibited = [ SP.a1
, SP.c12
, SP.c21
, SP.c22
, SP.c3
, SP.c4
, SP.c5
, SP.c6
, SP.c7
, SP.c8
, SP.c9
]
, SP.shouldCheckBidi = True
}
-- | Specify the method with which the connection is (re-)established
data ConnectionDetails = UseRealm -- ^ Use realm to resolv host. This is the
-- default.
| UseSrv HostName -- ^ Use this hostname for a SRV lookup
| UseHost HostName PortNumber -- ^ Use specified host
| UseConnection (ErrorT XmppFailure IO StreamHandle)
-- ^ Use a custom method to create a StreamHandle. This
-- will also be used by reconnect. For example, to
-- establish TLS before starting the stream as done by
-- GCM, see 'connectTls'. You can also return an
-- already established connection. This method should
-- also return a hostname that is used for TLS
-- signature verification. If startTLS is not used it
-- can be left empty
-- | Configuration settings related to the stream.
data StreamConfiguration =
StreamConfiguration { -- | Default language when no language tag is set
preferredLang :: !(Maybe LangTag)
-- | JID to include in the stream element's `to'
-- attribute when the connection is secured; if the
-- boolean is set to 'True', then the JID is also
-- included when the 'ConnectionState' is 'Plain'
, toJid :: !(Maybe (Jid, Bool))
-- | By settings this field, clients can specify the
-- network interface to use, override the SRV lookup
-- of the realm, as well as specify the use of a
-- non-standard port when connecting by IP or
-- connecting to a domain without SRV records.
, connectionDetails :: ConnectionDetails
-- | DNS resolver configuration
, resolvConf :: ResolvConf
-- | Whether or not to perform the legacy
-- session bind as defined in the (outdated)
-- RFC 3921 specification
, tlsBehaviour :: TlsBehaviour
-- | Settings to be used for TLS negotitation
, tlsParams :: ClientParams
}
-- | Default parameters for TLS restricted to strong ciphers
xmppDefaultParamsStrong :: ClientParams
xmppDefaultParamsStrong = (defaultParamsClient "" BS.empty)
{ clientSupported = def
{ supportedCiphers = ciphersuite_strong
++ [ cipher_AES256_SHA1
, cipher_AES128_SHA1
]
}
}
-- | Default parameters for TLS
xmppDefaultParams :: ClientParams
xmppDefaultParams = (defaultParamsClient "" BS.empty)
{ clientSupported = def
{ supportedCiphers = ciphersuite_all
}
}
instance Default StreamConfiguration where
def = StreamConfiguration { preferredLang = Nothing
, toJid = Nothing
, connectionDetails = UseRealm
, resolvConf = defaultResolvConf
, tlsBehaviour = PreferTls
, tlsParams = xmppDefaultParams
}
-- | How the client should behave in regards to TLS.
data TlsBehaviour = RequireTls -- ^ Require the use of TLS; disconnect if it's
-- not offered.
| PreferTls -- ^ Negotitate TLS if it's available.
| PreferPlain -- ^ Negotitate TLS only if the server requires
-- it
| RefuseTls -- ^ Never secure the stream with TLS.
|
Philonous/pontarius-xmpp
|
source/Network/Xmpp/Types.hs
|
bsd-3-clause
| 59,691 | 0 | 18 | 23,554 | 6,662 | 3,956 | 2,706 | 773 | 4 |
{-# LANGUAGE TemplateHaskell #-}
import Test.Framework (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.QuickCheck
import Test.HUnit hiding (Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Draughts
import Game.Board.BasicTurnGame
import Control.Monad
import Data.List
main :: IO ()
main = defaultMain [testCanMove, testTooglePlayer, quickCheckTests]
game = defaultDraughtsGame
testCanMove :: Test
testCanMove = testGroup "Testing canMove function"
[testCase "Testing white can move white" (
assertEqual "Should white could move white." True (canMove (game) White (1,2))),
testCase "Testing black can move black" (
assertEqual "Should black could move black." True (canMove (game) Black (7,8))),
testCase "Testing white can't move black" (
assertEqual "Should white couldn't move black." False (canMove (game) White (7,8))),
testCase "Testing black can't move white" (
assertEqual "Should black couldn't move white." False (canMove (game) Black (1,2))),
testCase "Testing white can't move nothing" (
assertEqual "Should white couldn't move nothing." False (canMove (game) White (4,5))),
testCase "Testing black can't move nothing" (
assertEqual "Should white couldn't move nothing." False (canMove (game) Black (5,4)))]
testTooglePlayer :: Test
testTooglePlayer = testGroup "Testing tooglePlayer function"
[testCase "Testing toogle White player" (
assertEqual "Should toogle White to Black." Black (curPlayer . togglePlayer $ (game))),
testCase "Testing toogle White player two times" (
assertEqual "Should toogle White to White." White (curPlayer . togglePlayer . togglePlayer $ (game)))]
quickCheckTests :: Test
quickCheckTests = testGroup "Testing with QuickCheck"
[testProperty "Testing MovePiece" prop_MovePiece,
testProperty "Testing RemovePiece and AddPiece" prop_RemoveAddPiece]
prop_MovePiece =
forAll generatePositions $ \(posO, posD) ->
((allPieces (applyChange game (MovePiece posO posD))) == (allPieces game)) ||
(( (sortPieces $ allPieces (applyChange (applyChange game (MovePiece posO posD)) (MovePiece posD posO))) == (sortPieces $ allPieces game)))
prop_RemoveAddPiece =
forAll generatePosition $ \pos -> case (getPieceAt (gameState game) pos) of
Just(player,piece) ->
((sortPieces $ allPieces (applyChange (applyChange game (RemovePiece pos)) (AddPiece pos player piece))) == (sortPieces $ allPieces game))
_ -> ((allPieces (applyChange game (RemovePiece pos))) == (allPieces game))
generatePosition :: Gen(Int,Int)
generatePosition = liftM2 (,) (choose (1,8)) (choose (1,8))
generatePositions :: Gen((Int, Int),(Int, Int))
generatePositions =
liftM2 (,) generatePosition generatePosition
sortPieces = (sortBy (\(x,y,_,_) (x2,y2,_,_) ->
if x>x2 then GT
else if x<x2 then LT
else if y>y2 then GT
else LT))
|
Raf0/draughts
|
test/Tests.hs
|
bsd-3-clause
| 2,978 | 0 | 20 | 548 | 902 | 496 | 406 | 56 | 4 |
module Haskell99Pointfree.P47
(
) where
import Haskell99Pointfree.P46
and_1' = and_1
or_1' = or_1
equ_1' = equ_1
nand_1' = nand_1
xor_1' = xor_1
impl_1' = impl_1
--I just declared the fixity to show how it is done, the values are not correct.
infixl 4 `and_1'`
infixl 6 `or_1'`
infixl 4 `equ_1'`
infixl 3 `nand_1'`
infix 7 `xor_1'`
infixr 2 `impl_1'`
|
SvenWille/Haskell99Pointfree
|
src/Haskell99Pointfree/P47.hs
|
bsd-3-clause
| 365 | 0 | 4 | 73 | 87 | 58 | 29 | 15 | 1 |
module Article.Router
(
module X
) where
import Article.Router.Handler as X
import Article.Router.Helper as X (requireArticle, requireTag,
requireTagAndArticle)
|
Lupino/dispatch-article
|
src/Article/Router.hs
|
bsd-3-clause
| 237 | 0 | 5 | 94 | 39 | 27 | 12 | 6 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Formats where
import qualified Data.ByteString.Lazy as B hiding (putStrLn)
import Data.Monoid ((<>))
import Control.Monad (when, forM_)
import Control.Lens
import Zeppelin as Z
import Databricks as D
import Notebook as N
import Pandoc as P
import Utils
type SourceFormat = String -> B.ByteString -> Either String [(String, N.Notebook)]
type TargetFormat = [(String, N.Notebook)] -> [(String, B.ByteString)]
type NotebookFormat = (SourceFormat, TargetFormat)
databricksDBCSource :: SourceFormat
databricksDBCSource f x = over (each . _2) D.toNotebook <$> fromByteStringArchive x
databricksJSONSource :: SourceFormat
databricksJSONSource f x = (singleton . D.toNotebook) <$> D.fromByteString x
where singleton y = [(f, y)]
zeppelinSource :: SourceFormat
zeppelinSource f x = (singleton . Z.toNotebook) <$> Z.fromByteString x
where singleton y = [(f, y)]
databricksJSONTarget :: TargetFormat
databricksJSONTarget = over (each . _2) compile
where compile = D.toByteString . D.fromNotebook
zeppelinTarget :: TargetFormat
zeppelinTarget = over (each . _1) (swapExtension ".json") . over (each . _2) compile
where compile = Z.toByteString . Z.fromNotebook
markdownTarget :: TargetFormat
markdownTarget = over (each . _1) (swapExtension ".md") . over (each . _2) compile
where compile = P.toMarkdown . P.fromNotebook
markdownTargetKaTeX :: TargetFormat
markdownTargetKaTeX = over (each . _1) (swapExtension ".md") . over (each . _2) compile
where compile = P.toMarkdownKaTeX . P.fromNotebook
htmlTarget :: TargetFormat
htmlTarget = over (each . _1) (swapExtension ".html") . over (each . _2) compile
where compile = P.toHtml . P.fromNotebook
pandocTarget :: TargetFormat
pandocTarget = over (each . _1) (swapExtension ".pandoc") . over (each . _2) compile
where compile = P.toNative . P.fromNotebook
zeppelinFormat = (zeppelinSource, zeppelinTarget)
databricksJSONFormat = (databricksJSONSource, databricksJSONTarget)
|
TiloWiklund/pinot
|
src/Formats.hs
|
bsd-3-clause
| 1,982 | 0 | 10 | 287 | 643 | 361 | 282 | 42 | 1 |
{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Numeric.MixedType.Power
Description : Bottom-up typed exponentiation
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Numeric.MixedTypes.Power
(
-- * Exponentiation
CanPow(..), CanPowBy
, (^), (^^)
, powUsingMul, integerPowCN
, powUsingMulRecip
, CanTestIsIntegerType(..)
-- ** Tests
, specCanPow
)
where
import Utils.TH.DeclForTypes
import Numeric.MixedTypes.PreludeHiding
import qualified Prelude as P
import Text.Printf
import Test.Hspec
import Test.QuickCheck
import Numeric.CollectErrors ( CN, cn, unCN )
import qualified Numeric.CollectErrors as CN
import Numeric.MixedTypes.Literals
import Numeric.MixedTypes.Bool
import Numeric.MixedTypes.Eq
import Numeric.MixedTypes.Ord
-- import Numeric.MixedTypes.MinMaxAbs
import Numeric.MixedTypes.AddSub
import Numeric.MixedTypes.Mul
-- import Numeric.MixedTypes.Div ()
{---- Exponentiation -----}
infixl 8 ^, ^^
(^) :: (CanPow t1 t2) => t1 -> t2 -> PowType t1 t2
(^) = pow
(^^) :: (CanPow t1 t2) => t1 -> t2 -> PPowType t1 t2
(^^) = ppow
{-|
A replacement for Prelude's binary `P.^` and `P.^^`.
-}
class CanPow b e where
type PowType b e
type PPowType b e
type PPowType b e = PowType b e
type PowType b e = b -- default
pow :: b -> e -> PowType b e
ppow :: b -> e -> PPowType b e
default ppow :: (PPowType b e ~ PowType b e) => b -> e -> PPowType b e
ppow = pow
{-|
Ability to detect whether a numeric type is restricted to (a subset of) integers.
This is useful eg when checking the arguments of the power operator in the CN instance for power.
-}
class CanTestIsIntegerType t where
isIntegerType :: t -> Bool
isIntegerType _ = False
instance CanTestIsIntegerType t => CanTestIsIntegerType (CN t) where
isIntegerType t = isIntegerType (unCN t)
instance CanTestIsIntegerType Int where
isIntegerType _ = True
instance CanTestIsIntegerType Integer where
isIntegerType _ = True
instance CanTestIsIntegerType Rational
instance CanTestIsIntegerType Double
integerPowCN ::
(HasOrderCertainly b Integer, HasOrderCertainly e Integer,
HasEqCertainly b Integer, HasEqCertainly e Integer)
=>
(b -> e -> r) -> CN b -> CN e -> CN r
integerPowCN unsafeIntegerPow b n
| n !<! 0 =
CN.noValueNumErrorCertain $ CN.OutOfDomain "illegal integer pow: negative exponent"
| n !==! 0 && b !==! 0 =
CN.noValueNumErrorCertain $ CN.OutOfDomain "illegal integer pow: 0^0"
| n ?<? 0 =
CN.noValueNumErrorCertain $ CN.OutOfDomain "illegal integer pow: negative exponent"
| n ?==? 0 && b ?==? 0 =
CN.noValueNumErrorPotential $ CN.OutOfDomain "illegal integer pow: 0^0"
| otherwise =
CN.lift2 unsafeIntegerPow b n
powCN ::
(HasOrderCertainly b Integer, HasOrderCertainly e Integer,
HasEqCertainly b Integer, CanTestIsIntegerType b, CanTestIsIntegerType e, CanTestInteger e)
=>
(b -> e -> r) -> CN b -> CN e -> CN r
powCN unsafePow b e
| isIntegerType b && isIntegerType e && e !<! 0 =
CN.noValueNumErrorCertain $ CN.OutOfDomain "illegal integer pow: negative exponent, consider using ppow or (^^)"
| otherwise = ppowCN unsafePow b e
ppowCN ::
(HasOrderCertainly b Integer, HasOrderCertainly e Integer,
HasEqCertainly b Integer, CanTestInteger e)
=>
(b -> e -> r) -> CN b -> CN e -> CN r
ppowCN unsafePow b e
| b !==! 0 && e !<=! 0 =
CN.noValueNumErrorCertain $ CN.OutOfDomain "illegal pow: 0^e with e <= 0"
| b !<! 0 && certainlyNotInteger e =
CN.noValueNumErrorCertain $ CN.OutOfDomain "illegal pow: b^e with b < 0 and e non-integer"
| b ?==? 0 && e ?<=? 0 =
CN.noValueNumErrorPotential $ CN.OutOfDomain "illegal pow: 0^e with e <= 0"
| b ?<? 0 && not (certainlyInteger e) =
CN.noValueNumErrorPotential $ CN.OutOfDomain "illegal pow: b^e with b < 0 and e non-integer"
| otherwise =
CN.lift2 unsafePow b e
powUsingMul ::
(CanBeInteger e)
=>
t -> (t -> t -> t) -> t -> e -> t
powUsingMul one mul' x nPre
| n < 0 = error $ "powUsingMul is not defined for negative exponent " ++ show n
| n == 0 = one
| otherwise = aux n
where
(.*) = mul'
n = integer nPre
aux m
| m == 1 = x
| even m =
let s = aux (m `P.div` 2) in s .* s
| otherwise =
let s = aux ((m-1) `P.div` 2) in x .* s .* s
powUsingMulRecip ::
(CanBeInteger e)
=>
t -> (t -> t -> t) -> (t -> t) -> t -> e -> t
powUsingMulRecip one mul' recip' x e
| eI < 0 = recip' $ powUsingMul one mul' x (negate eI)
| otherwise = powUsingMul one mul' x eI
where
eI = integer e
type CanPowBy t1 t2 =
(CanPow t1 t2, PowType t1 t2 ~ t1)
{-|
HSpec properties that each implementation of CanPow should satisfy.
-}
specCanPow ::
_ => T t1 -> T t2 -> Spec
specCanPow (T typeName1 :: T t1) (T typeName2 :: T t2) =
describe (printf "CanPow %s %s" typeName1 typeName2) $ do
it "x^0 = 1" $ do
property $ \ (x :: t1) ->
let one = (convertExactly 1 :: t1) in
let z = (convertExactly 0 :: t2) in
(x ^ z) ?==?$ one
it "x^1 = x" $ do
property $ \ (x :: t1) ->
let one = (convertExactly 1 :: t2) in
(x ^ one) ?==?$ x
it "x^(y+1) = x*x^y" $ do
property $ \ (x :: t1) (y :: t2) ->
(isCertainlyNonNegative y) ==>
x * (x ^ y) ?==?$ (x ^ (y + 1))
where
infix 4 ?==?$
(?==?$) :: (HasEqCertainlyAsymmetric a b, Show a, Show b) => a -> b -> Property
(?==?$) = printArgsIfFails2 "?==?" (?==?)
instance CanPow Integer Integer where
type PowType Integer Integer = Integer
type PPowType Integer Integer = Rational
pow b = (P.^) b
ppow b = (P.^^) (rational b)
instance CanPow Integer Int where
type PowType Integer Int = Integer
type PPowType Integer Int = Rational
pow b = (P.^) b
ppow b = (P.^^) (rational b)
instance CanPow Int Integer where
type PowType Int Integer = Integer
type PPowType Int Integer = Rational
pow b = (P.^) (integer b)
ppow b = (P.^^) (rational b)
instance CanPow Int Int where
type PowType Int Int = Rational
pow b = (P.^^) (rational b)
instance CanPow Rational Int where
pow = (P.^^)
instance CanPow Rational Integer where
pow = (P.^^)
instance CanPow Double Int where
pow = (P.^^)
instance CanPow Double Integer where
pow = (P.^^)
instance CanPow Double Double where
type PowType Double Double = Double
pow = (P.**)
instance CanPow Double Rational where
type PowType Double Rational = Double
pow b e = b ^ (double e)
instance CanPow Rational Double where
type PowType Rational Double = Double
pow b e = (double b) ^ e
instance CanPow Integer Double where
type PowType Integer Double = Double
pow b e = (double b) ^ e
instance CanPow Int Double where
type PowType Int Double = Double
pow b e = (double b) ^ e
-- instance (CanPow a b) => CanPow [a] [b] where
-- type PowType [a] [b] = [PowType a b]
-- pow (x:xs) (y:ys) = (pow x y) : (pow xs ys)
-- pow _ _ = []
instance (CanPow a b) => CanPow (Maybe a) (Maybe b) where
type PowType (Maybe a) (Maybe b) = Maybe (PowType a b)
pow (Just x) (Just y) = Just (pow x y)
pow _ _ = Nothing
instance
(CanPow b e, HasOrderCertainly b Integer, HasOrderCertainly e Integer,
HasEqCertainly b Integer, CanTestIsIntegerType b, CanTestIsIntegerType e, CanTestInteger e)
=>
CanPow (CN b) (CN e)
where
type PowType (CN b) (CN e) = CN (PowType b e)
type PPowType (CN b) (CN e) = CN (PPowType b e)
pow = powCN pow
ppow = ppowCN ppow
$(declForTypes
[[t| Integer |], [t| Int |], [t| Rational |], [t| Double |]]
(\ t -> [d|
instance
(CanPow $t e, HasOrderCertainly e Integer, CanTestIsIntegerType e, CanTestInteger e)
=>
CanPow $t (CN e)
where
type PowType $t (CN e) = CN (PowType $t e)
pow b e = powCN pow (cn b) e
type PPowType $t (CN e) = CN (PPowType $t e)
ppow b e = ppowCN ppow (cn b) e
instance
(CanPow b $t, HasOrderCertainly b Integer, HasEqCertainly b Integer, CanTestIsIntegerType b)
=>
CanPow (CN b) $t
where
type PowType (CN b) $t = CN (PowType b $t)
pow b e = powCN pow b (cn e)
type PPowType (CN b) $t = CN (PPowType b $t)
ppow b e = ppowCN ppow b (cn e)
|]))
|
michalkonecny/mixed-types-num
|
src/Numeric/MixedTypes/Power.hs
|
bsd-3-clause
| 8,392 | 0 | 20 | 2,017 | 2,642 | 1,381 | 1,261 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.