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
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.EC2.DescribeReservedInstancesListings -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Describes your account\'s Reserved Instance listings in the Reserved -- Instance Marketplace. -- -- The Reserved Instance Marketplace matches sellers who want to resell -- Reserved Instance capacity that they no longer need with buyers who want -- to purchase additional capacity. Reserved Instances bought and sold -- through the Reserved Instance Marketplace work like any other Reserved -- Instances. -- -- As a seller, you choose to list some or all of your Reserved Instances, -- and you specify the upfront price to receive for them. Your Reserved -- Instances are then listed in the Reserved Instance Marketplace and are -- available for purchase. -- -- As a buyer, you specify the configuration of the Reserved Instance to -- purchase, and the Marketplace matches what you\'re searching for with -- what\'s available. The Marketplace first sells the lowest priced -- Reserved Instances to you, and continues to sell available Reserved -- Instance listings to you until your demand is met. You are charged based -- on the total price of all of the listings that you purchase. -- -- For more information, see -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html Reserved Instance Marketplace> -- in the /Amazon Elastic Compute Cloud User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesListings.html AWS API Reference> for DescribeReservedInstancesListings. module Network.AWS.EC2.DescribeReservedInstancesListings ( -- * Creating a Request describeReservedInstancesListings , DescribeReservedInstancesListings -- * Request Lenses , drilFilters , drilReservedInstancesId , drilReservedInstancesListingId -- * Destructuring the Response , describeReservedInstancesListingsResponse , DescribeReservedInstancesListingsResponse -- * Response Lenses , drilrsReservedInstancesListings , drilrsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeReservedInstancesListings' smart constructor. data DescribeReservedInstancesListings = DescribeReservedInstancesListings' { _drilFilters :: !(Maybe [Filter]) , _drilReservedInstancesId :: !(Maybe Text) , _drilReservedInstancesListingId :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeReservedInstancesListings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'drilFilters' -- -- * 'drilReservedInstancesId' -- -- * 'drilReservedInstancesListingId' describeReservedInstancesListings :: DescribeReservedInstancesListings describeReservedInstancesListings = DescribeReservedInstancesListings' { _drilFilters = Nothing , _drilReservedInstancesId = Nothing , _drilReservedInstancesListingId = Nothing } -- | One or more filters. -- -- - 'reserved-instances-id' - The ID of the Reserved Instances. -- -- - 'reserved-instances-listing-id' - The ID of the Reserved Instances -- listing. -- -- - 'status' - The status of the Reserved Instance listing ('pending' | -- 'active' | 'cancelled' | 'closed'). -- -- - 'status-message' - The reason for the status. -- drilFilters :: Lens' DescribeReservedInstancesListings [Filter] drilFilters = lens _drilFilters (\ s a -> s{_drilFilters = a}) . _Default . _Coerce; -- | One or more Reserved Instance IDs. drilReservedInstancesId :: Lens' DescribeReservedInstancesListings (Maybe Text) drilReservedInstancesId = lens _drilReservedInstancesId (\ s a -> s{_drilReservedInstancesId = a}); -- | One or more Reserved Instance Listing IDs. drilReservedInstancesListingId :: Lens' DescribeReservedInstancesListings (Maybe Text) drilReservedInstancesListingId = lens _drilReservedInstancesListingId (\ s a -> s{_drilReservedInstancesListingId = a}); instance AWSRequest DescribeReservedInstancesListings where type Rs DescribeReservedInstancesListings = DescribeReservedInstancesListingsResponse request = postQuery eC2 response = receiveXML (\ s h x -> DescribeReservedInstancesListingsResponse' <$> (x .@? "reservedInstancesListingsSet" .!@ mempty >>= may (parseXMLList "item")) <*> (pure (fromEnum s))) instance ToHeaders DescribeReservedInstancesListings where toHeaders = const mempty instance ToPath DescribeReservedInstancesListings where toPath = const "/" instance ToQuery DescribeReservedInstancesListings where toQuery DescribeReservedInstancesListings'{..} = mconcat ["Action" =: ("DescribeReservedInstancesListings" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), toQuery (toQueryList "Filters" <$> _drilFilters), "ReservedInstancesId" =: _drilReservedInstancesId, "ReservedInstancesListingId" =: _drilReservedInstancesListingId] -- | /See:/ 'describeReservedInstancesListingsResponse' smart constructor. data DescribeReservedInstancesListingsResponse = DescribeReservedInstancesListingsResponse' { _drilrsReservedInstancesListings :: !(Maybe [ReservedInstancesListing]) , _drilrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeReservedInstancesListingsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'drilrsReservedInstancesListings' -- -- * 'drilrsResponseStatus' describeReservedInstancesListingsResponse :: Int -- ^ 'drilrsResponseStatus' -> DescribeReservedInstancesListingsResponse describeReservedInstancesListingsResponse pResponseStatus_ = DescribeReservedInstancesListingsResponse' { _drilrsReservedInstancesListings = Nothing , _drilrsResponseStatus = pResponseStatus_ } -- | Information about the Reserved Instance listing. drilrsReservedInstancesListings :: Lens' DescribeReservedInstancesListingsResponse [ReservedInstancesListing] drilrsReservedInstancesListings = lens _drilrsReservedInstancesListings (\ s a -> s{_drilrsReservedInstancesListings = a}) . _Default . _Coerce; -- | The response status code. drilrsResponseStatus :: Lens' DescribeReservedInstancesListingsResponse Int drilrsResponseStatus = lens _drilrsResponseStatus (\ s a -> s{_drilrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeReservedInstancesListings.hs
mpl-2.0
7,472
0
15
1,379
781
475
306
92
1
{-# LANGUAGE CPP, ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, LambdaCase, TypeOperators #-} module Reflex.Spider.Internal where import qualified Reflex.Class as R import qualified Reflex.Host.Class as R import Data.IORef import System.Mem.Weak import Data.Foldable import Data.Traversable import Control.Monad hiding (mapM, mapM_, forM_, forM, sequence) import Control.Monad.Reader hiding (mapM, mapM_, forM_, forM, sequence) import GHC.Exts import Control.Applicative -- Unconditionally import, because otherwise it breaks on GHC 7.10.1RC2 import Data.Dependent.Map (DMap, DSum (..)) import qualified Data.Dependent.Map as DMap import Data.GADT.Compare import Data.Functor.Misc import Data.Maybe import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Control.Monad.Ref import Control.Monad.Exception import Data.Monoid ((<>)) import System.IO.Unsafe import Unsafe.Coerce import Control.Monad.Primitive -- Note: must come last to silence warnings due to AMP on GHC < 7.10 import Prelude hiding (mapM, mapM_, any, sequence, concat) debugPropagate :: Bool debugInvalidateHeight :: Bool #ifdef DEBUG #define DEBUG_NODEIDS debugPropagate = True debugInvalidateHeight = True class HasNodeId a where getNodeId :: a -> Int instance HasNodeId (Hold a) where getNodeId = holdNodeId instance HasNodeId (PushSubscribed a b) where getNodeId = pushSubscribedNodeId instance HasNodeId (SwitchSubscribed a) where getNodeId = switchSubscribedNodeId instance HasNodeId (MergeSubscribed a) where getNodeId = mergeSubscribedNodeId instance HasNodeId (FanSubscribed a) where getNodeId = fanSubscribedNodeId instance HasNodeId (CoincidenceSubscribed a) where getNodeId = coincidenceSubscribedNodeId instance HasNodeId (RootSubscribed a) where getNodeId = rootSubscribedNodeId showNodeId :: HasNodeId a => a -> String showNodeId = ("#"<>) . show . getNodeId #else debugPropagate = False debugInvalidateHeight = False showNodeId :: a -> String showNodeId = const "" #endif #ifdef DEBUG_NODEIDS {-# NOINLINE nextNodeIdRef #-} nextNodeIdRef :: IORef Int nextNodeIdRef = unsafePerformIO $ newIORef 1 {-# NOINLINE unsafeNodeId #-} unsafeNodeId :: a -> Int unsafeNodeId a = unsafePerformIO $ do touch a atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n) #endif --TODO: Figure out why certain things are not 'representational', then make them representational so we can use coerce --type role Hold representational data Hold a = Hold { holdValue :: !(IORef a) , holdInvalidators :: !(IORef [Weak Invalidator]) -- We need to use 'Any' for the next two things, because otherwise Hold inherits a nominal role for its 'a' parameter, and we want to be able to use 'coerce' , holdSubscriber :: !(IORef Any) -- Keeps its subscription alive; for some reason, a regular (or strict) reference to the Subscriber itself wasn't working, so had to use an IORef , holdParent :: !(IORef Any) -- Keeps its parent alive (will be undefined until the hold is initialized --TODO: Probably shouldn't be an IORef #ifdef DEBUG_NODEIDS , holdNodeId :: Int #endif } data EventEnv = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment]) , eventEnvHoldInits :: !(IORef [SomeHoldInit]) , eventEnvClears :: !(IORef [SomeMaybeIORef]) , eventEnvRootClears :: !(IORef [SomeDMapIORef]) , eventEnvCurrentHeight :: !(IORef Int) , eventEnvCoincidenceInfos :: !(IORef [SomeCoincidenceInfo]) , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge])) } runEventM :: EventM a -> EventEnv -> IO a runEventM = runReaderT . unEventM askToAssignRef :: EventM (IORef [SomeAssignment]) askToAssignRef = EventM $ asks eventEnvAssignments askHoldInitRef :: EventM (IORef [SomeHoldInit]) askHoldInitRef = EventM $ asks eventEnvHoldInits getCurrentHeight :: EventM Int getCurrentHeight = EventM $ do heightRef <- asks eventEnvCurrentHeight liftIO $ readIORef heightRef putCurrentHeight :: Int -> EventM () putCurrentHeight h = EventM $ do heightRef <- asks eventEnvCurrentHeight liftIO $ writeIORef heightRef h scheduleClear :: IORef (Maybe a) -> EventM () scheduleClear r = EventM $ do clears <- asks eventEnvClears liftIO $ modifyIORef' clears (SomeMaybeIORef r :) scheduleRootClear :: IORef (DMap k) -> EventM () scheduleRootClear r = EventM $ do clears <- asks eventEnvRootClears liftIO $ modifyIORef' clears (SomeDMapIORef r :) scheduleMerge :: Int -> MergeSubscribed a -> EventM () scheduleMerge height subscribed = EventM $ do delayedRef <- asks eventEnvDelayedMerges liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) height [DelayedMerge subscribed] emitCoincidenceInfo :: SomeCoincidenceInfo -> EventM () emitCoincidenceInfo sci = EventM $ do ciRef <- asks eventEnvCoincidenceInfos liftIO $ modifyIORef' ciRef (sci:) -- Note: hold cannot examine its event until after the phase is over hold :: a -> Event a -> EventM (Behavior a) hold v0 e = do holdInitRef <- askHoldInitRef liftIO $ do valRef <- newIORef v0 invsRef <- newIORef [] parentRef <- newIORef $ error "hold not yet initialized (parent)" subscriberRef <- newIORef $ error "hold not yet initialized (subscriber)" let h = Hold { holdValue = valRef , holdInvalidators = invsRef , holdSubscriber = subscriberRef , holdParent = parentRef #ifdef DEBUG_NODEIDS , holdNodeId = unsafeNodeId (v0, e) #endif } s <- newSubscriberHold h writeIORef subscriberRef $ unsafeCoerce s modifyIORef' holdInitRef (SomeHoldInit e h :) return $ BehaviorHold h subscribeHold :: Event a -> Hold a -> EventM () subscribeHold e h = do toAssignRef <- askToAssignRef !s <- liftIO $ liftM unsafeCoerce $ readIORef $ holdSubscriber h -- This must be performed strictly so that the weak pointer points at the actual item ws <- liftIO $ mkWeakPtrWithDebug s "holdSubscriber" subd <- subscribe e $ WeakSubscriberSimple ws liftIO $ writeIORef (holdParent h) $ unsafeCoerce subd occ <- liftIO $ getEventSubscribedOcc subd case occ of Nothing -> return () Just o -> liftIO $ modifyIORef' toAssignRef (SomeAssignment h o :) --type role BehaviorM representational -- BehaviorM can sample behaviors newtype BehaviorM a = BehaviorM { unBehaviorM :: ReaderT (Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed])) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix) data BehaviorSubscribed a = BehaviorSubscribedHold (Hold a) | BehaviorSubscribedPull (PullSubscribed a) data SomeBehaviorSubscribed = forall a. SomeBehaviorSubscribed (BehaviorSubscribed a) --type role PullSubscribed representational data PullSubscribed a = PullSubscribed { pullSubscribedValue :: !a , pullSubscribedInvalidators :: !(IORef [Weak Invalidator]) , pullSubscribedOwnInvalidator :: !Invalidator , pullSubscribedParents :: ![SomeBehaviorSubscribed] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated } --type role Pull representational data Pull a = Pull { pullValue :: !(IORef (Maybe (PullSubscribed a))) , pullCompute :: !(BehaviorM a) } data Invalidator = forall a. InvalidatorPull (Pull a) | forall a. InvalidatorSwitch (SwitchSubscribed a) data RootSubscribed a = RootSubscribed { rootSubscribedSubscribers :: !(IORef [WeakSubscriber a]) , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence } data Root (k :: * -> *) = Root { rootOccurrence :: !(IORef (DMap k)) -- The currently-firing occurrence of this event , rootSubscribed :: !(IORef (DMap (WrapArg RootSubscribed k))) , rootInit :: !(forall a. k a -> RootTrigger a -> IO (IO ())) } data SomeHoldInit = forall a. SomeHoldInit (Event a) (Hold a) -- EventM can do everything BehaviorM can, plus create holds newtype EventM a = EventM { unEventM :: ReaderT EventEnv IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over data PushSubscribed a b = PushSubscribed { pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are) , pushSubscribedHeight :: !(IORef Int) , pushSubscribedSubscribers :: !(IORef [WeakSubscriber b]) , pushSubscribedSelf :: !(Subscriber a) -- Hold this in memory to ensure our WeakReferences don't die , pushSubscribedParent :: !(EventSubscribed a) #ifdef DEBUG_NODEIDS , pushSubscribedNodeId :: Int #endif } data Push a b = Push { pushCompute :: !(a -> EventM (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed , pushParent :: !(Event a) , pushSubscribed :: !(IORef (Maybe (PushSubscribed a b))) --TODO: Can we replace this with an unsafePerformIO thunk? } data MergeSubscribed k = MergeSubscribed { mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k))) , mergeSubscribedAccum :: !(IORef (DMap k)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence , mergeSubscribedHeight :: !(IORef Int) , mergeSubscribedSubscribers :: !(IORef [WeakSubscriber (DMap k)]) , mergeSubscribedSelf :: !Any -- Hold all our Subscribers in memory , mergeSubscribedParents :: !(DMap (WrapArg EventSubscribed k)) #ifdef DEBUG_NODEIDS , mergeSubscribedNodeId :: Int #endif } --TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key) data Merge k = Merge { mergeParents :: !(DMap (WrapArg Event k)) , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed k))) --TODO: Can we replace this with an unsafePerformIO thunk? } data FanSubscriberKey k a where FanSubscriberKey :: k a -> FanSubscriberKey k [WeakSubscriber a] instance GEq k => GEq (FanSubscriberKey k) where geq (FanSubscriberKey a) (FanSubscriberKey b) = case geq a b of Nothing -> Nothing Just Refl -> Just Refl instance GCompare k => GCompare (FanSubscriberKey k) where gcompare (FanSubscriberKey a) (FanSubscriberKey b) = case gcompare a b of GLT -> GLT GEQ -> GEQ GGT -> GGT data FanSubscribed k = FanSubscribed { fanSubscribedSubscribers :: !(IORef (DMap (FanSubscriberKey k))) , fanSubscribedParent :: !(EventSubscribed (DMap k)) , fanSubscribedSelf :: {-# NOUNPACK #-} (Subscriber (DMap k)) #ifdef DEBUG_NODEIDS , fanSubscribedNodeId :: Int #endif } data Fan k = Fan { fanParent :: !(Event (DMap k)) , fanSubscribed :: !(IORef (Maybe (FanSubscribed k))) } data SwitchSubscribed a = SwitchSubscribed { switchSubscribedOccurrence :: !(IORef (Maybe a)) , switchSubscribedHeight :: !(IORef Int) , switchSubscribedSubscribers :: !(IORef [WeakSubscriber a]) , switchSubscribedSelf :: {-# NOUNPACK #-} (Subscriber a) , switchSubscribedSelfWeak :: !(IORef (Weak (Subscriber a))) , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} Invalidator , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak Invalidator)) , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed]) , switchSubscribedParent :: !(Behavior (Event a)) , switchSubscribedCurrentParent :: !(IORef (EventSubscribed a)) #ifdef DEBUG_NODEIDS , switchSubscribedNodeId :: Int #endif } data Switch a = Switch { switchParent :: !(Behavior (Event a)) , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed a))) } data CoincidenceSubscribed a = CoincidenceSubscribed { coincidenceSubscribedOccurrence :: !(IORef (Maybe a)) , coincidenceSubscribedSubscribers :: !(IORef [WeakSubscriber a]) , coincidenceSubscribedHeight :: !(IORef Int) , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber (Event a)) , coincidenceSubscribedOuterParent :: !(EventSubscribed (Event a)) , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed a))) #ifdef DEBUG_NODEIDS , coincidenceSubscribedNodeId :: Int #endif } data Coincidence a = Coincidence { coincidenceParent :: !(Event (Event a)) , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a))) } data Box a = Box { unBox :: a } --type WeakSubscriber a = Weak (Subscriber a) data WeakSubscriber a = forall k. GCompare k => WeakSubscriberMerge !(k a) !(Weak (Box (MergeSubscribed k))) --TODO: Can we inline the GCompare? | WeakSubscriberSimple !(Weak (Subscriber a)) showWeakSubscriberType :: WeakSubscriber a -> String showWeakSubscriberType = \case WeakSubscriberMerge _ _ -> "WeakSubscriberMerge" WeakSubscriberSimple _ -> "WeakSubscriberSimple" deRefWeakSubscriber :: WeakSubscriber a -> IO (Maybe (Subscriber a)) deRefWeakSubscriber ws = case ws of WeakSubscriberSimple w -> deRefWeak w WeakSubscriberMerge k w -> liftM (fmap $ SubscriberMerge k . unBox) $ deRefWeak w data Subscriber a = forall b. SubscriberPush !(a -> EventM (Maybe b)) (PushSubscribed a b) | forall k. GCompare k => SubscriberMerge !(k a) (MergeSubscribed k) --TODO: Can we inline the GCompare? | forall k. (GCompare k, a ~ DMap k) => SubscriberFan (FanSubscribed k) | SubscriberHold !(Hold a) | SubscriberSwitch (SwitchSubscribed a) | forall b. a ~ Event b => SubscriberCoincidenceOuter (CoincidenceSubscribed b) | SubscriberCoincidenceInner (CoincidenceSubscribed a) showSubscriberType :: Subscriber a -> String showSubscriberType = \case SubscriberPush _ _ -> "SubscriberPush" SubscriberMerge _ _ -> "SubscriberMerge" SubscriberFan _ -> "SubscriberFan" SubscriberHold _ -> "SubscriberHold" SubscriberSwitch _ -> "SubscriberSwitch" SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter" SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner" data Event a = forall k. GCompare k => EventRoot !(k a) !(Root k) | EventNever | forall b. EventPush !(Push b a) | forall k. (GCompare k, a ~ DMap k) => EventMerge !(Merge k) | forall k. GCompare k => EventFan !(k a) !(Fan k) | EventSwitch !(Switch a) | EventCoincidence !(Coincidence a) showEventType :: Event a -> String showEventType = \case EventRoot _ _ -> "EventRoot" EventNever -> "EventNever" EventPush _ -> "EventPush" EventMerge _ -> "EventMerge" EventFan _ _ -> "EventFan" EventSwitch _ -> "EventSwitch" EventCoincidence _ -> "EventCoincidence" data EventSubscribed a = EventSubscribedRoot {-# NOUNPACK #-} (RootSubscribed a) | EventSubscribedNever | forall b. EventSubscribedPush !(PushSubscribed b a) | forall k. (GCompare k, a ~ DMap k) => EventSubscribedMerge !(MergeSubscribed k) | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed k) | EventSubscribedSwitch !(SwitchSubscribed a) | EventSubscribedCoincidence !(CoincidenceSubscribed a) -- These function are constructor functions that are marked NOINLINE so they are -- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away -- so any weak references that are attached to the constructors will have their -- finalizer run. Using the opaque constructor, does not see the -- constructor application, so it behaves like an IORef and cannot be fused away. -- -- The result is also evaluated to WHNF, since forcing a thunk invalidates -- the weak pointer to it in some cases. {-# NOINLINE newRootSubscribed #-} newRootSubscribed :: IO (Maybe a) -> IORef [WeakSubscriber a] -> IO (RootSubscribed a) newRootSubscribed occ subs = return $! RootSubscribed { rootSubscribedOccurrence = occ , rootSubscribedSubscribers = subs } {-# NOINLINE newSubscriberPush #-} newSubscriberPush :: (a -> EventM (Maybe b)) -> PushSubscribed a b -> IO (Subscriber a) newSubscriberPush compute subd = return $! SubscriberPush compute subd {-# NOINLINE newSubscriberHold #-} newSubscriberHold :: Hold a -> IO (Subscriber a) newSubscriberHold h = return $! SubscriberHold h {-# NOINLINE newSubscriberFan #-} newSubscriberFan :: GCompare k => FanSubscribed k -> IO (Subscriber (DMap k)) newSubscriberFan subd = return $! SubscriberFan subd {-# NOINLINE newSubscriberSwitch #-} newSubscriberSwitch :: SwitchSubscribed a -> IO (Subscriber a) newSubscriberSwitch subd = return $! SubscriberSwitch subd {-# NOINLINE newSubscriberCoincidenceOuter #-} newSubscriberCoincidenceOuter :: CoincidenceSubscribed b -> IO (Subscriber (Event b)) newSubscriberCoincidenceOuter subd = return $! SubscriberCoincidenceOuter subd {-# NOINLINE newSubscriberCoincidenceInner #-} newSubscriberCoincidenceInner :: CoincidenceSubscribed a -> IO (Subscriber a) newSubscriberCoincidenceInner subd = return $! SubscriberCoincidenceInner subd {-# NOINLINE newInvalidatorSwitch #-} newInvalidatorSwitch :: SwitchSubscribed a -> IO Invalidator newInvalidatorSwitch subd = return $! InvalidatorSwitch subd {-# NOINLINE newInvalidatorPull #-} newInvalidatorPull :: Pull a -> IO Invalidator newInvalidatorPull p = return $! InvalidatorPull p {-# NOINLINE newBox #-} newBox :: a -> IO (Box a) newBox a = return $! Box a --type role Behavior representational data Behavior a = BehaviorHold !(Hold a) | BehaviorConst !a | BehaviorPull !(Pull a) -- ResultM can read behaviors and events type ResultM = EventM {-# NOINLINE unsafeNewIORef #-} unsafeNewIORef :: a -> b -> IORef b unsafeNewIORef _ b = unsafePerformIO $ newIORef b instance Functor Event where fmap f = push $ return . Just . f instance Functor Behavior where fmap f = pull . liftM f . readBehaviorTracked {-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly push :: (a -> EventM (Maybe b)) -> Event a -> Event b push f e = EventPush $ Push { pushCompute = f , pushParent = e , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead? } {-# RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-} {-# NOINLINE pull #-} pull :: BehaviorM a -> Behavior a pull a = BehaviorPull $ Pull { pullCompute = a , pullValue = unsafeNewIORef a Nothing } {-# RULES "pull/pull" forall a. pull (readBehaviorTracked (pull a)) = pull a #-} {-# NOINLINE switch #-} switch :: Behavior (Event a) -> Event a switch a = EventSwitch $ Switch { switchParent = a , switchSubscribed = unsafeNewIORef a Nothing } {-# RULES "switch/constB" forall e. switch (BehaviorConst e) = e #-} coincidence :: Event (Event a) -> Event a coincidence a = EventCoincidence $ Coincidence { coincidenceParent = a , coincidenceSubscribed = unsafeNewIORef a Nothing } newRoot :: IO (Root k) newRoot = do occRef <- newIORef DMap.empty subscribedRef <- newIORef DMap.empty return $ Root { rootOccurrence = occRef , rootSubscribed = subscribedRef , rootInit = \_ _ -> return $ return () } propagateAndUpdateSubscribersRef :: IORef [WeakSubscriber a] -> a -> EventM () propagateAndUpdateSubscribersRef subscribersRef a = do subscribers <- liftIO $ readIORef subscribersRef liftIO $ writeIORef subscribersRef [] stillAlive <- propagate a subscribers liftIO $ modifyIORef' subscribersRef (++stillAlive) -- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors run :: [DSum RootTrigger] -> ResultM b -> IO b run roots after = do when debugPropagate $ putStrLn "Running an event frame" result <- runFrame $ do rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do occBefore <- liftIO $ do occBefore <- readIORef occRef writeIORef occRef $ DMap.insert k a occBefore return occBefore if DMap.null occBefore then do scheduleRootClear occRef return $ Just r else return Nothing forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> a) -> do propagateAndUpdateSubscribersRef subscribersRef a delayedRef <- EventM $ asks eventEnvDelayedMerges let go = do delayed <- liftIO $ readIORef delayedRef case IntMap.minViewWithKey delayed of Nothing -> return () Just ((currentHeight, current), future) -> do when debugPropagate $ liftIO $ putStrLn $ "Running height " ++ show currentHeight putCurrentHeight currentHeight liftIO $ writeIORef delayedRef future forM_ current $ \d -> case d of DelayedMerge subscribed -> do height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed case height `compare` currentHeight of LT -> error "Somehow a merge's height has been decreased after it was scheduled" GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?) EQ -> do m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed liftIO $ writeIORef (mergeSubscribedAccum subscribed) DMap.empty --TODO: Assert that m is not empty liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m scheduleClear $ mergeSubscribedOccurrence subscribed propagateAndUpdateSubscribersRef (mergeSubscribedSubscribers subscribed) m go go putCurrentHeight maxBound after when debugPropagate $ putStrLn "Done running an event frame" return result data SomeMaybeIORef = forall a. SomeMaybeIORef (IORef (Maybe a)) data SomeDMapIORef = forall k. SomeDMapIORef (IORef (DMap k)) data SomeAssignment = forall a. SomeAssignment (Hold a) a data DelayedMerge = forall k. DelayedMerge (MergeSubscribed k) debugFinalize :: Bool debugFinalize = False mkWeakPtrWithDebug :: a -> String -> IO (Weak a) mkWeakPtrWithDebug x debugNote = mkWeakPtr x $ if debugFinalize then Just $ putStrLn $ "finalizing: " ++ debugNote else Nothing type WeakList a = [Weak a] --TODO: Is it faster to clean up every time, or to occasionally go through and clean up as needed? traverseAndCleanWeakList_ :: Monad m => (wa -> m (Maybe a)) -> [wa] -> (a -> m ()) -> m [wa] traverseAndCleanWeakList_ deRef ws f = go ws where go [] = return [] go (h:t) = do ma <- deRef h case ma of Just a -> do f a t' <- go t return $ h : t' Nothing -> go t -- | Propagate everything at the current height propagate :: a -> [WeakSubscriber a] -> EventM [WeakSubscriber a] propagate a subscribers = do traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subscribers $ \s -> case s of SubscriberPush compute subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberPush" <> showNodeId subscribed occ <- compute a case occ of Nothing -> return () -- No need to write a Nothing back into the Ref Just o -> do liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ scheduleClear $ pushSubscribedOccurrence subscribed liftIO . writeIORef (pushSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (pushSubscribedSubscribers subscribed)) SubscriberMerge k subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberMerge" <> showNodeId subscribed oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed liftIO $ writeIORef (mergeSubscribedAccum subscribed) $ DMap.insertWith (error "Same key fired multiple times for") k a oldM when (DMap.null oldM) $ do -- Only schedule the firing once height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed --TODO: assertions about height currentHeight <- getCurrentHeight when (height <= currentHeight) $ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")" scheduleMerge height subscribed SubscriberFan subscribed -> do subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed when debugPropagate $ liftIO $ putStrLn $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing" --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large forM_ (DMap.toList a) $ \(k :=> v) -> case DMap.lookup (FanSubscriberKey k) subs of Nothing -> do when debugPropagate $ liftIO $ putStrLn "No subscriber for key" return () Just subsubs -> do _ <- propagate v subsubs --TODO: use the value of this return () --TODO: The following is way too slow to do all the time subs' <- liftIO $ forM (DMap.toList subs) $ ((\(FanSubscriberKey k :=> subsubs) -> do subsubs' <- traverseAndCleanWeakList_ (liftIO . deRefWeakSubscriber) subsubs (const $ return ()) return $ if null subsubs' then Nothing else Just $ FanSubscriberKey k :=> subsubs') :: DSum (FanSubscriberKey k) -> IO (Maybe (DSum (FanSubscriberKey k)))) liftIO $ writeIORef (fanSubscribedSubscribers subscribed) $ DMap.fromDistinctAscList $ catMaybes subs' SubscriberHold h -> do invalidators <- liftIO $ readIORef $ holdInvalidators h when debugPropagate $ liftIO $ putStrLn $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators) toAssignRef <- askToAssignRef liftIO $ modifyIORef' toAssignRef (SomeAssignment h a :) SubscriberSwitch subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberSwitch" <> showNodeId subscribed liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a scheduleClear $ switchSubscribedOccurrence subscribed subs <- liftIO $ readIORef $ switchSubscribedSubscribers subscribed liftIO . writeIORef (switchSubscribedSubscribers subscribed) =<< propagate a subs SubscriberCoincidenceOuter subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceOuter" <> showNodeId subscribed outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed when debugPropagate $ liftIO $ putStrLn $ " outerHeight = " <> show outerHeight (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed when debugPropagate $ liftIO $ putStrLn $ " isJust occ = " <> show (isJust occ) when debugPropagate $ liftIO $ putStrLn $ " innerHeight = " <> show innerHeight liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd scheduleClear $ coincidenceSubscribedInnerParent subscribed case occ of Nothing -> do when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height writeIORef (coincidenceSubscribedHeight subscribed) innerHeight mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) Just o -> do -- Since it's already firing, no need to adjust height liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ scheduleClear $ coincidenceSubscribedOccurrence subscribed liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate o =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed)) SubscriberCoincidenceInner subscribed -> do when debugPropagate $ liftIO $ putStrLn $ "SubscriberCoincidenceInner" <> showNodeId subscribed liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a scheduleClear $ coincidenceSubscribedOccurrence subscribed liftIO . writeIORef (coincidenceSubscribedSubscribers subscribed) =<< propagate a =<< liftIO (readIORef (coincidenceSubscribedSubscribers subscribed)) data SomeCoincidenceInfo = forall a. SomeCoincidenceInfo (Weak (Subscriber a)) (Subscriber a) (Maybe (CoincidenceSubscribed a)) -- The CoincidenceSubscriber will be present only if heights need to be reset subscribeCoincidenceInner :: Event a -> Int -> CoincidenceSubscribed a -> EventM (Maybe a, Int, EventSubscribed a) subscribeCoincidenceInner o outerHeight subscribedUnsafe = do subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe wsubInner <- liftIO $ mkWeakPtrWithDebug subInner "SubscriberCoincidenceInner" innerSubd <- {-# SCC "innerSubd" #-} (subscribe o $ WeakSubscriberSimple wsubInner) innerOcc <- liftIO $ getEventSubscribedOcc innerSubd innerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef innerSubd let height = max innerHeight outerHeight emitCoincidenceInfo $ SomeCoincidenceInfo wsubInner subInner $ if height > outerHeight then Just subscribedUnsafe else Nothing return (innerOcc, height, innerSubd) readBehavior :: Behavior a -> IO a readBehavior b = runBehaviorM (readBehaviorTracked b) Nothing --TODO: Specialize readBehaviorTracked to the Nothing and Just cases runBehaviorM :: BehaviorM a -> Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]) -> IO a runBehaviorM a mwi = runReaderT (unBehaviorM a) mwi askInvalidator :: BehaviorM (Maybe (Weak Invalidator)) askInvalidator = liftM (fmap fst) $ BehaviorM ask askParentsRef :: BehaviorM (Maybe (IORef [SomeBehaviorSubscribed])) askParentsRef = liftM (fmap snd) $ BehaviorM ask readBehaviorTracked :: Behavior a -> BehaviorM a readBehaviorTracked b = case b of BehaviorHold h -> do result <- liftIO $ readIORef $ holdValue h askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:)) askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :)) liftIO $ touch $ holdSubscriber h return result BehaviorConst a -> return a BehaviorPull p -> do val <- liftIO $ readIORef $ pullValue p case val of Just subscribed -> do askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :)) askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:)) liftIO $ touch $ pullSubscribedOwnInvalidator subscribed return $ pullSubscribedValue subscribed Nothing -> do i <- liftIO $ newInvalidatorPull p wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull" parentsRef <- liftIO $ newIORef [] a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) $ Just (wi, parentsRef) invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator parents <- liftIO $ readIORef parentsRef let subscribed = PullSubscribed { pullSubscribedValue = a , pullSubscribedInvalidators = invsRef , pullSubscribedOwnInvalidator = i , pullSubscribedParents = parents } liftIO $ writeIORef (pullValue p) $ Just subscribed askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :)) return a readEvent :: Event a -> ResultM (Maybe a) readEvent e = case e of EventRoot k r -> liftIO $ liftM (DMap.lookup k) $ readIORef $ rootOccurrence r EventNever -> return Nothing EventPush p -> do subscribed <- getPushSubscribed p liftIO $ do result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid touch $ pushSubscribedSelf subscribed return result EventMerge m -> do subscribed <- getMergeSubscribed m liftIO $ do result <- readIORef $ mergeSubscribedOccurrence subscribed touch $ mergeSubscribedSelf subscribed return result EventFan k f -> do parentOcc <- readEvent $ fanParent f return $ DMap.lookup k =<< parentOcc EventSwitch s -> do subscribed <- getSwitchSubscribed s liftIO $ do result <- readIORef $ switchSubscribedOccurrence subscribed touch $ switchSubscribedSelf subscribed touch $ switchSubscribedOwnInvalidator subscribed return result EventCoincidence c -> do subscribed <- getCoincidenceSubscribed c liftIO $ do result <- readIORef $ coincidenceSubscribedOccurrence subscribed touch $ coincidenceSubscribedOuter subscribed --TODO: do we need to touch the inner subscriber? return result -- Always refers to 0 {-# NOINLINE zeroRef #-} zeroRef :: IORef Int zeroRef = unsafePerformIO $ newIORef 0 getEventSubscribed :: Event a -> EventM (EventSubscribed a) getEventSubscribed e = case e of EventRoot k r -> liftM EventSubscribedRoot $ getRootSubscribed k r EventNever -> return EventSubscribedNever EventPush p -> liftM EventSubscribedPush $ getPushSubscribed p EventFan k f -> liftM (EventSubscribedFan k) $ getFanSubscribed f EventMerge m -> liftM EventSubscribedMerge $ getMergeSubscribed m EventSwitch s -> liftM EventSubscribedSwitch $ getSwitchSubscribed s EventCoincidence c -> liftM EventSubscribedCoincidence $ getCoincidenceSubscribed c debugSubscribe :: Bool debugSubscribe = False subscribeEventSubscribed :: EventSubscribed a -> WeakSubscriber a -> IO () subscribeEventSubscribed es ws = case es of EventSubscribedRoot r -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Root" modifyIORef' (rootSubscribedSubscribers r) (ws:) EventSubscribedNever -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Never" return () EventSubscribedPush subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Push" modifyIORef' (pushSubscribedSubscribers subscribed) (ws:) EventSubscribedFan k subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Fan" modifyIORef' (fanSubscribedSubscribers subscribed) $ DMap.insertWith (++) (FanSubscriberKey k) [ws] EventSubscribedMerge subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Merge" modifyIORef' (mergeSubscribedSubscribers subscribed) (ws:) EventSubscribedSwitch subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Switch" modifyIORef' (switchSubscribedSubscribers subscribed) (ws:) EventSubscribedCoincidence subscribed -> do when debugSubscribe $ liftIO $ putStrLn $ "subscribeEventSubscribed Coincidence" modifyIORef' (coincidenceSubscribedSubscribers subscribed) (ws:) getEventSubscribedOcc :: EventSubscribed a -> IO (Maybe a) getEventSubscribedOcc es = case es of EventSubscribedRoot r -> rootSubscribedOccurrence r EventSubscribedNever -> return Nothing EventSubscribedPush subscribed -> readIORef $ pushSubscribedOccurrence subscribed EventSubscribedFan k subscribed -> do parentOcc <- getEventSubscribedOcc $ fanSubscribedParent subscribed let occ = DMap.lookup k =<< parentOcc return occ EventSubscribedMerge subscribed -> readIORef $ mergeSubscribedOccurrence subscribed EventSubscribedSwitch subscribed -> readIORef $ switchSubscribedOccurrence subscribed EventSubscribedCoincidence subscribed -> readIORef $ coincidenceSubscribedOccurrence subscribed eventSubscribedHeightRef :: EventSubscribed a -> IORef Int eventSubscribedHeightRef es = case es of EventSubscribedRoot _ -> zeroRef EventSubscribedNever -> zeroRef EventSubscribedPush subscribed -> pushSubscribedHeight subscribed EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ fanSubscribedParent subscribed EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed subscribe :: Event a -> WeakSubscriber a -> EventM (EventSubscribed a) subscribe e ws = do subd <- getEventSubscribed e liftIO $ subscribeEventSubscribed subd ws return subd noinlineFalse :: Bool noinlineFalse = False {-# NOINLINE noinlineFalse #-} getRootSubscribed :: GCompare k => k a -> Root k -> EventM (RootSubscribed a) getRootSubscribed k r = do mSubscribed <- liftIO $ readIORef $ rootSubscribed r case DMap.lookup (WrapArg k) mSubscribed of Just subscribed -> return subscribed Nothing -> liftIO $ do subscribersRef <- newIORef [] subscribed <- newRootSubscribed (liftM (DMap.lookup k) $ readIORef $ rootOccurrence r) subscribersRef -- Strangely, init needs the same stuff as a RootSubscribed has, but it must not be the same as the one that everyone's subscribing to, or it'll leak memory uninit <- rootInit r k $ RootTrigger (subscribersRef, rootOccurrence r, k) addFinalizer subscribed $ do when noinlineFalse $ putStr "" -- For some reason, without this line, the finalizer will run earlier than it should -- putStrLn "Uninit root" uninit liftIO $ modifyIORef' (rootSubscribed r) $ DMap.insert (WrapArg k) subscribed return subscribed -- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in getPushSubscribed :: Push a b -> EventM (PushSubscribed a b) getPushSubscribed p = do mSubscribed <- liftIO $ readIORef $ pushSubscribed p case mSubscribed of Just subscribed -> return subscribed Nothing -> do -- Not yet subscribed subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ pushSubscribed p s <- liftIO $ newSubscriberPush (pushCompute p) subscribedUnsafe ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberPush" subd <- subscribe (pushParent p) $ WeakSubscriberSimple ws parentOcc <- liftIO $ getEventSubscribedOcc subd occ <- liftM join $ mapM (pushCompute p) parentOcc occRef <- liftIO $ newIORef occ when (isJust occ) $ scheduleClear occRef subscribersRef <- liftIO $ newIORef [] let subscribed = PushSubscribed { pushSubscribedOccurrence = occRef , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref , pushSubscribedSubscribers = subscribersRef , pushSubscribedSelf = unsafeCoerce s , pushSubscribedParent = subd #ifdef DEBUG_NODEIDS , pushSubscribedNodeId = unsafeNodeId p #endif } liftIO $ writeIORef (pushSubscribed p) $ Just subscribed return subscribed getMergeSubscribed :: forall k. GCompare k => Merge k -> EventM (MergeSubscribed k) getMergeSubscribed m = {-# SCC "getMergeSubscribed.entire" #-} do mSubscribed <- liftIO $ readIORef $ mergeSubscribed m case mSubscribed of Just subscribed -> return subscribed Nothing -> if DMap.null $ mergeParents m then emptyMergeSubscribed else do subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized" subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef s <- liftIO $ newBox subscribedUnsafe ws <- liftIO $ mkWeakPtrWithDebug s "SubscriberMerge" subscribers :: [(Any, Maybe (DSum k), Int, DSum (WrapArg EventSubscribed k))] <- forM (DMap.toList $ mergeParents m) $ {-# SCC "getMergeSubscribed.a" #-} \(WrapArg k :=> e) -> {-# SCC "getMergeSubscribed.a1" #-} do parentSubd <- {-# SCC "getMergeSubscribed.a.parentSubd" #-} subscribe e $ WeakSubscriberMerge k ws parentOcc <- {-# SCC "getMergeSubscribed.a.parentOcc" #-} liftIO $ getEventSubscribedOcc parentSubd height <- {-# SCC "getMergeSubscribed.a.height" #-} liftIO $ readIORef $ eventSubscribedHeightRef parentSubd return $ {-# SCC "getMergeSubscribed.a.returnVal" #-} (unsafeCoerce s :: Any, fmap (k :=>) parentOcc, height, WrapArg k :=> parentSubd) let dm = DMap.fromDistinctAscList $ catMaybes $ map (\(_, x, _, _) -> x) subscribers subscriberHeights = map (\(_, _, x, _) -> x) subscribers myHeight = if any (==invalidHeight) subscriberHeights --TODO: Replace 'any' with invalidHeight-preserving 'maximum' then invalidHeight else succ $ Prelude.maximum subscriberHeights -- This is safe because the DMap will never be empty here currentHeight <- getCurrentHeight let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now then (if DMap.null dm then Nothing else Just dm, DMap.empty) else (Nothing, dm) when (not $ DMap.null accum) $ do scheduleMerge myHeight subscribedUnsafe occRef <- liftIO $ newIORef occ when (isJust occ) $ scheduleClear occRef accumRef <- liftIO $ newIORef accum heightRef <- liftIO $ newIORef myHeight subsRef <- liftIO $ newIORef [] let subscribed = MergeSubscribed { mergeSubscribedOccurrence = occRef , mergeSubscribedAccum = accumRef , mergeSubscribedHeight = heightRef , mergeSubscribedSubscribers = subsRef , mergeSubscribedSelf = unsafeCoerce $ map (\(x, _, _, _) -> x) subscribers --TODO: Does lack of strictness make this leak? , mergeSubscribedParents = DMap.fromDistinctAscList $ map (\(_, _, _, x) -> x) subscribers #ifdef DEBUG_NODEIDS , mergeSubscribedNodeId = unsafeNodeId m #endif } liftIO $ writeIORef subscribedRef subscribed return subscribed where emptyMergeSubscribed = do --TODO: This should never happen occRef <- liftIO $ newIORef Nothing accumRef <- liftIO $ newIORef DMap.empty subsRef <- liftIO $ newIORef [] return $ MergeSubscribed { mergeSubscribedOccurrence = occRef , mergeSubscribedAccum = accumRef , mergeSubscribedHeight = zeroRef , mergeSubscribedSubscribers = subsRef --TODO: This will definitely leak , mergeSubscribedSelf = unsafeCoerce () , mergeSubscribedParents = DMap.empty #ifdef DEBUG_NODEIDS , mergeSubscribedNodeId = -1 #endif } getFanSubscribed :: GCompare k => Fan k -> EventM (FanSubscribed k) getFanSubscribed f = do mSubscribed <- liftIO $ readIORef $ fanSubscribed f case mSubscribed of Just subscribed -> return subscribed Nothing -> do subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ liftM fromJust $ readIORef $ fanSubscribed f sub <- liftIO $ newSubscriberFan subscribedUnsafe wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberFan" subd <- subscribe (fanParent f) $ WeakSubscriberSimple wsub subscribersRef <- liftIO $ newIORef DMap.empty let subscribed = FanSubscribed { fanSubscribedParent = subd , fanSubscribedSubscribers = subscribersRef , fanSubscribedSelf = sub #ifdef DEBUG_NODEIDS , fanSubscribedNodeId = unsafeNodeId f #endif } liftIO $ writeIORef (fanSubscribed f) $ Just subscribed return subscribed getSwitchSubscribed :: Switch a -> EventM (SwitchSubscribed a) getSwitchSubscribed s = do mSubscribed <- liftIO $ readIORef $ switchSubscribed s case mSubscribed of Just subscribed -> return subscribed Nothing -> do subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created" subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef i <- liftIO $ newInvalidatorSwitch subscribedUnsafe sub <- liftIO $ newSubscriberSwitch subscribedUnsafe wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch" wiRef <- liftIO $ newIORef wi wsub <- liftIO $ mkWeakPtrWithDebug sub "SubscriberSwitch" selfWeakRef <- liftIO $ newIORef wsub parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) $ Just (wi, parentsRef) subd <- subscribe e $ WeakSubscriberSimple wsub subdRef <- liftIO $ newIORef subd parentOcc <- liftIO $ getEventSubscribedOcc subd occRef <- liftIO $ newIORef parentOcc when (isJust parentOcc) $ scheduleClear occRef heightRef <- liftIO $ newIORef =<< readIORef (eventSubscribedHeightRef subd) subscribersRef <- liftIO $ newIORef [] let subscribed = SwitchSubscribed { switchSubscribedOccurrence = occRef , switchSubscribedHeight = heightRef , switchSubscribedSubscribers = subscribersRef , switchSubscribedSelf = sub , switchSubscribedSelfWeak = selfWeakRef , switchSubscribedOwnInvalidator = i , switchSubscribedOwnWeakInvalidator = wiRef , switchSubscribedBehaviorParents = parentsRef , switchSubscribedParent = switchParent s , switchSubscribedCurrentParent = subdRef #ifdef DEBUG_NODEIDS , switchSubscribedNodeId = unsafeNodeId s #endif } liftIO $ writeIORef subscribedRef subscribed liftIO $ writeIORef (switchSubscribed s) $ Just subscribed return subscribed getCoincidenceSubscribed :: forall a. Coincidence a -> EventM (CoincidenceSubscribed a) getCoincidenceSubscribed c = do mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c case mSubscribed of Just subscribed -> return subscribed Nothing -> do subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created" subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe wsubOuter <- liftIO $ mkWeakPtrWithDebug subOuter "subOuter" outerSubd <- subscribe (coincidenceParent c) $ WeakSubscriberSimple wsubOuter outerOcc <- liftIO $ getEventSubscribedOcc outerSubd outerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef outerSubd (occ, height, mInnerSubd) <- case outerOcc of Nothing -> return (Nothing, outerHeight, Nothing) Just o -> do (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe return (occ, height, Just innerSubd) occRef <- liftIO $ newIORef occ when (isJust occ) $ scheduleClear occRef heightRef <- liftIO $ newIORef height innerSubdRef <- liftIO $ newIORef mInnerSubd scheduleClear innerSubdRef subscribersRef <- liftIO $ newIORef [] let subscribed = CoincidenceSubscribed { coincidenceSubscribedOccurrence = occRef , coincidenceSubscribedHeight = heightRef , coincidenceSubscribedSubscribers = subscribersRef , coincidenceSubscribedOuter = subOuter , coincidenceSubscribedOuterParent = outerSubd , coincidenceSubscribedInnerParent = innerSubdRef #ifdef DEBUG_NODEIDS , coincidenceSubscribedNodeId = unsafeNodeId c #endif } liftIO $ writeIORef subscribedRef subscribed liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed return subscribed merge :: GCompare k => DMap (WrapArg Event k) -> Event (DMap k) merge m = EventMerge $ Merge { mergeParents = m , mergeSubscribed = unsafeNewIORef m Nothing } newtype EventSelector k = EventSelector { select :: forall a. k a -> Event a } fan :: GCompare k => Event (DMap k) -> EventSelector k fan e = let f = Fan { fanParent = e , fanSubscribed = unsafeNewIORef e Nothing } in EventSelector $ \k -> EventFan k f -- | Run an event action outside of a frame runFrame :: EventM a -> IO a runFrame a = do toAssignRef <- newIORef [] -- This should only actually get used when events are firing holdInitRef <- newIORef [] heightRef <- newIORef 0 toClearRef <- newIORef [] toClearRootRef <- newIORef [] coincidenceInfosRef <- newIORef [] delayedRef <- liftIO $ newIORef IntMap.empty result <- flip runEventM (EventEnv toAssignRef holdInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) $ do result <- a let runHoldInits = do holdInits <- liftIO $ readIORef holdInitRef if null holdInits then return () else do liftIO $ writeIORef holdInitRef [] forM_ holdInits $ \(SomeHoldInit e h) -> subscribeHold e h runHoldInits runHoldInits -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events return result toClear <- readIORef toClearRef forM_ toClear $ \(SomeMaybeIORef ref) -> writeIORef ref Nothing toClearRoot <- readIORef toClearRootRef forM_ toClearRoot $ \(SomeDMapIORef ref) -> writeIORef ref DMap.empty toAssign <- readIORef toAssignRef toReconnectRef <- newIORef [] forM_ toAssign $ \(SomeAssignment h v) -> do writeIORef (holdValue h) v writeIORef (holdInvalidators h) =<< invalidate toReconnectRef =<< readIORef (holdInvalidators h) coincidenceInfos <- readIORef coincidenceInfosRef forM_ coincidenceInfos $ \(SomeCoincidenceInfo wsubInner subInner mcs) -> do touch subInner finalize wsubInner mapM_ invalidateCoincidenceHeight mcs toReconnect <- readIORef toReconnectRef forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do wsub <- readIORef $ switchSubscribedSelfWeak subscribed finalize wsub wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed finalize wi let !i = switchSubscribedOwnInvalidator subscribed wi' <- mkWeakPtrWithDebug i "wi'" writeIORef (switchSubscribedBehaviorParents subscribed) [] e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times let !sub = switchSubscribedSelf subscribed -- Must be done strictly, or the weak pointer will refer to a useless thunk wsub' <- mkWeakPtrWithDebug sub "wsub'" writeIORef (switchSubscribedSelfWeak subscribed) wsub' subd' <- runFrame $ subscribe e $ WeakSubscriberSimple wsub' --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient {- stackTrace <- liftIO $ liftM renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed) liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of EventRoot _ -> "EventRoot" EventNever -> "EventNever" _ -> "something else" -} writeIORef (switchSubscribedCurrentParent subscribed) subd' parentHeight <- readIORef $ eventSubscribedHeightRef subd' myHeight <- readIORef $ switchSubscribedHeight subscribed if parentHeight == myHeight then return () else do writeIORef (switchSubscribedHeight subscribed) parentHeight mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) forM_ coincidenceInfos $ \(SomeCoincidenceInfo _ _ mcs) -> mapM_ recalculateCoincidenceHeight mcs forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) return result invalidHeight :: Int invalidHeight = -1000 invalidateSubscriberHeight :: WeakSubscriber a -> IO () invalidateSubscriberHeight ws = do ms <- deRefWeakSubscriber ws case ms of Nothing -> return () --TODO: cleanup? Just s -> case s of SubscriberPush _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed mapM_ invalidateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done" SubscriberMerge _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed oldHeight <- readIORef $ mergeSubscribedHeight subscribed when (oldHeight /= invalidHeight) $ do writeIORef (mergeSubscribedHeight subscribed) $ invalidHeight mapM_ invalidateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done" SubscriberFan subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed subscribers <- readIORef $ fanSubscribedSubscribers subscribed forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ invalidateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ()) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done" SubscriberHold _ -> return () SubscriberSwitch subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed oldHeight <- readIORef $ switchSubscribedHeight subscribed when (oldHeight /= invalidHeight) $ do writeIORef (switchSubscribedHeight subscribed) $ invalidHeight mapM_ invalidateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done" SubscriberCoincidenceOuter subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed invalidateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done" SubscriberCoincidenceInner subscribed -> do when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed invalidateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done" invalidateCoincidenceHeight :: CoincidenceSubscribed a -> IO () invalidateCoincidenceHeight subscribed = do oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed when (oldHeight /= invalidHeight) $ do writeIORef (coincidenceSubscribedHeight subscribed) $ invalidHeight mapM_ invalidateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: The recalculation algorithm seems a bit funky; make sure it doesn't miss stuff or hit stuff twice; also, it should probably be lazy recalculateSubscriberHeight :: WeakSubscriber a -> IO () recalculateSubscriberHeight ws = do ms <- deRefWeakSubscriber ws case ms of Nothing -> return () --TODO: cleanup? Just s -> case s of SubscriberPush _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed mapM_ recalculateSubscriberHeight =<< readIORef (pushSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done" SubscriberMerge _ subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed oldHeight <- readIORef $ mergeSubscribedHeight subscribed when (oldHeight == invalidHeight) $ do height <- calculateMergeHeight subscribed when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height when (height /= invalidHeight) $ do -- If height == invalidHeight, that means some of the prereqs have not yet been recomputed; when they do recompute, they'll catch this node again --TODO: this is O(n*m), where n is the number of children of this noe and m is the number that have been invalidated writeIORef (mergeSubscribedHeight subscribed) height mapM_ recalculateSubscriberHeight =<< readIORef (mergeSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done" SubscriberFan subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed subscribers <- readIORef $ fanSubscribedSubscribers subscribed forM_ (DMap.toList subscribers) $ ((\(FanSubscriberKey _ :=> v) -> mapM_ recalculateSubscriberHeight v) :: DSum (FanSubscriberKey k) -> IO ()) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done" SubscriberHold _ -> return () SubscriberSwitch subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed oldHeight <- readIORef $ switchSubscribedHeight subscribed when (oldHeight == invalidHeight) $ do height <- calculateSwitchHeight subscribed when (height /= invalidHeight) $ do writeIORef (switchSubscribedHeight subscribed) height mapM_ recalculateSubscriberHeight =<< readIORef (switchSubscribedSubscribers subscribed) when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done" SubscriberCoincidenceOuter subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed void $ recalculateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done" SubscriberCoincidenceInner subscribed -> do when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed void $ recalculateCoincidenceHeight subscribed when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done" recalculateCoincidenceHeight :: CoincidenceSubscribed a -> IO () recalculateCoincidenceHeight subscribed = do oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed when (oldHeight == invalidHeight) $ do height <- calculateCoincidenceHeight subscribed when (height /= invalidHeight) $ do writeIORef (coincidenceSubscribedHeight subscribed) height mapM_ recalculateSubscriberHeight =<< readIORef (coincidenceSubscribedSubscribers subscribed) --TODO: This should probably be mandatory, just like with the merge and switch ones calculateMergeHeight :: MergeSubscribed k -> IO Int calculateMergeHeight subscribed = if DMap.null (mergeSubscribedParents subscribed) then return 0 else do heights <- forM (DMap.toList $ mergeSubscribedParents subscribed) $ \(WrapArg _ :=> es) -> do readIORef $ eventSubscribedHeightRef es return $ if any (== invalidHeight) heights then invalidHeight else succ $ Prelude.maximum heights --TODO: Replace 'any' with invalidHeight-preserving 'maximum' calculateSwitchHeight :: SwitchSubscribed a -> IO Int calculateSwitchHeight subscribed = readIORef . eventSubscribedHeightRef =<< readIORef (switchSubscribedCurrentParent subscribed) calculateCoincidenceHeight :: CoincidenceSubscribed a -> IO Int calculateCoincidenceHeight subscribed = do outerHeight <- readIORef $ eventSubscribedHeightRef $ coincidenceSubscribedOuterParent subscribed innerHeight <- maybe (return 0) (readIORef . eventSubscribedHeightRef) =<< readIORef (coincidenceSubscribedInnerParent subscribed) return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight {- recalculateEventSubscribedHeight :: EventSubscribed a -> IO Int recalculateEventSubscribedHeight es = case es of EventSubscribedRoot _ -> return 0 EventSubscribedNever -> return 0 EventSubscribedPush subscribed -> recalculateEventSubscribedHeight $ pushSubscribedParent subscribed EventSubscribedMerge subscribed -> do oldHeight <- readIORef $ mergeSubscribedHeight subscribed if oldHeight /= invalidHeight then return oldHeight else do height <- calculateMergeHeight subscribed writeIORef (mergeSubscribedHeight subscribed) height return height EventSubscribedFan _ subscribed -> recalculateEventSubscribedHeight $ fanSubscribedParent subscribed EventSubscribedSwitch subscribed -> do oldHeight <- readIORef $ switchSubscribedHeight subscribed if oldHeight /= invalidHeight then return oldHeight else do height <- calculateSwitchHeight subscribed writeIORef (switchSubscribedHeight subscribed) height return height EventSubscribedCoincidence subscribed -> recalculateCoincidenceHeight subscribed -} data SomeSwitchSubscribed = forall a. SomeSwitchSubscribed (SwitchSubscribed a) debugInvalidate :: Bool debugInvalidate = False invalidate :: IORef [SomeSwitchSubscribed] -> WeakList Invalidator -> IO (WeakList Invalidator) invalidate toReconnectRef wis = do forM_ wis $ \wi -> do mi <- deRefWeak wi case mi of Nothing -> do when debugInvalidate $ liftIO $ putStrLn "invalidate Dead" return () --TODO: Should we clean this up here? Just i -> do finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict case i of InvalidatorPull p -> do when debugInvalidate $ liftIO $ putStrLn "invalidate Pull" mVal <- readIORef $ pullValue p forM_ mVal $ \val -> do writeIORef (pullValue p) Nothing writeIORef (pullSubscribedInvalidators val) =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val) InvalidatorSwitch subscribed -> do when debugInvalidate $ liftIO $ putStrLn "invalidate Switch" modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :) return [] -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them -------------------------------------------------------------------------------- -- Reflex integration -------------------------------------------------------------------------------- data Spider instance R.Reflex Spider where newtype Behavior Spider a = SpiderBehavior { unSpiderBehavior :: Behavior a } newtype Event Spider a = SpiderEvent { unSpiderEvent :: Event a } type PullM Spider = BehaviorM type PushM Spider = EventM {-# INLINE never #-} {-# INLINE constant #-} never = SpiderEvent EventNever constant = SpiderBehavior . BehaviorConst push f = SpiderEvent. push f . unSpiderEvent pull = SpiderBehavior . pull merge = SpiderEvent . merge . (unsafeCoerce :: DMap (WrapArg (R.Event Spider) k) -> DMap (WrapArg Event k)) fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e)) switch = SpiderEvent . switch . (unsafeCoerce :: Behavior (R.Event Spider a) -> Behavior (Event a)) . unSpiderBehavior coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event (R.Event Spider a) -> Event (Event a)) . unSpiderEvent instance R.MonadSample Spider SpiderHost where {-# INLINE sample #-} sample = SpiderHost . readBehavior . unSpiderBehavior instance R.MonadHold Spider SpiderHost where hold v0 = SpiderHost . liftM SpiderBehavior . runFrame . hold v0 . unSpiderEvent instance R.MonadSample Spider BehaviorM where {-# INLINE sample #-} sample = readBehaviorTracked . unSpiderBehavior instance R.MonadSample Spider EventM where {-# INLINE sample #-} sample = liftIO . readBehavior . unSpiderBehavior instance R.MonadHold Spider EventM where {-# INLINE hold #-} hold v0 e = SpiderBehavior <$> hold v0 (unSpiderEvent e) data RootTrigger a = forall k. GCompare k => RootTrigger (IORef [WeakSubscriber a], IORef (DMap k), k a) newtype SpiderEventHandle a = SpiderEventHandle { unEventHandle :: Event a } instance R.MonadSubscribeEvent Spider SpiderHostFrame where subscribeEvent e = SpiderHostFrame $ do _ <- getEventSubscribed $ unSpiderEvent e --TODO: The result of this should actually be used return $ SpiderEventHandle (unSpiderEvent e) instance R.ReflexHost Spider where type EventTrigger Spider = RootTrigger type EventHandle Spider = SpiderEventHandle type HostFrame Spider = SpiderHostFrame instance R.MonadReadEvent Spider ReadPhase where {-# INLINE readEvent #-} readEvent = ReadPhase . liftM (fmap return) . readEvent . unEventHandle instance MonadRef EventM where type Ref EventM = Ref IO {-# INLINE newRef #-} {-# INLINE readRef #-} {-# INLINE writeRef #-} newRef = liftIO . newRef readRef = liftIO . readRef writeRef r a = liftIO $ writeRef r a instance MonadAtomicRef EventM where {-# INLINE atomicModifyRef #-} atomicModifyRef r f = liftIO $ atomicModifyRef r f newtype SpiderHost a = SpiderHost { runSpiderHost :: IO a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException) newtype SpiderHostFrame a = SpiderHostFrame { runSpiderHostFrame :: EventM a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException) instance R.MonadSample Spider SpiderHostFrame where sample = SpiderHostFrame . R.sample --TODO: This can cause problems with laziness, so we should get rid of it if we can instance R.MonadHold Spider SpiderHostFrame where {-# INLINE hold #-} hold v0 e = SpiderHostFrame $ R.hold v0 e newEventWithTriggerIO :: forall a. (RootTrigger a -> IO (IO ())) -> IO (Event a) newEventWithTriggerIO f = do es <- newFanEventWithTriggerIO $ \Refl -> f return $ select es Refl newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger a -> IO (IO ())) -> IO (EventSelector k) newFanEventWithTriggerIO f = do occRef <- newIORef DMap.empty subscribedRef <- newIORef DMap.empty let !r = Root { rootOccurrence = occRef , rootSubscribed = subscribedRef , rootInit = f } return $ EventSelector $ \k -> EventRoot k r instance R.MonadReflexCreateTrigger Spider SpiderHost where newEventWithTrigger = SpiderHost . liftM SpiderEvent . newEventWithTriggerIO newFanEventWithTrigger f = SpiderHost $ do es <- newFanEventWithTriggerIO f return $ R.EventSelector $ SpiderEvent . select es instance R.MonadReflexCreateTrigger Spider SpiderHostFrame where newEventWithTrigger = SpiderHostFrame . EventM . liftIO . liftM SpiderEvent . newEventWithTriggerIO newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do es <- newFanEventWithTriggerIO f return $ R.EventSelector $ SpiderEvent . select es instance R.MonadSubscribeEvent Spider SpiderHost where subscribeEvent e = SpiderHost $ do _ <- runFrame $ getEventSubscribed $ unSpiderEvent e --TODO: The result of this should actually be used return $ SpiderEventHandle (unSpiderEvent e) newtype ReadPhase a = ReadPhase { runReadPhase :: ResultM a } deriving (Functor, Applicative, Monad, MonadFix, R.MonadSample Spider, R.MonadHold Spider) instance R.MonadReflexHost Spider SpiderHost where type ReadPhase SpiderHost = ReadPhase fireEventsAndRead es (ReadPhase a) = SpiderHost $ run es a runHostFrame = SpiderHost . runFrame . runSpiderHostFrame instance MonadRef SpiderHost where type Ref SpiderHost = Ref IO newRef = SpiderHost . newRef readRef = SpiderHost . readRef writeRef r = SpiderHost . writeRef r instance MonadAtomicRef SpiderHost where atomicModifyRef r = SpiderHost . atomicModifyRef r instance MonadRef SpiderHostFrame where type Ref SpiderHostFrame = Ref IO newRef = SpiderHostFrame . newRef readRef = SpiderHostFrame . readRef writeRef r = SpiderHostFrame . writeRef r instance MonadAtomicRef SpiderHostFrame where atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
k0001/reflex
src/Reflex/Spider/Internal.hs
bsd-3-clause
70,084
82
37
14,671
16,623
8,144
8,479
-1
-1
-- Local and global IVars -- -- Author: Patrick Maier {-# LANGUAGE RankNTypes , ExistentialQuantification , BangPatterns #-} ----------------------------------------------------------------------------- module Control.Parallel.HdpH.Internal.IVar ( -- * local IVar type IVar, -- synonym: IVar m a = IORef <IVarContent m a> IVarContent(..), -- * operations on local IVars newIVar, -- :: IO (IVar m a) newSupervisedIVar, -- :: Closure (ParM m ()) -> Scheduling -> CurrentLocation -> IO (IVar m a) superviseIVar, -- TODO: document putIVar, -- :: IVar m a -> a -> IO [Thread m] getIVar, -- :: IVar m a -> (a -> Thread m) -> IO (Maybe a) pollIVar, -- :: IVar m a -> IO (Maybe a) probeIVar, -- :: IVar m a -> IO Bool -- * global IVar type GIVar, -- synonym: GIVar m a = GRef (IVar m a) -- * operations on global IVars globIVar, -- :: Int -> IVar m a -> IO (GIVar m a) hostGIVar, -- :: GIVar m a -> NodeId slotGIVar, -- :: GIVar m a -> Integer putGIVar, -- :: Int -> GIVar m a -> a -> IO [Thread m] -- * check state of empty IVars isNewestReplica, -- :: TaskRef -> Int -> IO (Maybe Bool) locationOfTask, -- :: TaskRef -> IO (Maybe CurrentLocation) vulnerableEmptyFutures, -- :: NodeId -> IO [IVar m a] -- * Update state of empty IVars taskInTransition, -- :: TaskRef -> NodeId -> NodeId -> IO () taskOnNode, -- :: TaskRef -> NodeId -> IO () replicateSpark, -- :: IVar m a -> IO (Maybe (SupervisedSpark m)) replicateThread -- :: IVar m a -> IO (Maybe (Closure (ParM m ())) ) where import Prelude import Data.Functor ((<$>)) import Data.IORef (IORef, newIORef, readIORef, atomicModifyIORef,writeIORef) import qualified Data.IntMap.Strict as Map import Data.Maybe (isJust,fromMaybe,fromJust,isNothing) import Data.Binary import Control.Monad (filterM,unless,void) import Control.Concurrent (forkIO) import Control.DeepSeq (NFData(rnf)) import Control.Parallel.HdpH.Internal.Location (NodeId, debug, dbgGIVar, dbgIVar,dbgGRef,myNode) import Control.Parallel.HdpH.Internal.Type.GRef import Control.Parallel.HdpH.Closure (Closure) import Control.Parallel.HdpH.Internal.Type.Par import System.IO.Unsafe (unsafePerformIO) import Control.Parallel.HdpH.Internal.Misc (atomicWriteIORef) ----------------------------------------------------------------------------- -- type of local IVars -- An IVar is a mutable reference to either a value or a list of blocked -- continuations (waiting for a value); -- the parameter 'm' abstracts a monad (cf. module HdpH.Internal.Type.Par). type IVar m a = IORef (IVarContent m a) data IVarContent m a = Full a | Empty { blockedThreads :: [a -> Thread m] , taskLocalState :: Maybe (SupervisedTaskState m) } ----------------------------------------------------------------------------- -- operations on local IVars, borrowing from -- [1] Marlow et al. "A monad for deterministic parallelism". Haskell 2011. newSupervisedIVar :: Closure (ParM m ()) -> Scheduling -> CurrentLocation -> IO (IVar m a) newSupervisedIVar closure howScheduled taskLocation = do let localSt = SupervisedTaskState { task = closure , scheduling = howScheduled , location = taskLocation , newestReplica = 0 } newIORef $ Empty { blockedThreads = [] , taskLocalState = Just localSt } -- | Create a new unsupervised empty IVar. newIVar :: IO (IVar m a) newIVar = newIORef $ Empty { blockedThreads = [] , taskLocalState = Nothing } -- Write 'x' to the IVar 'v' and return the list of blocked threads. -- Unlike [1], multiple writes fail silently (ie. they do not change -- the value stored, and return an empty list of threads). putIVar :: IVar m a -> a -> IO [Thread m] putIVar v x = do e <- readIORef v case e of Full _ -> do debug dbgIVar $ "Put to full IVar" return [] Empty _ _ -> do maybe_ts <- atomicModifyIORef v fill_and_unblock case maybe_ts of Nothing -> do debug dbgIVar $ "Put to full IVar" return [] Just ts -> do debug dbgIVar $ "Put to empty IVar; unblocking " ++ show (length ts) ++ " threads" return ts where -- fill_and_unblock :: IVarContent m a -> -- (IVarContent m a, Maybe [Thread m]) fill_and_unblock e' = case e' of Full _ -> (e', Nothing) Empty cs _ -> (Full x, Just $ map ($ x) cs) -- Read from the given IVar 'v' and return the value if it is full. -- Otherwise add the given continuation 'c' to the list of blocked -- continuations and return nothing. getIVar :: IVar m a -> (a -> Thread m) -> IO (Maybe a) getIVar v c = do e <- readIORef v case e of Full x -> do return (Just x) Empty _ _ -> do maybe_x <- atomicModifyIORef v get_or_block case maybe_x of Just _ -> do return maybe_x Nothing -> do debug dbgIVar $ "Blocking on IVar" return maybe_x where -- get_or_block :: IVarContent m a -> (IVarContent m a, Maybe a) get_or_block e' = case e' of Full x -> (e', Just x) Empty cs st -> (Empty (c:cs) st, Nothing) -- Poll the given IVar 'v' and return its value if full, Nothing otherwise. -- Does not block. pollIVar :: IVar m a -> IO (Maybe a) pollIVar v = do e <- readIORef v case e of Full x -> return (Just x) Empty _ _ -> return Nothing -- Probe whether the given IVar is full, returning True if it is. -- Does not block. probeIVar :: IVar m a -> IO Bool probeIVar v = isJust <$> pollIVar v ----------------------------------------------------------------------------- -- type of global IVars; instances mostly inherited from global references -- A global IVar is a global reference to an IVar; 'm' abstracts a monad. -- NOTE: The HdpH interface will restrict the type parameter 'a' to -- 'Closure b' for some type 'b', but but the type constructor 'GIVar' -- does not enforce this restriction. type GIVar m a = GRef (IVar m a) ----------------------------------------------------------------------------- -- operations on global IVars -- Returns node hosting given global IVar. hostGIVar :: GIVar m a -> NodeId hostGIVar = at slotGIVar :: GIVar m a -> Int slotGIVar = slot -- Globalise the given IVar; globIVar :: IVar m a -> IO (GIVar m a) globIVar v = do gv <- globalise v debug dbgGIVar $ "New global IVar " ++ show gv return gv superviseIVar :: IVar m a -> Int -> IO () superviseIVar newV i = do supervise newV i debug dbgGIVar $ "IVar supervised at slot " ++ show i -- Write 'x' to the locally hosted global IVar 'gv', free 'gv' and return -- the list of blocked threads. Like putIVar, multiple writes fail silently -- (as do writes to a dead global IVar); putGIVar :: GIVar m a -> a -> IO [Thread m] putGIVar gv x = do debug dbgGIVar $ "Put to global IVar " ++ show gv ts <- withGRef gv (\ v -> putIVar v x) (return []) free gv -- free 'gv' (eventually) return ts ------------------------------ -- direct access to registry. lookupIVar :: TaskRef -> IO (Maybe (IVar m a)) lookupIVar taskRef = do reg <- table <$> readIORef regRef return $ Map.lookup (slotT taskRef) reg -- | This is called when notification of a dead node has been received. -- It looks through the registry, identifying all empty IVars whose associated -- task may have sank with sunken node. The criteria for selection is: -- -- 1. The location of the task was either deadNode in (OnNode deadNode) or -- one of nodes in (InTransition from to). -- -- 2. The IVar is empty i.e. yet to be filled by the task. vulnerableEmptyFutures :: NodeId -> IO [(Int,IVar m a)] vulnerableEmptyFutures deadNode = do reg <- table <$> readIORef regRef let ivars = Map.toList reg atRiskIVars <- filterM taskAtRisk ivars filterM (\(_,i) -> not <$> probeIVar i) atRiskIVars where taskAtRisk :: (Int,IVar m a) -> IO Bool taskAtRisk (_,v) = do e <- readIORef v case e of Full _ -> return False Empty _ maybe_st -> do if isNothing maybe_st then return False else do let st = fromJust (taskLocalState e) case location st of OnNode node -> return (node == deadNode) InTransition from to -> return $ (from == deadNode) || (to == deadNode) -- | Creates a replica of the task that will fill the 'IVar'. -- It extracts the closure within the Empty IVar state. It -- then increments the 'newestReplica' replica number within the -- IVar state, and attaches this sequence number to the duplicate -- task. The supervisor only permits subsequent 'FISH' requests -- that refer to this task, so that book keeping for a future is not -- corrupted by nonsensical sequences of book keeping updates. replicateSpark :: (Int,IVar m a) -> IO (Maybe (SupervisedSpark m)) replicateSpark (indexRef,v) = do me <- myNode atomicModifyIORef v $ \e -> case e of Full _ -> (e,Nothing) -- TODO turn to debug message -- cannot duplicate task, IVar full, task garbage collected Empty b maybe_st -> let ivarSt = fromMaybe (error "cannot duplicate non-supervised task") maybe_st newTaskLocation = OnNode me newReplica = (newestReplica ivarSt) + 1 supervisedTask = SupervisedSpark { clo = task ivarSt , thisReplica = newReplica , remoteRef = TaskRef indexRef me } newIVarSt = ivarSt { newestReplica = newReplica , location = newTaskLocation} in (Empty b (Just newIVarSt),Just supervisedTask) replicateThread :: (Int,IVar m a) -> IO (Maybe (Closure (ParM m ()))) replicateThread (indexRef,v) = do me <- myNode atomicModifyIORef v $ \e -> case e of Full _ -> (e,Nothing) -- TODO turn to debug message -- cannot duplicate task, IVar full, task garbage collected Empty b maybe_st -> let ivarSt = fromMaybe (error "cannot duplicate non-supervised task") maybe_st newTaskLocation = OnNode me newReplica = (newestReplica ivarSt) + 1 threadCopy = task ivarSt newIVarSt = ivarSt { newestReplica = newReplica , location = newTaskLocation} in (Empty b (Just newIVarSt),Just threadCopy) -- | Updates location of empty IVar to 'OnNode'. taskOnNode :: TaskRef -> NodeId -> IO () taskOnNode taskRef newNode = do maybe_ivar <- lookupIVar taskRef let v = fromMaybe (error "taskInTransition: Local IVar not found") maybe_ivar updateLocation v (OnNode newNode) -- | Updates location of empty IVar to 'InTransition'. taskInTransition :: TaskRef -> NodeId -> NodeId -> IO () taskInTransition taskRef from to = do maybe_ivar <- lookupIVar taskRef let v = fromMaybe (error "taskInTransition: Local IVar not found") maybe_ivar updateLocation v (InTransition from to) -- | Lookup location book keeping for an empty IVar. -- Returns 'Nothing' is the IVar is full. locationOfTask :: TaskRef -> IO (Maybe CurrentLocation) locationOfTask taskRef = do maybe_ivar <- lookupIVar taskRef let v = fromMaybe (error "taskInTransition: Local IVar not found") maybe_ivar e <- readIORef v case e of Full{} -> return Nothing -- IVar full, no longer maintains location Empty _ maybe_st -> do return (if isNothing maybe_st then Nothing else Just $ location (fromJust maybe_st)) if isNothing maybe_st then return Nothing -- not supervised else return $ Just $ location (fromJust maybe_st) -- | Checks in the local registry. Returns 'Just True' iff the -- sequence number of the task matches the 'newestReplica' in -- the IVar state. Returns 'Just False' if lower than 'newestReplica'. -- Returns 'Nothing' if the IVar has been filled by a copy of the task. isNewestReplica :: TaskRef -> Int -> IO (Maybe Bool) isNewestReplica taskRef taskSeq = do maybe_ivar <- lookupIVar taskRef let v = fromMaybe (error "isNewestReplica: Local IVar not found") maybe_ivar e <- readIORef v case e of Full{} -> return Nothing -- IVar full Empty _ maybe_st -> do if isNothing maybe_st then return Nothing -- task not supervise else do return $ Just $ taskSeq == newestReplica (fromJust maybe_st) -- not exposed. updateLocation :: IVar m a -> CurrentLocation -> IO () updateLocation v newLoc = do atomicModifyIORef v $ \e -> do case e of Full _ -> error "updating task location of full IVar" Empty _ maybe_st -> let st = fromMaybe (error "trying to update location of unsupervised task") maybe_st newSt = Just $ updateLocationSt st newLoc in (e { taskLocalState = newSt },()) where updateLocationSt :: SupervisedTaskState m -> CurrentLocation -> SupervisedTaskState m updateLocationSt st loc = st { location = loc } ----------------------------------------------------------------------------- -- registry for global references -- Registry, comprising of the most recently allocated slot and a table -- mapping slots to objects (wrapped in an existential type). data GRefReg m a = GRefReg { lastSlot :: !Int, table :: Map.IntMap (IVar m a) } regRef :: IORef (GRefReg m a) regRef = unsafePerformIO $ newIORef $ GRefReg { lastSlot = 0, table = Map.empty } {-# NOINLINE regRef #-} -- required to protect unsafePerformIO hack ----------------------------------------------------------------------------- -- Key facts about global references -- -- * A global reference is a globally unique handle naming a Haskell value; -- the type of the value is reflected in a phantom type argument to the -- type of global reference, similar to the type of stable names. -- -- * The link between a global reference and the value it names is established -- by a registry mapping references to values. The registry mapping a -- global reference resides on the node hosting its value. All operations -- involving the reference must be executed on the hosting node; the only -- exception is the function 'at', projecting a global reference to its -- hosting node. -- -- * The life time of a global reference is not linked to the life time of -- the named value, and vice versa. One consequence is that global -- references can never be re-used, unlike stable names. -- -- * For now, global references must be freed explicitly (from the map -- on the hosting node). This could (and should) be changed by using -- weak pointers and finalizers. ----------------------------------------------------------------------------- -- global references (abstract outwith this module) -- NOTE: Global references are hyperstrict. -- Constructs a 'GRef' value of a given node ID and slot (on the given node); -- ensures the resulting 'GRef' value is hyperstrict; -- this constructor is not to be exported. mkGRef :: NodeId -> Int -> GRef a mkGRef node i = rnf node `seq` rnf i `seq` GRef { slot = i, at = node } instance Eq (GRef a) where ref1 == ref2 = slot ref1 == slot ref2 && at ref1 == at ref2 instance Ord (GRef a) where compare ref1 ref2 = case compare (slot ref1) (slot ref2) of LT -> LT GT -> GT EQ -> compare (at ref1) (at ref2) -- Show instance (mainly for debugging) instance Show (GRef a) where showsPrec _ ref = showString "GRef:" . shows (at ref) . showString "." . shows (slot ref) instance NFData (GRef a) -- default instance suffices (due to hyperstrictness) instance Binary (GRef a) where put ref = Data.Binary.put (at ref) >> Data.Binary.put (slot ref) get = do node <- Data.Binary.get i <- Data.Binary.get return $ mkGRef node i -- 'mkGRef' ensures result is hyperstrict ----------------------------------------------------------------------------- -- predicates on global references -- Monadic projection; True iff the current node hosts the object refered -- to by the given global 'ref'. isLocal :: GRef a -> IO Bool isLocal ref = (at ref ==) <$> myNode -- Checks if a locally hosted global 'ref' is live. -- Aborts with an error if 'ref' is a not hosted locally. isLive :: GRef a -> IO Bool isLive ref = do refIsLocal <- isLocal ref unless refIsLocal $ error $ "HdpH.Internal.GRef.isLive: " ++ show ref ++ " not local" reg <- readIORef regRef return $ Map.member (slot ref) (table reg) ----------------------------------------------------------------------------- -- updating the registry -- Registers its argument as a global object (hosted on the current node), -- returning a fresh global reference. May block when attempting to access -- the registry. globalise :: IVar m a -> IO (GRef (IVar m a)) globalise x = do node <- myNode ref <- atomicModifyIORef regRef (createEntry x node) debug dbgGRef $ "GRef.globalise " ++ show ref return ref supervise :: IVar m a -> Int -> IO () supervise newV i = do node <- myNode atomicModifyIORef regRef (promoteToSupervisedIVar newV node i) -- Asynchronously frees a locally hosted global 'ref'; no-op if 'ref' is dead. -- Aborts with an error if 'ref' is a not hosted locally. free :: GRef a -> IO () free ref = do refIsLocal <- isLocal ref unless refIsLocal $ error $ "HdpH.Internal.GRef.free: " ++ show ref ++ " not local" void $ forkIO $ do debug dbgGRef $ "GRef.free " ++ show ref atomicModifyIORef regRef (deleteEntry $ slot ref) return () -- Frees a locally hosted global 'ref'; no-op if 'ref' is dead. -- Aborts with an error if 'ref' is a not hosted locally. freeNow :: GRef a -> IO () freeNow ref = do refIsLocal <- isLocal ref unless refIsLocal $ error $ "HdpH.Internal.GRef.freeNow: " ++ show ref ++ " not local" debug dbgGRef $ "GRef.freeNow " ++ show ref atomicModifyIORef regRef (deleteEntry $ slot ref) -- Create new entry in 'reg' (hosted on 'node') mapping to 'val'; not exported createEntry :: IVar m a -> NodeId -> GRefReg m a -> (GRefReg m a, GRef (IVar m a)) createEntry val node reg = ref `seq` (reg', ref) where newSlot = lastSlot reg + 1 ref = mkGRef node newSlot -- 'seq' above forces hyperstrict 'ref' to NF reg' = reg { lastSlot = newSlot, table = Map.insert newSlot val (table reg) } promoteToSupervisedIVar :: IVar m a -> NodeId -> Int -> GRefReg m a -> (GRefReg m a,()) promoteToSupervisedIVar newVal node !slot reg = (reg', ()) where reg' = reg { table = Map.insert slot newVal (table reg) } -- Delete entry 'slot' from 'reg'; not exported deleteEntry :: Int -> GRefReg m a -> (GRefReg m a, ()) deleteEntry ivarSlot reg = (reg { table = Map.delete ivarSlot (table reg) }, ()) ----------------------------------------------------------------------------- -- Dereferencing global refs -- Attempts to dereference a locally hosted global 'ref' and apply 'action' -- to the refered-to object; executes 'dead' if that is not possible (ie. -- 'dead' acts as an exception handler) because the global 'ref' is dead. -- Aborts with an error if 'ref' is a not hosted locally. withGRef :: GRef (IVar m a) -> (IVar m a -> IO b) -> IO b -> IO b withGRef ref action dead = do refIsLocal <- isLocal ref unless refIsLocal $ error $ "HdpH.Internal.GRef.withGRef: " ++ show ref ++ " not local" reg <- readIORef regRef case Map.lookup (slot ref) (table reg) of Nothing -> do debug dbgGRef $ "GRef.withGRef " ++ show ref ++ " dead" dead Just (x) -> do action x -- (unsafeCoerce x) -- see below for an argument why unsafeCoerce is safe here ------------------------------------------------------------------------------- -- Notes on the design of the registry -- -- * A global reference is represented as a pair consisting of the ID -- of the hosting node together with its 'slot' in the registry on -- that node. The slot is an unbounded integer so that there is an -- infinite supply of slots. (Slots can't be re-used as there is no -- global garbage collection of global references.) -- -- * The registry maps slots to values, which are essentially untyped -- (the type information being swallowed by an existential wrapper). -- However, the value type information is not lost as it can be -- recovered from the phantom type argument of its global reference. -- In fact, the function 'withGRef' super-imposes a reference's phantom -- type on to its value via 'unsafeCoerce'. The reasons why this is safe -- are laid out below. -- Why 'unsafeCoerce' in safe in 'withGRef': -- -- * Global references can only be created by the function 'globalise'. -- Whenever this function generates a global reference 'ref' of type -- 'GRef t' it guarantees that 'ref' is globally fresh, ie. its -- representation does not exist any where else in the system, nor has -- it ever existed in the past. (Note that freshness relies on the -- assumption that node IDs themselves are fresh, which is relevant -- in case nodes can leave and join dynmically.) -- -- * A consequence of global freshness is that there is a functional relation -- from representations to phantom types of global references. For all -- global references 'ref1 :: GRef t1' and 'ref2 :: GRef t2', -- 'at ref1 == at ref2 && slot ref1 == slot ref2' implies the identity -- of the phantom types t1 and t2. -- -- * Thus, we can safely super-impose (using 'unsafeCoerce') the phantom type -- of a global reference on to its value.
robstewart57/hdph-rs
src/Control/Parallel/HdpH/Internal/IVar.hs
bsd-3-clause
22,211
0
23
5,601
4,322
2,240
2,082
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE QuasiQuotes #-} -- | C code generation for 'Program' module Language.Embedded.Backend.C ( module Language.Embedded.Backend.C.Expression , module Language.Embedded.Backend.C , Default (..) ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative import Data.Monoid #endif import Control.Exception import Data.Time (getCurrentTime, formatTime, defaultTimeLocale) import System.Directory (getTemporaryDirectory, removeFile) import System.Exit (ExitCode (..)) import System.IO import System.Process (system, readProcess) import Data.Default.Class import Data.Loc (noLoc) import qualified Language.C.Syntax as C import Text.PrettyPrint.Mainland (pretty) import Control.Monad.Operational.Higher import System.IO.Fake import Language.C.Monad import Language.Embedded.Backend.C.Expression -------------------------------------------------------------------------------- -- * Utilities -------------------------------------------------------------------------------- -- | Create a named type namedType :: String -> C.Type namedType t = C.Type (C.DeclSpec [] [] (C.Tnamed (C.Id t noLoc) [] noLoc) noLoc) (C.DeclRoot noLoc) noLoc -- | Return the argument of a boolean negation expression viewNotExp :: C.Exp -> Maybe C.Exp viewNotExp (C.UnOp C.Lnot a _) = Just a viewNotExp (C.FnCall (C.Var (C.Id "!" _) _) [a] _) = Just a -- Apparently this is what `!` parses to viewNotExp _ = Nothing arrayInit :: [C.Exp] -> C.Initializer arrayInit as = C.CompoundInitializer [(Nothing, C.ExpInitializer a noLoc) | a <- as] noLoc -------------------------------------------------------------------------------- -- * Code generation user interface -------------------------------------------------------------------------------- -- | Compile a program to C code represented as a string. To compile the -- resulting C code, use something like -- -- > cc -std=c99 YOURPROGRAM.c -- -- This function returns only the first (main) module. To get all C translation -- unit, use 'compileAll'. compile :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -> String compile = snd . head . compileAll -- | Compile a program to C modules, each one represented as a pair of a name -- and the code represented as a string. To compile the resulting C code, use -- something like -- -- > cc -std=c99 YOURPROGRAM.c compileAll :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -> [(String, String)] compileAll = map (("", pretty 80) <*>) . prettyCGen . liftSharedLocals . wrapMain . interpret -- | Compile a program to C code and print it on the screen. To compile the -- resulting C code, use something like -- -- > cc -std=c99 YOURPROGRAM.c icompile :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -> IO () icompile prog = case compileAll prog of [m] -> putStrLn $ snd m ms -> mapM_ (\(n, m) -> putStrLn ("// module " ++ n) >> putStrLn m) ms removeFileIfPossible :: FilePath -> IO () removeFileIfPossible file = catch (removeFile file) (\(_ :: SomeException) -> return ()) data ExternalCompilerOpts = ExternalCompilerOpts { externalKeepFiles :: Bool -- ^ Keep generated files? , externalFlagsPre :: [String] -- ^ External compiler flags (e.g. @["-Ipath"]@) , externalFlagsPost :: [String] -- ^ External compiler flags after C source (e.g. @["-lm","-lpthread"]@) , externalSilent :: Bool -- ^ Don't print anything besides what the program prints } instance Default ExternalCompilerOpts where def = ExternalCompilerOpts { externalKeepFiles = False , externalFlagsPre = [] , externalFlagsPost = [] , externalSilent = False } maybePutStrLn :: Bool -> String -> IO () maybePutStrLn False str = putStrLn str maybePutStrLn _ _ = return () -- | Generate C code and use CC to compile it compileC :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => ExternalCompilerOpts -> Program instr (Param2 exp pred) a -- ^ Program to compile -> IO FilePath -- ^ Path to the generated executable compileC (ExternalCompilerOpts {..}) prog = do tmp <- getTemporaryDirectory t <- fmap (formatTime defaultTimeLocale format) getCurrentTime (exeFile,exeh) <- openTempFile tmp ("edsl_" ++ t) hClose exeh let cFile = exeFile ++ ".c" writeFile cFile $ compile prog when externalKeepFiles $ maybePutStrLn externalSilent $ "Created temporary file: " ++ cFile let compileCMD = unwords $ ["cc", "-std=c99"] ++ externalFlagsPre ++ [cFile, "-o", exeFile] ++ externalFlagsPost maybePutStrLn externalSilent compileCMD exit <- system compileCMD unless externalKeepFiles $ removeFileIfPossible cFile case exit of ExitSuccess -> return exeFile err -> do removeFileIfPossible exeFile error "compileC: failed to compile generated C code" where format = if externalKeepFiles then "%a-%H-%M-%S_" else "" -- | Generate C code and use CC to check that it compiles (no linking) compileAndCheck' :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => ExternalCompilerOpts -> Program instr (Param2 exp pred) a -> IO () compileAndCheck' opts prog = do let opts' = opts {externalFlagsPre = "-c" : externalFlagsPre opts} exe <- compileC opts' prog removeFileIfPossible exe -- | Generate C code and use CC to check that it compiles (no linking) compileAndCheck :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -> IO () compileAndCheck = compileAndCheck' def -- | Generate C code, use CC to compile it, and run the resulting executable runCompiled' :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => ExternalCompilerOpts -> Program instr (Param2 exp pred) a -> IO () runCompiled' opts@(ExternalCompilerOpts {..}) prog = bracket (compileC opts prog) removeFileIfPossible ( \exe -> do maybePutStrLn externalSilent "" maybePutStrLn externalSilent "#### Running:" system exe >> return () ) -- | Generate C code, use CC to compile it, and run the resulting executable runCompiled :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -> IO () runCompiled = runCompiled' def -- | Compile a program and make it available as an 'IO' function from 'String' -- to 'String' (connected to @stdin@/@stdout@. respectively). Note that -- compilation only happens once, even if the 'IO' function is used many times -- in the body. withCompiled' :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => ExternalCompilerOpts -> Program instr (Param2 exp pred) a -- ^ Program to compile -> ((String -> IO String) -> IO b) -- ^ Function that has access to the compiled executable as a function -> IO b withCompiled' opts prog body = bracket (compileC opts prog) removeFileIfPossible (\exe -> body $ readProcess exe []) -- | Compile a program and make it available as an 'IO' function from 'String' -- to 'String' (connected to @stdin@/@stdout@. respectively). Note that -- compilation only happens once, even if the 'IO' function is used many times -- in the body. withCompiled :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -- ^ Program to compile -> ((String -> IO String) -> IO b) -- ^ Function that has access to the compiled executable as a function -> IO b withCompiled = withCompiled' def {externalSilent = True} -- | Like 'runCompiled'' but with explicit input/output connected to -- @stdin@/@stdout@. Note that the program will be compiled every time the -- function is applied to a string. In order to compile once and run many times, -- use the function 'withCompiled''. captureCompiled' :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => ExternalCompilerOpts -> Program instr (Param2 exp pred) a -- ^ Program to run -> String -- ^ Input to send to @stdin@ -> IO String -- ^ Result from @stdout@ captureCompiled' opts prog inp = withCompiled' opts prog ($ inp) -- | Like 'runCompiled' but with explicit input/output connected to -- @stdin@/@stdout@. Note that the program will be compiled every time the -- function is applied to a string. In order to compile once and run many times, -- use the function 'withCompiled'. captureCompiled :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -- ^ Program to run -> String -- ^ Input to send to @stdin@ -> IO String -- ^ Result from @stdout@ captureCompiled = captureCompiled' def -- | Compare the content written to @stdout@ from the reference program and from -- running the compiled C code compareCompiled' :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => ExternalCompilerOpts -> Program instr (Param2 exp pred) a -- ^ Program to run -> IO a -- ^ Reference program -> String -- ^ Input to send to @stdin@ -> IO () compareCompiled' opts@(ExternalCompilerOpts {..}) prog ref inp = do maybePutStrLn externalSilent "#### Reference program:" outRef <- fakeIO ref inp maybePutStrLn externalSilent outRef maybePutStrLn externalSilent "#### runCompiled:" outComp <- captureCompiled' opts prog inp maybePutStrLn externalSilent outComp if outRef /= outComp then error "runCompiled differs from reference program" else maybePutStrLn externalSilent " -- runCompiled is consistent with reference program\n\n\n\n" -- | Compare the content written to @stdout@ from the reference program and from -- running the compiled C code compareCompiled :: (Interp instr CGen (Param2 exp pred), HFunctor instr) => Program instr (Param2 exp pred) a -- ^ Program to run -> IO a -- ^ Reference program -> String -- ^ Input to send to @stdin@ -> IO () compareCompiled = compareCompiled' def
kmate/imperative-edsl
src/Language/Embedded/Backend/C.hs
bsd-3-clause
10,346
0
14
2,295
2,253
1,192
1,061
-1
-1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} module Adjrn.Config ( JrnlConfig(..) , Journals , readConfig ) where import Control.Applicative ((<|>)) import Data.Aeson import Data.Aeson.Types import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.HashMap.Lazy (HashMap, fromList) import Data.Text (Text) import qualified Data.Text as T import System.Directory type Journals = HashMap Text (FilePath, Maybe Bool) data JrnlConfig = JrnlConfig { encrypt :: Bool , timeformat :: String , tagsymbols :: String , journals :: Journals } deriving (Show,Eq) instance FromJSON JrnlConfig where parseJSON (Object v) = JrnlConfig <$> v .: "encrypt" <*> v .: "timeformat" <*> v .: "tagsymbols" <*> ((v .: "journals") >>= parseJournals) parseJSON invalid = fail $ "invalid config: " ++ show invalid parseJournals :: Object -> Parser Journals parseJournals = traverse $ \info -> (,Nothing) <$> withText "" (return . T.unpack) info <|> withObject "expected json of form {journal,encrypt}" parseInfo info where parseInfo i = (,) <$> i .: "journal" <*> i .:? "encrypt" xdgConfig :: IO FilePath xdgConfig = getXdgDirectory XdgConfig "jrnl" homeConfig :: IO FilePath homeConfig = getAppUserDataDirectory "jrnl_config" getConfig :: IO (Either String ByteString) getConfig = do xdgF <- xdgConfig homeF <- homeConfig xdg <- doesFileExist xdgF home <- doesFileExist homeF case (xdg, home) of (True,_) -> Right <$> BS.readFile xdgF (_,True) -> Right <$> BS.readFile homeF (_,_) -> return $ Left "no config file" readConfig :: IO (Either String JrnlConfig) readConfig = (eitherDecodeStrict =<<) <$> getConfig
timds/adjourn
src/Adjrn/Config.hs
bsd-3-clause
1,812
0
12
411
530
291
239
52
3
module Language.Vielfache where import Language.Type import Random alpha = [ '0' .. '9' ] vielfache :: Integer -> Language vielfache m = Language { abbreviation = "{ dezimal(n) : " ++ show m ++ " teilt n }" , alphabet = mkSet alpha , contains = \ w -> all isDigit w && ( 0 == (read w :: Integer) `rem` m ) , sample = \ m c n -> sequence $ replicate c $ sam m n } zahl :: Int -> IO Integer -- ein Integer dieser Länge zahl 0 = return 0 zahl l = do c <- randomRIO [ '1' .. '9' ] cs <- sequence $ replicate l $ randomRIO alpha return $ read ( c : cs ) sam :: Integer -> Int -> IO String -- würfelt ein Wort von ungefähr passender Länge sam m l = do n <- zahl l let nn = n - rem n m return $ show n
Erdwolf/autotool-bonn
src/Language/Drei.hs
gpl-2.0
784
10
13
247
304
156
148
22
1
module GameEngine.Graphics.Frustum where import Data.List import Data.Vect.Float import Data.Vect.Float.Instances data Frustum = Frustum { frPlanes :: [(Vec3, Float)] , ntl :: Vec3 , ntr :: Vec3 , nbl :: Vec3 , nbr :: Vec3 , ftl :: Vec3 , ftr :: Vec3 , fbl :: Vec3 , fbr :: Vec3 } deriving Show pointInFrustum :: Vec3 -> Frustum -> Bool pointInFrustum p fr = foldl' (\b (n,d) -> b && d + n `dotprod` p >= 0) True $ frPlanes fr sphereInFrustum :: Vec3 -> Float -> Frustum -> Bool sphereInFrustum p r fr = foldl' (\b (n,d) -> b && d + n `dotprod` p >= (-r)) True $ frPlanes fr boxInFrustum :: Vec3 -> Vec3 -> Frustum -> Bool boxInFrustum pp pn fr = foldl' (\b (n,d) -> b && d + n `dotprod` (g pp pn n) >= 0) True $ frPlanes fr where g (Vec3 px py pz) (Vec3 nx ny nz) n = Vec3 (fx px nx) (fy py ny) (fz pz nz) where Vec3 x y z = n [fx,fy,fz] = map (\a -> if a > 0 then max else min) [x,y,z] frustum :: Float -> Float -> Float -> Float -> Vec3 -> Vec3 -> Vec3 -> Frustum frustum viewAngle aspectRatio nearDistance farDistance position lookat up = Frustum [ (pl ntr ntl ftl) , (pl nbl nbr fbr) , (pl ntl nbl fbl) , (pl nbr ntr fbr) , (pl ntl ntr nbr) , (pl ftr ftl fbl) ] ntl ntr nbl nbr ftl ftr fbl fbr where pl a b c = (n,d) where n = normalize $ (c - b) `crossprod` (a - b) d = -(n `dotprod` b) m a v = scalarMul a v ang2rad = pi / 180 tang = tan $ viewAngle * ang2rad * 0.5 nh = nearDistance * tang nw = nh * aspectRatio fh = farDistance * tang fw = fh * aspectRatio z = normalize $ position - lookat x = normalize $ up `crossprod` z y = z `crossprod` x nc = position - m nearDistance z fc = position - m farDistance z ntl = nc + m nh y - m nw x ntr = nc + m nh y + m nw x nbl = nc - m nh y - m nw x nbr = nc - m nh y + m nw x ftl = fc + m fh y - m fw x ftr = fc + m fh y + m fw x fbl = fc - m fh y - m fw x fbr = fc - m fh y + m fw x
csabahruska/quake3
game-engine/GameEngine/Graphics/Frustum.hs
bsd-3-clause
2,149
0
13
756
1,008
542
466
57
2
{-# LANGUAGE RecordWildCards #-} module Hpack.Yaml where import Data.Yaml decodeYaml :: FromJSON a => FilePath -> IO (Either String a) decodeYaml file = do result <- decodeFileEither file return $ either (Left . errToString) Right result where errToString err = file ++ case err of AesonException e -> ": " ++ e InvalidYaml (Just (YamlException s)) -> ": " ++ s InvalidYaml (Just (YamlParseException{..})) -> ":" ++ show yamlLine ++ ":" ++ show yamlColumn ++ ": " ++ yamlProblem ++ " " ++ yamlContext where YamlMark{..} = yamlProblemMark _ -> ": " ++ show err
yamadapc/hpack-convert
src/Hpack/Yaml.hs
mit
614
0
18
149
219
107
112
13
4
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} -- | Versions for packages. module Stack.Types.Version (Version ,Cabal.VersionRange -- TODO in the future should have a newtype wrapper ,VersionCheck(..) ,versionParser ,parseVersion ,parseVersionFromString ,versionString ,versionText ,toCabalVersion ,fromCabalVersion ,mkVersion ,versionRangeText ,withinRange ,Stack.Types.Version.intersectVersionRanges ,toMajorVersion ,latestApplicableVersion ,checkVersion ,nextMajorVersion) where import Control.Applicative import Control.DeepSeq import Control.Monad.Catch import Data.Aeson.Extended import Data.Attoparsec.Text import Data.Binary.VersionTagged (Binary, HasStructuralInfo) import Data.Data import Data.Hashable import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (listToMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Binary () import Data.Vector.Binary () import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import Data.Word import Distribution.Text (disp) import qualified Distribution.Version as Cabal import GHC.Generics import Language.Haskell.TH import Language.Haskell.TH.Syntax import Prelude -- Fix warning: Word in Prelude from base-4.8. import Text.PrettyPrint (render) -- | A parse fail. data VersionParseFail = VersionParseFail Text deriving (Typeable) instance Exception VersionParseFail instance Show VersionParseFail where show (VersionParseFail bs) = "Invalid version: " ++ show bs -- | A package version. newtype Version = Version {unVersion :: Vector Word} deriving (Eq,Ord,Typeable,Data,Generic,Binary,NFData) instance HasStructuralInfo Version instance Hashable Version where hashWithSalt i = hashWithSalt i . V.toList . unVersion instance Lift Version where lift (Version n) = appE (conE 'Version) (appE (varE 'V.fromList) (listE (map (litE . IntegerL . fromIntegral) (V.toList n)))) instance Show Version where show (Version v) = intercalate "." (map show (V.toList v)) instance ToJSON Version where toJSON = toJSON . versionText instance FromJSON Version where parseJSON j = do s <- parseJSON j case parseVersionFromString s of Nothing -> fail ("Couldn't parse package version: " ++ s) Just ver -> return ver instance FromJSON a => FromJSON (Map Version a) where parseJSON val = do m <- parseJSON val fmap Map.fromList $ mapM go $ Map.toList m where go (k, v) = do k' <- either (fail . show) return $ parseVersionFromString k return (k', v) -- | Attoparsec parser for a package version. versionParser :: Parser Version versionParser = do ls <- ((:) <$> num <*> many num') let !v = V.fromList ls return (Version v) where num = decimal num' = point *> num point = satisfy (== '.') -- | Convenient way to parse a package version from a 'Text'. parseVersion :: MonadThrow m => Text -> m Version parseVersion x = go x where go = either (const (throwM (VersionParseFail x))) return . parseOnly (versionParser <* endOfInput) -- | Migration function. parseVersionFromString :: MonadThrow m => String -> m Version parseVersionFromString = parseVersion . T.pack -- | Get a string representation of a package version. versionString :: Version -> String versionString (Version v) = intercalate "." (map show (V.toList v)) -- | Get a string representation of a package version. versionText :: Version -> Text versionText (Version v) = T.intercalate "." (map (T.pack . show) (V.toList v)) -- | Convert to a Cabal version. toCabalVersion :: Version -> Cabal.Version toCabalVersion (Version v) = Cabal.Version (map fromIntegral (V.toList v)) [] -- | Convert from a Cabal version. fromCabalVersion :: Cabal.Version -> Version fromCabalVersion (Cabal.Version vs _) = let !v = V.fromList (map fromIntegral vs) in Version v -- | Make a package version. mkVersion :: String -> Q Exp mkVersion s = case parseVersionFromString s of Nothing -> error ("Invalid package version: " ++ show s) Just pn -> [|pn|] -- | Display a version range versionRangeText :: Cabal.VersionRange -> Text versionRangeText = T.pack . render . disp -- | Check if a version is within a version range. withinRange :: Version -> Cabal.VersionRange -> Bool withinRange v r = toCabalVersion v `Cabal.withinRange` r -- | A modified intersection which also simplifies, for better display. intersectVersionRanges :: Cabal.VersionRange -> Cabal.VersionRange -> Cabal.VersionRange intersectVersionRanges x y = Cabal.simplifyVersionRange $ Cabal.intersectVersionRanges x y -- | Returns the first two components, defaulting to 0 if not present toMajorVersion :: Version -> Version toMajorVersion (Version v) = case V.length v of 0 -> Version (V.fromList [0, 0]) 1 -> Version (V.fromList [V.head v, 0]) _ -> Version (V.fromList [V.head v, v V.! 1]) -- | Given a version range and a set of versions, find the latest version from -- the set that is within the range. latestApplicableVersion :: Cabal.VersionRange -> Set Version -> Maybe Version latestApplicableVersion r = listToMaybe . filter (`withinRange` r) . Set.toDescList -- | Get the next major version number for the given version nextMajorVersion :: Version -> Version nextMajorVersion (Version v) = case V.length v of 0 -> Version (V.fromList [0, 1]) 1 -> Version (V.fromList [V.head v, 1]) _ -> Version (V.fromList [V.head v, (v V.! 1) + 1]) data VersionCheck = MatchMinor | MatchExact | NewerMinor deriving (Show, Eq, Ord) instance ToJSON VersionCheck where toJSON MatchMinor = String "match-minor" toJSON MatchExact = String "match-exact" toJSON NewerMinor = String "newer-minor" instance FromJSON VersionCheck where parseJSON = withText expected $ \t -> case t of "match-minor" -> return MatchMinor "match-exact" -> return MatchExact "newer-minor" -> return NewerMinor _ -> fail ("Expected " ++ expected ++ ", but got " ++ show t) where expected = "VersionCheck value (match-minor, match-exact, or newer-minor)" checkVersion :: VersionCheck -> Version -> Version -> Bool checkVersion check (Version wanted) (Version actual) = case check of MatchMinor -> V.and (V.take 3 matching) MatchExact -> V.length wanted == V.length actual && V.and matching NewerMinor -> V.and (V.take 2 matching) && newerMinor where matching = V.zipWith (==) wanted actual newerMinor = case (wanted V.!? 2, actual V.!? 2) of (Nothing, _) -> True (Just _, Nothing) -> False (Just w, Just a) -> a >= w
luigy/stack
src/Stack/Types/Version.hs
bsd-3-clause
7,386
0
15
1,776
2,002
1,059
943
179
5
-- | A test for ensuring that GHC's supporting language extensions remains in -- sync with Cabal's own extension list. -- -- If you have ended up here due to a test failure, please see -- Note [Adding a language extension] in compiler/main/DynFlags.hs. module Main (main) where import Control.Monad import Data.List import DynFlags import Language.Haskell.Extension main :: IO () main = do let ghcExtensions = map flagSpecName xFlags cabalExtensions = map show [ toEnum 0 :: KnownExtension .. ] ghcOnlyExtensions = ghcExtensions \\ cabalExtensions cabalOnlyExtensions = cabalExtensions \\ ghcExtensions check "GHC-only flags" expectedGhcOnlyExtensions ghcOnlyExtensions check "Cabal-only flags" expectedCabalOnlyExtensions cabalOnlyExtensions check :: String -> [String] -> [String] -> IO () check title expected got = do let unexpected = got \\ expected missing = expected \\ got showProblems problemType problems = unless (null problems) $ do putStrLn (title ++ ": " ++ problemType) putStrLn "-----" mapM_ putStrLn problems putStrLn "-----" putStrLn "" showProblems "Unexpected flags" unexpected showProblems "Missing flags" missing -- See Note [Adding a language extension] in compiler/main/DynFlags.hs. expectedGhcOnlyExtensions :: [String] expectedGhcOnlyExtensions = ["RelaxedLayout", "AlternativeLayoutRule", "AlternativeLayoutRuleTransitional", "UnboxedSums", "DerivingStrategies"] expectedCabalOnlyExtensions :: [String] expectedCabalOnlyExtensions = ["Generics", "ExtensibleRecords", "RestrictedTypeSynonyms", "HereDocuments", "NewQualifiedOperators", "XmlSyntax", "RegularPatterns", "SafeImports", "Safe", "Unsafe", "Trustworthy"]
snoyberg/ghc
testsuite/tests/driver/T4437.hs
bsd-3-clause
2,302
0
16
854
339
181
158
44
1
{-| Module : Idris.Inliner Description : Idris' Inliner. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} module Idris.Inliner(inlineDef, inlineTerm) where import Idris.AbsSyntax import Idris.Core.TT inlineDef :: IState -> [([Name], Term, Term)] -> [([Name], Term, Term)] inlineDef ist ds = map (\ (ns, lhs, rhs) -> (ns, lhs, inlineTerm ist rhs)) ds -- | Inlining is either top level (i.e. not in a function arg) or argument level -- -- For each application in a term: -- * Check if the function is inlinable -- (Dictionaries are inlinable in an argument, not otherwise) -- - If so, try inlining without reducing its arguments -- + If successful, then continue on the result (top level) -- + If not, reduce the arguments (argument level) and try again -- - If not, inline all the arguments (top level) inlineTerm :: IState -> Term -> Term inlineTerm ist tm = inl tm where inl orig@(P _ n _) = inlApp n [] orig inl orig@(App _ f a) | (P _ fn _, args) <- unApply orig = inlApp fn args orig inl (Bind n (Let t v) sc) = Bind n (Let t (inl v)) (inl sc) inl (Bind n b sc) = Bind n b (inl sc) inl tm = tm inlApp fn args orig = orig
markuspf/Idris-dev
src/Idris/Inliner.hs
bsd-3-clause
1,240
0
12
291
341
186
155
15
5
----------------------------------------------------------------------------- -- -- Code generation for coverage -- -- (c) Galois Connections, Inc. 2006 -- ----------------------------------------------------------------------------- module StgCmmHpc ( initHpc, mkTickBox ) where import StgCmmMonad import MkGraph import CmmExpr import CLabel import Module import CmmUtils import StgCmmUtils import HscTypes import DynFlags import Control.Monad mkTickBox :: DynFlags -> Module -> Int -> CmmAGraph mkTickBox dflags mod n = mkStore tick_box (CmmMachOp (MO_Add W64) [ CmmLoad tick_box b64 , CmmLit (CmmInt 1 W64) ]) where tick_box = cmmIndex dflags W64 (CmmLit $ CmmLabel $ mkHpcTicksLabel $ mod) n initHpc :: Module -> HpcInfo -> FCode () -- Emit top-level tables for HPC and return code to initialise initHpc _ (NoHpcInfo {}) = return () initHpc this_mod (HpcInfo tickCount _hashNo) = do dflags <- getDynFlags when (gopt Opt_Hpc dflags) $ do emitDataLits (mkHpcTicksLabel this_mod) [ (CmmInt 0 W64) | _ <- take tickCount [0 :: Int ..] ]
wxwxwwxxx/ghc
compiler/codeGen/StgCmmHpc.hs
bsd-3-clause
1,298
0
15
407
281
151
130
28
1
{-# LANGUAGE TypeFamilies, ScopedTypeVariables, FlexibleContexts #-} -- See also Trac #5763 for why we don't really want to see -- an occurs-check error from this program module T4272 where class Family f where terms :: f a -> a class Family (TermFamily a) => TermLike a where type TermFamily a :: * -> * laws :: forall a b. TermLike a => TermFamily a a -> b laws t = prune t (terms (undefined :: TermFamily a a)) prune :: TermLike x => TermFamily x x -> TermFamily x x -> b prune = undefined -- terms :: Family f => f a -> a -- Instantiate with f = TermFamily a -- terms :: Family (TermFamily a) => TermFamily a a -> a -- (terms (undefined::TermFamily a a) :: Family (TermFamily a) => a -- So the call to prune forces the equality -- TermFamily a a ~ a -- which triggers an occurs check
urbanslug/ghc
testsuite/tests/indexed-types/should_fail/T4272.hs
bsd-3-clause
813
0
9
180
160
86
74
10
1
-- Copyright © 2021 Mark Raynsford <[email protected]> https://www.io7m.com -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. module Vector3f ( T (V3), x, y, z, add3, cross, dot3, magnitude, magnitude_squared, mult3, negation, normalize, scale, sub3 ) where data T = V3 { x :: Float, y :: Float, z :: Float } deriving (Eq, Ord, Show) -- | Add vectors, @v0 + v1@. add3 :: T -> T -> T add3 (V3 x0 y0 z0) (V3 x1 y1 z1) = V3 (x0 + x1) (y0 + y1) (z0 + z1) -- | Subtract vectors, @v0 - v1@. sub3 :: T -> T -> T sub3 (V3 x0 y0 z0) (V3 x1 y1 z1) = V3 (x0 - x1) (y0 - y1) (z0 - z1) -- | Component-wise multiply vectors, @v0 * v1@. mult3 :: T -> T -> T mult3 (V3 x0 y0 z0) (V3 x1 y1 z1) = V3 (x0 * x1) (y0 * y1) (z0 * z1) -- | Scale vectors by scalars, @v * s@. scale :: T -> Float -> T scale (V3 x0 y0 z0) s = V3 (x0 * s) (y0 * s) (z0 * s) -- | Dot product of @v0@ and @v1@. dot3 :: T -> T -> Float dot3 v0 v1 = case mult3 v0 v1 of V3 x y z -> x + y + z -- | The squared magnitude of the @v = 'dot3' v v@. magnitude_squared :: T -> Float magnitude_squared v = dot3 v v -- | The magnitude of @v@. magnitude :: T -> Float magnitude = sqrt . magnitude_squared -- | @v@ with unit length. normalize :: T -> T normalize v = let m = magnitude_squared v in if m > 0.0 then scale v (1.0 / m) else v -- | The negation of @v@. negation :: T -> T negation (V3 x y z) = V3 (0.0 - x) (0.0 - y) (0.0 - z) -- | The cross product of @v0@ and @v1@. cross :: T -> T -> T cross (V3 x0 y0 z0) (V3 x1 y1 z1) = let x = (y0 * z1) - (z0 * y1) y = (z0 * x1) - (x0 * z1) z = (x0 * y1) - (y0 * x1) in V3 x y z
io7m/jcamera
com.io7m.jcamera.documentation/src/main/resources/com/io7m/jcamera/documentation/haskell/Vector3f.hs
isc
2,351
0
11
596
719
396
323
55
2
{-# LANGUAGE OverloadedStrings #-} -- | This module defines an efficient value representation as well as -- parsing and comparison functions. This is because the standard -- Futhark parser is not able to cope with large values (like arrays -- that are tens of megabytes in size). The representation defined -- here does not support tuples, so don't use those as input/output -- for your test programs. module Futhark.Test.Values ( Value -- * Reading Values , readValues -- * Comparing Values , compareValues , Mismatch , explainMismatch ) where import Control.Applicative import Control.Monad import Control.Monad.ST import Data.Binary import Data.Binary.Put import Data.Binary.Get import Data.Binary.IEEE754 import qualified Data.ByteString.Lazy.Char8 as BS import Data.Maybe import Data.Int (Int8, Int16, Int32, Int64) import Data.Char (isSpace, ord, chr) import Data.List import Data.Vector.Binary import qualified Data.Vector.Unboxed.Mutable as UMVec import qualified Data.Vector.Unboxed as UVec import Data.Vector.Generic (freeze) import Prelude import qualified Language.Futhark.Syntax as F import Language.Futhark.Pretty() import Futhark.Representation.Primitive (PrimValue) import Language.Futhark.Parser.Lexer import qualified Futhark.Util.Pretty as PP import Futhark.Representation.AST.Attributes.Constants (IsValue(..)) import Futhark.Representation.AST.Pretty () import Futhark.Util.Pretty type STVector s = UMVec.STVector s type Vector = UVec.Vector -- | An efficiently represented Futhark value. Use 'pretty' to get a -- human-readable representation, and the instances of 'Get' and 'Put' -- to obtain binary representations data Value = Int8Value (Vector Int) (Vector Int8) | Int16Value (Vector Int) (Vector Int16) | Int32Value (Vector Int) (Vector Int32) | Int64Value (Vector Int) (Vector Int64) | Word8Value (Vector Int) (Vector Word8) | Word16Value (Vector Int) (Vector Word16) | Word32Value (Vector Int) (Vector Word32) | Word64Value (Vector Int) (Vector Word64) | Float32Value (Vector Int) (Vector Float) | Float64Value (Vector Int) (Vector Double) | BoolValue (Vector Int) (Vector Bool) deriving Show binaryFormatVersion :: Word8 binaryFormatVersion = 2 instance Binary Value where put (Int8Value shape vs) = putBinaryValue " i8" shape vs putInt8 put (Int16Value shape vs) = putBinaryValue " i16" shape vs putInt16le put (Int32Value shape vs) = putBinaryValue " i32" shape vs putInt32le put (Int64Value shape vs) = putBinaryValue " i64" shape vs putInt64le put (Word8Value shape vs) = putBinaryValue " i8" shape vs putWord8 put (Word16Value shape vs) = putBinaryValue " i16" shape vs putWord16le put (Word32Value shape vs) = putBinaryValue " i32" shape vs putWord32le put (Word64Value shape vs) = putBinaryValue " i64" shape vs putWord64le put (Float32Value shape vs) = putBinaryValue " f32" shape vs putFloat32le put (Float64Value shape vs) = putBinaryValue " f64" shape vs putFloat64le put (BoolValue shape vs) = putBinaryValue " f64" shape vs $ putInt8 . boolToInt where boolToInt True = 1 boolToInt False = 0 get = do first <- getInt8 version <- getWord8 rank <- getInt8 unless (chr (fromIntegral first) == 'b') $ fail "Input does not begin with ASCII 'b'." unless (version == binaryFormatVersion) $ fail $ "Expecting binary format version 1; found version: " ++ show version unless (rank >= 0) $ fail $ "Rank must be non-negative, but is: " ++ show rank type_f <- getLazyByteString 4 shape <- replicateM (fromIntegral rank) $ fromIntegral <$> getInt64le let num_elems = product shape shape' = UVec.fromList shape case BS.unpack type_f of " i8" -> get' (Int8Value shape') getInt8 num_elems " i16" -> get' (Int16Value shape') getInt16le num_elems " i32" -> get' (Int32Value shape') getInt32le num_elems " i64" -> get' (Int64Value shape') getInt64le num_elems " u8" -> get' (Word8Value shape') getWord8 num_elems " u16" -> get' (Word16Value shape') getWord16le num_elems " u32" -> get' (Word32Value shape') getWord32le num_elems " u64" -> get' (Word64Value shape') getWord64le num_elems " f32" -> get' (Float32Value shape') getFloat32le num_elems " f64" -> get' (Float64Value shape') getFloat64le num_elems "bool" -> get' (BoolValue shape') getBool num_elems s -> fail $ "Cannot parse binary values of type " ++ show s where getBool = (/=0) <$> getWord8 get' mk get_elem num_elems = mk <$> genericGetVectorWith (pure num_elems) get_elem putBinaryValue :: UVec.Unbox a => String -> Vector Int -> Vector a -> (a -> Put) -> Put putBinaryValue tstr shape vs putv = do putInt8 $ fromIntegral $ ord 'b' putWord8 binaryFormatVersion putWord8 $ fromIntegral $ UVec.length shape mapM_ (putInt8 . fromIntegral . ord) tstr mapM_ (putInt64le . fromIntegral) $ UVec.toList shape mapM_ putv $ UVec.toList vs instance PP.Pretty Value where ppr v | product (valueShape v) == 0 = text "empty" <> parens (dims <> text (valueType v)) where dims = mconcat $ replicate (length (valueShape v)-1) $ text "[]" ppr (Int8Value shape vs) = pprArray (UVec.toList shape) vs ppr (Int16Value shape vs) = pprArray (UVec.toList shape) vs ppr (Int32Value shape vs) = pprArray (UVec.toList shape) vs ppr (Int64Value shape vs) = pprArray (UVec.toList shape) vs ppr (Word8Value shape vs) = pprArray (UVec.toList shape) vs ppr (Word16Value shape vs) = pprArray (UVec.toList shape) vs ppr (Word32Value shape vs) = pprArray (UVec.toList shape) vs ppr (Word64Value shape vs) = pprArray (UVec.toList shape) vs ppr (Float32Value shape vs) = pprArray (UVec.toList shape) vs ppr (Float64Value shape vs) = pprArray (UVec.toList shape) vs ppr (BoolValue shape vs) = pprArray (UVec.toList shape) vs pprArray :: (UVec.Unbox a, F.IsPrimValue a) => [Int] -> UVec.Vector a -> Doc pprArray [] vs = ppr $ F.primValue $ UVec.head vs pprArray (d:ds) vs = brackets $ commasep $ map (pprArray ds . slice) [0..d-1] where slice_size = product ds slice i = UVec.slice (i*slice_size) slice_size vs valueType :: Value -> String valueType (Int8Value _ _) = "i8" valueType (Int16Value _ _) = "i16" valueType (Int32Value _ _) = "i32" valueType (Int64Value _ _) = "i64" valueType (Word8Value _ _) = "u8" valueType (Word16Value _ _) = "u16" valueType (Word32Value _ _) = "u32" valueType (Word64Value _ _) = "u64" valueType (Float32Value _ _) = "f32" valueType (Float64Value _ _) = "f64" valueType (BoolValue _ _) = "bool" valueShape :: Value -> [Int] valueShape (Int8Value shape _) = UVec.toList shape valueShape (Int16Value shape _) = UVec.toList shape valueShape (Int32Value shape _) = UVec.toList shape valueShape (Int64Value shape _) = UVec.toList shape valueShape (Word8Value shape _) = UVec.toList shape valueShape (Word16Value shape _) = UVec.toList shape valueShape (Word32Value shape _) = UVec.toList shape valueShape (Word64Value shape _) = UVec.toList shape valueShape (Float32Value shape _) = UVec.toList shape valueShape (Float64Value shape _) = UVec.toList shape valueShape (BoolValue shape _) = UVec.toList shape -- The parser dropRestOfLine, dropSpaces :: BS.ByteString -> BS.ByteString dropRestOfLine = BS.drop 1 . BS.dropWhile (/='\n') dropSpaces t = case BS.dropWhile isSpace t of t' | "--" `BS.isPrefixOf` t' -> dropSpaces $ dropRestOfLine t' | otherwise -> t' type ReadValue v = BS.ByteString -> Maybe (v, BS.ByteString) symbol :: Char -> BS.ByteString -> Maybe BS.ByteString symbol c t | Just (c', t') <- BS.uncons t, c' == c = Just $ dropSpaces t' | otherwise = Nothing lexeme :: BS.ByteString -> BS.ByteString -> Maybe BS.ByteString lexeme l t | l `BS.isPrefixOf` t = Just $ dropSpaces $ BS.drop (BS.length l) t | otherwise = Nothing -- (Used elements, shape, elements, remaining input) type State s v = (Int, Vector Int, STVector s v, BS.ByteString) readArrayElemsST :: UMVec.Unbox v => Int -> Int -> ReadValue v -> State s v -> ST s (Maybe (Int, State s v)) readArrayElemsST j r rv s = do ms <- readRankedArrayOfST r rv s case ms of Just (i, shape, arr, t) | Just t' <- symbol ',' t -> readArrayElemsST (j+1) r rv (i, shape, arr, t') | otherwise -> return $ Just (j, (i, shape, arr, t)) _ -> return $ Just (0, s) updateShape :: Int -> Int -> Vector Int -> Maybe (Vector Int) updateShape d n shape | old_n < 0 = Just $ shape UVec.// [(r-d, n)] | old_n == n = Just shape | otherwise = Nothing where r = UVec.length shape old_n = shape UVec.! (r-d) growIfFilled :: UVec.Unbox v => Int -> STVector s v -> ST s (STVector s v) growIfFilled i arr = if i >= capacity then UMVec.grow arr capacity else return arr where capacity = UMVec.length arr readRankedArrayOfST :: UMVec.Unbox v => Int -> ReadValue v -> State s v -> ST s (Maybe (State s v)) readRankedArrayOfST 0 rv (i, shape, arr, t) | Just (v, t') <- rv t = do arr' <- growIfFilled i arr UMVec.write arr' i v return $ Just (i+1, shape, arr', t') readRankedArrayOfST r rv (i, shape, arr, t) | Just t' <- symbol '[' t = do ms <- readArrayElemsST 1 (r-1) rv (i, shape, arr, t') return $ do (j, s) <- ms closeArray r j s readRankedArrayOfST _ _ _ = return Nothing closeArray :: Int -> Int -> State s v -> Maybe (State s v) closeArray r j (i, shape, arr, t) = do t' <- symbol ']' t shape' <- updateShape r j shape return (i, shape', arr, t') readRankedArrayOf :: UMVec.Unbox v => Int -> ReadValue v -> BS.ByteString -> Maybe (Vector Int, Vector v, BS.ByteString) readRankedArrayOf r rv t = runST $ do arr <- UMVec.new 1024 ms <- readRankedArrayOfST r rv (0, UVec.replicate r (-1), arr, t) case ms of Just (i, shape, arr', t') -> do arr'' <- freeze (UMVec.slice 0 i arr') return $ Just (shape, arr'', t') Nothing -> return Nothing -- | A character that can be part of a value. This doesn't work for -- string and character literals. constituent :: Char -> Bool constituent ',' = False constituent ']' = False constituent ')' = False constituent c = not $ isSpace c readIntegral :: Integral int => (Token -> Maybe int) -> ReadValue int readIntegral f t = do v <- case scanTokens "" a of Right [L _ NEGATE, L _ (INTLIT x)] -> Just $ negate $ fromIntegral x Right [L _ NEGATE, L _ (DECLIT x)] -> Just $ negate $ fromIntegral x Right [L _ (INTLIT x)] -> Just $ fromIntegral x Right [L _ (DECLIT x)] -> Just $ fromIntegral x Right [L _ tok] -> f tok Right [L _ NEGATE, L _ tok] -> negate <$> f tok _ -> Nothing return (v, dropSpaces b) where (a,b) = BS.span constituent t readInt8 :: ReadValue Int8 readInt8 = readIntegral f where f (I8LIT x) = Just x f _ = Nothing readInt16 :: ReadValue Int16 readInt16 = readIntegral f where f (I16LIT x) = Just x f _ = Nothing readInt32 :: ReadValue Int32 readInt32 = readIntegral f where f (I32LIT x) = Just x f _ = Nothing readInt64 :: ReadValue Int64 readInt64 = readIntegral f where f (I64LIT x) = Just x f _ = Nothing readWord8 :: ReadValue Word8 readWord8 = readIntegral f where f (U8LIT x) = Just x f _ = Nothing readWord16 :: ReadValue Word16 readWord16 = readIntegral f where f (U16LIT x) = Just x f _ = Nothing readWord32 :: ReadValue Word32 readWord32 = readIntegral f where f (U32LIT x) = Just x f _ = Nothing readWord64 :: ReadValue Word64 readWord64 = readIntegral f where f (U64LIT x) = Just x f _ = Nothing readFloat :: RealFloat float => (Token -> Maybe float) -> ReadValue float readFloat f t = do v <- case scanTokens "" a of Right [L _ NEGATE, L _ (REALLIT x)] -> Just $ negate $ fromDouble x Right [L _ (REALLIT x)] -> Just $ fromDouble x Right [L _ tok] -> f tok Right [L _ NEGATE, L _ tok] -> negate <$> f tok _ -> Nothing return (v, dropSpaces b) where (a,b) = BS.span constituent t fromDouble = uncurry encodeFloat . decodeFloat readFloat32 :: ReadValue Float readFloat32 = readFloat lexFloat32 where lexFloat32 (F32LIT x) = Just x lexFloat32 _ = Nothing readFloat64 :: ReadValue Double readFloat64 = readFloat lexFloat64 where lexFloat64 (F64LIT x) = Just x lexFloat64 _ = Nothing readBool :: ReadValue Bool readBool t = do v <- case scanTokens "" a of Right [L _ TRUE] -> Just True Right [L _ FALSE] -> Just False _ -> Nothing return (v, dropSpaces b) where (a,b) = BS.span constituent t readPrimType :: ReadValue String readPrimType t = do pt <- case scanTokens "" a of Right [L _ (ID s)] -> Just $ F.nameToString s _ -> Nothing return (pt, dropSpaces b) where (a,b) = BS.span constituent t readEmptyArrayOfRank :: Int -> BS.ByteString -> Maybe (Value, BS.ByteString) readEmptyArrayOfRank r t | Just t' <- symbol '[' t, Just t'' <- symbol ']' t' = readEmptyArrayOfRank (r+1) t'' | otherwise = do (pt, t') <- readPrimType t v <- case pt of "i8" -> Just $ Int8Value (UVec.replicate r 0) UVec.empty "i16" -> Just $ Int16Value (UVec.replicate r 0) UVec.empty "i32" -> Just $ Int32Value (UVec.replicate r 0) UVec.empty "i64" -> Just $ Int64Value (UVec.replicate r 0) UVec.empty "u8" -> Just $ Word8Value (UVec.replicate r 0) UVec.empty "u16" -> Just $ Word16Value (UVec.replicate r 0) UVec.empty "u32" -> Just $ Word32Value (UVec.replicate r 0) UVec.empty "u64" -> Just $ Word64Value (UVec.replicate r 0) UVec.empty "f32" -> Just $ Float32Value (UVec.replicate r 0) UVec.empty "f64" -> Just $ Float64Value (UVec.replicate r 0) UVec.empty "bool" -> Just $ BoolValue (UVec.replicate r 0) UVec.empty _ -> Nothing return (v, t') readEmptyArray :: BS.ByteString -> Maybe (Value, BS.ByteString) readEmptyArray t = do t' <- symbol '(' =<< lexeme "empty" t (v, t'') <- readEmptyArrayOfRank 1 t' t''' <- symbol ')' t'' return (v, t''') readValue :: BS.ByteString -> Maybe (Value, BS.ByteString) readValue full_t | Right (t', _, v) <- decodeOrFail full_t = Just (v, dropSpaces t') | otherwise = readEmptyArray full_t `mplus` insideBrackets 0 full_t where insideBrackets r t = maybe (tryValueAndReadValue r t) (insideBrackets (r+1)) $ symbol '[' t tryWith f mk r t | Just _ <- f t = do (shape, arr, rest_t) <- readRankedArrayOf r f full_t return (mk shape arr, rest_t) | otherwise = Nothing tryValueAndReadValue r t = -- 32-bit signed integers come first such that we parse -- unsuffixed integer constants as of that type. tryWith readInt32 Int32Value r t `mplus` tryWith readInt8 Int8Value r t `mplus` tryWith readInt16 Int16Value r t `mplus` tryWith readInt64 Int64Value r t `mplus` tryWith readWord8 Word8Value r t `mplus` tryWith readWord16 Word16Value r t `mplus` tryWith readWord32 Word32Value r t `mplus` tryWith readWord64 Word64Value r t `mplus` tryWith readFloat64 Float64Value r t `mplus` tryWith readFloat32 Float32Value r t `mplus` tryWith readBool BoolValue r t -- | Parse Futhark values from the given bytestring. readValues :: BS.ByteString -> Maybe [Value] readValues = readValues' . dropSpaces where readValues' t | BS.null t = Just [] | otherwise = do (a, t') <- readValue t (a:) <$> readValues' t' -- Comparisons -- | Two values differ in some way. data Mismatch = PrimValueMismatch (Int,Int) PrimValue PrimValue -- ^ The position the value number and a flat index -- into the array. | ArrayShapeMismatch Int [Int] [Int] | TypeMismatch Int String String | ValueCountMismatch Int Int instance Show Mismatch where show (PrimValueMismatch (i,j) got expected) = explainMismatch (i,j) "" got expected show (ArrayShapeMismatch i got expected) = explainMismatch i "array of shape " got expected show (TypeMismatch i got expected) = explainMismatch i "value of type " got expected show (ValueCountMismatch got expected) = "Expected " ++ show expected ++ " values, got " ++ show got -- | A human-readable description of how two values are not the same. explainMismatch :: (Show i, PP.Pretty a) => i -> String -> a -> a -> String explainMismatch i what got expected = "Value " ++ show i ++ " expected " ++ what ++ PP.pretty expected ++ ", got " ++ PP.pretty got -- | Compare two sets of Futhark values for equality. Shapes and -- types must also match. compareValues :: [Value] -> [Value] -> Maybe Mismatch compareValues got expected | n /= m = Just $ ValueCountMismatch n m | otherwise = case catMaybes $ zipWith3 compareValue [0..] got expected of e : _ -> Just e [] -> Nothing where n = length got m = length expected compareValue :: Int -> Value -> Value -> Maybe Mismatch compareValue i got_v expected_v | valueShape got_v == valueShape expected_v = case (got_v, expected_v) of (Int8Value _ got_vs, Int8Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Int16Value _ got_vs, Int16Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Int32Value _ got_vs, Int32Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Int64Value _ got_vs, Int64Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Word8Value _ got_vs, Word8Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Word16Value _ got_vs, Word16Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Word32Value _ got_vs, Word32Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Word64Value _ got_vs, Word64Value _ expected_vs) -> compareNum 1 got_vs expected_vs (Float32Value _ got_vs, Float32Value _ expected_vs) -> compareNum (tolerance expected_vs) got_vs expected_vs (Float64Value _ got_vs, Float64Value _ expected_vs) -> compareNum (tolerance expected_vs) got_vs expected_vs (BoolValue _ got_vs, BoolValue _ expected_vs) -> compareGen compareBool got_vs expected_vs _ -> Just $ TypeMismatch i (valueType got_v) (valueType expected_v) | otherwise = Just $ ArrayShapeMismatch i (valueShape got_v) (valueShape expected_v) where compareNum tol = compareGen $ compareElement tol compareGen cmp got expected = foldl mplus Nothing $ zipWith cmp (UVec.toList $ UVec.indexed got) (UVec.toList expected) compareElement tol (j, got) expected | comparePrimValue tol got expected = Nothing | otherwise = Just $ PrimValueMismatch (i,j) (value got) (value expected) compareBool (j, got) expected | got == expected = Nothing | otherwise = Just $ PrimValueMismatch (i,j) (value got) (value expected) comparePrimValue :: (Ord num, Num num) => num -> num -> num -> Bool comparePrimValue tol x y = diff < tol where diff = abs $ x - y minTolerance :: Fractional a => a minTolerance = 0.002 -- 0.2% tolerance :: (Ord a, Fractional a, UVec.Unbox a) => Vector a -> a tolerance = UVec.foldl tolerance' minTolerance where tolerance' t v = max t $ minTolerance * v
ihc/futhark
src/Futhark/Test/Values.hs
isc
20,061
0
17
5,086
7,123
3,551
3,572
431
12
module Graphics.Cogh.Text ( Font , newFont , fontSize , newTextureFromText ) where import Foreign.C import Foreign.ForeignPtr import Foreign.Ptr import Graphics.Cogh.Color import Graphics.Cogh.Render import Graphics.Cogh.Window.Internal data Font = Font (ForeignPtr ()) Int type FontPtr = Ptr () type TextPtr = Ptr () newFont :: FilePath -> Int -> IO Font newFont file size = do cFont <- withCString file $ \cFile -> cNewFont cFile $ fromIntegral size foreignPtr <- newForeignPtr deleteFontFunPtr cFont return $ Font foreignPtr size fontSize :: Font -> Int fontSize (Font _ size) = size withCFont :: Font -> (FontPtr -> IO a) -> IO a withCFont (Font foreignPtr _) = withForeignPtr foreignPtr foreign import ccall unsafe "newFont" cNewFont :: CString -> CInt -> IO FontPtr foreign import ccall unsafe "&deleteFont" deleteFontFunPtr :: FunPtr (FontPtr -> IO ()) newTextureFromText :: Window -> Font -> String -> Color -> IO Texture newTextureFromText w f text c = do cTexture <- withCFont f $ \cFont -> withCString text $ \cText -> withColorPtr c $ \cColor -> cNewTextureFromText w cFont cText cColor newTexture cTexture foreign import ccall unsafe "newTextureFromText" cNewTextureFromText :: Window -> FontPtr -> CString -> Ptr Float -> IO TextPtr
ivokosir/cogh
src/Graphics/Cogh/Text.hs
mit
1,365
0
14
309
431
221
210
39
1
{-# LANGUAGE BangPatterns #-} module Tools.Mill (main) where import Data.Map (unions) import Data.Either (rights) import Control.Monad (forM_,forever,replicateM_) import Tools.Mill.Table import Tools.Mill.Query import Text.Parsec.Prim import qualified Data.ByteString.Char8 as C import Data.Map(fromList,lookup) import Prelude hiding (lookup) import System.Environment (getArgs) import System.IO(stdin,stderr) import System.IO(hPutStrLn) import Data.ByteString(ByteString,hGetLine,hGetContents,pack,unpack) import Control.Concurrent import Control.Concurrent.MVar match :: Header -> Query -> DataLine -> Bool match header qs = match' $ map ((flip lookup) qs) header match' tests line = all passTest' $ zip tests cols where cols = C.split ' ' line passTest' (Nothing, _) = True passTest' ((Just t), v) = passTest t v infoMode keys = do headerString <- hGetLine stdin let parsedHeader = runParser parseHeader () "" headerString either wrongHeader (\_ -> print headerString) parsedHeader where wrongHeader _ = hPutStrLn stderr "wrong Header" filterMode keys = do let query = unions $ rights $ map parseQuery keys hPutStrLn stderr $ show query headerString <- hGetLine stdin let parsedHeader = runParser parseHeader () "" headerString either wrongHeader (filterBody headerString query) parsedHeader where wrongHeader _ = hPutStrLn stderr "wrong Header" filterBody headerString query header = do C.putStrLn headerString body <- hGetContents stdin let matcher = match header query forM_ (filter matcher (C.split '\n' body)) $ C.putStrLn main = do args <- getArgs case args of ("--infos" : keys) -> infoMode keys ("--filter" : keys) -> filterMode $ map C.pack keys otherwise -> print usage usage = "--filter [queries] | --infos"
lucasdicioccio/mill
Tools/Mill.hs
mit
1,953
0
15
464
613
316
297
47
3
-- Generated by protobuf-simple. DO NOT EDIT! module Types.SInt32ListPacked where import Control.Applicative ((<$>)) import Prelude () import qualified Data.ProtoBufInt as PB newtype SInt32ListPacked = SInt32ListPacked { value :: PB.Seq PB.Int32 } deriving (PB.Show, PB.Eq, PB.Ord) instance PB.Default SInt32ListPacked where defaultVal = SInt32ListPacked { value = PB.defaultVal } instance PB.Mergeable SInt32ListPacked where merge a b = SInt32ListPacked { value = PB.merge (value a) (value b) } instance PB.Required SInt32ListPacked where reqTags _ = PB.fromList [] instance PB.WireMessage SInt32ListPacked where fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getSInt32Packed fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getSInt32 fieldToValue tag self = PB.getUnknown tag self messageToFields self = do PB.putSInt32Packed (PB.WireTag 1 PB.LenDelim) (value self)
sru-systems/protobuf-simple
test/Types/SInt32ListPacked.hs
mit
1,018
0
13
174
348
186
162
21
0
{-# LANGUAGE OverloadedStrings #-} module Database.EventSafe.HTTP.Client ( apiGetResource , apiCreateEvent ) where import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BSL import Network.HTTP import Network.URI -- | A helper to build a 'Request BSL.ByteString', setting the content length properly in the header buildRequest :: RequestMethod -> URI -> BSL.ByteString -- ^ The request body -> Request BSL.ByteString buildRequest method url body = setContentLength . setBody $ (mkRequest method url :: Request BSL.ByteString) where setBody req = req { rqBody = body } setContentLength = replaceHeader HdrContentLength $ show (BSL.length body) apiGetResource :: FromJSON res => (ref -> String) -- ^ Function to build the /ref/ parameter of the request -> String -- ^ Endpoint, e.g. "/users" -> URI -- ^ The base URL of the database, e.g. http://localhost:1337 -> ref -- ^ The reference to the -> IO (Either String res) apiGetResource mkRefParam frag baseUrl ref = do let endpoint = baseUrl { uriPath = uriPath baseUrl ++ frag , uriQuery = "?ref=" ++ mkRefParam ref } req :: Request BSL.ByteString req = mkRequest GET endpoint eresp <- simpleHTTP req return $ case eresp of Left err -> Left $ "Error from HTTP: " ++ show err Right resp -> let mRes = decode $ rspBody resp in case mRes of Nothing -> Left "Can't parse the JSON response" Just res -> Right res apiCreateEvent :: ToJSON event => URI -> event -> IO (Either String ()) apiCreateEvent baseUrl event = do let endpoint = baseUrl { uriPath = uriPath baseUrl ++ "/create-event" } req :: Request BSL.ByteString req = buildRequest POST endpoint $ encode event eresp <- simpleHTTP req return $ case eresp of Left err -> Left $ "Error from HTTP: " ++ show err Right resp -> case rspCode resp of (2, 0, 1) -> Right () _ -> Left "Error code returned" -- FIXME (return a Maybe CreationError ?)
thoferon/eventsafe
src/Database/EventSafe/HTTP/Client.hs
mit
2,189
0
16
649
540
273
267
47
3
module PrettyPrinter (pprDefns, pprExpr) where import Language import Iseq import Types pprDefns :: [(Name,CoreExpr)] -> Iseq pprDefns defns = iInterleave sep (map pprDefn defns) where sep = iConcat [ iStr ";", iNewline ] pprDefn :: (Name, CoreExpr) -> Iseq pprDefn (name, expr) = iConcat [ iStr name, iStr " = ", iIndent (pprExpr expr) ] pprExpr :: CoreExpr -> Iseq pprExpr (EVar v) = iStr v pprExpr (EAp (EAp (EVar "+") e1) e2) = iConcat [pprAExpr e1, iStr " + ", pprAExpr e2] pprExpr (EAp e1 e2) = (pprExpr e1) `iAppend` (iStr " ") `iAppend` (pprAExpr e2) pprExpr (ELet isRec defns expr) = iConcat [iStr keyword, iNewline, iStr " ", iIndent (pprDefns defns), iNewline, iStr "in ", pprExpr expr] where keyword | not isRec = "let" | isRec = "letrec" -- pprAExpr is pprExpr with parenthesis when required pprAExpr :: CoreExpr -> Iseq pprAExpr e | isAtomicExpr e = pprExpr e | otherwise = (iStr "(") `iAppend` pprExpr e `iAppend` (iStr ")") -- end of file
typedvar/hLand
hcore/PrettyPrinter.hs
mit
1,077
0
11
288
413
215
198
24
1
module Util where liftFst f (x,y) = (f x, y) liftSnd f (x,y) = (x, f y)
bhamrick/puzzlib
Util.hs
mit
73
0
6
18
54
31
23
3
1
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import System.FilePath (FilePath) import qualified Data.Aeson as JSON import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.Digest.Murmur3 as Hash import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified System.Environment as IO import qualified System.Exit as IO import qualified System.FilePath as IO import qualified System.Directory as IO import qualified System.IO as IO import qualified Text.RTF as RTF import qualified Text.XML as XML import qualified Paths_docgen as Paths import Control.DeepSeq import Control.Monad.Identity import Data.Char import Data.List import Data.Maybe import Data.String import Numeric import Text.XML.Cursor import Debug.Trace data Section = Section { sectionPath :: [(Int, T.Text)], sectionType :: SectionType, sectionDocumentID :: T.Text, sectionChildren :: [Section] } instance NFData Section where rnf section = (sectionPath section) `deepseq` (sectionType section) `deepseq` (sectionDocumentID section) `deepseq` (sectionChildren section) `deepseq` () data SectionType = Numbered | Lettered | Anonymous | InParent Bool instance NFData SectionType where rnf Numbered = Numbered `seq` () rnf Lettered = Lettered `seq` () rnf Anonymous = Anonymous `seq` () rnf (InParent flag) = InParent `seq` flag `deepseq` () data OutputSection = OutputSection { outputSectionID :: T.Text, outputSectionNumber :: Maybe T.Text, outputSectionTitle :: Maybe [(T.Text, T.Text)], outputSectionProperTitle :: Maybe T.Text, outputSectionParentBody :: [BodyItem], outputSectionSelfBody :: [BodyItem], outputSectionChildren :: [OutputSection] } instance NFData OutputSection where rnf section = (outputSectionID section) `deepseq` (outputSectionNumber section) `deepseq` (outputSectionTitle section) `deepseq` (outputSectionProperTitle section) `deepseq` (outputSectionParentBody section) `deepseq` (outputSectionSelfBody section) `deepseq` (outputSectionChildren section) `deepseq` () data FlattenedOutputSection = FlattenedOutputSection { flattenedOutputSectionTitle :: T.Text, flattenedOutputSectionNavigation :: [[TextItem]], flattenedOutputSectionBody :: [BodyItem] } instance JSON.ToJSON FlattenedOutputSection where toJSON section = JSON.object ["title" JSON..= (JSON.toJSON $ flattenedOutputSectionTitle section), "navigation" JSON..= (JSON.toJSON $ flattenedOutputSectionNavigation section), "body" JSON..= (JSON.toJSON $ flattenedOutputSectionBody section)] instance NFData FlattenedOutputSection where rnf section = (flattenedOutputSectionTitle section) `deepseq` (flattenedOutputSectionNavigation section) `deepseq` (flattenedOutputSectionBody section) `deepseq` () data BodyItem = Header [TextItem] | Paragraph [TextItem] instance JSON.ToJSON BodyItem where toJSON (Header items) = JSON.toJSON $ JSON.String "header" : map JSON.toJSON items toJSON (Paragraph items) = JSON.toJSON $ JSON.String "paragraph" : map JSON.toJSON items instance NFData BodyItem where rnf (Header items) = items `deepseq` () rnf (Paragraph items) = items `deepseq` () data TextItem = Link T.Text [TextItem] | Text T.Text instance JSON.ToJSON TextItem where toJSON (Link identifier items) = JSON.toJSON $ JSON.String "link" : JSON.String identifier : map JSON.toJSON items toJSON (Text text) = JSON.String text instance NFData TextItem where rnf (Link destination items) = destination `deepseq` items `deepseq` () rnf (Text item) = item `deepseq` () main :: IO () main = do arguments <- IO.getArgs case arguments of [inputWrapperPath, outputDirectoryPath] -> do inputExists <- IO.doesDirectoryExist inputWrapperPath case inputExists of True -> return () False -> do putStrLn $ "Couldn't find " ++ show inputWrapperPath ++ "." IO.exitFailure outputExistsAsFile <- IO.doesFileExist outputDirectoryPath outputExistsAsDirectory <- IO.doesDirectoryExist outputDirectoryPath case outputExistsAsFile || outputExistsAsDirectory of True -> do putStrLn $ "Refusing to overwrite " ++ show outputDirectoryPath ++ "." IO.exitFailure False -> return () process inputWrapperPath outputDirectoryPath _ -> do putStrLn $ "Usage: docgen Input.scriv output/" IO.exitFailure process :: FilePath -> FilePath -> IO () process inputWrapperPath outputDirectoryPath = do putStrLn "Processing the binder..." let inputBinderPath = fromString $ inputWrapperPath ++ "/" ++ (IO.takeBaseName inputWrapperPath) ++ ".scrivx" inputBinder <- XML.readFile XML.def inputBinderPath let labels = Map.fromList $ fromDocument inputBinder $/ element "LabelSettings" &/ element "Labels" &/ element "Label" &| (\itemCursor -> let key = T.concat $ attribute "ID" itemCursor name = T.concat $ itemCursor $/ content in (key, name)) statuses = Map.fromList $ fromDocument inputBinder $/ element "StatusSettings" &/ element "StatusItems" &/ element "Status" &| (\itemCursor -> let key = attribute "ID" itemCursor name = T.concat $ itemCursor $/ content in (key, name)) binder <- mapM (\(index, binderItem) -> do collectBinderItem labels binderItem [(index, binderItemTitle binderItem)]) (zip [1 ..] $ (fromDocument inputBinder) $/ element "Binder" &/ element "BinderItem" &| node) draft <- case computeDraft binder of Nothing -> do putStrLn $ "Draft not found by that name in the binder." IO.exitFailure Just draft -> getOutputDraft inputWrapperPath draft >>= return . (\draft -> computeFlattenedOutput (outputSectionID draft) (outputSectionID draft) Nothing Nothing draft) return $!! draft putStrLn "Writing output..." IO.createDirectory outputDirectoryPath LBS.writeFile (outputDirectoryPath ++ "/content.json") (JSON.encode $ JSON.object ["toc" JSON..= (JSON.String $ fst $ head draft), "sections" JSON..= (JSON.object $ map (uncurry (JSON..=)) draft)]) mapM_ (\dataFileInputName -> do dataFileInputPath <- Paths.getDataFileName dataFileInputName data' <- BS.readFile dataFileInputPath let dataFileOutputPath = outputDirectoryPath ++ "/" ++ IO.takeFileName dataFileInputName BS.writeFile dataFileOutputPath data') ["Data/handlebars.js", "Data/index.css", "Data/index.html", "Data/index.js"] binderItemTitle :: XML.Node -> T.Text binderItemTitle binderItem = T.concat $ (fromNode binderItem) $/ element "Title" &/ content collectBinderItem :: Map.Map T.Text T.Text -> XML.Node -> [(Int, T.Text)] -> IO Section collectBinderItem labels binderItem path = do children <- mapM (\(index, child) -> do collectBinderItem labels child (path ++ [(index, binderItemTitle child)])) (zip [1 ..] ((fromNode binderItem) $/ element "Children" &/ element "BinderItem" &| node)) let labelID = T.concat ((fromNode binderItem) $/ element "MetaData" &/ element "LabelID" &/ content) maybeLabel = Map.lookup labelID labels sectionType' = case maybeLabel of Just "Overview" -> InParent False Just "Synopsis" -> InParent True Just "Reference" -> Numbered Just "Tutorial" -> Numbered Just "Parameters" -> InParent True Just "Semantics" -> InParent True Just "Xref" -> InParent True Just "Manpage" -> Anonymous Just "Appendix" -> Lettered _ -> Numbered documentID = T.concat ((fromNode binderItem) $| attribute "ID") return $!! Section { sectionPath = path, sectionType = sectionType', sectionDocumentID = documentID, sectionChildren = children } visitSectionTree :: (Monad m) => ([a] -> Section -> m a) -> Section -> m a visitSectionTree action section = do childResults <- mapM (visitSectionTree action) (sectionChildren section) action childResults section findPreorder :: (Monad m) => (Section -> m Bool) -> Section -> m (Maybe Section) findPreorder predicate section = visitSectionTree (\childResults section -> do foundHere <- predicate section case foundHere of True -> return (Just section) False -> return $ listToMaybe $ catMaybes childResults) section computeDraft :: [Section] -> Maybe Section computeDraft binder = let maybeDraft = foldl' (\maybeResult section -> case maybeResult of Nothing -> runIdentity $ findPreorder isDraft section Just _ -> maybeResult) Nothing binder isDraft section = let (_, title) = last (sectionPath section) in return $ title == "Draft" stripPathPrefix length section = Section { sectionPath = drop length (sectionPath section), sectionType = sectionType section, sectionDocumentID = sectionDocumentID section, sectionChildren = map (stripPathPrefix length) (sectionChildren section) } in fmap (\draft -> stripPathPrefix (length $ sectionPath draft) draft) maybeDraft getOutputDraft :: FilePath -> Section -> IO OutputSection getOutputDraft inputWrapperPath draft = do (result, _) <- getOutputSection inputWrapperPath True Nothing 1 [] draft return result getOutputSection :: FilePath -> Bool -> Maybe T.Text -> Int -> [(T.Text, T.Text)] -> Section -> IO (OutputSection, Bool) getOutputSection inputWrapperPath isRoot numberSoFar nextNumberPart titleSoFar section = do let number = if isRoot then Nothing else case sectionType section of Numbered -> Just $ T.concat [fromMaybe "" numberSoFar, T.pack $ show nextNumberPart, "."] Lettered -> Just $ T.concat [fromMaybe "" numberSoFar, T.pack [chr (ord 'A' + nextNumberPart - 1)], "."] Anonymous -> Nothing InParent _ -> Nothing identifier = computeIdentifierHash $ sectionDocumentID section finalTitleComponent = case sectionPath section of [] -> Nothing path -> Just (identifier, snd $ last path) initialTitle = case sectionType section of InParent False -> Nothing InParent True -> fmap (\item -> [item]) finalTitleComponent Anonymous -> Just titleSoFar _ -> case titleSoFar ++ maybeToList finalTitleComponent of [] -> Nothing result -> Just result properTitle = case sectionType section of Anonymous -> fmap snd finalTitleComponent _ -> Nothing inParent = case sectionType section of InParent _ -> True _ -> False childNumber = if inParent then numberSoFar else number (_, _, title, children, body) <- foldM (\(indexSoFar, letteredModeSoFar, titleSoFar, childrenSoFar, bodySoFar) childSection -> do let (indexHere, letteredMode) = case sectionType childSection of Lettered -> if letteredModeSoFar then (indexSoFar, True) else (1, True) _ -> (indexSoFar, letteredModeSoFar) (child, childInLine) <- getOutputSection inputWrapperPath False childNumber indexHere (fromMaybe [] titleSoFar) childSection let title = case titleSoFar of Just _ -> titleSoFar Nothing -> if childInLine then outputSectionTitle child else Nothing body = bodySoFar ++ outputSectionParentBody child children = if childInLine then childrenSoFar else childrenSoFar ++ [child] index = if childInLine then indexHere else indexHere + 1 return $!! (index, letteredMode, title, children, body)) (1, False, initialTitle, [], []) (sectionChildren section) let bodyPrefix = if inParent then case title of Nothing -> [] Just title -> [Header $ concat [map (\(identifier, name) -> Link identifier [Text name]) (init title), [Text $ snd $ last title]]] else [] parentBody = case (number, finalTitleComponent) of (Just number, Just (_, title)) -> [Header [Link identifier [Text number, Text " ", Text title]]] (Just number, Nothing) -> [Header [Link identifier [Text number]]] (Nothing, Just (_, title)) -> [Header [Link identifier [Text title]]] (Nothing, Nothing) -> [Header [Link identifier [Text "?"]]] putStrLn $ "Processing " ++ (case number of Nothing -> "" Just number -> T.unpack number ++ " ") ++ (case title of Nothing -> "(Untitled)" Just title -> T.unpack $ T.intercalate titleSeparator $ map snd title) ++ (case properTitle of Nothing -> "" Just properTitle -> T.unpack titleSeparator ++ T.unpack properTitle) ++ "..." bodyMain <- getSectionBody inputWrapperPath (sectionDocumentID section) return $!! (OutputSection { outputSectionID = identifier, outputSectionNumber = number, outputSectionTitle = title, outputSectionProperTitle = properTitle, outputSectionParentBody = if inParent then bodyPrefix ++ bodyMain ++ body else parentBody, outputSectionSelfBody = if inParent then [] else bodyPrefix ++ bodyMain ++ body, outputSectionChildren = children }, inParent) getSectionBody :: FilePath -> T.Text -> IO [BodyItem] getSectionBody inputWrapperPath documentID = do let inputDocumentPath = fromString $ inputWrapperPath ++ "/Files/Docs/" ++ (T.unpack documentID) ++ ".rtf" exists <- IO.doesFileExist inputDocumentPath if exists then do rtf <- RTF.readFile inputDocumentPath case rtf of Nothing -> do putStrLn $ "Unable to read from " ++ inputDocumentPath IO.exitFailure Just rtf -> do let paragraphs = map (\paragraphIn -> Paragraph [Text $ RTF.paragraphText paragraphIn]) (RTF.rtfParagraphs rtf) return $!! paragraphs else return [] computeIdentifierHash :: T.Text -> T.Text computeIdentifierHash documentID = T.pack $ concatMap (\byte -> let hex = showHex byte "" padding = take (2 - length hex) (repeat '0') in hex ++ padding) $ BS.unpack $ BS.take 4 $ Hash.asByteString $ Hash.hash $ T.encodeUtf8 documentID computeFlattenedOutput :: T.Text -> T.Text -> Maybe T.Text -> Maybe [(T.Text, T.Text)] -> OutputSection -> [(T.Text, FlattenedOutputSection)] computeFlattenedOutput tableOfContentsIdentifier symbolIndexIdentifier maybeParentNumber maybeParentTitle section = [(outputSectionID section, FlattenedOutputSection { flattenedOutputSectionTitle = case (outputSectionNumber section, outputSectionTitle section) of (Just number, Just title) -> T.concat [number, " ", T.intercalate titleSeparator $ map snd title, " | Modern Data the Reference"] (Just number, Nothing) -> T.concat [number, " | Modern Data the Reference"] (Nothing, Just title) -> T.concat [T.intercalate titleSeparator $ map snd title, " | Modern Data the Reference"] (Nothing, Nothing) -> "Modern Data the Reference", flattenedOutputSectionNavigation = let titleParts title = map (\(identifier, name) -> linkIfNotHere identifier name) title linkIfNotHere identifier name = if outputSectionID section == identifier then Text name else Link identifier [Text name] overallNavigation = [[linkIfNotHere tableOfContentsIdentifier "Modern Data the Reference"]] maybeDrillDownNumber = case outputSectionNumber section of Nothing -> case maybeParentNumber of Nothing -> Nothing Just parentNumber -> Just [Text parentNumber] Just number -> Just [Text number] maybeDrillDownParts = case outputSectionTitle section of Just title -> Just $ intersperse (Text titleSeparator) (titleParts title) Nothing -> Nothing maybeDrillDownLine = case (maybeDrillDownNumber, maybeDrillDownParts) of (Nothing, Nothing) -> Nothing (Just number, Nothing) -> Just number (Nothing, Just parts) -> Just parts (Just number, Just parts) -> Just $ number ++ [Text " "] ++ parts maybeProperLine = case outputSectionProperTitle section of Just properTitle -> Just [Text properTitle] Nothing -> Nothing in overallNavigation ++ maybeToList maybeDrillDownLine ++ maybeToList maybeProperLine, flattenedOutputSectionBody = outputSectionSelfBody section })] ++ concatMap (computeFlattenedOutput tableOfContentsIdentifier symbolIndexIdentifier (outputSectionNumber section) (outputSectionTitle section)) (outputSectionChildren section) titleSeparator :: T.Text titleSeparator = " ∙ "
IreneKnapp/modern-data
Tools/DocGen/Haskell/Main.hs
mit
20,717
0
25
7,662
5,012
2,602
2,410
518
29
-- Asteroids game import Graphics.Gloss import World import Render main = do mode <- displayMode print mode play (displayMode width height) black startingState render handleInput stepWorld displayMode :: IO Display displayMode = do putStrLn "Enter window width and height:" width <- prompt "Width: " height <- prompt "Height: " return $ InWindow "Asteroids" (width, height) (50, 50) prompt :: Read a => String -> IO a prompt s = putStr s >> fmap read getLine
Solonarv/Asteroids
Asteroids.hs
mit
492
0
9
108
159
76
83
15
1
{-# LANGUAGE StandaloneDeriving, DeriveDataTypeable, DeriveGeneric #-} {-# LANGUAGE OverloadedLists, TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Commands.Instances where import Control.Monad.Catch import Text.Parsec (ParseError) import Data.List.NonEmpty (NonEmpty(..)) import Language.Haskell.TH.Lift import Data.Map (Map) import qualified Data.Map as Map import Control.Exception (throwIO) import Data.Typeable import Language.Haskell.TH import GHC.Exts deriving instance Typeable ParseError instance Exception ParseError -- | any 'MonadThrow' instance must satisfy @throwM e >> f = throwM e@ -- -- the docs for 'Q.report' say "use 'fail' to stop". but 'fail' holds a 'String', where 'throwIO' holds an 'Exception'. from experiments/documentation, I'm pretty sure 'throwIO' short-circuits. -- -- this instance seems to work, and I think I've satisfied the laws. but, by reading the documentation, not understanding the code. i.e. beware. 'Q' seems too cyclic, simplified: -- -- * @class (Monad m) => 'Quasi' m where qF :: m a -> m a@ -- * @instance 'Quasi' 'Q' where qF (Q a) = Q (qF a)@ -- * @instance 'Quasi' 'IO' where qF _ = fail ""@ -- * @newtype 'Q' a = Q { unQ :: forall m. 'Quasi' m => m a }@ -- -- what does (e.g.) @Q.report@ ever do? 'Q' and 'IO' are the only instances of 'Quasi'. -- instance MonadThrow Q where throwM exception = (runIO . throwIO) exception -- | idky this instance isn't in "GHC.Exts" instance (Ord k) => IsList (Map k v) where type Item (Map k v) = (k,v) fromList = Map.fromList toList = Map.toList -- | needed by @Commands.Grammar@, a child type of "Commands.GrammarGrammar" $(deriveLift ''NonEmpty)
sboosali/Haskell-DragonNaturallySpeaking
sources/Commands/Instances.hs
mit
1,756
0
8
330
222
135
87
24
0
{-# LANGUAGE RankNTypes #-} module Bot.Component.Impl.Reputation ( reputation ) where import Bot.Component import Bot.Component.Combinator import Bot.Component.Command import Bot.Component.Impl.NickCluster import Bot.Component.Impl.History import Bot.Component.Stateful import Bot.IO import Control.Applicative import Control.Monad.State import Data.List import Data.Maybe import GHC.Exts import qualified Data.Map as M import qualified Data.Sequence as S -- | Reputation is stored in a mapping from nicks to integers. The nicks are -- cluster agnostic. Which means that when retrieving the reputation for a given -- nick, that all of the reputation points for all nicks in that nick's cluster -- must be summed to get the total reputation for that user. type Reputation a = BotMonad b => StateT (M.Map Nick Int) b a help :: HelpMessage help = HelpMessage { canonicalName = "reputation" , helpAliases = ["reputation", "!rep", "rep", "+1", "-1"] , helpString = [ "usage: +1 [nick]" , " -1 [nick]" , " !rep [nick]" , "" , " The reputation component keeps track of the 'reputation' of" , "users in the channel. Reputation here being an arbitrary integer" , "value. Users can grant each other reputation via the `+1` command." , "If no user is supplied, the last nick that spoke something other" , "than a `+1` command will gain 1 reputation point. If a nick is" , "supplied, then that nick will be granted the point." , "" , " The !rep command is used to query reputation scores. If no nick" , "Is given, then the reputation score of all known nicks will be" , "displayed. Otherwise, if a nick is given, then only the reputation" , "score for that user is displayed." ] } -- | The reputation component. Keeps a mapping of nicks to arbitrary integers. reputation :: ClusterNickHandle -> HistoryHandle -> Bot Component reputation nickClusterHandle historyHandle = persistent "reputation.txt" (plus +++ minus +++ query) initialState `withHelpMessage` help where initialState :: Bot (M.Map Nick Int) initialState = return M.empty -- | The +1 command. plus :: String -> Reputation () plus = commandT "+1" $ grantReputationAction (+ 1) -- | The -1 command. minus :: String -> Reputation () minus = commandT "-1" $ grantReputationAction (\x -> x - 1) -- | The action that is performed when the string "+1" is said in -- a channel. grantReputationAction :: (Int -> Int) -> [Nick] -> Reputation () grantReputationAction delta (nick:_) = grantReputation delta nick grantReputationAction delta [] = do lastNick <- listToMaybe . map fst <$> validHistory fromMaybe (return ()) (Just (grantReputation delta) <*> lastNick) -- | Grant a nick one point of reputation. This will either increment -- the existing value in the map, or insert 1 if there is no value -- present. grantReputation :: (Int -> Int) -> Nick -> Reputation () grantReputation delta nick = modify $ flip M.alter nick $ return . delta . fromMaybe 0 -- | Returns a list of messages that are not "+1"'s. validHistory :: Reputation [(Nick, Message)] validHistory = filter (not . isPrefixOf "+1" . snd) . lazilyReverseSeq <$> getHistory historyHandle -- | Lazily reverse a sequence as a list. lazilyReverseSeq :: S.Seq a -> [a] lazilyReverseSeq sequence = lazilyReverseSeq' (S.length sequence - 1) where lazilyReverseSeq' index | index == 0 = [current] | index > 0 = current : lazilyReverseSeq' (index - 1) | otherwise = [] where current = sequence `S.index` index -- | The !rep command. query :: String -> Reputation () query = commandT "!rep" queryAction -- | The action that is performed when the string "!rep" is said in -- a channel. queryAction :: [Nick] -> Reputation () queryAction (nick:_) = totalForNick nick >>= showReputation nick queryAction [] = do aliases <- liftBot $ allNickAliases nickClusterHandle scores <- mapM sumForGroup aliases let combined = zip (map head aliases) scores let filtered = filter ((/= 0) . snd) combined let sorted = reverse $ sortWith snd filtered mapM_ (uncurry showReputation) sorted totalForNick :: Nick -> Reputation Int totalForNick nick = do aliases <- liftBot $ aliasesForNick nickClusterHandle nick sumForGroup aliases -- | Return the total reputation score for a list of nicks. sumForGroup :: [Nick] -> Reputation Int sumForGroup nicks = do reputation <- get return $ sum $ mapMaybe (`M.lookup` reputation) nicks -- | Display the given nick and reputation score in the IRC channel. showReputation :: Nick -> Int -> Reputation () showReputation nick reputation = liftBot $ ircReply $ nick ++ " has " ++ show reputation ++ " rep"
numberten/zhenya_bot
Bot/Component/Impl/Reputation.hs
mit
5,438
0
15
1,648
1,059
566
493
88
3
module Main where data Fix f = Fix (f (Fix f)) -- -- Base AST template -- data Expression binOp expr = ExprInt { exprInt :: Int } | ExprBinOp { exprLeft :: expr , exprBinOp :: binOp , exprRight :: expr } -- data BinOp = Add | Sub -- -- Extending with more binary operations -- data BinOpExt = Mul | Div | BinOpBase BinOp -- -- Extending with unary operations -- data ExpressionExt uniOp binOp expr = ExprUniOp { exprUniOp :: uniOp , exprArg :: expr } | ExprBase (Expression binOp expr) -- data UniOp = Fac | Log -- -- Instantiation of the base AST. -- type SimpleExpr = Fix (Expression BinOp) evalSimpleExpr :: SimpleExpr -> Int evalSimpleExpr (Fix (ExprInt i)) = i evalSimpleExpr (Fix (ExprBinOp l op r)) = evalL `evalOp` evalR where evalL = evalSimpleExpr l evalR = evalSimpleExpr r evalOp = case op of Add -> (+) Sub -> (-) -- simple01 :: SimpleExpr simple01 = Fix (ExprBinOp (Fix (ExprInt 5)) Add (Fix (ExprInt 5))) -- -- Instantiation of the extended AST. -- type ExtendedExpr = Fix (ExpressionExt UniOp BinOpExt) evalExtendedExpr :: ExtendedExpr -> Int evalExtendedExpr (Fix (ExprUniOp op arg)) = evalOp evalArg where evalOp = case op of Fac -> product . flip take [1..] Log -> floor . log . fromIntegral evalArg = evalExtendedExpr arg evalExtendedExpr (Fix (ExprBase (ExprInt i))) = i evalExtendedExpr (Fix (ExprBase (ExprBinOp l op r))) = evalL `evalOp` evalR where evalL = evalExtendedExpr l evalR = evalExtendedExpr r evalOp = case op of Mul -> (*) Div -> div BinOpBase Add -> (+) BinOpBase Sub -> (-) -- extended01 :: ExtendedExpr extended01 = Fix (ExprUniOp Fac (Fix (ExprBase (ExprBinOp (Fix (ExprBase (ExprInt 3))) Mul (Fix (ExprBase (ExprInt 2))))))) -- This is to make the compiler happy. main :: IO () main = putStrLn "Hello World"
erisco/extensible-ast
example01/main.hs
mit
2,079
0
19
638
646
359
287
45
5
module ProjectEuler.Problem129 ( problem , genInput , computeA ) where import Petbox import ProjectEuler.Types problem :: Problem problem = pureProblem 129 Solved result {- Well, I really hoped that the description is something that normal human would understand. And as always not all things turn out to be what I hoped. So first few repunits are: R(1) = 1 R(2) = 11 R(3) = 111 = 3 x 37 R(4) = 1111 = 11 x 101 R(5) = 11111 = 41 x 271 R(6) = 111111 = 3 x 7 x 11 x 13 x 37 R(7) = 1111111 = 239 x 4649 R(8) = 11111111 = 11 x 73 x 101 x 137 R(9) = 111111111 = 3^2 x 37 x 333667 R(10) = 1111111111 = 11 x 41 x 271 x 9091 R(11) = 11111111111 = 21649 x 513239 R(12) = 111111111111 = 3 x 7 x 11 x 13 x 37 x 101 x 9901 R(13) = 1111111111111 = 53 x 79 x 265371653 R(14) = 11111111111111 = 11 x 239 x 4649 x 909091 R(15) = 111111111111111 = 3 x 31 x 37 x 41 x 271 x 2906161 R(16) = 1111111111111111 = 11 x 17 x 73 x 101 x 137 x 5882353 To find A(7), as 7 is a prime, simply lookup this table from up to down and find its first appearance, which is in R(6), therefore A(7) = 6. To find A(41), as 41 is a prime, repeat the same process. 41 first appears in R(5), therefore A(41) = 5. So first few As: A(1) = 1 A(3) = 3 A(7) = 6 A(9) = 8 A(11) = 2 A(13) = 6 A(17) = 16, exceeds 10. Only those end with 1,3,7,9 are included, as we are only looking at those n s.t. GCD(n, 10) = 1. some interpretation: A(n) is the number of 1's in the repunit. So there's an opportunity of sharing results: say we computed that R(k) `mod` n = r: R(k+1) `mod` n > (R(k) * 10 + 1) `mod` n > ((R(k) `mod` n) * 10 + 1) `mod` n (since GCD(n, 10) = 1) This allows us to reuse r to check for R(k+1) `mod` n. -} genInput :: Int -> [Int] genInput base = concat $ iterate (fmap (+10)) (fmap (+base) [1,3,7,9]) computeA :: Int -> Int computeA n = go 1 1 where go 0 acc = acc go x acc = go ((x * 10 + 1) `rem` n) (acc+1) result :: Int result = firstSuchThat ((> 1000000) . computeA) $ genInput 1000000
Javran/Project-Euler
src/ProjectEuler/Problem129.hs
mit
2,080
0
12
552
213
119
94
17
2
{- - Strategy (AI) implemented using the negamax algorithm. - -} module Strategy.Negamax ( negamaxStrategy ) where import Control.Lens (view) import Data.List (maximumBy, sortBy, zipWith4) import Data.Maybe (mapMaybe) import Data.Ord (comparing) import Data.Tree import Board import GameState import Strategy.Evaluation (evaluate) -- |Data structure that contains (1) the state of the board at a given time, -- (2) the column where a piece has been inserted to reach said state, (3) -- the next player and (4) the depth of the node in the search tree. data GameNode = GN { gnBoard :: Board , gnColumn :: Int, gnPlayer :: Player, gnDepth :: Int } -- |Generates the game tree up to a given depth ('maxDepth'). The 'Tree' data -- structure from the 'Data.Tree' package is lazy, which means that its nodes -- will be generated on demand as opposed to being generated at once. -- The alpha-beta pruning algorithm takes advantage of this by not visiting -- the pruned subtrees. genGameTree :: Int -> GameNode -> Tree GameNode genGameTree maxDepth = unfoldTree generatingFun where -- Function used to generate the nodes of the tree. The seed value is -- of the same type as the node type ('GameNode'). At each step, the -- function expands the current node generating its children -- except when the node is a child node or it's already at the -- maximum depth. generatingFun node@(GN board _ player depth) = let genNode col = do newBoard <- putPiece player col board return (newBoard, col) -- Create a column ordering for the children nodes to be -- generated. Here, we want to prioritise the columns closer -- to the center of the board, as these are the ones that are -- more likely to be the best choices. columnArrangement = sortBy (comparing (\col -> abs $ (boardCols `div` 2) - col)) [0..boardCols-1] -- Get lists of possible boards and used columns. (possiblePlays, columns) = unzip $ mapMaybe genNode columnArrangement newDepth = depth + 1 -- Generate childs of current node. childNodes = if newDepth > maxDepth then [] else zipWith4 GN possiblePlays columns (repeat $ nextPlayer player) (repeat newDepth) in case getMatchState board of Win _ -> (node, []) Tie -> (node, []) NotEnd -> (node, childNodes) -- |Eval the game tree using the negamax algorithm, returning the best -- column selection for the current player. evalGameTree :: Tree GameNode -> Int evalGameTree (Node _ childTrees) = -- Takes children nodes and evaluates them using the negamax with -- alpha-beta pruning optimisation, then take the column of the best -- option. snd . iterateChildren (-pseudoInf) pseudoInf (-pseudoInf, 0) $ childTrees where -- Leaf node. Return the evaluation of this node using the -- 'winning rows' method. evalGameTree' (Node (GN board _ pl _) []) _ _ = evaluate pl 1 (-1) board -- Internal node. Evaluate children and get the best rating. evalGameTree' (Node _ childTrees) alpha beta = fst . iterateChildren alpha beta (-pseudoInf, 0) $ childTrees -- Evaluate children nodes using depth-first search. -- No remaining children. Return the data of the best child -- (rating and column). iterateChildren _ _ best [] = best -- There are children remaining. Calculate new alpha value, new best -- child and check pruning case. iterateChildren alpha beta (bestRating, bestCol) (t:ts) = let childValue = -(evalGameTree' t (-beta) (-alpha)) newBestRat = max bestRating childValue newAlpha = max alpha childValue newBestCol = if newBestRat > bestRating then gnColumn . rootLabel $ t else bestCol newBest = (newBestRat, newBestCol) in if newAlpha >= beta then newBest else iterateChildren newAlpha beta newBest ts pseudoInf = 1000000 -- |The exported strategy. negamaxStrategy :: Int -> GameStrategy negamaxStrategy maxDepth = do player <- view gsCurrentPlayer curBoard <- view gsBoard --Return the result of evaluating the game tree. return . evalGameTree $ genGameTree maxDepth (GN curBoard 0 player 0)
joslugd/connect4-haskell
src/Strategy/Negamax.hs
mit
4,998
0
19
1,740
786
434
352
61
5
{-# LANGUAGE FlexibleContexts #-} module Chimera.Scripts.Stage1 ( stage1 ) where import FreeGame import Control.Lens import Data.Default (def) import Data.Reflection import Chimera.State import Chimera.Engine.Core import Chimera.Engine.Scripts import Chimera.Scripts.Common stage1 :: (Given Resource) => Stage () stage1 = do lift $ addEffect effPlayerBack talk $ do say' $ aline "メッセージのテスト" lufe <- character 0 $ V2 500 300 say lufe $ aline "こんにちは。" `click` aline "ルーフェです。" delCharacter lufe say' $ aline "メッセージのテストを終わります。" keeper $ initEnemy (V2 240 (-40)) 100 & runAuto .~ debug keeper $ initEnemy (V2 320 (-40)) 100 & runAuto .~ boss4 appearAt 5 $ initEnemy (V2 320 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 350 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 370 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 390 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 220 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 200 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 180 (-40)) 10 & runAuto .~ zako 10 appearAt 5 $ initEnemy (V2 160 (-40)) 10 & runAuto .~ zako 10 wait 350 appearAt 5 $ initEnemy (V2 320 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 350 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 370 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 390 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 220 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 200 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 180 (-40)) 5 & runAuto .~ zako 20 appearAt 5 $ initEnemy (V2 160 (-40)) 5 & runAuto .~ zako 20 wait 20 keeper $ initEnemy (V2 240 (-40)) 100 & runAuto .~ boss3 keeper $ initEnemy (V2 240 (-40)) 100 & runAuto .~ boss2 keeper $ initEnemy (V2 240 (-40)) 100 & runAuto .~ boss1 zako :: (Given Resource, HasChara c, HasPiece c, HasObject c) => Int -> Danmaku c () zako n | n >= 20 = zakoCommon 0 (motionCommon 100 (Curve (acc $ n `mod` 10))) 50 Needle Purple | n >= 10 = zakoCommon 0 (motionCommon 100 Straight) 50 BallMedium (toEnum $ n `mod` 10) | otherwise = return () where acc :: Int -> Vec2 acc 0 = V2 (-0.05) 0.005 acc 1 = V2 0.05 0.005 acc _ = error "otherwise case in acc" boss1 :: (Given Resource, HasChara c, HasPiece c, HasObject c) => Danmaku c () boss1 = do setName "回転弾" e <- use self zoom _1 $ motionCommon 100 Stay when (e^.counter == 130) $ effs $ return $ effEnemyStart (e^.pos) when (e^.counter == 200) $ do mapM_ enemyEffect $ [ effEnemyAttack 0 (e^.pos), effEnemyAttack 1 (e^.pos), effEnemyAttack 2 (e^.pos)] let def' = def & pos .~ e^.pos & ang .~ (fromIntegral $ e^.counter)/30 when ((e^.counter) >= 200 && (e^.counter) `mod` 15 == 0 && e^.statePiece == Attack) $ do shots $ (flip map) [1..4] $ \i -> makeBullet Oval Red def' & speed .~ 3.15 & ang +~ 2*pi*i/4 & runAuto %~ (go 190 300 >>) shots $ (flip map) [1..4] $ \i -> makeBullet Oval Yellow def' & speed .~ 3 & ang +~ 2*pi*i/4 & runAuto %~ (go 135 290 >>) shots $ (flip map) [1..4] $ \i -> makeBullet Oval Green def' & speed .~ 2.5 & ang +~ 2*pi*i/4 & runAuto %~ (go 120 280 >>) shots $ (flip map) [1..4] $ \i -> makeBullet Oval Blue def' & speed .~ 2.2 & ang +~ 2*pi*i/4 & runAuto %~ (go 100 270 >>) where go t1 t2 = zoom _1 $ do cnt <- use counter when (30 < cnt && cnt < 200) $ do ang %= (+ pi/t1) speed %= (subtract (7.0/t2)) when (cnt == 170) $ id %= makeBullet BallTiny Purple boss2 :: (Given Resource, HasChara c, HasPiece c, HasObject c) => Danmaku c () boss2 = do setName "分裂弾" e <- use self zoom _1 $ motionCommon 100 Stay ang' <- anglePlayer when (e^.counter == 150) $ mapM_ enemyEffect $ [ effEnemyAttack 0 (e^.pos), effEnemyAttack 1 (e^.pos), effEnemyAttack 2 (e^.pos)] when (e^.counter `mod` 50 == 0 && e^.statePiece == Attack) $ shots $ (flip map) [0..5] $ \i -> makeBullet BallMedium (toEnum $ i*2 `mod` 8) def & pos .~ e^.pos & speed .~ 2 & ang .~ ang' + fromIntegral i*2*pi/5 & runAuto %~ (go >>) when (e^.counter `mod` 100 == 0 && e^.statePiece == Attack) $ shots $ return $ makeBullet BallLarge Purple def & pos .~ e^.pos & speed .~ 1.5 & ang .~ ang' where go = do b <- use self let t = pi/3 let time = 50 when ((b^.counter) < 200 && (b^.counter) `mod` time == 0) $ shots $ return $ def & auto .~ b & ang +~ t zoom _1 $ do cnt <- use counter when (cnt < 200 && cnt `mod` time == 0) $ do speed += 1.5 ang -= t when (cnt < 200) $ speed -= (fromIntegral $ time - cnt `mod` time)/1000 boss3 :: (Given Resource, HasChara c, HasPiece c, HasObject c) => Danmaku c () boss3 = do setName "爆発弾" e <- use self zoom _1 $ motionCommon 100 Stay ang' <- anglePlayer when (e^.counter == 150) $ do enemyEffect $ effEnemyAttack 0 (e^.pos) enemyEffect $ effEnemyAttack 1 (e^.pos) enemyEffect $ effEnemyAttack 2 (e^.pos) let n = 8 :: Int when (e^.counter `mod` 100 == 0 && e^.statePiece == Attack) $ do shots $ (flip map) [0..n] $ \i -> makeBullet Needle (toEnum $ i*2 `mod` 2) def & pos .~ e^.pos & speed .~ 3 & ang .~ ang' + fromIntegral i*2*pi/fromIntegral n & runAuto %~ (go >>) where go = do zoom _1 $ do use counter >>= \c -> when (c <= 150) $ speed -= 0.01 counter += 1 b <- use self let n = 8 :: Int when (b^.counter == 150) $ shots $ flip map [0..n] $ \i -> makeBullet BallLarge Blue def & auto .~ b & speed .~ 1.5 & ang .~ fromIntegral i*2*pi/fromIntegral n boss4 :: (Given Resource, HasPiece c, HasObject c, HasChara c) => Danmaku c () boss4 = do setName "ホーミング弾" e <- use self zoom _1 $ motionCommon 100 Stay ang' <- anglePlayer when (e^.counter == 150) $ do enemyEffect $ effEnemyAttack 0 (e^.pos) enemyEffect $ effEnemyAttack 1 (e^.pos) enemyEffect $ effEnemyAttack 2 (e^.pos) let n = 3 :: Int when (e^.counter `mod` 50 == 0 && e^.statePiece == Attack) $ do shots $ (flip map) [0..n] $ \i -> makeBullet Oval (toEnum $ i*2 `mod` 2) def & pos .~ e^.pos & speed .~ 5 & ang .~ ang' + fromIntegral i*2*pi/fromIntegral n & runAuto %~ (go >>) where go = do ang' <- anglePlayer zoom _1 $ do use counter >>= \c -> when (c <= 50) $ speed -= 0.02 counter += 1 b <- use ang let V2 ax ay = unitV2 ang'; V2 bx by = unitV2 b use counter >>= \c -> when (c `mod` 5 == 0) $ do ang += case ax*by - ay*bx > 0 of True -> -10*pi/180 False -> 10*pi/180
myuon/Chimera
Chimera/Scripts/Stage1.hs
mit
7,106
0
29
2,066
3,539
1,721
1,818
177
3
-- | Nix store archives. module Nix.Nar ( module Nix.Nar.Types, module Nix.Nar.Serialization, module Nix.Nar.Subprocess ) where import Nix.Nar.Types import Nix.Nar.Serialization import Nix.Nar.Subprocess
adnelson/nix-binary-cache
src/Nix/Nar.hs
mit
213
0
5
31
48
33
15
7
0
module Main where import Data.IORef import Graphics.Rendering.OpenGL import Graphics.UI.GLUT hiding (exit) import System.Exit (exitSuccess) import Hogldev.Pipeline ( Pipeline(..), getTrans, PersProj(..) ) import Hogldev.Camera ( Camera(..), cameraOnKeyboard, initCamera, cameraOnMouse, cameraOnRender ) import Hogldev.Texture import LightingTechnique import Hogldev.Mesh windowWidth = 1920 windowHeight = 1080 persProjection = PersProj { persFOV = 60 , persWidth = fromIntegral windowWidth , persHeigh = fromIntegral windowHeight , persZNear = 1 , persZFar = 100 } dirLight :: DirectionLight dirLight = DirectionLight { ambientColor = Vertex3 1 1 1 , ambientIntensity = 0.2 , diffuseIntensity = 0.8 , diffuseDirection = Vertex3 1.0 0.0 0.0 } main :: IO () main = do getArgsAndInitialize initialDisplayMode $= [DoubleBuffered, RGBAMode, WithDepthBuffer] initialWindowSize $= Size windowWidth windowHeight initialWindowPosition $= Position 100 100 createWindow "Tutorial 26" -- frontFace $= CW -- cullFace $= Just Back depthFunc $= Just Lequal gScale <- newIORef 0.0 cameraRef <- newIORef newCamera bampMapRef <- newIORef True lightingEffect <- initLightingTechnique enableLightingTechnique lightingEffect setLightingTextureUnit lightingEffect 0 setLightingNormalMapTextureUnit lightingEffect 2 setDirectionalLight lightingEffect dirLight pointerPosition $= mousePos boxMesh <- loadMesh "assets/box.obj" Just texture <- textureLoad "assets/bricks.jpg" Texture2D Just normalMap <- textureLoad "assets/normal_map.jpg" Texture2D Just trivialNormalMap <- textureLoad "assets/normal_up.jpg" Texture2D initializeGlutCallbacks boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap clearColor $= Color4 0 0 0 0 mainLoop where newCamera = initCamera (Just (Vector3 0.5 1.025 0.25, Vector3 0 (-0.5) 1, Vector3 0 1 0) ) windowWidth windowHeight mousePos = Position (windowWidth `div` 2) (windowHeight `div` 2) initializeGlutCallbacks :: Mesh -> LightingTechnique -> IORef GLfloat -> IORef Camera -> IORef Bool -> Texture -> Texture -> Texture -> IO () initializeGlutCallbacks boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap = do displayCallback $= renderSceneCB boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap idleCallback $= Just (idleCB gScale cameraRef) specialCallback $= Just (specialKeyboardCB cameraRef) keyboardCallback $= Just (keyboardCB bampMapRef) passiveMotionCallback $= Just (passiveMotionCB cameraRef) keyboardCB :: IORef Bool -> KeyboardCallback keyboardCB _ 'q' _ = exitSuccess keyboardCB bumpMapRef 'b' _ = modifyIORef bumpMapRef not keyboardCB _ _ _ = return () specialKeyboardCB :: IORef Camera -> SpecialCallback specialKeyboardCB cameraRef key _ = cameraRef $~! cameraOnKeyboard key passiveMotionCB :: IORef Camera -> MotionCallback passiveMotionCB cameraRef position = cameraRef $~! cameraOnMouse position idleCB :: IORef GLfloat -> IORef Camera -> IdleCallback idleCB gScale cameraRef = do gScale $~! (+ 0.01) cameraRef $~! cameraOnRender postRedisplay Nothing renderSceneCB :: Mesh -> LightingTechnique -> IORef GLfloat -> IORef Camera -> IORef Bool -> Texture -> Texture -> Texture -> DisplayCallback renderSceneCB boxMesh lightingEffect gScale cameraRef bampMapRef texture normalMap trivialNormalMap = do cameraRef $~! cameraOnRender gScaleVal <- readIORef gScale camera <- readIORef cameraRef bampMapEnabled <- readIORef bampMapRef clear [ColorBuffer, DepthBuffer] enableLightingTechnique lightingEffect textureBind texture (TextureUnit 0) if bampMapEnabled then textureBind normalMap (TextureUnit 2) else textureBind trivialNormalMap (TextureUnit 2) setLightingWVP lightingEffect $ getTrans WVPPipeline { worldInfo = Vector3 0 0 3, scaleInfo = Vector3 1 1 1, rotateInfo = Vector3 (-90) gScaleVal 0, persProj = persProjection, pipeCamera = camera } setLightingWorldMatrix lightingEffect $ getTrans WPipeline { worldInfo = Vector3 0 0 3, scaleInfo = Vector3 1 1 1, rotateInfo = Vector3 (-90) gScaleVal 0 } renderMesh boxMesh swapBuffers
triplepointfive/hogldev
tutorial26/Tutorial26.hs
mit
5,074
0
14
1,520
1,173
581
592
119
2
{-# LANGUAGE OverloadedStrings #-} module TransformationTest (tests) where import Control.Monad import Test.Tasty import Test.Tasty.SmallCheck import Test.Tasty.HUnit import qualified HotDB.Core.Node as N import qualified HotDB.Core.Operation as O import qualified HotDB.Core.Transformation as T import SCInstances () import Util (assertNothing) tests :: TestTree tests = testGroup "Transformation tests" [propertyTests, unitTests] c :: N.Node c = N.IntNode 123 c2 :: N.Node c2 = N.BoolNode False propertyTests :: TestTree propertyTests = testGroup "Property tests" [ testProperty "NoOps do not transform anything" $ \op -> T.transform op O.NoOp T.Left == Just op && T.transform op O.NoOp T.Right == Just op , testProperty "IntIncs do not interfere" $ \(x,y) -> let o1 = O.IntInc $ fromInteger x o2 = O.IntInc $ fromInteger y in T.transform o1 o2 T.Left == Just o1 && T.transform o1 o2 T.Right == Just o1 ] unitTests :: TestTree unitTests = testGroup "Unit tests" [ testRootSetRootSet , testTextInsertTextInsert , testTextInsertTextDelete , testTextDeleteTextInsert , testTextDeleteTextDelete , testSequenceSetSequenceSet , testSequenceSetSequenceInsert , testSequenceSetSequenceDelete , testSequenceInsertSequenceSet , testSequenceInsertSequenceInsert , testSequenceInsertSequenceDelete , testSequenceDeleteSequenceSet , testSequenceDeleteSequenceInsert , testSequenceDeleteSequenceDelete , testMapSetMapSet , testMapSetMapUnset , testMapUnsetMapSet , testMapUnsetMapUnset , testTransformChildRootSet , testTransformChildSequenceSet , testTransformChildSequenceInsert , testTransformChildSequenceDelete , testTransformChildMapSet , testTransformChildMapUnset , testTransformChildNonAffecting ] testRootSetRootSet :: TestTree testRootSetRootSet = let rs1 = O.RootSet (N.IntNode 123) 1 rs2 = O.RootSet (N.BoolNode False) 2 rs3 = O.RootSet (N.BoolNode False) 1 in testGroup "RootSet vs RootSet" [ testCase "Wins tiebreaker" $ do assertEqual "a" (Just rs2) $ T.transform rs2 rs1 T.Left assertEqual "b" (Just rs2) $ T.transform rs2 rs1 T.Right assertEqual "c" (Just rs1) $ T.transform rs1 rs3 T.Right , testCase "Loses tiebreaker" $ do assertEqual "a" (Just O.NoOp) $ T.transform rs1 rs2 T.Left assertEqual "b" (Just O.NoOp) $ T.transform rs1 rs2 T.Right assertEqual "c" (Just O.NoOp) $ T.transform rs1 rs3 T.Left , testCase "EqualValues" $ do assertEqual "a" (Just O.NoOp) $ T.transform rs2 rs3 T.Left assertEqual "b" (Just O.NoOp) $ T.transform rs2 rs3 T.Right assertEqual "c" (Just O.NoOp) $ T.transform rs3 rs2 T.Left assertEqual "c" (Just O.NoOp) $ T.transform rs3 rs2 T.Right ] testTextInsertTextInsert :: TestTree testTextInsertTextInsert = let ti1 = O.TextInsert 0 'x' 0 ti2 = O.TextInsert 0 'y' 1 ti3 = O.TextInsert 0 'z' 0 ti4 = O.TextInsert 1 '_' 10 in testGroup "TextInsert vs TextInsert" [ testCase "Wins tiebreaker" $ do assertEqual "a" (Just ti2) $ T.transform ti2 ti1 T.Left assertEqual "b" (Just ti2) $ T.transform ti2 ti1 T.Right assertEqual "c" (Just ti1) $ T.transform ti1 ti3 T.Right , testCase "Loses tiebreaker" $ do assertEqual "a" (Just $ O.TextInsert 1 'x' 0) $ T.transform ti1 ti2 T.Left assertEqual "b" (Just $ O.TextInsert 1 'x' 0) $ T.transform ti1 ti2 T.Right assertEqual "c" (Just $ O.TextInsert 1 'x' 0) $ T.transform ti1 ti3 T.Left , testCase "Not affected" $ do assertEqual "a" (Just ti1) $ T.transform ti1 ti4 T.Left assertEqual "b" (Just ti1) $ T.transform ti1 ti4 T.Right , testCase "Index incremented" $ do assertEqual "a" (Just $ O.TextInsert 2 '_' 10) $ T.transform ti4 ti1 T.Left assertEqual "b" (Just $ O.TextInsert 2 '_' 10) $ T.transform ti4 ti1 T.Right ] testTextInsertTextDelete :: TestTree testTextInsertTextDelete = let ti1 = O.TextInsert 0 'x' 0 td1 = O.TextDelete 0 ti2 = O.TextInsert 1 'y' 0 td2 = O.TextDelete 1 in testGroup "TextInsert vs TextDelete" [ testCase "Delete >= Insert" $ do assertEqual "a" (Just ti1) $ T.transform ti1 td1 T.Left assertEqual "b" (Just ti1) $ T.transform ti1 td1 T.Right assertEqual "c" (Just ti1) $ T.transform ti1 td2 T.Left assertEqual "d" (Just ti1) $ T.transform ti1 td2 T.Right , testCase "Delete < Insert" $ do assertEqual "a" (Just $ O.TextInsert 0 'y' 0) $ T.transform ti2 td1 T.Left assertEqual "b" (Just $ O.TextInsert 0 'y' 0) $ T.transform ti2 td1 T.Right ] testTextDeleteTextInsert :: TestTree testTextDeleteTextInsert = let ti1 = O.TextInsert 0 'x' 0 td1 = O.TextDelete 0 ti2 = O.TextInsert 1 'y' 0 td2 = O.TextDelete 1 in testGroup "TextDelete vs TextInsert" [ testCase "Delete < Insert" $ do assertEqual "a" (Just td1) $ T.transform td1 ti2 T.Left assertEqual "b" (Just td1) $ T.transform td1 ti2 T.Right , testCase "Delete >= Insert" $ do assertEqual "a" (Just $ O.TextDelete 1) $ T.transform td1 ti1 T.Left assertEqual "b" (Just $ O.TextDelete 1) $ T.transform td1 ti1 T.Right assertEqual "c" (Just $ O.TextDelete 2) $ T.transform td2 ti1 T.Left assertEqual "c" (Just $ O.TextDelete 2) $ T.transform td2 ti1 T.Right ] testTextDeleteTextDelete :: TestTree testTextDeleteTextDelete = let td1 = O.TextDelete 0 td2 = O.TextDelete 1 in testGroup "TextDelete vs TextDelete" [ testCase "Before other" $ do assertEqual "a" (Just td1) $ T.transform td1 td2 T.Left assertEqual "b" (Just td1) $ T.transform td1 td2 T.Right , testCase "Equal to other" $ do assertEqual "a" (Just O.NoOp) $ T.transform td1 td1 T.Left assertEqual "b" (Just O.NoOp) $ T.transform td1 td1 T.Right , testCase "After other" $ do assertEqual "a" (Just td1) $ T.transform td2 td1 T.Left assertEqual "b" (Just td1) $ T.transform td2 td1 T.Right ] testSequenceSetSequenceSet :: TestTree testSequenceSetSequenceSet = let ss1 = O.SequenceSet 0 c 0 ss2 = O.SequenceSet 0 c2 1 ss3 = O.SequenceSet 1 c 0 ss4 = O.SequenceSet 0 c2 0 in testGroup "SequenceSet vs SequenceSet" [ testCase "Wins tiebreaker" $ do assertEqual "a" (Just ss2) $ T.transform ss2 ss1 T.Left assertEqual "b" (Just ss2) $ T.transform ss2 ss1 T.Right assertEqual "c" (Just ss1) $ T.transform ss1 ss4 T.Right , testCase "Loses tiebreaker" $ do assertEqual "a" (Just O.NoOp) $ T.transform ss1 ss2 T.Left assertEqual "b" (Just O.NoOp) $ T.transform ss1 ss2 T.Right assertEqual "c" (Just O.NoOp) $ T.transform ss1 ss4 T.Left , testCase "Non-conflicting" $ do assertEqual "a" (Just ss1) $ T.transform ss1 ss3 T.Left assertEqual "b" (Just ss1) $ T.transform ss1 ss3 T.Right assertEqual "c" (Just ss3) $ T.transform ss3 ss1 T.Left assertEqual "d" (Just ss3) $ T.transform ss3 ss1 T.Right , testCase "Equal objects" $ do assertEqual "a" (Just O.NoOp) $ T.transform ss2 ss4 T.Left assertEqual "b" (Just O.NoOp) $ T.transform ss2 ss4 T.Right assertEqual "c" (Just O.NoOp) $ T.transform ss4 ss2 T.Left assertEqual "d" (Just O.NoOp) $ T.transform ss4 ss2 T.Right ] testSequenceSetSequenceInsert :: TestTree testSequenceSetSequenceInsert = let ss1 = O.SequenceSet 0 c 0 ss2 = O.SequenceSet 1 c 0 si1 = O.SequenceInsert 0 c 0 si2 = O.SequenceInsert 1 c 0 in testGroup "SequenceSet vs SequenceInsert" [ testCase "Non-affecting" $ do assertEqual "a" (Just ss1) $ T.transform ss1 si2 T.Left assertEqual "b" (Just ss1) $ T.transform ss1 si2 T.Right , testCase "Shifted" $ do assertEqual "a" (Just ss2) $ T.transform ss1 si1 T.Left assertEqual "b" (Just ss2) $ T.transform ss1 si1 T.Right assertEqual "c" (Just $ O.SequenceSet 2 c 0) $ T.transform ss2 si1 T.Left assertEqual "d" (Just $ O.SequenceSet 2 c 0) $ T.transform ss2 si1 T.Right ] testSequenceSetSequenceDelete :: TestTree testSequenceSetSequenceDelete = let ss1 = O.SequenceSet 0 c 0 ss2 = O.SequenceSet 1 c 0 sd1 = O.SequenceDelete 0 sd2 = O.SequenceDelete 1 in testGroup "SequenceSet vs SequenceDelete" [ testCase "Non-affecting" $ do assertEqual "a" (Just ss1) $ T.transform ss1 sd2 T.Left assertEqual "b" (Just ss1) $ T.transform ss1 sd2 T.Right , testCase "Same index"$ do assertEqual "a" (Just O.NoOp) $ T.transform ss1 sd1 T.Left assertEqual "b" (Just O.NoOp) $ T.transform ss1 sd1 T.Right , testCase "Shifted" $ do assertEqual "a" (Just ss1) $ T.transform ss2 sd1 T.Left assertEqual "b" (Just ss1) $ T.transform ss2 sd1 T.Right ] testSequenceInsertSequenceSet :: TestTree testSequenceInsertSequenceSet = let si1 = O.SequenceInsert 0 c 0 si2 = O.SequenceInsert 1 c 0 ss1 = O.SequenceSet 0 c 0 ss2 = O.SequenceSet 1 c 0 in testGroup "SequenceInsert vs SequenceSet" [ testCase "Non-affecting" $ do assertEqual "a" (Just si1) $ T.transform si1 ss1 T.Left assertEqual "b" (Just si1) $ T.transform si1 ss1 T.Right assertEqual "c" (Just si1) $ T.transform si1 ss2 T.Left assertEqual "d" (Just si1) $ T.transform si1 ss2 T.Right assertEqual "e" (Just si2) $ T.transform si2 ss1 T.Left assertEqual "f" (Just si2) $ T.transform si2 ss1 T.Right ] testSequenceInsertSequenceInsert :: TestTree testSequenceInsertSequenceInsert = let si1 = O.SequenceInsert 0 c 0 si2 = O.SequenceInsert 0 c 1 si3 = O.SequenceInsert 0 c 0 si4 = O.SequenceInsert 1 c 10 in testGroup "SequenceInsert vs SequenceInsert" [ testCase "Wins tiebreaker" $ do assertEqual "a" (Just si2) $ T.transform si2 si1 T.Left assertEqual "b" (Just si2) $ T.transform si2 si1 T.Right assertEqual "c" (Just si1) $ T.transform si1 si3 T.Right , testCase "Loses tiebreaker" $ do assertEqual "a" (Just $ O.SequenceInsert 1 c 0) $ T.transform si1 si2 T.Left assertEqual "b" (Just $ O.SequenceInsert 1 c 0) $ T.transform si1 si2 T.Right assertEqual "c" (Just $ O.SequenceInsert 1 c 0) $ T.transform si1 si3 T.Left , testCase "Not affected" $ do assertEqual "a" (Just si1) $ T.transform si1 si4 T.Left assertEqual "b" (Just si1) $ T.transform si1 si4 T.Right , testCase "Index incremented" $ do assertEqual "a" (Just $ O.SequenceInsert 2 c 10) $ T.transform si4 si1 T.Left assertEqual "b" (Just $ O.SequenceInsert 2 c 10) $ T.transform si4 si1 T.Right ] testSequenceInsertSequenceDelete :: TestTree testSequenceInsertSequenceDelete = let si1 = O.SequenceInsert 0 c 0 sd1 = O.SequenceDelete 0 si2 = O.SequenceInsert 1 c 0 sd2 = O.SequenceDelete 1 in testGroup "SequenceInsert vs SequenceDelete" [ testCase "Delete >= Insert" $ do assertEqual "a" (Just si1) $ T.transform si1 sd1 T.Left assertEqual "b" (Just si1) $ T.transform si1 sd1 T.Right assertEqual "c" (Just si1) $ T.transform si1 sd2 T.Left assertEqual "d" (Just si1) $ T.transform si1 sd2 T.Right , testCase "Delete < Insert" $ do assertEqual "a" (Just $ O.SequenceInsert 0 c 0) $ T.transform si2 sd1 T.Left assertEqual "b" (Just $ O.SequenceInsert 0 c 0) $ T.transform si2 sd1 T.Right ] testSequenceDeleteSequenceSet :: TestTree testSequenceDeleteSequenceSet = let ss1 = O.SequenceSet 0 c 0 ss2 = O.SequenceSet 1 c 0 sd1 = O.SequenceDelete 0 sd2 = O.SequenceDelete 1 in testGroup "SequenceDelete vs SequenceSet" [ testCase "Non-affecting" $ do assertEqual "a" (Just sd1) $ T.transform sd1 ss1 T.Left assertEqual "b" (Just sd1) $ T.transform sd1 ss1 T.Right assertEqual "c" (Just sd1) $ T.transform sd1 ss2 T.Left assertEqual "d" (Just sd1) $ T.transform sd1 ss2 T.Right assertEqual "e" (Just sd2) $ T.transform sd2 ss1 T.Left assertEqual "f" (Just sd2) $ T.transform sd2 ss1 T.Right ] testSequenceDeleteSequenceInsert :: TestTree testSequenceDeleteSequenceInsert = let si1 = O.SequenceInsert 0 c 0 sd1 = O.SequenceDelete 0 si2 = O.SequenceInsert 1 c 0 sd2 = O.SequenceDelete 1 in testGroup "SequenceDelete vs SequenceInsert" [ testCase "Delete < Insert" $ do assertEqual "a" (Just sd1) $ T.transform sd1 si2 T.Left assertEqual "b" (Just sd1) $ T.transform sd1 si2 T.Right , testCase "Delete >= Insert" $ do assertEqual "a" (Just $ O.SequenceDelete 1) $ T.transform sd1 si1 T.Left assertEqual "b" (Just $ O.SequenceDelete 1) $ T.transform sd1 si1 T.Right assertEqual "c" (Just $ O.SequenceDelete 2) $ T.transform sd2 si1 T.Left assertEqual "c" (Just $ O.SequenceDelete 2) $ T.transform sd2 si1 T.Right ] testSequenceDeleteSequenceDelete :: TestTree testSequenceDeleteSequenceDelete = let sd1 = O.SequenceDelete 0 sd2 = O.SequenceDelete 1 in testGroup "SequenceDelete vs SequenceDelete" [ testCase "Before other" $ do assertEqual "a" (Just sd1) $ T.transform sd1 sd2 T.Left assertEqual "b" (Just sd1) $ T.transform sd1 sd2 T.Right , testCase "Equal to other" $ do assertEqual "a" (Just O.NoOp) $ T.transform sd1 sd1 T.Left assertEqual "b" (Just O.NoOp) $ T.transform sd1 sd1 T.Right , testCase "After other" $ do assertEqual "a" (Just sd1) $ T.transform sd2 sd1 T.Left assertEqual "b" (Just sd1) $ T.transform sd2 sd1 T.Right ] testMapSetMapSet :: TestTree testMapSetMapSet = let ms1 = O.MapSet "foo" c 0 ms2 = O.MapSet "foo" c2 1 ms3 = O.MapSet "bar" c 0 ms4 = O.MapSet "foo" c 1 in testGroup "MapSet vs MapSet" [ testCase "Non-conflicting" $ do assertEqual "a" (Just ms1) $ T.transform ms1 ms3 T.Left assertEqual "b" (Just ms1) $ T.transform ms1 ms3 T.Right , testCase "Wins tiebreaker" $ do assertEqual "a" (Just ms2) $ T.transform ms2 ms1 T.Left assertEqual "b" (Just ms2) $ T.transform ms2 ms1 T.Right assertEqual "c" (Just ms2) $ T.transform ms2 ms4 T.Right , testCase "Loses tiebreaker" $ do assertEqual "a" (Just O.NoOp) $ T.transform ms1 ms2 T.Left assertEqual "b" (Just O.NoOp) $ T.transform ms1 ms2 T.Right assertEqual "c" (Just O.NoOp) $ T.transform ms2 ms4 T.Left , testCase "Equal objects" $ do assertEqual "a" (Just O.NoOp) $ T.transform ms1 ms4 T.Left assertEqual "b" (Just O.NoOp) $ T.transform ms1 ms4 T.Right assertEqual "c" (Just O.NoOp) $ T.transform ms4 ms1 T.Left assertEqual "d" (Just O.NoOp) $ T.transform ms4 ms1 T.Right ] testMapSetMapUnset :: TestTree testMapSetMapUnset = let ms1 = O.MapSet "foo" c 0 mu1 = O.MapUnset "foo" mu2 = O.MapUnset "bar" in testGroup "MapSet vs MapUnset" [ testCase "Non-conflicting" $ do assertEqual "a" (Just ms1) $ T.transform ms1 mu1 T.Left assertEqual "b" (Just ms1) $ T.transform ms1 mu1 T.Right assertEqual "c" (Just ms1) $ T.transform ms1 mu2 T.Left assertEqual "d" (Just ms1) $ T.transform ms1 mu2 T.Right ] testMapUnsetMapSet :: TestTree testMapUnsetMapSet = let mu1 = O.MapUnset "foo" mu2 = O.MapUnset "bar" ms1 = O.MapSet "foo" c 0 in testGroup "MapUnset vs MapSet" [ testCase "Non-conflicting" $ do assertEqual "a" (Just mu2) $ T.transform mu2 ms1 T.Left assertEqual "b" (Just mu2) $ T.transform mu2 ms1 T.Right , testCase "Conflicting" $ do assertEqual "a" (Just O.NoOp) $ T.transform mu1 ms1 T.Left assertEqual "b" (Just O.NoOp) $ T.transform mu1 ms1 T.Right ] testMapUnsetMapUnset :: TestTree testMapUnsetMapUnset = let mu1 = O.MapUnset "foo" mu2 = O.MapUnset "bar" in testGroup "MapUnset vs MapUnset" [ testCase "Non-conflicting" $ do assertEqual "a" (Just mu1) $ T.transform mu1 mu2 T.Left assertEqual "b" (Just mu1) $ T.transform mu1 mu2 T.Right , testCase "Conflicting" $ do assertEqual "a" (Just O.NoOp) $ T.transform mu1 mu1 T.Left assertEqual "a" (Just O.NoOp) $ T.transform mu1 mu1 T.Right ] testTransformChildRootSet :: TestTree testTransformChildRootSet = let dop1 = O.DirectedOperation "/" $ O.IntInc 1 dop2 = O.DirectedOperation "/foo" $ O.IntInc 1 dop3 = O.DirectedOperation "" $ O.IntInc 1 rs = O.DirectedOperation "" $ O.RootSet c 0 in testCase "Transform Child against RootSet" $ do assertEqual "a" (Just O.directedNoOp) $ T.transformDirected dop1 rs T.Left assertEqual "b" (Just O.directedNoOp) $ T.transformDirected dop1 rs T.Right assertEqual "c" (Just O.directedNoOp) $ T.transformDirected dop2 rs T.Left assertEqual "d" (Just O.directedNoOp) $ T.transformDirected dop2 rs T.Right assertEqual "e" Nothing $ T.transformDirected dop3 rs T.Left assertEqual "f" Nothing $ T.transformDirected dop3 rs T.Right testTransformChildSequenceSet :: TestTree testTransformChildSequenceSet = let dop1 = O.DirectedOperation "3/foo" $ O.IntInc 1 dop2 = O.DirectedOperation "foo/bar" $ O.IntInc 1 dop3 = O.DirectedOperation "" $ O.IntInc 1 ss1 = O.DirectedOperation "" $ O.SequenceSet 2 c 0 ss2 = O.DirectedOperation "" $ O.SequenceSet 3 c 0 ss3 = O.DirectedOperation "" $ O.SequenceSet 4 c 0 in testCase "Transform Child against SequenceSet" $ do assertEqual "a" (Just dop1) $ T.transformDirected dop1 ss1 T.Left assertEqual "b" (Just dop1) $ T.transformDirected dop1 ss1 T.Right assertEqual "c" (Just O.directedNoOp) $ T.transformDirected dop1 ss2 T.Left assertEqual "d" (Just O.directedNoOp) $ T.transformDirected dop1 ss2 T.Right assertEqual "e" (Just dop1) $ T.transformDirected dop1 ss3 T.Left assertEqual "f" (Just dop1) $ T.transformDirected dop1 ss3 T.Right assertEqual "g" Nothing $ T.transformDirected dop2 ss1 T.Left assertEqual "h" Nothing $ T.transformDirected dop2 ss1 T.Right assertEqual "i" Nothing $ T.transformDirected dop3 ss1 T.Left assertEqual "j" Nothing $ T.transformDirected dop3 ss1 T.Right testTransformChildSequenceInsert :: TestTree testTransformChildSequenceInsert = let dop1 = O.DirectedOperation "3/foo" $ O.IntInc 1 dop2 = O.DirectedOperation "foo/bar" $ O.IntInc 1 dop3 = O.DirectedOperation "" $ O.IntInc 1 dop4 = O.DirectedOperation "4/foo" $ O.IntInc 1 ss1 = O.DirectedOperation "" $ O.SequenceInsert 2 c 0 ss2 = O.DirectedOperation "" $ O.SequenceInsert 3 c 0 ss3 = O.DirectedOperation "" $ O.SequenceInsert 4 c 0 in testCase "Transform Child against SequenceSet" $ do assertEqual "a" (Just dop4) $ T.transformDirected dop1 ss1 T.Left assertEqual "b" (Just dop4) $ T.transformDirected dop1 ss1 T.Right assertEqual "c" (Just dop4) $ T.transformDirected dop1 ss2 T.Left assertEqual "d" (Just dop4) $ T.transformDirected dop1 ss2 T.Right assertEqual "e" (Just dop1) $ T.transformDirected dop1 ss3 T.Left assertEqual "f" (Just dop1) $ T.transformDirected dop1 ss3 T.Right assertEqual "g" Nothing $ T.transformDirected dop2 ss1 T.Left assertEqual "h" Nothing $ T.transformDirected dop2 ss1 T.Right assertEqual "i" Nothing $ T.transformDirected dop3 ss1 T.Left assertEqual "j" Nothing $ T.transformDirected dop3 ss1 T.Right testTransformChildSequenceDelete :: TestTree testTransformChildSequenceDelete = let dop1 = O.DirectedOperation "3/foo" $ O.IntInc 1 dop2 = O.DirectedOperation "foo/bar" $ O.IntInc 1 dop3 = O.DirectedOperation "" $ O.IntInc 1 dop4 = O.DirectedOperation "2/foo" $ O.IntInc 1 ss1 = O.DirectedOperation "" $ O.SequenceDelete 2 ss2 = O.DirectedOperation "" $ O.SequenceDelete 3 ss3 = O.DirectedOperation "" $ O.SequenceDelete 4 in testCase "Transform Child against SequenceSet" $ do assertEqual "a" (Just dop4) $ T.transformDirected dop1 ss1 T.Left assertEqual "b" (Just dop4) $ T.transformDirected dop1 ss1 T.Right assertEqual "c" (Just O.directedNoOp) $ T.transformDirected dop1 ss2 T.Left assertEqual "d" (Just O.directedNoOp) $ T.transformDirected dop1 ss2 T.Right assertEqual "e" (Just dop1) $ T.transformDirected dop1 ss3 T.Left assertEqual "f" (Just dop1) $ T.transformDirected dop1 ss3 T.Right assertEqual "g" Nothing $ T.transformDirected dop2 ss1 T.Left assertEqual "h" Nothing $ T.transformDirected dop2 ss1 T.Right assertEqual "i" Nothing $ T.transformDirected dop3 ss1 T.Left assertEqual "j" Nothing $ T.transformDirected dop3 ss1 T.Right testTransformChildMapSet :: TestTree testTransformChildMapSet = let dop1 = O.DirectedOperation "foo/bar" $ O.IntInc 1 dop2 = O.DirectedOperation "" $ O.IntInc 1 ss1 = O.DirectedOperation "" $ O.MapSet "foo" c 0 ss2 = O.DirectedOperation "" $ O.MapSet "bar" c 0 in testCase "Transform Child against MapSet" $ do assertEqual "a" (Just dop1) $ T.transformDirected dop1 ss2 T.Left assertEqual "b" (Just dop1) $ T.transformDirected dop1 ss2 T.Right assertEqual "c" (Just O.directedNoOp) $ T.transformDirected dop1 ss1 T.Left assertEqual "d" (Just O.directedNoOp) $ T.transformDirected dop1 ss1 T.Right assertEqual "e" Nothing $ T.transformDirected dop2 ss1 T.Left assertEqual "f" Nothing $ T.transformDirected dop2 ss1 T.Right testTransformChildMapUnset :: TestTree testTransformChildMapUnset = let dop1 = O.DirectedOperation "foo/bar" $ O.IntInc 1 dop2 = O.DirectedOperation "" $ O.IntInc 1 ss1 = O.DirectedOperation "" $ O.MapUnset "foo" ss2 = O.DirectedOperation "" $ O.MapUnset "bar" in testCase "Transform Child against MapUnset" $ do assertEqual "a" (Just dop1) $ T.transformDirected dop1 ss2 T.Left assertEqual "b" (Just dop1) $ T.transformDirected dop1 ss2 T.Right assertEqual "c" (Just O.directedNoOp) $ T.transformDirected dop1 ss1 T.Left assertEqual "d" (Just O.directedNoOp) $ T.transformDirected dop1 ss1 T.Right assertEqual "e" Nothing $ T.transformDirected dop2 ss2 T.Left assertEqual "f" Nothing $ T.transformDirected dop2 ss2 T.Right testTransformChildNonAffecting :: TestTree testTransformChildNonAffecting = let dop1 = O.DirectedOperation "foo/bar" $ O.IntInc 1 dop1' = O.DirectedOperation "foo/0" $ O.IntInc 1 dop2 = O.DirectedOperation "foo/bar/baz" $ O.MapUnset "bar" dop3 = O.DirectedOperation "foo/baz" $ O.MapUnset "baz" dop4 = O.DirectedOperation "baz" $ O.MapUnset "baz" dop5 = O.DirectedOperation "foo/bar/baz" $ O.MapSet "bar" c 0 dop6 = O.DirectedOperation "foo/baz" $ O.MapSet "baz" c 0 dop7 = O.DirectedOperation "baz" $ O.MapSet "baz" c 0 dop8 = O.DirectedOperation "foo/bar/baz" $ O.SequenceSet 0 c 0 dop9 = O.DirectedOperation "foo/baz" $ O.SequenceSet 0 c 0 dop10 = O.DirectedOperation "baz" $ O.SequenceSet 0 c 0 dop11 = O.DirectedOperation "foo/bar/baz" $ O.SequenceInsert 0 c 0 dop12 = O.DirectedOperation "foo/baz" $ O.SequenceInsert 0 c 0 dop13 = O.DirectedOperation "baz" $ O.SequenceInsert 0 c 0 dop14 = O.DirectedOperation "foo/bar/baz" $ O.SequenceDelete 0 dop15 = O.DirectedOperation "foo/baz" $ O.SequenceDelete 0 dop16 = O.DirectedOperation "baz" $ O.SequenceDelete 0 dop17 = O.DirectedOperation "foo/bar/baz" $ O.RootSet c 0 dop18 = O.DirectedOperation "foo/baz" $ O.RootSet c 0 dop19 = O.DirectedOperation "baz" $ O.RootSet c 0 in testCase "Transform Child Non-Affecting" $ do assertEqual "a" (Just dop1) $ T.transformDirected dop1 dop2 T.Left assertEqual "b" (Just dop1) $ T.transformDirected dop1 dop2 T.Right assertEqual "c" (Just dop1) $ T.transformDirected dop1 dop3 T.Left assertEqual "d" (Just dop1) $ T.transformDirected dop1 dop3 T.Right assertEqual "e" (Just dop1) $ T.transformDirected dop1 dop4 T.Left assertEqual "f" (Just dop1) $ T.transformDirected dop1 dop4 T.Right assertEqual "g" (Just dop1) $ T.transformDirected dop1 dop5 T.Left assertEqual "h" (Just dop1) $ T.transformDirected dop1 dop5 T.Right assertEqual "i" (Just dop1) $ T.transformDirected dop1 dop6 T.Left assertEqual "j" (Just dop1) $ T.transformDirected dop1 dop6 T.Right assertEqual "k" (Just dop1) $ T.transformDirected dop1 dop7 T.Left assertEqual "l" (Just dop1) $ T.transformDirected dop1 dop7 T.Right assertEqual "m" (Just dop1') $ T.transformDirected dop1' dop8 T.Left assertEqual "n" (Just dop1') $ T.transformDirected dop1' dop8 T.Right assertEqual "o" (Just dop1') $ T.transformDirected dop1' dop9 T.Left assertEqual "p" (Just dop1') $ T.transformDirected dop1' dop9 T.Right assertEqual "q" (Just dop1') $ T.transformDirected dop1' dop10 T.Left assertEqual "r" (Just dop1') $ T.transformDirected dop1' dop10 T.Right assertEqual "s" (Just dop1') $ T.transformDirected dop1' dop11 T.Left assertEqual "t" (Just dop1') $ T.transformDirected dop1' dop11 T.Right assertEqual "u" (Just dop1') $ T.transformDirected dop1' dop12 T.Left assertEqual "v" (Just dop1') $ T.transformDirected dop1' dop12 T.Right assertEqual "w" (Just dop1') $ T.transformDirected dop1' dop13 T.Left assertEqual "x" (Just dop1') $ T.transformDirected dop1' dop13 T.Right assertEqual "y" (Just dop1') $ T.transformDirected dop1' dop14 T.Left assertEqual "z" (Just dop1') $ T.transformDirected dop1' dop14 T.Right assertEqual "aa" (Just dop1') $ T.transformDirected dop1' dop15 T.Left assertEqual "ab" (Just dop1') $ T.transformDirected dop1' dop15 T.Right assertEqual "ac" (Just dop1') $ T.transformDirected dop1' dop16 T.Left assertEqual "ad" (Just dop1') $ T.transformDirected dop1' dop16 T.Right assertEqual "ae" (Just dop1') $ T.transformDirected dop1' dop17 T.Left assertEqual "af" (Just dop1') $ T.transformDirected dop1' dop17 T.Right assertEqual "ag" (Just dop1') $ T.transformDirected dop1' dop18 T.Left assertEqual "ah" (Just dop1') $ T.transformDirected dop1' dop18 T.Right assertEqual "ai" (Just dop1') $ T.transformDirected dop1' dop19 T.Left assertEqual "aj" (Just dop1') $ T.transformDirected dop1' dop19 T.Right
jjwchoy/hotdb
tests/TransformationTest.hs
mit
26,028
0
17
5,528
9,586
4,464
5,122
501
1
--------------------------------------------------------- -- -- Module : Elca -- Copyright : Bartosz Wójcik (2011) -- License : Private -- -- Maintainer : [email protected] -- Stability : Unstable -- Portability : portable -- -- Early Payment module. --------------------------------------------------------- module LoanEarlyPayment --(earlyPayment) where import BWLib import Loans import LoanCalculator import LoanConfiguration import LoanConfigurationType import LoanUserInterface (postponedAmount ,calcAmorPlanPure) -- | Early payment of a loan -- Rules: -- 1. postponed capital will be paid off first -- 2. late interest will be paid off next -- 3. e = 0 => no changes (exceptions will be added later) -- 4. there are no fallen installments => result is undefined yet earlyPayment :: Int -- ^ Early payment amount -> EarlyRepaymentWish Int -- ^ the wish -> ClassicLoan -- ^ input loan -> ClassicLoan -- ^ output loan earlyPayment e w cl | fallenInst runCl >= nbrInst calcCl = cl -- loan paid off already | e == 0 && w == OnePeriod = cl -- no repayment => no changes | otherwise = setNewREff auxClc $ setNewRNom auxClc $ setNewInstalments e auxClc cl' where runCl = run cl calcCl = calc cl cl' = partialEarlyPayment w $ setAllCapital e cl -- Final reminder of the loan auxClc = auxiliaryCl w cl' -- ==================================================================================== -- | Loan with finally updated capitals. partialEarlyPayment :: EarlyRepaymentWish Int -> ClassicLoan -> ClassicLoan partialEarlyPayment w cl | feeDiff == 0 = cl -- case with very small remaining capital | remPureCap (run cl) + feeDiff < 0 = cl | otherwise = partialEarlyPayment w $ resetNewPureCapital feeDiff cl where feeDiff = fee (auxiliaryCl w cl) - remFeeCap (run cl) -- ==================================================================================== -- | Updates capital and late interest by figures of early payment -- Necessary to keep it separate, because the update may not be final in case of too -- high fees. -- Late capital and deferred interest diminish early payment amount. setAllCapital :: Int -> ClassicLoan -> ClassicLoan setAllCapital e cl = setNewPureCapital e'' $ setNewCapital e'' $ setNewLateInterest e' $ postponedAmount p $ cl where runCl = run cl e'' = max (e' - crLateInterest runCl) 0 e' = max (e - crPostponedCap runCl) 0 p = (-1) * min e (crPostponedCap runCl) -- ==================================================================================== setNewREff :: ClassicCalc -- ^ The reminder -> ClassicLoan -- ^ Original loan partially updated -> ClassicLoan setNewREff clc cl = cl { calc = (calc cl) {rEffRec = newREffRec ++ rEffRec clc ,rateEff = replicate (length $ rNom calcCl) $ head $ rateEff calcCl }} where calcCl = calc cl runCl = run cl prevPerIs1 = (fst.last.(take nbrPerFallen).installments) calcCl == 1 nbrPerFallen = getCurrPer cl - 1 -- Future effective rate calculation and change of its plan newREffRec | fallenInstInCurrPer cl > 1 = (take nbrPerFallen $ rEffRec calcCl) ++ [getPrevREffRec, rateOfPaidFee] | fallenInstInCurrPer cl == 0 && prevPerIs1 = (take (nbrPerFallen - 1) $ rEffRec calcCl) ++ [rateOfPaidFee] | otherwise = (take nbrPerFallen $ rEffRec calcCl) ++ [rateOfPaidFee] -- Gets effective interest rate of last fallen installment getPrevREffRec | getCurrPer cl == 1 || fallenInstInCurrPer cl > 0 = (head $ drop (getCurrPer cl - 1) (rEffRec calcCl)) | otherwise = (last $ take (getCurrPer cl - 1) (rEffRec calcCl)) -- Pure capital before last installment before early repayment. -- Needed as early repayment will be merged with last installment. rateOfPaidFee | fallenInst runCl == 1 = f ** (1/((fromIntegral $ delay calcCl ) + (fromIntegral $ fstInstDur calcCl) / 30)) - 1 | otherwise = f - 1 where f = fromIntegral (crInterestBaseRow runCl + prevInst) / (fromIntegral interestBaseRowBefLastFallenInst) -- The instalment which contains also early paiment amount -- the "-2" is theoretically correct, in case of problems check prevInst = (snd $ head $ drop (getCurrPer cl - 2) (installments calcCl)) -- returns pure capital before last fallen installment interestBaseRowBefLastFallenInst | fallenInst runCl <= 1 = capitalRow calcCl | otherwise = frthOf5 sndLastFallenInst + fvthOf5 sndLastFallenInst where sndLastFallenInst = last $ take (fallenInst runCl - 1) $ calcAmorPlanPure calcCl -- ==================================================================================== setNewRNom :: ClassicCalc -- ^ The reminder -> ClassicLoan -- ^ Original loan partially updated -> ClassicLoan setNewRNom clc cl = cl { calc = (calc cl) {rNom = newRNom ++ rNom clc }} where calcCl = calc cl prevPerIs1 = (fst.last.(take nbrPerFallen).installments) calcCl == 1 newRNom | fallenInstInCurrPer cl > 1 = (take nbrPerFallen $ rNom calcCl) ++ [getPrevRNom,getPrevRNom] | fallenInstInCurrPer cl == 0 && prevPerIs1 = (take (nbrPerFallen - 1) $ rNom calcCl) ++ [getPrevRNom] | otherwise = (take nbrPerFallen $ rNom calcCl) ++ [getPrevRNom] -- Gets nominal interest rate of last fallen installment getPrevRNom | getCurrPer cl == 1 || fallenInstInCurrPer cl > 0 = (head $ drop (getCurrPer cl - 1) (rNom calcCl)) | otherwise = (last $ take (getCurrPer cl - 1) (rNom calcCl)) nbrPerFallen = getCurrPer cl - 1 -- ==================================================================================== setNewInstalments :: Int -- ^ Early payment amount -> ClassicCalc -- ^ The reminder -> ClassicLoan -- ^ Original loan with updated capital -> ClassicLoan setNewInstalments e clc cl = cl { calc = (calc cl) { installments = newInstallments (fallenInstInCurrPer cl) , duration = duration calcCl - futureInst cl + duration clc , nbrInst = nbrInst calcCl - futureInst cl + nbrInst clc }} where calcCl = calc cl newInstallments 0 = (prevPerShorter . (take nbrPerFallen) . installments) calcCl ++ [(1,newSingleInst cl e)] ++ installments clc newInstallments 1 = (take nbrPerFallen (installments calcCl)) ++ [(1,newSingleInst cl e)] ++ installments clc newInstallments _ = (take nbrPerFallen (installments calcCl)) ++ [(fallenInstInCurrPer cl - 1, getNthInst (installments calcCl) (fallenInst $ run cl))] ++ [(1,newSingleInst cl e)] ++ installments clc -- diminish duration by 1 in the InstPlan data type construction prevPerShorter [] = [] prevPerShorter ls = init ls ++ perShorter [last ls] where perShorter [(1,i)] = [] perShorter [(n,i)] = [(n-1,i)] nbrPerFallen = getCurrPer cl - 1 -- ==================================================================================== -- | Creates a separate loan representing the reminder of the original loan auxiliaryCl :: EarlyRepaymentWish Int -> ClassicLoan -> ClassicCalc auxiliaryCl w cl = calcRateEffRec $ calcRateNom $ instPlan $ setFee feeAmt $ mkClassEmpty c (n w) r b 0 cf where runCl = run cl calcCl = calc cl -- Remaining pure capital + late interest c = crInterestBaseRow runCl c' = fromIntegral c r = head $ futureRateEff cl remainingDuration = nbrInst calcCl - fallenInst runCl -- Instalment amount in case remider was a Balloon with -- same balloon instalment. -- Expected to give negative value in case balloon amount -- is greater than capital accrued by interest. iOfBalloon = calcInstBal (rounding cf) c' remainingDuration r 0 $ fromIntegral $ ballAmt calcCl -- Reminder has own loan type cf = (conf calcCl) { clType = newClType , ccConfName = "Auxiliary Reminder of Advanced Paid Balloon" , ccConfFun = "confAdvPaidBalloon" } where cltype = clType $ conf calcCl newClType | remainingDuration == 1 = Classical | w == AdvancedPayment && cltype `elem` [Balloon,ReversBalloon] = AdvancedPaidBalloon sndLastInstAmt | w `elem` [BalloonFix] && cltype `elem` [Balloon,ReversBalloon] && iOfBalloon >= 0 = Balloon | sndLastInstAmt == 0 = Classical | w `elem` [BalloonFix] && cltype `elem` [Balloon,ReversBalloon] && iOfBalloon < 0 = ReversBalloon | w `elem` [BalloonReduced] && cltype `elem` [Balloon,ReversBalloon] = ReversBalloon | otherwise = Classical -- ReversalBalloon has duration equal to Classical of same conditions. -- Doesn't work for instalment = 0. -- Reversal balloon gets its instalment fixed to 2nd last instalment. durOfRevBalloon | sndLastInstAmt == 0 = remainingDuration | otherwise = min remainingDuration $ calcDurCl c sndLastInstAmt r 0 ceiling i | clType cf == ReversBalloon && w `elem` [BalloonFix] = 0 | clType cf == ReversBalloon = sndLastInstAmt | clType cf == Balloon = iOfBalloon | w == FixedAmount = sndLastInstAmt -- In other cases new instalment amount is not defined yet | otherwise = -1 -- b' = min c $ ballAmt calcCl -- Here we assume that balloon was greater than capital + interest so Balloon -- was changed to ReversBalloon with instalment == 0. b | clType cf == ReversBalloon = i -- | clType cf == ReversBalloon && w `elem` [BalloonFix] -- = calcBalBal (rounding cf) c' remainingDuration r 0 0 -- Here we assume that ReversBalloon is selected only if sndLastInstAmt > 0 -- | clType cf == ReversBalloon -- = calcBalBal (rounding cf) c' durOfRevBalloon r 0 sndLastInstAmt' -- Here we assume that balloon amount is limited to capital + interest. | otherwise = ballAmt calcCl feeAmt = remFeeCap runCl n FixedAmount = n2 sndLastInstAmt n (GivenAmount i') = n2 i' n (GivenDuration n') = n' n AdvancedPayment = remainingDuration --n BalloonFix = n2Bal sndLastInstAmt lastInstAmt n _ | remainingDuration == 1 = 1 | clType cf == ReversBalloon = durOfRevBalloon | clType cf == Balloon = n2Bal i b | otherwise = n2 sndLastInstAmt -- n _ = n2 sndLastInstAmt --lastInstAmt = snd $ last $ installments calcCl -- Second last instalmentAmount (nthInstAmt) sndLastInstAmt = getNthInst (installments calcCl) (nbrInst calcCl - 1) sndLastInstAmt' = fromIntegral sndLastInstAmt -- Duration of future instalment plan with all instalments equal i. n2 i | (cccERType.conf) calcCl == ERNoInstInc = calcDurCl c i r 0 ceiling | otherwise = max 1 $ calcDurCl c i r 0 round -- Duration of future instalment plan for balloon case and instalments equal i. n2Bal i b | (cccERType $ conf calcCl) == ERNoInstInc = calcDurBal b c i r 0 ceiling | otherwise = max 1 $ calcDurBal b c i r 0 round -- ==================================================================================== setNewLateInterest e cl = cl { run = (run cl) {crLateInterest = newLateInterest ,crLateInterestRow = newLateInterest }} where newLateInterest = max (crLateInterest (run cl) - e) 0 setNewCapital e cl = cl { run = (run cl) {remCapital = newCap ,crInterestBase = newCap + crLateInterest (run cl) }} where newCap = remCapital (run cl) - e setNewPureCapital e cl = cl { run = (run cl) {remFeeCap = newFee ,remPureCap = remCapital runCl - newFee ,crInterestBaseRow = remCapital runCl + crLateInterest runCl - newFee }} where newFee = remFeeCap runCl - (round $ proportionFee * fromIntegral e) proportionFee = (fromIntegral $ remFeeCap runCl) / (fromIntegral $ remPureCap runCl + remFeeCap runCl) runCl = run cl -- | Updates pure remaining capital and remaining fee using given amount resetNewPureCapital :: Int -- ^ given amount -> ClassicLoan -- ^ input loan -> ClassicLoan resetNewPureCapital diff cl = cl { run = (run cl) {remFeeCap = remFeeCap (run cl) + diff ,remPureCap = remPureCap (run cl) + diff ,crInterestBaseRow = crInterestBaseRow (run cl) + diff }} -- ==================================================================================== -- For test purposes epTest :: Int -- ^ Early payment amount -> EarlyRepaymentWish Int -- ^ the wish -> ClassicLoan -- ^ input loan -> ClassicLoan -- ^ output loan epTest e w cl | fallenInst runCl >= nbrInst calcCl = cl -- loan paid off already | e == 0 && w == OnePeriod = cl -- no repayment => no changes | otherwise = partialEarlyPayment w $ setAllCapital e cl where runCl = run cl calcCl = calc cl epTest1 :: Int -- ^ Early payment amount -> EarlyRepaymentWish Int -- ^ the wish -> ClassicLoan -- ^ input loan -> ClassicLoan -- ^ output loan epTest1 e w cl | fallenInst runCl >= nbrInst calcCl = cl -- loan paid off already | e == 0 && w == OnePeriod = cl -- no repayment => no changes | otherwise = setAllCapital e cl where runCl = run cl calcCl = calc cl epTest2 :: Int -- ^ Early payment amount -> EarlyRepaymentWish Int -- ^ the wish -> ClassicLoan -- ^ input loan -> ClassicCalc -- ^ output loan epTest2 e w cl | fallenInst runCl >= nbrInst calcCl = calcCl -- loan paid off already | e == 0 && w == OnePeriod = calcCl -- no repayment => no changes | otherwise = auxiliaryCl w $ partialEarlyPayment w $ setAllCapital e cl where runCl = run cl calcCl = calc cl
bartoszw/elca
LoanEarlyPayment.hs
gpl-2.0
17,584
2
17
7,092
3,340
1,709
1,631
229
5
module Behaviour.ACO.Ant where import Domain import Behaviour.Genetics.Algorithm import Behaviour.ACO.Solver import Data.List initialTour :: Path initialTour = [((0,0),0)] {- Starting from: - the tour - the node Return a new state with the two path updated -} visitNode :: Path -> Node -> Path visitNode t x | x `elem` t = error "node already visited" | x `notElem` t = t ++ [x] | otherwise = error "strange problem in a exaustive pattern" {- Starting from: - the tour - the node Return if the node is in the path -} isVisited :: Path -> Node -> Bool isVisited xs n = n `elem` xs nextToVisit :: Path -> [((Node, Node),(Float, Float))] -> IO Node nextToVisit xs ys = singleMontecarloExtraction 1.0 zs'' where lastNode = head $ reverse xs ys' = filter (\((a,b),(_,_)) -> (a == lastNode && not (isVisited xs b)) || (b == lastNode && not (isVisited xs a))) ys zs' = map (\(((a,b),(_,_)),f) -> if a == lastNode then (b,f) else (a,f)) $ zip ys' $ moveToProbability $ map snd ys' ranges = montecarloRages zs' (map snd) 0 zs'' = map (\((a,_),c) -> (a,c)) $ zip zs' ranges buildSolution :: [((Node, Node),(Float, Float))] -> Path -> IO Path buildSolution xs solution = if all (\n -> isVisited solution n) (nub (map (fst.fst) xs)) then return solution else do next <- nextToVisit solution xs buildSolution xs (visitNode solution next)
benkio/VRP
src/Behaviour/ACO/Ant.hs
gpl-3.0
1,424
0
15
330
573
317
256
28
2
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.SetUserPassword (postSetUserPasswordR) where import Import import Handler.DB import Network.HTTP.Types (status400) import Yesod.Auth import Yesod.Auth.HashDB (setPassword) import qualified Data.Aeson as A postSetUserPasswordR :: UserId -> Handler () postSetUserPasswordR userId = do (Entity authId auth) <- requireAuth if authId == userId || userAdmin auth then do password <- lookupPostParam ("password"::Text) case password of Just pw -> do maybeUser <- runDB $ get userId case maybeUser of Just user -> do user' <- liftIO $ setPassword pw user runDB $ update userId [ UserPassword =. userPassword user', UserSalt =. userSalt user' ] Nothing -> reply "User not found" Nothing -> reply "Missing required parameter 'password'" else reply "Unauthorized password change attempt" where reply msg = sendResponseStatus status400 $ A.object [ "error" .= (msg :: Text)]
tlaitinen/sms
backend/Handler/SetUserPassword.hs
gpl-3.0
1,334
0
24
534
280
142
138
28
4
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-} module CSpec (spec) where import Test.Hspec import Language.Mulang.Ast import Language.Mulang.Ast.Operator import Language.Mulang.Parsers.C import Data.Text (Text, unpack) import NeatInterpolation (text) run :: Text -> Expression run = c . unpack cContext :: Expression -> Expression cContext expr = Sequence [SubroutineSignature "main" [] "int" [], SimpleFunction "main" [] expr] spec :: Spec spec = do describe "parse" $ do context "declare variabels" $ do it "parses simple variable" $ do run "int a;" `shouldBe` Sequence [ TypeSignature "a" (SimpleType "int" []), Variable "a" None ] it "parses pointer to variable" $ do run "int * a;" `shouldBe` Sequence [ TypeSignature "*a" (SimpleType "int" []), Variable "a" None ] it "parses array without size variable" $ do run "int a[];" `shouldBe` Sequence [ TypeSignature "a[]" (SimpleType "int" []), Variable "a" None ] it "parses array with size variable" $ do run "int a[10];" `shouldBe` Sequence [ TypeSignature "a[10]" (SimpleType "int" []), Variable "a" None ] it "parses int with inicialization" $ do run "int a = 10;" `shouldBe` Sequence [ TypeSignature "a" (SimpleType "int" []), Variable "a" (MuNumber 10.0) ] it "parses char with initialization" $ do run "char a = 'a';" `shouldBe` Sequence [ TypeSignature "a" (SimpleType "char" []), Variable "a" (MuChar 'a') ] it "parses string with initialization" $ do run "char *a = \"Hello\";" `shouldBe` Sequence [ TypeSignature "*a" (SimpleType "char" []), Variable "a" (MuString "Hello") ] it "parses double with initialization" $ do run "double a = 0.1;" `shouldBe` Sequence [ TypeSignature "a" (SimpleType "double" []), Variable "a" (MuNumber 0.1) ] it "parses array with initialization" $ do run "int a[3] = {1, 2, 3};" `shouldBe` Sequence [ TypeSignature "a[3]" (SimpleType "int" []), Variable "a" (MuList [MuNumber 1, MuNumber 2, MuNumber 3]) ] it "parses references" $ do run "int main () { a; }" `shouldBe` cContext (Reference "a") it "parses if" $ do run [text| int main () { if(1) { 2; } else { 3; } } |] `shouldBe` cContext (If (MuNumber 1) (MuNumber 2) (MuNumber 3)) it "parses for" $ do run [text| int main () { for(i; i; i) { i; } } |] `shouldBe` cContext (ForLoop (Reference "i") (Reference "i") (Reference "i") (Reference "i")) it "parses return" $ do run [text| int main () { return 123; } |] `shouldBe` cContext (Return (MuNumber 123)) it "parses binary operators" $ do run [text| int main () { a + b; } |] `shouldBe` cContext (Application (Primitive Plus) [Reference "a", Reference "b"]) it "parses unary operators" $ do run [text| int main () { !a; } |] `shouldBe` cContext (Application (Primitive Negation) [Reference "a"]) it "parses assign operators" $ do run [text| int main () { a *= 2; } |] `shouldBe` cContext (Assignment "a" (Application (Primitive Multiply) [Reference "a", MuNumber 2])) it "parses logical operators" $ do run [text| int main () { a || b; } |] `shouldBe` cContext (Application (Primitive Or) [Reference "a", Reference "b"]) it "parses simple assignment" $ do run [text| int main () { a = 123; } |] `shouldBe` cContext (Assignment "a" (MuNumber 123)) it "parses while" $ do run [text| int main () { while(1) { 2; } } |] `shouldBe` cContext (While (MuNumber 1) (MuNumber 2)) it "parses while" $ do run [text| int main () { switch(a) { case 1: break; case 2: continue; default: 1; } } |] `shouldBe` cContext (Switch (Reference "a") [(MuNumber 1, Break None), (MuNumber 2, Continue None)] (MuNumber 1)) it "does parse structs access" $ do run [text| int main () { person.age; } |] `shouldBe` cContext (FieldReference (Reference "person") "age") it "does parse expression struct access" $ do run [text| int main () { f_person().age; } |] `shouldBe` cContext (FieldReference (Application (Reference "f_person") []) "age") it "does parse struct field assignment" $ do run [text| int main () { person.age = 10; } |] `shouldBe` cContext (FieldAssignment (Reference "person") "age" (MuNumber 10)) it "does parse struct pointer field assignment" $ do run [text| int main () { person->age = 10; } |] `shouldBe` cContext (Other (Just "CMember (CVar (Ident \"person\" 243067487 (NodeInfo <no file> (<no file>,6) (Name {nameId = 4}))) (NodeInfo <no file> (<no file>,6) (Name {nameId = 5}))) (Ident \"age\" 1668065 (NodeInfo <no file> (<no file>,3) (Name {nameId = 6}))) True (NodeInfo <no file> (<no file>,3) (Name {nameId = 7}))") Nothing) it "does parse struct pointer field assignment operation" $ do run [text| int main () { person.age += 10; } |] `shouldBe` cContext (FieldAssignment (Reference "person") "age" (Application (Primitive Plus) [Reference "age", MuNumber 10])) it "parses complex c example" $ do run [text| int cantidadDeNumerosImpares(int unosNumeros[]) { int cantidadDeImpares; for (int indice = 0; unosNumeros[indice] != NULL; indice++) { if (esNumeroImpar(c[b])) { cantidadDeImpares++; } } return cantidadDeImpares; } |] `shouldBe` Sequence [ TypeSignature "cantidadDeNumerosImpares" (ParameterizedType ["int"] "int" []), Function "cantidadDeNumerosImpares" [Equation [VariablePattern "unosNumeros[]"] (UnguardedBody ( Sequence [ Sequence [ TypeSignature "cantidadDeImpares" (SimpleType "int" []), Variable "cantidadDeImpares" None ], ForLoop (Sequence [ TypeSignature "indice" (SimpleType "int" []), Variable "indice" (MuNumber 0.0) ]) (Application (Primitive NotEqual) [Application (Reference "[]") [Reference "unosNumeros",Reference "indice"],Reference "NULL"]) (Assignment "indice" (Application (Primitive Plus) [Reference "indice",MuNumber 1.0])) (If (Application (Reference "esNumeroImpar") [Application (Reference "[]") [Reference "c",Reference "b"]]) (Assignment "cantidadDeImpares" (Application (Primitive Plus) [Reference "cantidadDeImpares",MuNumber 1.0])) None ), Return (Reference "cantidadDeImpares")]))]]
mumuki/mulang
spec/CSpec.hs
gpl-3.0
8,175
0
35
3,222
1,853
930
923
119
1
type Two = Either () ()
hmemcpy/milewski-ctfp-pdf
src/content/3.14/code/haskell/snippet01.hs
gpl-3.0
23
0
6
5
16
8
8
1
0
{-# 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.AndroidEnterprise.Storelayoutpages.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 store page. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.storelayoutpages.delete@. module Network.Google.Resource.AndroidEnterprise.Storelayoutpages.Delete ( -- * REST Resource StorelayoutpagesDeleteResource -- * Creating a Request , storelayoutpagesDelete , StorelayoutpagesDelete -- * Request Lenses , sdEnterpriseId , sdPageId ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.storelayoutpages.delete@ method which the -- 'StorelayoutpagesDelete' request conforms to. type StorelayoutpagesDeleteResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "storeLayout" :> "pages" :> Capture "pageId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deletes a store page. -- -- /See:/ 'storelayoutpagesDelete' smart constructor. data StorelayoutpagesDelete = StorelayoutpagesDelete' { _sdEnterpriseId :: !Text , _sdPageId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'StorelayoutpagesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdEnterpriseId' -- -- * 'sdPageId' storelayoutpagesDelete :: Text -- ^ 'sdEnterpriseId' -> Text -- ^ 'sdPageId' -> StorelayoutpagesDelete storelayoutpagesDelete pSdEnterpriseId_ pSdPageId_ = StorelayoutpagesDelete' { _sdEnterpriseId = pSdEnterpriseId_ , _sdPageId = pSdPageId_ } -- | The ID of the enterprise. sdEnterpriseId :: Lens' StorelayoutpagesDelete Text sdEnterpriseId = lens _sdEnterpriseId (\ s a -> s{_sdEnterpriseId = a}) -- | The ID of the page. sdPageId :: Lens' StorelayoutpagesDelete Text sdPageId = lens _sdPageId (\ s a -> s{_sdPageId = a}) instance GoogleRequest StorelayoutpagesDelete where type Rs StorelayoutpagesDelete = () type Scopes StorelayoutpagesDelete = '["https://www.googleapis.com/auth/androidenterprise"] requestClient StorelayoutpagesDelete'{..} = go _sdEnterpriseId _sdPageId (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy StorelayoutpagesDeleteResource) mempty
rueshyna/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Storelayoutpages/Delete.hs
mpl-2.0
3,341
0
15
755
389
233
156
63
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.EC2.AssociateAddress -- 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. -- | Associates an Elastic IP address with an instance or a network interface. -- -- An Elastic IP address is for use in either the EC2-Classic platform or in a -- VPC. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html Elastic IP Addresses> in the /Amazon ElasticCompute Cloud User Guide/. -- -- [EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is -- already associated with a different instance, it is disassociated from that -- instance and associated with the specified instance. -- -- [VPC in an EC2-Classic account] If you don't specify a private IP address, -- the Elastic IP address is associated with the primary IP address. If the -- Elastic IP address is already associated with a different instance or a -- network interface, you get an error unless you allow reassociation. -- -- This is an idempotent operation. If you perform the operation more than -- once, Amazon EC2 doesn't return an error. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateAddress.html> module Network.AWS.EC2.AssociateAddress ( -- * Request AssociateAddress -- ** Request constructor , associateAddress -- ** Request lenses , aa1AllocationId , aa1AllowReassociation , aa1DryRun , aa1InstanceId , aa1NetworkInterfaceId , aa1PrivateIpAddress , aa1PublicIp -- * Response , AssociateAddressResponse -- ** Response constructor , associateAddressResponse -- ** Response lenses , aarAssociationId ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data AssociateAddress = AssociateAddress { _aa1AllocationId :: Maybe Text , _aa1AllowReassociation :: Maybe Bool , _aa1DryRun :: Maybe Bool , _aa1InstanceId :: Maybe Text , _aa1NetworkInterfaceId :: Maybe Text , _aa1PrivateIpAddress :: Maybe Text , _aa1PublicIp :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AssociateAddress' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aa1AllocationId' @::@ 'Maybe' 'Text' -- -- * 'aa1AllowReassociation' @::@ 'Maybe' 'Bool' -- -- * 'aa1DryRun' @::@ 'Maybe' 'Bool' -- -- * 'aa1InstanceId' @::@ 'Maybe' 'Text' -- -- * 'aa1NetworkInterfaceId' @::@ 'Maybe' 'Text' -- -- * 'aa1PrivateIpAddress' @::@ 'Maybe' 'Text' -- -- * 'aa1PublicIp' @::@ 'Maybe' 'Text' -- associateAddress :: AssociateAddress associateAddress = AssociateAddress { _aa1DryRun = Nothing , _aa1InstanceId = Nothing , _aa1PublicIp = Nothing , _aa1AllocationId = Nothing , _aa1NetworkInterfaceId = Nothing , _aa1PrivateIpAddress = Nothing , _aa1AllowReassociation = Nothing } -- | [EC2-VPC] The allocation ID. This is required for EC2-VPC. aa1AllocationId :: Lens' AssociateAddress (Maybe Text) aa1AllocationId = lens _aa1AllocationId (\s a -> s { _aa1AllocationId = a }) -- | [EC2-VPC] Allows an Elastic IP address that is already associated with an -- instance or network interface to be re-associated with the specified instance -- or network interface. Otherwise, the operation fails. -- -- Default: 'false' aa1AllowReassociation :: Lens' AssociateAddress (Maybe Bool) aa1AllowReassociation = lens _aa1AllowReassociation (\s a -> s { _aa1AllowReassociation = a }) -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have the -- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'. aa1DryRun :: Lens' AssociateAddress (Maybe Bool) aa1DryRun = lens _aa1DryRun (\s a -> s { _aa1DryRun = a }) -- | The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you -- can specify either the instance ID or the network interface ID, but not both. -- The operation fails if you specify an instance ID unless exactly one network -- interface is attached. aa1InstanceId :: Lens' AssociateAddress (Maybe Text) aa1InstanceId = lens _aa1InstanceId (\s a -> s { _aa1InstanceId = a }) -- | [EC2-VPC] The ID of the network interface. If the instance has more than one -- network interface, you must specify a network interface ID. aa1NetworkInterfaceId :: Lens' AssociateAddress (Maybe Text) aa1NetworkInterfaceId = lens _aa1NetworkInterfaceId (\s a -> s { _aa1NetworkInterfaceId = a }) -- | [EC2-VPC] The primary or secondary private IP address to associate with the -- Elastic IP address. If no private IP address is specified, the Elastic IP -- address is associated with the primary private IP address. aa1PrivateIpAddress :: Lens' AssociateAddress (Maybe Text) aa1PrivateIpAddress = lens _aa1PrivateIpAddress (\s a -> s { _aa1PrivateIpAddress = a }) -- | The Elastic IP address. This is required for EC2-Classic. aa1PublicIp :: Lens' AssociateAddress (Maybe Text) aa1PublicIp = lens _aa1PublicIp (\s a -> s { _aa1PublicIp = a }) newtype AssociateAddressResponse = AssociateAddressResponse { _aarAssociationId :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'AssociateAddressResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aarAssociationId' @::@ 'Maybe' 'Text' -- associateAddressResponse :: AssociateAddressResponse associateAddressResponse = AssociateAddressResponse { _aarAssociationId = Nothing } -- | [EC2-VPC] The ID that represents the association of the Elastic IP address -- with an instance. aarAssociationId :: Lens' AssociateAddressResponse (Maybe Text) aarAssociationId = lens _aarAssociationId (\s a -> s { _aarAssociationId = a }) instance ToPath AssociateAddress where toPath = const "/" instance ToQuery AssociateAddress where toQuery AssociateAddress{..} = mconcat [ "AllocationId" =? _aa1AllocationId , "AllowReassociation" =? _aa1AllowReassociation , "DryRun" =? _aa1DryRun , "InstanceId" =? _aa1InstanceId , "NetworkInterfaceId" =? _aa1NetworkInterfaceId , "PrivateIpAddress" =? _aa1PrivateIpAddress , "PublicIp" =? _aa1PublicIp ] instance ToHeaders AssociateAddress instance AWSRequest AssociateAddress where type Sv AssociateAddress = EC2 type Rs AssociateAddress = AssociateAddressResponse request = post "AssociateAddress" response = xmlResponse instance FromXML AssociateAddressResponse where parseXML x = AssociateAddressResponse <$> x .@? "associationId"
romanb/amazonka
amazonka-ec2/gen/Network/AWS/EC2/AssociateAddress.hs
mpl-2.0
7,697
0
9
1,567
876
533
343
91
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.Datastore.Projects.Lookup -- 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) -- -- Looks up entities by key. -- -- /See:/ <https://cloud.google.com/datastore/ Cloud Datastore API Reference> for @datastore.projects.lookup@. module Network.Google.Resource.Datastore.Projects.Lookup ( -- * REST Resource ProjectsLookupResource -- * Creating a Request , projectsLookup , ProjectsLookup -- * Request Lenses , plXgafv , plUploadProtocol , plAccessToken , plUploadType , plPayload , plProjectId , plCallback ) where import Network.Google.Datastore.Types import Network.Google.Prelude -- | A resource alias for @datastore.projects.lookup@ method which the -- 'ProjectsLookup' request conforms to. type ProjectsLookupResource = "v1" :> "projects" :> CaptureMode "projectId" "lookup" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] LookupRequest :> Post '[JSON] LookupResponse -- | Looks up entities by key. -- -- /See:/ 'projectsLookup' smart constructor. data ProjectsLookup = ProjectsLookup' { _plXgafv :: !(Maybe Xgafv) , _plUploadProtocol :: !(Maybe Text) , _plAccessToken :: !(Maybe Text) , _plUploadType :: !(Maybe Text) , _plPayload :: !LookupRequest , _plProjectId :: !Text , _plCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLookup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plXgafv' -- -- * 'plUploadProtocol' -- -- * 'plAccessToken' -- -- * 'plUploadType' -- -- * 'plPayload' -- -- * 'plProjectId' -- -- * 'plCallback' projectsLookup :: LookupRequest -- ^ 'plPayload' -> Text -- ^ 'plProjectId' -> ProjectsLookup projectsLookup pPlPayload_ pPlProjectId_ = ProjectsLookup' { _plXgafv = Nothing , _plUploadProtocol = Nothing , _plAccessToken = Nothing , _plUploadType = Nothing , _plPayload = pPlPayload_ , _plProjectId = pPlProjectId_ , _plCallback = Nothing } -- | V1 error format. plXgafv :: Lens' ProjectsLookup (Maybe Xgafv) plXgafv = lens _plXgafv (\ s a -> s{_plXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plUploadProtocol :: Lens' ProjectsLookup (Maybe Text) plUploadProtocol = lens _plUploadProtocol (\ s a -> s{_plUploadProtocol = a}) -- | OAuth access token. plAccessToken :: Lens' ProjectsLookup (Maybe Text) plAccessToken = lens _plAccessToken (\ s a -> s{_plAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plUploadType :: Lens' ProjectsLookup (Maybe Text) plUploadType = lens _plUploadType (\ s a -> s{_plUploadType = a}) -- | Multipart request metadata. plPayload :: Lens' ProjectsLookup LookupRequest plPayload = lens _plPayload (\ s a -> s{_plPayload = a}) -- | Required. The ID of the project against which to make the request. plProjectId :: Lens' ProjectsLookup Text plProjectId = lens _plProjectId (\ s a -> s{_plProjectId = a}) -- | JSONP plCallback :: Lens' ProjectsLookup (Maybe Text) plCallback = lens _plCallback (\ s a -> s{_plCallback = a}) instance GoogleRequest ProjectsLookup where type Rs ProjectsLookup = LookupResponse type Scopes ProjectsLookup = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/datastore"] requestClient ProjectsLookup'{..} = go _plProjectId _plXgafv _plUploadProtocol _plAccessToken _plUploadType _plCallback (Just AltJSON) _plPayload datastoreService where go = buildClient (Proxy :: Proxy ProjectsLookupResource) mempty
brendanhay/gogol
gogol-datastore/gen/Network/Google/Resource/Datastore/Projects/Lookup.hs
mpl-2.0
4,837
0
17
1,169
783
456
327
113
1
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func :: asd -> ( Trither lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd ) lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
lspitzner/brittany
data/Test378.hs
agpl-3.0
298
1
9
55
27
12
15
6
0
-- Test file for the SourceView widget. module Main where import Graphics.UI.Gtk import Graphics.UI.Gtk.SourceView main = do initGUI win <- windowNew win `onDestroy` mainQuit -- create the appropriate language lm <- sourceLanguagesManagerNew langM <- sourceLanguagesManagerGetLanguageFromMimeType lm "text/x-haskell" lang <- case langM of (Just lang) -> return lang Nothing -> do langDirs <- sourceLanguagesManagerGetLangFilesDirs lm error ("please copy haskell.lang to one of the following directories:\n" ++unlines langDirs) -- create a new SourceBuffer object buffer <- sourceBufferNewWithLanguage lang -- load up and display a file fileContents <- readFile "SourceViewTest.hs" textBufferSetText buffer fileContents textBufferSetModified buffer False sourceBufferSetHighlight buffer True -- create a new SourceView Widget sv <- sourceViewNewWithBuffer buffer -- put it in a scrolled window sw <- scrolledWindowNew Nothing Nothing sw `containerAdd` sv scrolledWindowSetPolicy sw PolicyAutomatic PolicyAutomatic sw `scrolledWindowSetShadowType` ShadowIn win `containerAdd` sw -- show the widget and run the main loop windowSetDefaultSize win 400 500 widgetShowAll win mainGUI
thiagoarrais/gtk2hs
demo/sourceview/SourceViewTest.hs
lgpl-2.1
1,266
0
16
236
247
117
130
29
2
{-# LANGUAGE RankNTypes #-} import System.Plugins import API src = "../Plugin.hs" apipath = "../api" main = do status <- make src ["-i"++apipath] case status of MakeSuccess _ _ -> f MakeFailure e -> mapM_ putStrLn e where f = do v <- pdynload "../Plugin.o" [apipath] [] "API.Interface" "resource" case v of LoadSuccess _ a -> putStrLn "loaded .. yay!" LoadFailure e -> mapM_ putStrLn e
Changaco/haskell-plugins
testsuite/pdynload/poly/prog/Main.hs
lgpl-2.1
493
0
10
172
142
68
74
13
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} module Gossim.Protocol.PingPong ( agent ) where import Data.Text.Format (Only(Only)) import Data.Typeable (Typeable) import Gossim (Agent, AgentId, getSelf, getAgents, broadcast, (!), receive, logInfo, logError) data Message = Ping AgentId | Pong AgentId deriving Typeable agent :: Agent () agent = do master <- isMaster if master then do $logInfo "I am master" () loopMaster else do $logInfo "I am slave" () loopSlave where loopMaster :: Agent () loopMaster = do agents <- getAgents self <- getSelf $logInfo "Sending ping to {} agents" (Only $ length agents) broadcast agents (Ping self) receive handleMsg loopMaster where handleMsg :: Message -> Agent () handleMsg (Pong aid) = $logInfo "Got pong from {}" (Only aid) handleMsg (Ping aid) = $logError "Got unexpected ping from {}" (Only aid) loopSlave :: Agent () loopSlave = do receive handleMsg loopSlave where handleMsg :: Message -> Agent () handleMsg (Ping aid) = do $logInfo "Got ping from {}. Sending pong in response." (Only aid) self <- getSelf aid ! Pong self handleMsg (Pong aid) = $logError "Got unexpected pong from {}" (Only aid) isMaster :: Agent Bool isMaster = do self <- getSelf agents <- getAgents return $ self == minimum agents
aartamonau/gossim
src/Gossim/Protocol/PingPong.hs
lgpl-3.0
1,675
0
13
576
446
221
225
49
4
module FreePalace.Domain.Chat where import qualified FreePalace.Domain.User as User import qualified FreePalace.Messages.Inbound as Messages data Communication = Communication { speaker :: User.UserId, target :: Maybe User.UserId, message :: String, chatMode :: ChatMode } deriving Show data ChatMode = TalkAloud | Whispering | Thought | Exclamation | Notice | Announcement | Outbound deriving Show data Movement = Movement data ChatLog = ChatLog { -- TODO logEntryTimestamp logEntries :: [ Communication ] } deriving Show makeRoomAnnouncement :: String -> Communication makeRoomAnnouncement announcement = Communication { speaker = User.roomAnnouncementUserId , target = Nothing , message = announcement , chatMode = Announcement }
psfblair/freepalace
src/FreePalace/Domain/Chat.hs
apache-2.0
772
0
10
137
170
108
62
21
1
splitBy :: Char -> String -> [String] splitBy _ [] = [] splitBy a x = let s = takeWhile (/= a) x x'= dropWhile (/= a) x in if x' == [] then [s] else s:(splitBy a $ drop 1 x') f :: Integer -> String -> Integer f n ('n':'^':s) = let m = read s :: Integer in n ^ m ans n t s = let a = splitBy '+' s v = (* t) $ sum $ map (f n) a in if v <= 1000000000 then show(v) else "TLE" main = do nt <- getLine s <- getLine let [n,t] = map read $ words nt :: [Integer] o = ans n t s putStrLn o
a143753/AOJ
2523.hs
apache-2.0
545
0
12
188
313
158
155
22
2
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} module DNA.AST ( -- * AST Expr(..) , Idx(..) , typeOfExpr -- ** Tuple , Tuple(..) , TupleIdx(..) , IsTuple(..) , Arity(..) -- ** Array and array shaped , Array(..) , Shape(..) , Slice(..) -- ** Connection encoding , Out , ConnId(..) , ConnType(..) , Conn(..) , Outbound(..) -- ** Dictionaries , ScalarDict(..) , IsScalar(..) , ShapeDict(..) , IsShape(..) , VectorDict(..) , IsVector(..) , ValueDict(..) , IsValue(..) ) where import Control.Applicative import qualified Data.Vector.Storable as S import Data.Typeable import Data.Functor.Identity import Data.Binary (Binary) import GHC.Generics (Generic) ---------------------------------------------------------------- -- AST ---------------------------------------------------------------- -- | AST for expression. data Expr env a where -- | Local let binding Let :: Expr env expr -- Bound expression -> Expr (env,expr) a -- Expression in scope of let -> Expr env a -- | Variable bound by let Var :: Idx env a -> Expr env a -- | Apply Ap :: Expr env (a -> b) -> Expr env a -> Expr env b -- | Lambda abstraction Lam :: IsValue a => Expr (env,a) b -> Expr env (a -> b) -- | Fold Fold :: (Expr env (a -> a -> a)) -> Expr env a -> Expr env (Array sh a) -> Expr env a -- | Zip two vectors Zip :: (Expr env (a -> b -> c)) -> Expr env (Array sh a) -> Expr env (Array sh b) -> Expr env (Array sh c) -- | Generate vector Generate :: IsShape sh => Expr env sh -> Expr env (Int -> a) -> Expr env (Array sh a) -- Primitive operations Add :: Num a => Expr env (a -> a -> a) Mul :: Num a => Expr env (a -> a -> a) FromInt :: Expr env (Int -> Double) Out :: [Outbound env] -> Expr env Out -- Scalars Scalar :: IsScalar a => a -> Expr env a -- | Tuple expression Tup :: IsTuple tup => Tuple (Expr env) (Elems tup) -> Expr env tup -- | Tuple projection Prj :: TupleIdx (Elems tup) a -> Expr env (tup -> a) String :: String -> Expr env String -- Array sizes EShape :: Shape -> Expr env Shape ESlice :: Slice -> Expr env Slice -- Primitive array Vec :: Array sh a -> Expr env (Array sh a) -- | List literal List :: IsScalar a => [a] -> Expr env [a] -- | Functor instance for list FMap :: Expr env (a -> b) -> Expr env [a] -> Expr env [b] -- | Special form for scattering values ScatterShape :: Expr env (Int -> Shape -> [Slice]) -- Read data from file. Arguably it shouldn't be primitive but -- implemented as some foreign function. ReadFile :: IsShape sh => Expr env String -> Expr env sh -> Expr env (Array sh Double) -- | De-Bruijn index for variable data Idx env t where ZeroIdx :: Idx (env,t) t SuccIdx :: Idx env t -> Idx (env,s) t typeOfExpr :: Expr env a -> a typeOfExpr = error "DNA.AST.typeOfExpr: Impossible!" ---------------------------------------------------------------- -- Tuples ---------------------------------------------------------------- -- | Encoding for a tuple data Tuple :: (* -> *) -> [*] -> * where Nil :: Tuple f '[] Cons :: f a -> Tuple f as -> Tuple f (a ': as) infixr `Cons` -- | Index for tuple index data TupleIdx xs e where Here :: Arity xs => TupleIdx (x ': xs) x There :: TupleIdx xs e -> TupleIdx (x ': xs) e class Arity (xs :: [*]) where arity :: p xs -> Int instance Arity '[] where arity _ = 0 instance Arity xs => Arity (x ': xs) where arity p = 1 + arity (sub p) where sub :: p (x ': xs) -> p xs sub _ = undefined class IsTuple a where type Elems a :: [*] toRepr :: a -> Tuple Identity (Elems a) fromRepr :: Tuple Identity (Elems a) -> a instance IsTuple (a,b) where type Elems (a,b) = '[a,b] toRepr (a,b) = pure a `Cons` pure b `Cons` Nil fromRepr (Identity a `Cons` Identity b `Cons` Nil) = (a,b) fromRepr _ = error "Impossible" instance IsTuple (a,b,c) where type Elems (a,b,c) = '[a,b,c] toRepr (a,b,c) = pure a `Cons` pure b `Cons` pure c `Cons` Nil fromRepr (Identity a `Cons` Identity b `Cons` Identity c `Cons` Nil) = (a,b,c) fromRepr _ = error "Impossible" newtype Shape = Shape Int deriving (Show,Eq,Typeable,Generic) instance Binary Shape data Slice = Slice Int Int deriving (Show,Eq,Typeable,Generic) instance Binary Slice data Array sh a = Array sh (S.Vector a) ---------------------------------------------------------------- -- Connection encoding ---------------------------------------------------------------- -- | Type tag for expressions for sending data data Out -- | ID of outgoing connection. Each actor can have several outgoing -- connections which are identified by tat ID. newtype ConnId = ConnId Int deriving (Show,Eq,Ord) -- | Connection type data ConnType = ConnOne -- ^ We allow to connect to one deriving (Show,Eq,Ord) -- | Typed wrapper for connection ID. data Conn a where -- | Connection for which only Conn :: Typeable a => ConnId -> ConnType -> Conn a -- | Outgoing message data Outbound env where -- | Simple outgoing connection Outbound :: Conn a -> Expr env a -> Outbound env -- | Sending result of computation OutRes :: Expr env a -> Outbound env -- | Log message PrintInt :: Expr env Int -> Outbound env ---------------------------------------------------------------- data ScalarDict a where DoubleDict :: ScalarDict Double IntDict :: ScalarDict Int UnitDict :: ScalarDict () class IsScalar a where reifyScalar :: a -> ScalarDict a instance IsScalar Double where reifyScalar _ = DoubleDict instance IsScalar Int where reifyScalar _ = IntDict instance IsScalar () where reifyScalar _ = UnitDict data ShapeDict a where ShShape :: ShapeDict Shape ShSlice :: ShapeDict Slice class IsShape a where reifyShape :: a -> ShapeDict a instance IsShape Shape where reifyShape _ = ShShape instance IsShape Slice where reifyShape _ = ShSlice data VectorDict a where VecD :: IsShape sh => VectorDict (Array sh Double) class IsVector a where reifyVector :: a -> VectorDict a instance IsShape sh => IsVector (Array sh Double) where reifyVector _ = VecD data ValueDict a where ValScalar :: IsScalar a => ValueDict a ValShape :: IsShape a => ValueDict a ValVec :: IsVector a => ValueDict a class IsValue a where reifyValue :: a -> ValueDict a instance IsValue Int where reifyValue _ = ValScalar instance IsValue Double where reifyValue _ = ValScalar instance IsValue () where reifyValue _ = ValScalar instance IsValue Shape where reifyValue _ = ValShape instance IsValue Slice where reifyValue _ = ValShape instance IsShape sh => IsValue (Array sh Double) where reifyValue _ = ValVec
SKA-ScienceDataProcessor/RC
MS1/dna/DNA/AST.hs
apache-2.0
7,111
0
11
1,743
2,298
1,253
1,045
-1
-1
module Data.Multimap ( Multimap , empty , null , insert , deleteAll , delete , lookup , fromList , elems , size , foldr , foldl , foldrWithKey , foldlWithKey , foldMapWithKey ) where import Prelude hiding (foldl, foldr, lookup, null) import qualified Prelude import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Maybe as Maybe import Data.Set (Set) import qualified Data.Set as Set newtype Multimap k v = Multimap { unMultimap :: Map k (Set v) } deriving (Eq, Ord, Show) empty :: Multimap k v empty = Multimap Map.empty null :: Multimap k v -> Bool null (Multimap m) = Map.null m inserter :: Ord v => v -> Maybe (Set v) -> Maybe (Set v) inserter v Nothing = Just (Set.singleton v) inserter v (Just s) = Just (Set.insert v s) insert :: (Ord k, Ord v) => k -> v -> Multimap k v -> Multimap k v insert k v (Multimap m) = Multimap $ Map.alter (inserter v) k m deleteAll :: Ord k => k -> Multimap k v -> Multimap k v deleteAll k (Multimap m) = Multimap $ Map.delete k m deleter :: Ord v => v -> Maybe (Set v) -> Maybe (Set v) deleter _ Nothing = Nothing deleter v (Just s) | Set.null updated = Nothing | otherwise = Just updated where updated = Set.delete v s delete :: (Ord k, Ord v) => k -> v -> Multimap k v -> Multimap k v delete k v (Multimap m) = Multimap $ Map.alter (deleter v) k m lookup :: Ord k => k -> Multimap k v -> Set v lookup k (Multimap m) = Maybe.fromMaybe Set.empty (Map.lookup k m) fromList :: (Ord k, Ord v) => [(k, v)] -> Multimap k v fromList = Prelude.foldr f empty where f (k, v) = insert k v elems :: Multimap k v -> [v] elems (Multimap m) = Map.elems m >>= Set.elems size :: Multimap k v -> Int size = length . elems foldr :: (Set a -> b -> b) -> b -> Multimap k a -> b foldr f b (Multimap m) = Map.foldr f b m foldl :: (a -> Set b -> a) -> a -> Multimap k b -> a foldl f a (Multimap m) = Map.foldl f a m foldrWithKey :: (k -> Set a -> b -> b) -> b -> Multimap k a -> b foldrWithKey f b (Multimap m) = Map.foldrWithKey f b m foldlWithKey :: (a -> k -> Set b -> a) -> a -> Multimap k b -> a foldlWithKey f a (Multimap m) = Map.foldlWithKey f a m foldMapWithKey :: Monoid m => (k -> Set a -> m) -> Multimap k a -> m foldMapWithKey f (Multimap m) = Map.foldMapWithKey f m
henrytill/hecate
src/Data/Multimap.hs
apache-2.0
2,370
0
10
623
1,138
583
555
62
1
import Data.Maybe f n _ [] = Just n f n s (a:as) = if s' < 0 then Nothing else f n s' as where s' = s + a - n ans a@(h:_) = fromJust $ head $ filter (/= Nothing ) $ map (\n -> f n 0 a) $ reverse [1..h] main = do _ <- getLine l <- getLine let i = map read $ words l o = ans i print o
a143753/AOJ
2921.hs
apache-2.0
307
0
11
102
198
97
101
12
2
import Prelude isPrime :: Int -> Bool isPrime n | n <= 0 = error "You must insert a natural number.\n" | otherwise = length [i | i <- [1..n], n `mod` i == 0] == 2 dividesN :: Int -> [Int] -> [Int] dividesN n xs = [x | x <- xs, n `mod` x == 0] primeFactors :: Int -> [Int] primeFactors 1 = [] primeFactors n | n <= 0 = error "n must be positive.\n" | otherwise = (minimum (dividesN n (filter isPrime [1..n]))):(primeFactors (n `div` (minimum (dividesN n (filter isPrime [1..n])))))
2dor/99-problems-Haskell
31-41-arithmetic/problem-35.hs
bsd-2-clause
500
0
17
115
259
134
125
12
1
module TimeSeriesData.Counts where import Data.Time (NominalDiffTime) import Data.List (sort) import Control.Exception (assert) import TimeSeriesData.Types (TSInterval) data StartEnd = Start | End deriving (Eq, Ord) counts :: [[TSInterval]] -> [(TSInterval, Int)] counts ss = if null times then [] else counts' 0 (fst $ head times) times where toTimes = concat . map (\ (a, b) -> [(a, Start), (b, End)]) times = sort (concat $ map toTimes ss) counts' :: Int -> NominalDiffTime -> [(NominalDiffTime, StartEnd)] -> [(TSInterval, Int)] counts' acc time ((now, pos):[]) = assert (acc == 1 && pos == End) $ if now == time then [] else [((time, now), acc)] counts' acc time ((now, pos):times) | now == time = counts' (if pos == Start then acc + 1 else acc - 1) now times | now > time = ((time, now), acc) : counts' (if pos == Start then acc + 1 else acc - 1) now times counts' _ _ _ = assert False undefined
hectorhon/autotrace2
src/TimeSeriesData/Counts.hs
bsd-3-clause
949
0
12
208
449
251
198
19
4
-- http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_8_D -- Ring -- input: -- vanceknowledgetoad -- advance -- output: -- Yes -- input2: -- vanceknowledgetoad -- advanced -- output2: -- No import qualified Data.List as List (elemIndices) main = do s <- getLine p <- getLine putStrLn $ if elemFromRing (List.elemIndices (head p) s) s p then "Yes" else "No" elemFromRing :: [Int] -> String -> String -> Bool elemFromRing [] _ _ = False elemFromRing (x:xs) s p | pickFromRing [x..(x + length p - 1)] s == p = True | otherwise = elemFromRing xs s p pickFromRing :: [Int] -> String -> String pickFromRing [] _ = [] pickFromRing (n:ns) xs = xs !! (n `mod` length xs) : pickFromRing ns xs
ku00/aoj-haskell
src/ITP1_8_D.hs
bsd-3-clause
757
0
14
181
258
138
120
13
2
-------------------------------------------------------------------------------- module Language.Haskell.Stylish.Step.LanguagePragmas.Tests ( tests ) where -------------------------------------------------------------------------------- import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@=?)) -------------------------------------------------------------------------------- import Language.Haskell.Stylish.Step.LanguagePragmas import Language.Haskell.Stylish.Tests.Util -------------------------------------------------------------------------------- tests :: Test tests = testGroup "Language.Haskell.Stylish.Step.LanguagePragmas.Tests" [ testCase "case 01" case01 , testCase "case 02" case02 , testCase "case 03" case03 , testCase "case 04" case04 , testCase "case 05" case05 , testCase "case 06" case06 , testCase "case 07" case07 , testCase "case 08" case08 , testCase "case 09" case09 , testCase "case 10" case10 , testCase "case 11" case11 ] -------------------------------------------------------------------------------- case01 :: Assertion case01 = expected @=? testStep (step 80 Vertical True False) input where input = unlines [ "{-# LANGUAGE ViewPatterns #-}" , "{-# LANGUAGE TemplateHaskell, ViewPatterns #-}" , "{-# LANGUAGE ScopedTypeVariables #-}" , "module Main where" ] expected = unlines [ "{-# LANGUAGE ScopedTypeVariables #-}" , "{-# LANGUAGE TemplateHaskell #-}" , "{-# LANGUAGE ViewPatterns #-}" , "module Main where" ] -------------------------------------------------------------------------------- case02 :: Assertion case02 = expected @=? testStep (step 80 Vertical True True) input where input = unlines [ "{-# LANGUAGE BangPatterns #-}" , "{-# LANGUAGE ViewPatterns #-}" , "increment ((+ 1) -> x) = x" ] expected = unlines [ "{-# LANGUAGE ViewPatterns #-}" , "increment ((+ 1) -> x) = x" ] -------------------------------------------------------------------------------- case03 :: Assertion case03 = expected @=? testStep (step 80 Vertical True True) input where input = unlines [ "{-# LANGUAGE BangPatterns #-}" , "{-# LANGUAGE ViewPatterns #-}" , "increment x = case x of !_ -> x + 1" ] expected = unlines [ "{-# LANGUAGE BangPatterns #-}" , "increment x = case x of !_ -> x + 1" ] -------------------------------------------------------------------------------- case04 :: Assertion case04 = expected @=? testStep (step 80 Compact True False) input where input = unlines [ "{-# LANGUAGE TypeOperators, StandaloneDeriving, DeriveDataTypeable," , " TemplateHaskell #-}" , "{-# LANGUAGE TemplateHaskell, ViewPatterns #-}" ] expected = unlines [ "{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving, " ++ "TemplateHaskell," , " TypeOperators, ViewPatterns #-}" ] -------------------------------------------------------------------------------- case05 :: Assertion case05 = expected @=? testStep (step 80 Vertical True False) input where input = unlines [ "{-# LANGUAGE CPP #-}" , "" , "#if __GLASGOW_HASKELL__ >= 702" , "{-# LANGUAGE Trustworthy #-}" , "#endif" ] expected = unlines [ "{-# LANGUAGE CPP #-}" , "" , "#if __GLASGOW_HASKELL__ >= 702" , "{-# LANGUAGE Trustworthy #-}" , "#endif" ] -------------------------------------------------------------------------------- case06 :: Assertion case06 = expected @=? testStep (step 80 CompactLine True False) input where input = unlines [ "{-# LANGUAGE TypeOperators, StandaloneDeriving, DeriveDataTypeable," , " TemplateHaskell #-}" , "{-# LANGUAGE TemplateHaskell, ViewPatterns #-}" ] expected = unlines [ "{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving, " ++ "TemplateHaskell #-}" , "{-# LANGUAGE TypeOperators, ViewPatterns #-}" ] -------------------------------------------------------------------------------- case07 :: Assertion case07 = expected @=? testStep (step 80 Vertical False False) input where input = unlines [ "{-# LANGUAGE ViewPatterns #-}" , "{-# LANGUAGE TemplateHaskell, ViewPatterns #-}" , "{-# LANGUAGE ScopedTypeVariables, NoImplicitPrelude #-}" , "module Main where" ] expected = unlines [ "{-# LANGUAGE NoImplicitPrelude #-}" , "{-# LANGUAGE ScopedTypeVariables #-}" , "{-# LANGUAGE TemplateHaskell #-}" , "{-# LANGUAGE ViewPatterns #-}" , "module Main where" ] -------------------------------------------------------------------------------- case08 :: Assertion case08 = expected @=? testStep (step 80 CompactLine False False) input where input = unlines [ "{-# LANGUAGE TypeOperators, StandaloneDeriving, DeriveDataTypeable," , " TemplateHaskell #-}" , "{-# LANGUAGE TemplateHaskell, ViewPatterns #-}" ] expected = unlines [ "{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving, " ++ "TemplateHaskell #-}" , "{-# LANGUAGE TypeOperators, ViewPatterns #-}" ] -------------------------------------------------------------------------------- case09 :: Assertion case09 = expected @=? testStep (step 80 Utrecht False False) input where input = unlines [ "{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}" , "" , "main = undefined" ] expected = unlines [ "{-# LANGUAGE" , " OverloadedStrings" , " , TemplateHaskell" , " #-}" , "" , "main = undefined" ] -------------------------------------------------------------------------------- case10 :: Assertion case10 = expected @=? testStep (step 80 Utrecht False False) input where input = unlines [ "{-# LANGUAGE OverloadedStrings, TemplateHaskell, RecordWildCards #-}" , "" , "main = undefined" ] expected = unlines [ "{-# LANGUAGE" , " OverloadedStrings" , " , RecordWildCards" , " , TemplateHaskell" , " #-}" , "" , "main = undefined" ] -------------------------------------------------------------------------------- case11 :: Assertion case11 = expected @=? testStep (step 80 Utrecht False False) input where input = unlines [ "{-# LANGUAGE OverloadedStrings #-}" , "" , "main = undefined" ] expected = unlines [ "{-# LANGUAGE OverloadedStrings #-}" , "" , "main = undefined" ]
silkapp/stylish-haskell
tests/Language/Haskell/Stylish/Step/LanguagePragmas/Tests.hs
bsd-3-clause
7,047
0
9
1,865
971
551
420
144
1
{-# LANGUAGE PatternGuards, ViewPatterns, TupleSections #-} module Config.Haskell( readPragma, readComment ) where import Data.Char import Data.List.Extra import Text.Read import Data.Tuple.Extra import Data.Maybe import Config.Type import Util import Prelude import GHC.Util import GHC.Types.SrcLoc import GHC.Hs.Extension import GHC.Hs.Decls hiding (SpliceDecl) import GHC.Hs.Expr hiding (Match) import GHC.Hs.Lit import GHC.Data.FastString import GHC.Parser.Annotation import GHC.Utils.Outputable import Language.Haskell.GhclibParserEx.GHC.Utils.Outputable import Language.Haskell.GhclibParserEx.GHC.Types.Name.Reader -- | Read an {-# ANN #-} pragma and determine if it is intended for HLint. -- Return Nothing if it is not an HLint pragma, otherwise what it means. readPragma :: AnnDecl GhcPs -> Maybe Classify readPragma (HsAnnotation _ _ provenance expr) = f expr where name = case provenance of ValueAnnProvenance (L _ x) -> occNameStr x TypeAnnProvenance (L _ x) -> occNameStr x ModuleAnnProvenance -> "" f :: LocatedA (HsExpr GhcPs) -> Maybe Classify f (L _ (HsLit _ (HsString _ (unpackFS -> s)))) | "hlint:" `isPrefixOf` lower s = case getSeverity a of Nothing -> errorOn expr "bad classify pragma" Just severity -> Just $ Classify severity (trimStart b) "" name where (a,b) = break isSpace $ trimStart $ drop 6 s f (L _ (HsPar _ x)) = f x f (L _ (ExprWithTySig _ x _)) = f x f _ = Nothing readComment :: LEpaComment -> [Classify] readComment c@(L pos (EpaComment EpaBlockComment{} _)) | (hash, x) <- maybe (False, x) (True,) $ stripPrefix "#" x , x <- trim x , (hlint, x) <- word1 x , lower hlint == "hlint" = f hash x where x = commentText c f hash x | Just x <- if hash then stripSuffix "#" x else Just x , (sev, x) <- word1 x , Just sev <- getSeverity sev , (things, x) <- g x , Just hint <- if x == "" then Just "" else readMaybe x = map (Classify sev hint "") $ ["" | null things] ++ things f hash _ = errorOnComment c $ "bad HLINT pragma, expected:\n {-" ++ h ++ " HLINT <severity> <identifier> \"Hint name\" " ++ h ++ "-}" where h = ['#' | hash] g x | (s, x) <- word1 x , s /= "" , not $ "\"" `isPrefixOf` s = first ((if s == "module" then "" else s):) $ g x g x = ([], x) readComment _ = [] errorOn :: Outputable a => LocatedA a -> String -> b errorOn (L pos val) msg = exitMessageImpure $ showSrcSpan (locA pos) ++ ": Error while reading hint file, " ++ msg ++ "\n" ++ unsafePrettyPrint val errorOnComment :: LEpaComment -> String -> b errorOnComment c@(L s _) msg = exitMessageImpure $ let isMultiline = isCommentMultiline c in showSrcSpan (RealSrcSpan (anchor s) Nothing) ++ ": Error while reading hint file, " ++ msg ++ "\n" ++ (if isMultiline then "{-" else "--") ++ commentText c ++ (if isMultiline then "-}" else "")
ndmitchell/hlint
src/Config/Haskell.hs
bsd-3-clause
3,139
0
18
872
1,075
559
516
72
7
{-| Module : Game.GoreAndAsh.Network Description : Network backend API Copyright : (c) Anton Gushcha, 2015-2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : POSIX -} module Game.GoreAndAsh.Network.Backend( ChannelId(..) , RemoteAddress , MessageType(..) , NetworkBackendContext(..) , NetworkBackend(..) , HasNetworkBackend(..) , SendError(..) ) where import Control.DeepSeq import Control.Monad.IO.Class import Data.ByteString (ByteString) import Data.Typeable import Data.Word import GHC.Generics -- | Channel ID for network connection. Channels can be used to separate data -- streams with different format. newtype ChannelId = ChannelId { unChannelId :: Word32 } deriving (Generic, Show, Eq, Ord) instance NFData ChannelId -- | Abstract remote node address. It could be IP + port, or hostname, or -- name of unix socket, etc. type RemoteAddress = ByteString -- | Strategy how given message is delivered to remote host data MessageType = ReliableMessage -- ^ TCP like, ordered reliable delivery | UnreliableMessage -- ^ Unrelieable, sequenced but fragments are sent with reliability | UnsequencedMessage -- ^ Unreliable and unsequenced (not sort while receiving) | UnreliableFragmentedMessage -- ^ Unreliable, sequenced sent with fragments sent within unreliable method | UnsequencedFragmentedMessage -- ^ Unreliable, unsequenced with fragments sent within unreliable method deriving (Eq, Ord, Bounded, Enum, Show, Generic) instance NFData MessageType -- | Payload of event for send errors data SendError a = SendError { sendPeer :: !(Peer a) , sendChan :: !ChannelId , sendMessageType :: !MessageType , sendPayload :: !ByteString , sendDetails :: !(BackendSendError a) } deriving (Generic) deriving instance HasNetworkBackend a => Show (SendError a) -- | Holds info about FRP triggers the backend should use and creation options -- specific for the backend. data NetworkBackendContext a = NetworkBackendContext { -- | Backend specific options (ex. bandwith limits, channel count) networkBackendOptions :: BackendOptions a -- | Trigger for event when connection process is finished (succ or fail) , networkTriggerLocalConnected :: Peer a -> IO () -- | Trigger event about disconnection of remote peer , networkTriggerLocalDisonnected :: IO () -- | Trigger for event when a remote connection is opened , networkTriggerRemoteConnected :: Peer a -> IO () -- | Trigger event about disconnection of remote peer , networkTriggerRemoteDisonnected :: Peer a -> IO () -- | Trigger incoming message event , networkTriggerIncomingMessage :: Peer a -> ChannelId -> MessageType -> ByteString -> IO () -- | Trigger event about some async error in backend , networkTriggerSomeError :: BackendEventError a -> IO () -- | Trigger event about message sending error , networkTriggerSendError :: SendError a -> IO () -- | Trigger event when connection to remote host is failed , networkTriggerConnectionError :: (BackendConnectError a, RemoteAddress) -> IO () } deriving (Generic) -- | Holds network backend operations data NetworkBackend a = NetworkBackend { -- | Emmit command to connect to remote endpoint networkConnect :: RemoteAddress -> ConnectOptions a -> IO () -- | Emmit command to disconnect connected peer (or yourself in case of client) , networkDisconnect :: Peer a -> IO () -- | Send a message to remote peer. , networkSendMessage :: Peer a -> ChannelId -> MessageType -> ByteString -> IO () -- | Shutdown the backend , networkTerminate :: IO () } deriving (Generic) -- | Abstract over network backend (ENet or TCP, for instance) class ( Show (BackendCreateError a) , Show (BackendSendError a) , Show (BackendConnectError a) , Show (BackendEventError a) , Show (BackendSendError a) , Eq (Peer a) , Ord (Peer a) , Show (Peer a) , Typeable a) => HasNetworkBackend a where -- | Represents connection to remote machine type Peer a :: * -- | Represents additional options of backend type BackendOptions a :: * -- | Represents additional options for connection creation type ConnectOptions a :: * -- | Type of creation error for the backend type BackendCreateError a :: * -- | Type of connection error for the backend type BackendConnectError a :: * -- | Type of generic event error for the backend type BackendEventError a :: * -- | Type of send message error for the backend type BackendSendError a :: * -- | Initiate network backend with given parameters and event triggers. createNetworkBackend :: MonadIO m => NetworkBackendContext a -> m (Either (BackendCreateError a) (NetworkBackend a))
Teaspot-Studio/gore-and-ash-network
src/Game/GoreAndAsh/Network/Backend.hs
bsd-3-clause
4,788
0
14
952
796
457
339
-1
-1
module Duck.Hypothesis where import Duck.Types type Hypothesis = (Double -> Double) -- |Builds a named hypothesis. hypothesis :: String -> Hypothesis -> (String, Hypothesis) hypothesis name hp = (name, hp) -- |Default hypothesis function. hp, hpc, hpln, hp2, hp3, hp4 :: Hypothesis hpc n = 1 hp n = n hpln n = n * (log n) / (log 2) hp2 n = n^2 hp3 n = n^3 hp4 n = n^4
gangsterveggies/duck-analyzer
Duck/Hypothesis.hs
bsd-3-clause
372
0
8
76
156
90
66
12
1
-- | This module imports the entire package, except 'Sound.OpenAL.Proto.IO'. module Sound.OpenAL.Proto ( -- * Overview {-| Audio playback and capture prototype with Haskell OpenAL bindings -} -- * Sound.OpenAL.Proto module Sound.OpenAL.Proto.Capture, module Sound.OpenAL.Proto.Conversion, module Sound.OpenAL.Proto.Play, module Sound.OpenAL.Proto.Types, module Sound.OpenAL.Proto.UnitGen ) where import Sound.OpenAL.Proto.Capture import Sound.OpenAL.Proto.Conversion import Sound.OpenAL.Proto.Play import Sound.OpenAL.Proto.Types import Sound.OpenAL.Proto.UnitGen
peterhil/hs-openal-proto
src/Sound/OpenAL/Proto.hs
bsd-3-clause
576
0
5
64
88
65
23
11
0
-- | -- Module : Archive.Nar.UTF8 -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- -- a tiny UTF8 decoding/encoding -- {-# LANGUAGE MagicHash #-} {-# LANGUAGE BangPatterns #-} module Archive.Nar.UTF8 ( utf8Encode , utf8Decode ) where import qualified Data.ByteString as B import Data.Bits import GHC.Prim import GHC.Word import GHC.Types data Table = Table Addr# indexTableI :: Table -> Word8 -> Int indexTableI (Table addr) (W8# i) = I# (word2Int# (indexWord8OffAddr# addr (word2Int# i))) indexTableB :: Table -> Word8 -> Bool indexTableB (Table addr) (W8# i) = W# (indexWord8OffAddr# addr (word2Int# i)) /= W# 0## utf8Decode :: B.ByteString -> String utf8Decode = decode . B.unpack where decode :: [Word8] -> [Char] decode [] = [] decode (x:xs) = case getNbBytes x of 0 -> toEnum (fromIntegral x) : decode xs 1 -> case xs of b1:xs2 | isCont b1 -> toChar (x .&. 0x1f) [b1] : decode xs2 | otherwise -> error "continuation bytes invalid" _ -> error "not enough bytes (1) " 2 -> case xs of b1:b2:xs2 | and $ map isCont [b1,b2] -> toChar (x .&. 0xf) [b1,b2] : decode xs2 | otherwise -> error "continuation bytes invalid" _ -> error "not enough bytes (2)" 3 -> case xs of b1:b2:b3:xs2 | and $ map isCont [b1,b2,b3] -> toChar (x .&. 0x7) [b1,b2,b3] : decode xs2 | otherwise -> error "continuation bytes invalid" _ -> error "not enough bytes (3)" _ -> error "invalid heading byte" toChar :: Word8 -> [Word8] -> Char toChar h l = toEnum $ foldl (\acc v -> (acc `shiftL` 6) + clearCont v) (fromIntegral h) l where clearCont w = fromIntegral (w `clearBit` 7) getNbBytes = indexTableI headTable headTable = Table "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\ \\x03\x03\x03\x03\x03\x03\x03\x03\xff\xff\xff\xff\xff\xff\xff\xff"# isCont :: Word8 -> Bool isCont = indexTableB contTable contTable = Table "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"# utf8Encode :: String -> B.ByteString utf8Encode = B.pack . concatMap unf . map fromEnum where unf x | x < 0x80 = [fromIntegral x] | x < 0x07ff = [0xc0 .|. (sh 6 .&. 0x1f), cont 0] | x < 0xffff = [0xe0 .|. (sh 12 .&. 0xf), cont 6, cont 0] | otherwise = [0xf0 .|. (sh 18 .&. 0x7), cont 12, cont 6, cont 0] where sh w = fromIntegral (x `shiftR` w) cont w = (sh w `setBit` 7) `clearBit` 6
nar-org/hs-nar
Archive/Nar/UTF8.hs
bsd-3-clause
5,435
0
18
1,564
908
468
440
57
9
{-# LANGUAGE StandaloneDeriving , DataKinds , TypeOperators , TypeFamilies , GeneralizedNewtypeDeriving , TemplateHaskell , QuasiQuotes , MultiParamTypeClasses , FlexibleContexts , FlexibleInstances , TypeSynonymInstances , RankNTypes , CPP , KindSignatures , ScopedTypeVariables , FunctionalDependencies , UndecidableInstances , BangPatterns #-} module Sigym4.Geometry.Types ( Geometry (..) , LineString (..) , MultiLineString (..) , LinearRing (..) , Vertex , SqMatrix , Point (..) , MultiPoint (..) , Polygon (..) , MultiPolygon (..) , Triangle (..) , TIN (..) , PolyhedralSurface (..) , GeometryCollection (..) , Feature (..) , FeatureCollection (..) , VectorSpace (..) , HasOffset (..) , Pixel (..) , Size (..) , Offset (..) , RowMajor , ColumnMajor , Extent (..) , GeoTransform (..) , Raster (..) , rasterIndexPixel , unsafeRasterIndexPixel , rasterIndex , unsafeRasterIndex , northUpGeoTransform , generateMRaster , GeoReference (..) , mkGeoReference , pointOffset , unsafePointOffset , grScalarSize , scalarSize , grForward , grBackward , mkLineString , mkLinearRing , mkPolygon , mkTriangle , HasCoordinates (..) , polygonRings , convertRasterOffsetType , eSize , rasterSize , invertible -- lenses & prisms , HasGeometry (..) , HasVertices (..) , HasProperties (..) , HasFeatures (..) , HasPoints (..) , HasLineStrings (..) , HasOuterRing (..) , HasInnerRings (..) , HasPolygons (..) , HasTriangles (..) , HasGeometries (..) , HasVertex (..) , featureCollectionFeatures , featureGeometry , featureProperties , _GeoPoint , _GeoMultiPoint , _GeoLineString , _GeoMultiLineString , _GeoPolygon , _GeoMultiPolygon , _GeoTriangle , _GeoPolyhedralSurface , _GeoTIN , _GeoCollection -- re-exports , KnownNat , module V1 , module V2 , module V3 , module V4 , module VN , module Linear.Epsilon , module SpatialReference ) where import Prelude hiding (product) import Control.Lens hiding (coerce) import Data.Coerce (coerce) import Data.Distributive (Distributive) import Data.Proxy (Proxy(..)) import Data.Semigroup (Semigroup(..)) import Data.Hashable (Hashable(..)) import Control.DeepSeq (NFData(rnf)) import Control.Exception (assert) import Control.Monad.Primitive (PrimMonad(..)) import qualified Data.Semigroup as SG import Data.Foldable (product) import Data.Maybe (fromMaybe) import qualified Data.Vector as V import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import Foreign.Storable (Storable) import qualified Data.Vector.Generic.Mutable as GM import Data.Vector.Unboxed.Deriving (derivingUnbox) import Language.Haskell.TH.Syntax import Linear.V1 as V1 import Linear.V2 as V2 import Linear.V3 as V3 import Linear.V4 as V4 hiding (vector, point) import Linear.Epsilon import Linear.V as VN hiding (dim, Size) import Linear.Matrix ((!*), (*!), inv22, inv33, inv44, det22, det33, det44) import Linear.Metric (Metric) import GHC.TypeLits import SpatialReference -- | A vertex type Vertex v = v Double -- | A square Matrix type SqMatrix v = v (Vertex v) -- | A vector space class ( KnownNat (VsDim v), Num (Vertex v), Fractional (Vertex v) , Show (Vertex v), Eq (Vertex v), Ord (Vertex v), Epsilon (Vertex v) , U.Unbox (Vertex v), NFData (Vertex v), NFData (SqMatrix v) , NFData (v Int) , Show (v Int), Eq (v Int), Ord (v Int) , Num (SqMatrix v), Show (SqMatrix v), Eq (SqMatrix v), Ord (SqMatrix v) , Metric v, Applicative v, Foldable v, Traversable v, Distributive v) => VectorSpace (v :: * -> *) where type VsDim v :: Nat inv :: SqMatrix v -> SqMatrix v det :: SqMatrix v -> Double dim :: Proxy v -> Int dim = const (reflectDim (Proxy :: Proxy (VsDim v))) {-# INLINE dim #-} coords :: v a -> [a] fromCoords :: [a] -> Maybe (v a) unsafeFromCoords :: [a] -> v a unsafeFromCoords = fromMaybe (error "unsafeFromCoords") . fromCoords {-# INLINE CONLIKE [1] unsafeFromCoords #-} liftTExp :: Lift a => v a -> Q (TExp (v a)) {-# MINIMAL inv, det, coords , fromCoords, liftTExp #-} {-# RULES "unsafeFromCoords/V2" forall u v. unsafeFromCoords (u:v:[]) = V2 u v "unsafeFromCoords/V3" forall u v z. unsafeFromCoords (u:v:z:[]) = V3 u v z "unsafeFromCoords/V4" forall u v z w. unsafeFromCoords (u:v:z:w:[]) = V4 u v z w #-} invertible :: VectorSpace v => SqMatrix v -> Bool invertible = not . nearZero . det {-# INLINE invertible #-} instance VectorSpace V1 where type VsDim V1 = 1 inv = (pure 1 /) det (V1 (V1 u)) = u coords (V1 u) = [u] fromCoords [u] = Just (V1 u) fromCoords _ = Nothing liftTExp (V1 u) = [|| V1 u ||] {-# INLINE CONLIKE [1] coords #-} {-# INLINE fromCoords #-} {-# INLINE inv #-} {-# INLINE det #-} instance VectorSpace V2 where type VsDim V2 = 2 inv = inv22 det = det22 coords (V2 u v) = [u, v] fromCoords [u, v] = Just (V2 u v) fromCoords _ = Nothing liftTExp (V2 u v) = [|| V2 u v ||] {-# INLINE CONLIKE [1] coords #-} {-# INLINE fromCoords #-} {-# INLINE inv #-} {-# INLINE det #-} instance VectorSpace V3 where type VsDim V3 = 3 inv = inv33 det = det33 coords (V3 u v z) = [u, v, z] fromCoords [u, v, z] = Just (V3 u v z) fromCoords _ = Nothing liftTExp (V3 u v z) = [|| V3 u v z ||] {-# INLINE CONLIKE [1] coords #-} {-# INLINE fromCoords #-} {-# INLINE inv #-} {-# INLINE det #-} instance VectorSpace V4 where type VsDim V4 = 4 inv = inv44 det = det44 coords (V4 u v z w) = [u, v, z, w] fromCoords [u, v, z, w] = Just (V4 u v z w) fromCoords _ = Nothing liftTExp (V4 u v z w) = [|| V4 u v z w ||] {-# INLINE CONLIKE [1] coords #-} {-# INLINE fromCoords #-} {-# INLINE inv #-} {-# INLINE det #-} instance KnownNat n => VectorSpace (V n) where type VsDim (V n) = n inv = error ("inv not implemented for V " ++ show (dim (Proxy :: Proxy (V n)))) det = error ("det not implemented for V " ++ show (dim (Proxy :: Proxy (V n)))) coords = G.toList . toVector fromCoords = fromVector . G.fromList liftTExp (V n) = let l = G.toList n d = dim (Proxy :: Proxy (V n)) in [|| V (G.fromListN d l) ||] {-# INLINE CONLIKE [1] coords #-} {-# INLINE fromCoords #-} {-# INLINE inv #-} {-# INLINE det #-} newtype Offset (t :: OffsetType) = Offset {unOff :: Int} deriving (Eq, Show, Ord, Num) data OffsetType = RowMajor | ColumnMajor type RowMajor = 'RowMajor type ColumnMajor = 'ColumnMajor class VectorSpace v => HasOffset v (t :: OffsetType) where toOffset :: Size v -> Pixel v -> Maybe (Offset t) fromOffset :: Size v -> Offset t -> Maybe (Pixel v) unsafeToOffset :: Size v -> Pixel v -> Offset t unsafeFromOffset :: Size v -> Offset t -> Pixel v instance HasOffset V2 RowMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy = Just (unsafeToOffset s p) | otherwise = Nothing where V2 sx sy = unSize s V2 px py = fmap truncate $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset off where V2 sx sy = unSize s V2 px py = fmap truncate $ unPx p off = assert (0<=px && px<sx && 0<=py && py<sy) (py * sx + px) {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V2 sx sy)) o@(Offset o') | 0<=o' && o'<sx*sy = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V2 sx sy)) (Offset o) = Pixel (V2 (fromIntegral px) (fromIntegral py)) where (py,px) = assert (0<=o && o<(sx*sy)) (o `divMod` sx) {-# INLINE unsafeFromOffset #-} instance HasOffset V2 ColumnMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy = Just (unsafeToOffset s p) | otherwise = Nothing where V2 sx sy = unSize s V2 px py = fmap truncate $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset off where V2 sx sy = unSize s V2 px py = fmap truncate $ unPx p off = assert (0<=px && px<sx && 0<=py && py<sy) (px * sy + py) {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V2 sx sy)) o@(Offset o') | 0<=o' && o'<sx*sy = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V2 sx sy)) (Offset o) = Pixel (V2 (fromIntegral px) (fromIntegral py)) where (px,py) = assert (0<=o && o<(sx*sy)) (o `divMod` sy) {-# INLINE unsafeFromOffset #-} instance HasOffset V3 RowMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy , 0<=pz && pz < sz = Just (unsafeToOffset s p) | otherwise = Nothing where V3 sx sy sz = unSize s V3 px py pz = fmap truncate $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset $ (pz * sx * sy) + (py * sx) + px where V3 sx sy _ = unSize s V3 px py pz = fmap truncate $ unPx p {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V3 sx sy sz)) o@(Offset o') | 0<=o' && o'<sx*sy*sz = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V3 sx sy _)) (Offset o) = Pixel (V3 (fromIntegral px) (fromIntegral py) (fromIntegral pz)) where (pz, r) = o `divMod` (sx*sy) (py,px) = r `divMod` sx {-# INLINE unsafeFromOffset #-} instance HasOffset V3 ColumnMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy , 0<=pz && pz < sz = Just (unsafeToOffset s p) | otherwise = Nothing where V3 sx sy sz = unSize s V3 px py pz = fmap truncate $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset $ (px * sz * sy) + (py * sz) + pz where V3 _ sy sz = unSize s V3 px py pz = fmap truncate $ unPx p {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V3 sx sy sz)) o@(Offset o') | 0<=o' && o'<sx*sy*sz = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V3 _ sy sz)) (Offset o) = Pixel (V3 (fromIntegral px) (fromIntegral py) (fromIntegral pz)) where (px, r) = o `divMod` (sz*sy) (py,pz) = r `divMod` sz {-# INLINE unsafeFromOffset #-} -- | An extent in v space is a pair of minimum and maximum vertices data Extent v crs = Extent {eMin :: !(Vertex v), eMax :: !(Vertex v)} deriving instance VectorSpace v => Eq (Extent v crs) deriving instance VectorSpace v => Show (Extent v crs) instance NFData (Vertex v) => NFData (Extent v crs) where rnf (Extent lo hi) = rnf lo `seq` rnf hi `seq` () instance Hashable (Vertex v) => Hashable (Extent v crs) where hashWithSalt i (Extent l h) = hashWithSalt i l + hashWithSalt i h eSize :: VectorSpace v => Extent v crs -> Vertex v eSize e = eMax e - eMin e {-# INLINE eSize #-} instance VectorSpace v => SG.Semigroup (Extent v crs) where Extent a0 a1 <> Extent b0 b1 = Extent (min <$> a0 <*> b0) (max <$> a1 <*> b1) {-# INLINE (<>) #-} -- | A pixel is a newtype around a vertex newtype Pixel v = Pixel {unPx :: Vertex v} deriving instance VectorSpace v => Show (Pixel v) deriving instance VectorSpace v => Eq (Pixel v) newtype Size v = Size {unSize :: v Int} deriving instance VectorSpace v => Eq (Size v) deriving instance VectorSpace v => Ord(Size v) deriving instance VectorSpace v => Show (Size v) deriving instance VectorSpace v => NFData (Size v) scalarSize :: VectorSpace v => Size v -> Int scalarSize = product . unSize {-# INLINE scalarSize #-} -- A GeoTransform defines how we translate from geographic 'Vertex'es to -- 'Pixel' coordinates and back. gtMatrix *must* be invertible so smart -- constructors are provided data GeoTransform v crs = GeoTransform { gtMatrix :: !(SqMatrix v) , gtOrigin :: !(Vertex v) } deriving instance VectorSpace v => Ord (GeoTransform v crs) deriving instance VectorSpace v => Eq (GeoTransform v crs) deriving instance VectorSpace v => Show (GeoTransform v crs) instance VectorSpace v => NFData (GeoTransform v crs) where rnf (GeoTransform gr s) = rnf gr `seq` rnf s `seq` () northUpGeoTransform :: Extent V2 crs -> Size V2 -> Either String (GeoTransform V2 crs) northUpGeoTransform e s | not isValidBox = Left "northUpGeoTransform: invalid extent" | not isValidSize = Left "northUpGeoTransform: invalid size" | otherwise = Right $ GeoTransform matrix origin where isValidBox = fmap (> 0) (eMax e - eMin e) == pure True isValidSize = fmap (> 0) s' == pure True V2 x0 _ = eMin e V2 _ y1 = eMax e origin = V2 x0 y1 s' = fmap fromIntegral $ unSize s V2 dx dy = (eMax e - eMin e)/s' matrix = V2 (V2 dx 0) (V2 0 (-dy)) gtForward :: VectorSpace v => GeoTransform v crs -> Point v crs -> Pixel v gtForward gt (Point v) = Pixel $ m !* (v-v0) where v0 = gtOrigin gt m #if ASSERTS | not (invertible (gtMatrix gt)) = error "gtMatrix is not invertible" #endif | otherwise = inv (gtMatrix gt) gtBackward :: VectorSpace v => GeoTransform v crs -> Pixel v -> Point v crs gtBackward gt p = Point $ v0 + (unPx p) *! m where m = gtMatrix gt v0 = gtOrigin gt data GeoReference v crs = GeoReference { grTransform :: !(GeoTransform v crs) , grSize :: !(Size v) } deriving instance VectorSpace v => Eq (GeoReference v crs) deriving instance VectorSpace v => Ord (GeoReference v crs) deriving instance VectorSpace v => Show (GeoReference v crs) instance VectorSpace v => NFData (GeoReference v crs) where rnf (GeoReference gr s) = rnf gr `seq` rnf s `seq` () grScalarSize :: VectorSpace v => GeoReference v crs -> Int grScalarSize = scalarSize . grSize {-# INLINE grScalarSize #-} pointOffset :: (HasOffset v t, VectorSpace v) => GeoReference v crs -> Point v crs -> Maybe (Offset t) pointOffset gr = toOffset (grSize gr) . grForward gr {-# INLINE pointOffset #-} unsafePointOffset :: (HasOffset v t, VectorSpace v) => GeoReference v crs -> Point v crs -> Offset t unsafePointOffset gr = unsafeToOffset (grSize gr) . grForward gr {-# INLINE unsafePointOffset #-} grForward :: VectorSpace v => GeoReference v crs -> Point v crs -> Pixel v grForward gr = gtForward (grTransform gr) {-# INLINE grForward #-} grBackward :: VectorSpace v => GeoReference v crs -> Pixel v -> Point v crs grBackward gr = gtBackward (grTransform gr) {-# INLINE grBackward #-} mkGeoReference :: Extent V2 crs -> Size V2 -> Either String (GeoReference V2 crs) mkGeoReference e s = fmap (\gt -> GeoReference gt s) (northUpGeoTransform e s) newtype Point v crs = Point {_pointVertex:: Vertex v} deriving instance VectorSpace v => Show (Point v crs) deriving instance VectorSpace v => Eq (Point v crs) deriving instance VectorSpace v => Ord (Point v crs) deriving instance NFData (Vertex v) => NFData (Point v crs) deriving instance Hashable (Vertex v) => Hashable (Point v crs) deriving instance Storable (Vertex v) => Storable (Point v crs) class HasVertex o a | o->a where vertex :: Lens' o a class VectorSpace v => HasVertices a v | a->v where vertices :: Traversal a a (Vertex v) (Vertex v) instance HasVertex (Point v crs) (Vertex v) where vertex = lens coerce (const coerce) {-# INLINE vertex #-} instance HasVertex (WithSomeCrs (Point v)) (Vertex v) where vertex = lens (\(WithSomeCrs (Point v)) -> v) (\(WithSomeCrs p) v -> WithSomeCrs (p&vertex.~v)) {-# INLINE vertex #-} derivingUnbox "Point" [t| forall v crs. VectorSpace v => Point v crs -> Vertex v |] [| coerce |] [| coerce |] derivingUnbox "Extent" [t| forall v crs. VectorSpace v => Extent v crs -> (Vertex v,Vertex v) |] [| \(Extent e0 e1) -> (e0,e1) |] [| \(e0,e1) -> Extent e0 e1 |] derivingUnbox "Pixel" [t| forall v. VectorSpace v => Pixel v -> Vertex v |] [| coerce |] [| coerce |] derivingUnbox "Offset" [t| forall t. Offset (t :: OffsetType) -> Int |] [| coerce |] [| coerce |] newtype MultiPoint v crs = MultiPoint { _multiPointPoints :: U.Vector (Point v crs) } deriving (Eq, Show) makeFields ''MultiPoint deriving instance VectorSpace v => NFData (MultiPoint v crs) newtype LinearRing v crs = LinearRing {_linearRingPoints :: U.Vector (Point v crs)} deriving (Eq, Show) makeFields ''LinearRing deriving instance VectorSpace v => NFData (LinearRing v crs) newtype LineString v crs = LineString {_lineStringPoints :: U.Vector (Point v crs)} deriving (Eq, Show) makeFields ''LineString deriving instance VectorSpace v => NFData (LineString v crs) newtype MultiLineString v crs = MultiLineString { _multiLineStringLineStrings :: V.Vector (LineString v crs) } deriving (Eq, Show) makeFields ''MultiLineString deriving instance VectorSpace v => NFData (MultiLineString v crs) data Triangle v crs = Triangle !(Point v crs) !(Point v crs) !(Point v crs) deriving (Eq, Show) instance VectorSpace v => NFData (Triangle v crs) where rnf (Triangle a b c) = rnf a `seq` rnf b `seq` rnf c `seq` () derivingUnbox "Triangle" [t| forall v crs. VectorSpace v => Triangle v crs -> (Point v crs, Point v crs, Point v crs) |] [| \(Triangle a b c) -> (a, b, c) |] [| \(a, b, c) -> Triangle a b c|] data Polygon v crs = Polygon { _polygonOuterRing :: !(LinearRing v crs) , _polygonInnerRings :: !(V.Vector (LinearRing v crs)) } deriving (Eq, Show) makeFields ''Polygon instance VectorSpace v => NFData (Polygon v crs) where rnf (Polygon o r) = rnf o `seq` rnf r `seq` () newtype MultiPolygon v crs = MultiPolygon { _multiPolygonPolygons :: V.Vector (Polygon v crs) } deriving (Eq, Show) makeFields ''MultiPolygon deriving instance VectorSpace v => NFData (MultiPolygon v crs) newtype PolyhedralSurface v crs = PolyhedralSurface { _polyhedralSurfacePolygons :: V.Vector (Polygon v crs) } deriving (Eq, Show) makeFields ''PolyhedralSurface deriving instance VectorSpace v => NFData (PolyhedralSurface v crs) newtype TIN v crs = TIN { _tINTriangles :: U.Vector (Triangle v crs) } deriving (Eq, Show) makeFields ''TIN deriving instance VectorSpace v => NFData (TIN v crs) data Geometry v crs = GeoPoint !(Point v crs) | GeoMultiPoint !(MultiPoint v crs) | GeoLineString !(LineString v crs) | GeoMultiLineString !(MultiLineString v crs) | GeoPolygon !(Polygon v crs) | GeoMultiPolygon !(MultiPolygon v crs) | GeoTriangle !(Triangle v crs) | GeoPolyhedralSurface !(PolyhedralSurface v crs) | GeoTIN !(TIN v crs) | GeoCollection !(GeometryCollection v crs) deriving (Eq, Show) instance VectorSpace v => NFData (Geometry v crs) where rnf (GeoPoint g) = rnf g rnf (GeoMultiPoint g) = rnf g rnf (GeoLineString g) = rnf g rnf (GeoMultiLineString g) = rnf g rnf (GeoPolygon g) = rnf g rnf (GeoMultiPolygon g) = rnf g rnf (GeoTriangle g) = rnf g rnf (GeoPolyhedralSurface g) = rnf g rnf (GeoTIN g) = rnf g rnf (GeoCollection g) = rnf g newtype GeometryCollection v crs = GeometryCollection { _geometryCollectionGeometries :: V.Vector (Geometry v crs) } deriving (Eq, Show) makeFields ''GeometryCollection makePrisms ''Geometry deriving instance VectorSpace v => NFData (GeometryCollection v crs) mkLineString :: VectorSpace v => [Point v crs] -> Maybe (LineString v crs) mkLineString ls | U.length v >= 2 = Just $ LineString v | otherwise = Nothing where v = U.fromList ls mkLinearRing :: VectorSpace v => [Point v crs] -> Maybe (LinearRing v crs) mkLinearRing ls | U.length v >= 4, U.last v == U.head v = Just $ LinearRing v | otherwise = Nothing where v = U.fromList ls mkPolygon :: [LinearRing v crs] -> Maybe (Polygon v crs) mkPolygon (oRing:rings_) = Just $ Polygon oRing $ V.fromList rings_ mkPolygon _ = Nothing mkTriangle :: VectorSpace v => Point v crs -> Point v crs -> Point v crs -> Maybe (Triangle v crs) mkTriangle a b c | a/=b, b/=c, a/=c = Just $ Triangle a b c | otherwise = Nothing class HasCoordinates o a | o -> a where coordinates :: o -> a instance VectorSpace v => HasCoordinates (Point v crs) [Double] where coordinates = views vertex coords {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (MultiPoint v crs) [[Double]] where coordinates = views points (G.toList . V.map coordinates . G.convert) {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (LineString v crs) [[Double]] where coordinates = views points coordinates {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (MultiLineString v crs) [[[Double]]] where coordinates = views lineStrings (G.toList . G.map coordinates) {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (LinearRing v crs) [[Double]] where coordinates = views points coordinates {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (Polygon v crs) [[[Double]]] where coordinates = V.toList . V.map coordinates . polygonRings {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (MultiPolygon v crs) [[[[Double]]]] where coordinates = views polygons (G.toList . G.map coordinates) {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (PolyhedralSurface v crs) [[[[Double]]]] where coordinates = views polygons (G.toList . G.map coordinates) {-# INLINE coordinates #-} polygonRings :: Polygon v crs -> V.Vector (LinearRing v crs) polygonRings (Polygon ir rs) = V.cons ir rs {-# INLINE polygonRings #-} instance VectorSpace v => HasCoordinates (Triangle v crs) [[Double]] where coordinates (Triangle a b c) = map coordinates [a, b, c, a] {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (TIN v crs) [[[Double]]] where coordinates = views triangles (V.toList . V.map coordinates . G.convert) {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (U.Vector (Point v crs)) [[Double]] where coordinates = V.toList . V.map coordinates . V.convert {-# INLINE coordinates #-} instance VectorSpace v => HasCoordinates (V.Vector (Point v crs)) [[Double]] where coordinates = V.toList . V.map coordinates {-# INLINE coordinates #-} -- | A feature of 'GeometryType' t, vertex type 'v' and associated data 'd' data Feature (g :: * -> *) d crs = Feature { _featureGeometry :: g crs , _featureProperties :: d } deriving (Eq, Show) makeFields ''Feature makeLenses ''Feature instance HasProperties (WithSomeCrs (Feature g d)) d where properties = lens (\(WithSomeCrs f) -> f^.properties) (\(WithSomeCrs f) p -> WithSomeCrs (f & properties .~ p)) instance HasGeometry (WithSomeCrs (Feature g d)) (WithSomeCrs g) where geometry = lens (\(WithSomeCrs f) -> WithSomeCrs (f^.geometry)) (\(WithSomeCrs (Feature _ p)) (WithSomeCrs g) -> WithSomeCrs (Feature g p)) instance (NFData d, NFData (g crs)) => NFData (Feature g d crs) where rnf (Feature g v) = rnf g `seq` rnf v `seq` () derivingUnbox "UnboxFeature" [t| forall g crs a. (U.Unbox a, U.Unbox (g crs)) => Feature g a crs -> (g crs, a) |] [| \(Feature p v) -> (p,v) |] [| \(p,v) -> Feature p v|] newtype FeatureCollection (g :: * -> *) d crs = FeatureCollection { _featureCollectionFeatures :: [Feature g d crs] } deriving (Eq, Show) makeFields ''FeatureCollection makeLenses ''FeatureCollection instance Monoid (FeatureCollection g d crs) where mempty = FeatureCollection mempty mappend = (<>) instance Semigroup (FeatureCollection g d crs) where FeatureCollection as <> FeatureCollection bs = FeatureCollection (as <> bs) instance VectorSpace v => HasVertices (FeatureCollection (Point v) d crs) v where vertices = features.traverse.geometry.vertex data Raster vs (t :: OffsetType) crs v a = Raster { rGeoReference :: !(GeoReference vs crs) , rData :: !(v a) } deriving (Eq, Show) instance (NFData (v a), VectorSpace vs) => NFData (Raster vs t crs v a) where rnf (Raster a b) = rnf a `seq` rnf b `seq` () rasterSize :: VectorSpace v => Extent v crs -> Vertex v -> Size v rasterSize e pxSize = Size $ fmap ceiling (eSize e / pxSize) {-# INLINE rasterSize #-} generateMRaster :: forall m v a vs t crs. (PrimMonad m, GM.MVector v a, HasOffset vs t) => GeoReference vs crs -> (Point vs crs -> a) -> m (Raster vs t crs (v (PrimState m)) a) generateMRaster geoRef fun = do v <- GM.new sz loop v (sz-1) return (Raster geoRef v) where sz = grScalarSize geoRef loop v !i | i<0 = return () loop v !i = let !px = unsafeFromOffset (grSize geoRef) (Offset i :: Offset t) !p = grBackward geoRef px in GM.unsafeWrite v i (fun p) >> loop v (i-1) {-# INLINE generateMRaster #-} rasterIndex :: forall vs t crs v a. (HasOffset vs t) => Raster vs t crs v a -> Point vs crs -> Maybe Int rasterIndex r p = fmap unOff offset where offset = pointOffset (rGeoReference r) p :: Maybe (Offset t) {-# INLINE rasterIndex #-} unsafeRasterIndex :: forall vs t crs v a. (HasOffset vs t) => Raster vs t crs v a -> Point vs crs -> Int unsafeRasterIndex r p = unOff offset where offset = unsafePointOffset (rGeoReference r) p :: Offset t {-# INLINE unsafeRasterIndex #-} rasterIndexPixel :: forall vs t crs v a. (HasOffset vs t) => Raster vs t crs v a -> Pixel vs -> Maybe Int rasterIndexPixel r px = fmap unOff offset where offset = toOffset (grSize (rGeoReference r)) px :: Maybe (Offset t) {-# INLINE rasterIndexPixel #-} unsafeRasterIndexPixel :: forall vs t crs v a. (HasOffset vs t) => Raster vs t crs v a -> Pixel vs -> Int unsafeRasterIndexPixel r px = unOff offset where offset = unsafeToOffset (grSize (rGeoReference r)) px :: Offset t {-# INLINE unsafeRasterIndexPixel #-} convertRasterOffsetType :: forall vs t1 t2 crs v a. (G.Vector v a, HasOffset vs t1, HasOffset vs t2) => Raster vs t1 crs v a -> Raster vs t2 crs v a convertRasterOffsetType r = r {rData = G.generate n go} where go i = let px = unsafeFromOffset s (Offset i :: Offset t2) Offset i' = unsafeToOffset s px :: Offset t1 in rd `G.unsafeIndex` i' s = grSize (rGeoReference r) rd = rData r n = G.length rd
meteogrid/sigym4-geometry
src/Sigym4/Geometry/Types.hs
bsd-3-clause
27,024
1
15
6,766
5,324
2,880
2,444
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} module Duckling.Rules.NL ( defaultRules , langRules , localeRules ) where import Prelude import Duckling.Dimensions.Types import Duckling.Locale import Duckling.Types import qualified Duckling.AmountOfMoney.NL.Rules as AmountOfMoney import qualified Duckling.Distance.NL.Rules as Distance import qualified Duckling.Duration.NL.Rules as Duration import qualified Duckling.Numeral.NL.Rules as Numeral import qualified Duckling.Ordinal.NL.Rules as Ordinal import qualified Duckling.Quantity.NL.Rules as Quantity import qualified Duckling.Time.NL.Rules as Time import qualified Duckling.Time.NL.BE.Rules as TimeBE import qualified Duckling.Time.NL.NL.Rules as TimeNL import qualified Duckling.TimeGrain.NL.Rules as TimeGrain import qualified Duckling.Volume.NL.Rules as Volume defaultRules :: Seal Dimension -> [Rule] defaultRules dim@(Seal Time) = TimeNL.rulesBackwardCompatible ++ langRules dim defaultRules dim = langRules dim localeRules :: Region -> Seal Dimension -> [Rule] localeRules region (Seal (CustomDimension dim)) = dimLocaleRules region dim localeRules BE (Seal Time) = TimeBE.rules localeRules _ _ = [] langRules :: Seal Dimension -> [Rule] langRules (Seal AmountOfMoney) = AmountOfMoney.rules langRules (Seal CreditCardNumber) = [] langRules (Seal Distance) = Distance.rules langRules (Seal Duration) = Duration.rules langRules (Seal Email) = [] langRules (Seal Numeral) = Numeral.rules langRules (Seal Ordinal) = Ordinal.rules langRules (Seal PhoneNumber) = [] langRules (Seal Quantity) = Quantity.rules langRules (Seal RegexMatch) = [] langRules (Seal Temperature) = [] langRules (Seal Time) = Time.rules langRules (Seal TimeGrain) = TimeGrain.rules langRules (Seal Url) = [] langRules (Seal Volume) = Volume.rules langRules (Seal (CustomDimension dim)) = dimLangRules NL dim
facebookincubator/duckling
Duckling/Rules/NL.hs
bsd-3-clause
2,035
0
9
264
563
324
239
44
1
module Vulkan.Utils.ShaderQQ.Backend.Shaderc ( ShadercError , ShadercWarning , processShadercMessages ) where import Control.Monad ( void ) import qualified Data.ByteString.Lazy.Char8 as BSL import Data.Foldable ( asum ) import Text.ParserCombinators.ReadP type ShadercError = String type ShadercWarning = String processShadercMessages :: BSL.ByteString -> ([ShadercWarning], [ShadercError]) processShadercMessages = foldMap parseMsg . lines . BSL.unpack -- >>> parseMsg "blah" -- ([],[]) -- -- >>> parseMsg "blah" -- ([],["blah"]) -- -- >>> parseMsg "foo:2: error: unknown var" -- ([],["foo:2: unknown var"]) -- -- >>> parseMsg "foo:2: warning: unknown var" -- (["foo:2: unknown var"],[]) -- -- >>> parseMsg "bar:2: error: 'a' : unknown variable" -- ([],["bar:2: 'a' : unknown variable"]) -- -- >>> parseMsg "f:o: error: f:o:2: 'a' : unknown variable" -- ([],["f:o:2: 'a' : unknown variable"]) -- -- >>> parseMsg "f:o: error: f:o:2: 'return' : type does not match, or is not convertible to, the function's return type" -- ([],["f:o:2: 'return' : type does not match, or is not convertible to, the function's return type"]) -- -- >>> parseMsg "foo: foo(1): error at column 3, HLSL parsing failed." -- ([],["foo:1: error at column 3, HLSL parsing failed."]) parseMsg :: String -> ([ShadercWarning], [ShadercError]) parseMsg = runParser $ foldl1 (<++) [ do f <- filename line <- between colon colon number skipSpaces t <- msgType msg <- manyTill get eof pure $ formatMsg t f line msg , do f <- filename colon *> skipSpaces t <- msgType _ <- string f line <- between (char ':') (char ':') number skipSpaces msg <- manyTill get eof pure $ formatMsg t f line msg , do f <- filename colon *> skipSpaces _ <- string f line <- between (char '(') (char ')') number colon *> skipSpaces let t x = ([], [x]) msg <- manyTill get eof pure $ formatMsg t f line msg , do _ <- number skipSpaces _ <- string "errors generated" eof pure ([], []) , do -- Unknown format msg <- manyTill get eof eof pure ([], [msg]) ] where formatMsg t f line msg = t (f <> ":" <> show line <> ": " <> msg) filename = many1 get number = readS_to_P (reads @Integer) colon = void $ char ':' msgType = asum [ (\x -> ([], [x])) <$ string "error" , (\x -> ([x], [])) <$ string "warning" ] <* colon <* skipSpaces runParser :: Monoid p => ReadP p -> String -> p runParser p s = case readP_to_S p s of [(r, "")] -> r _ -> mempty
expipiplus1/vulkan
utils/src/Vulkan/Utils/ShaderQQ/Backend/Shaderc.hs
bsd-3-clause
2,683
0
15
711
725
381
344
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# OPTIONS -fno-warn-orphans #-} module Wishlist.Utils where import Control.Monad.Except import Prelude hiding (log) import Servant.API import Wishlist.Types.Common instance Show a => Show (Headers ls a) where show (Headers x _headers) = show x log :: Show a => String -> Controller' st a -> Controller' st a log msg action = do liftIO $ putStrLn $ "> " ++ msg ++ "..." val <- action `catchError` printError liftIO $ putStrLn $ "< " ++ show val return val where printError err = do liftIO $ putStrLn $ "ERROR: " ++ show err throwError err logWith :: (Show a, Show b) => String -> a -> Controller' st b -> Controller' st b logWith msg val action = log (msg ++ " " ++ show val) action
bollmann/lunchtalk
src/Wishlist/Utils.hs
bsd-3-clause
754
0
11
165
279
139
140
21
1
-------------------------------------------------------------------------------- -- | -- Module : Language.Verilog.PrettyPrint -- Copyright : (c) Signali Corp. 2010 -- License : All rights reserved -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (DeriveDataTypeable) -- -- A pretty printer for the Verilog AST. -------------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module Language.Verilog.PrettyPrint where import Data.Maybe ( fromMaybe ) import Text.PrettyPrint import Language.Verilog.Syntax -- ----------------------------------------------------------------------------- -- some utilities, which should go in a common module elsewhere commasep :: [Doc] -> Doc commasep = vcat . punctuate comma lineParens :: Doc -> Doc lineParens p = char '(' $$ p <> char '\n' <> char ')' mb :: (x -> Doc) -> Maybe x -> Doc mb = maybe empty period :: Doc period = char '.' tick :: Doc tick = char '\'' -- ----------------------------------------------------------------------------- -- 1. Source Text ppVerilog :: Verilog -> Doc ppVerilog (Verilog ds) = vcat (map ppDescription ds) ppDescription :: Description -> Doc ppDescription (ModuleDescription m) = ppModule m ppDescription (UDPDescription udp) = ppUDP udp ppModule :: Module -> Doc ppModule (Module name mb_paras ports body) = text "module" <+> ppIdent name $$ mb ppParas mb_paras $$ ppPorts ports <> semi <> char '\n' $$ vcat (map ppItem body) $$ text "endmodule" <> char '\n' ppPorts :: [PortDecl] -> Doc ppPorts [] = empty ppPorts x = lineParens $ commasep $ map (ppPortDecl (getMaxLen x)) x where ppPortDecl l (PortDecl dir mb_type mb_range name c) = ppItem c <> text (ppPortSub dir mb_type mb_range) <+> text (replicate (l - length (ppPortSub dir mb_type mb_range)) ' ') <+> ppIdent name ppPortSub dir mb_type mb_range = render (ppPortDir dir <+> maybe (text "wire") ppPortType mb_type <+> mb ppRange mb_range) ppPortSubDecl (PortDecl dir mb_type mb_range name c) = render (ppPortDir dir <+> maybe (text "wire") ppPortType mb_type <+> mb ppRange mb_range) getMaxLen xs = (maximum (map length $ map ppPortSubDecl xs)) ppParas :: [ParamDecl] -> Doc ppParas [] = empty ppParas paras = char '#' <> ppParaList paras where ppParaList = lineParens . commasep . map ppParamDecl0 ppPortDir :: PortDir -> Doc ppPortDir (PortDir dir) = text (show dir) ppPortType :: PortType -> Doc ppPortType (PortType t) = text (show t) ppItem :: Item -> Doc ppItem (ParamDeclItem x) = char '\n' <> ppParamDecl x ppItem (InputDeclItem x) = ppInputDecl x ppItem (OutputDeclItem x) = ppOutputDecl x ppItem (InOutDeclItem x) = ppInOutDecl x ppItem (NetDeclItem x) = ppNetDecl x ppItem (RegDeclItem x) = ppRegDecl x ppItem (EventDeclItem x) = ppEventDecl x ppItem (LocalParamItem x) = char '\n' <> ppLocalParam x ppItem (PrimitiveInstItem x) = char '\n' <> ppPrimitiveInst x ppItem (InstanceItem x) = char '\n' <> ppInstance x ppItem (ParamOverrideItem xs) = text "defparam" <+> ppParamAssigns xs <> semi ppItem (AssignItem mb_strength mb_delay assignments) = text "assign" <+> mb ppDriveStrength mb_strength <+> mb ppDelay mb_delay <+> commasep (map ppAssignment assignments) <> semi ppItem (InitialItem (EventControlStmt ctrl stmt)) = char '\n' <> fsep [ text "initial", ppEventControl ctrl, nest 2 (maybe semi ppStatement stmt) ] ppItem (InitialItem stmt) = char '\n' <> fsep [ text "initial", nest 2 (ppStatement stmt) ] ppItem (AlwaysItem (EventControlStmt ctrl stmt)) = char '\n' <> fsep [ text "always", ppEventControl ctrl, (maybe semi ppStatement stmt) ] ppItem (AlwaysItem stmt) = char '\n' <> fsep [ text "always", nest 2 (ppStatement stmt) ] ppItem (TaskItem name decls stmt) = char '\n' <> text "task" <+> ppIdent name <> semi $$ nest 2 (vcat (map ppLocalDecl decls) $$ ppStatement stmt) $$ text "endtask" ppItem (FunctionItem t name decls stmt) = char '\n' <> text "function" <+> mb ppFunctionType t <+> ppIdent name <> semi $$ nest 2 (vcat (map ppLocalDecl decls) $$ ppStatement stmt) $$ text "endfunction" -- (copied from andy's code in GenVHDL) -- TODO: get multline working ppItem (CommentItem msg) = vcat [ text "//" <> text m | m <- lines msg ] ppItem (GenerateDeclItem g) = char '\n' <> ppStatement g ppItem (GenVarItem s) = ppGenVar s ppGenVar :: [Ident] -> Doc ppGenVar s = text "genvar" <+> vcat (map ppIdent s) <> semi ppUDP :: UDP -> Doc ppUDP (UDP name output_var input_vars decls maybe_initial table_definition) = text "primitive" <+> ppIdent name <+> parens (ppIdents (output_var : input_vars)) <> semi $$ nest 2 ( vcat (map ppUDPDecl decls) $$ maybe empty ppUDPInitialStatement maybe_initial $$ ppTableDefinition table_definition ) $$ text "endprimitive" ppUDPDecl :: UDPDecl -> Doc ppUDPDecl (UDPOutputDecl d) = ppOutputDecl d ppUDPDecl (UDPInputDecl d) = ppInputDecl d ppUDPDecl (UDPRegDecl x) = text "reg" <+> ppIdent x <> semi ppUDPInitialStatement :: UDPInitialStatement -> Doc ppUDPInitialStatement (UDPInitialStatement name value) = text "initial" <+> ppIdent name <+> equals <+> ppExpr value <> semi ppTableDefinition :: TableDefinition -> Doc ppTableDefinition table = text "table" $$ nest 2 (vcat xs) $$ text "endtable" where xs = case table of CombinationalTable entries -> map ppCombinationalEntry entries SequentialTable entries -> map ppSequentialEntry entries ppCombinationalEntry :: CombinationalEntry -> Doc ppCombinationalEntry (CombinationalEntry inputs output) = hsep (map ppLevelSymbol inputs) <+> colon <+> ppOutputSymbol output <> semi ppSequentialEntry :: SequentialEntry -> Doc ppSequentialEntry (SequentialEntry inputs state next_state) = hsep (map (either ppLevelSymbol ppEdge) inputs) <+> colon <+> ppLevelSymbol state <+> colon <+> ppNextState next_state <> semi ppEdge :: Edge -> Doc ppEdge (EdgeLevels x y) = parens (ppLevelSymbol x <+> ppLevelSymbol y) ppEdge (EdgeSymbol x) = ppEdgeSymbol x ppOutputSymbol :: OutputSymbol -> Doc ppOutputSymbol x | validOutputSymbol x = char x | otherwise = error ("ppOutputSymbol: invalid character: " ++ [x]) ppLevelSymbol :: LevelSymbol -> Doc ppLevelSymbol x | validLevelSymbol x = char x | otherwise = error ("ppLevelSymbol: invalid character: " ++ [x]) ppNextState :: NextState -> Doc ppNextState x | validNextState x = char x | otherwise = error ("ppNextState: invalid character: " ++ [x]) ppEdgeSymbol :: EdgeSymbol -> Doc ppEdgeSymbol x | validEdgeSymbol x = char x | otherwise = error ("ppEdgeSymbol: invalid character: " ++ [x]) -- ----------------------------------------------------------------------------- -- 2. Declarations ppFunctionType :: FunctionType -> Doc ppFunctionType (FunctionTypeRange r) = ppRange r ppFunctionType FunctionTypeInteger = text "integer" ppFunctionType FunctionTypeReal = text "real" ppLocalDecl :: LocalDecl -> Doc ppLocalDecl (LocalParamDecl x) = ppParamDecl x ppLocalDecl (LocalInputDecl x) = ppInputDecl x ppLocalDecl (LocalOutputDecl x) = ppOutputDecl x ppLocalDecl (LocalInOutDecl x) = ppInOutDecl x ppLocalDecl (LocalRegDecl x) = ppRegDecl x ppParamDecl :: ParamDecl -> Doc ppParamDecl (ParamDecl paramAssigns) = text "parameter" <+> ppParamAssigns paramAssigns <> semi ppLocalParam :: LocalParam -> Doc ppLocalParam (LocalParam paramAssigns) = text "localparam" <+> ppParamAssigns paramAssigns <> semi ppParamDecl0 :: ParamDecl -> Doc ppParamDecl0 (ParamDecl paramAssigns) = text "parameter" <+> ppParamAssigns paramAssigns ppInputDecl :: InputDecl -> Doc ppInputDecl (InputDecl mb_range vars) = text "input" <+> mb ppRange mb_range <+> ppIdents vars <> semi ppOutputDecl :: OutputDecl -> Doc ppOutputDecl (OutputDecl mb_range vars) = text "output" <+> mb ppRange mb_range <+> ppIdents vars <> semi ppInOutDecl :: InOutDecl -> Doc ppInOutDecl (InOutDecl mb_range vars) = text "inout" <+> mb ppRange mb_range <+> ppIdents vars <> semi ppNetDecl :: NetDecl -> Doc ppNetDecl (NetDecl t mb_range mb_delay vars) = text (show t) <+> mb ppExpandRange mb_range <+> mb ppDelay mb_delay <+> ppIdents vars <> semi ppNetDecl (NetDeclAssign t mb_strength mb_range mb_delay assignments) = text (show t) <+> mb ppDriveStrength mb_strength <+> mb ppExpandRange mb_range <+> mb ppDelay mb_delay <+> commasep [ ppIdent x <+> equals <+> ppExpr e | (x, e) <- assignments ] <> semi ppRegDecl :: RegDecl -> Doc ppRegDecl (RegDecl reg_type mb_range vars) = text (show reg_type) <+> mb ppRange mb_range <+> ppRegVars vars <> semi ppRegVar :: RegVar -> Doc ppRegVar (RegVar x Nothing) = ppIdent x ppRegVar (RegVar x (Just e)) = ppIdent x <+> equals <+> ppExpr e ppRegVar (MemVar x r) = ppIdent x <+> ppRange r ppRegVars :: [RegVar] -> Doc ppRegVars = commasep . map ppRegVar ppEventDecl :: EventDecl -> Doc ppEventDecl (EventDecl vars) = text "event" <+> ppIdents vars <> semi -- ----------------------------------------------------------------------------- -- 3. Primitive Instances ppPrimitiveInst :: PrimitiveInst -> Doc ppPrimitiveInst (PrimitiveInst prim_type strength delay insts) = text (show prim_type) <+> mb ppDriveStrength strength <+> mb ppDelay delay <+> commasep (map ppPrimInst insts) <> semi ppPrimInst :: PrimInst -> Doc ppPrimInst (PrimInst prim_name es) = mb ppPrimName prim_name <+> parens (commasep (map ppExpr es)) ppPrimName :: PrimInstName -> Doc ppPrimName (PrimInstName x r) = ppIdent x <> mb ppRange r -- ----------------------------------------------------------------------------- -- 4. Module Instantiations ppInstance :: Instance -> Doc ppInstance (Instance name delays_or_params insts) = ppIdent name <+> ppDelaysOrParams delays_or_params <> char '\n' <> (ppInsts insts) <> semi ppDelaysOrParams :: Either [Expression] [Parameter] -> Doc ppDelaysOrParams (Left []) = empty ppDelaysOrParams (Right []) = empty ppDelaysOrParams (Left es) = char '\n' <> char '#' <> parens (commasep (map ppExpr es)) ppDelaysOrParams (Right ps) = char '\n' <> char '#' <> lineParens (commasep (map ppParameter ps)) ppParameter :: Parameter -> Doc ppParameter (Parameter x expr) = period <> ppIdent x <> parens (ppExpr expr) ppInsts :: [Inst] -> Doc ppInsts insts = vcat (punctuate comma (map ppInst insts)) ppInst :: Inst -> Doc ppInst (Inst x r cs) = ppIdent x <> mb ppRange r <> char '\n' <> lineParens (commasep ppCs) where ppCs = case cs of Connections exprs -> map ppExpr exprs NamedConnections ncs -> map ppNamedConnection ncs -- this is used for both port connections and parameter assignments ppNamedConnection :: NamedConnection -> Doc ppNamedConnection (NamedConnection x expr (CommentItem "")) = period <> ppIdent x <> parens (ppExpr expr) ppNamedConnection (NamedConnection x expr cs) = ppItem cs $$ period <> ppIdent x <> parens (ppExpr expr) -- ---------------------------------------------------------------------------- -- 5. Behavioral Statements ppStatement :: Statement -> Doc ppStatement (BlockingAssignment x ctrl expr) = ppLValue x <+> equals <+> mb ppAssignmentControl ctrl <+> ppExpr expr <> semi ppStatement (NonBlockingAssignment x ctrl expr) = ppLValue x <+> text "<=" <+> mb ppAssignmentControl ctrl <+> ppExpr expr <> semi -- we have to add a begin-end pair in order to avoid ambiguity, otherwise in the -- concrete syntax the else-branch (if2) will be associated with if1 instead of -- the outer if-statement. ppStatement (IfStmt expr (Just if1@IfStmt {}) (Just if2@IfStmt {})) = ppStatement (IfStmt expr (Just if1') (Just if2)) where if1' = SeqBlock Nothing [] [if1] ppStatement (IfStmt expr stmt1 stmt2) = (text "if" <+> parens (ppExpr expr)) `nestStmt` (maybe semi ppStatement stmt1) $$ case stmt2 of Just stmt -> ppElseBranch stmt Nothing -> empty where ppElseBranch (IfStmt e s1 s2) = (text "else if" <+> parens (ppExpr e)) `nestStmt` (maybe semi ppStatement s1) $$ case s2 of Just s -> ppElseBranch s Nothing -> empty ppElseBranch s = text "else" `nestStmt` ppStatement s ppStatement (CaseStmt case_type expr case_items) = text (show case_type) <+> parens (ppExpr expr) $$ nest 2 (vcat (map ppCaseItem case_items)) $$ text "endcase" ppStatement (ForeverStmt stmt) = text "forever" `nestStmt` ppStatement stmt ppStatement (RepeatStmt expr stmt) = (text "repeat" <+> parens (ppExpr expr)) `nestStmt` ppStatement stmt ppStatement (WhileStmt expr stmt) = (text "while" <+> parens (ppExpr expr)) `nestStmt` ppStatement stmt ppStatement (ForStmt init_assign expr_cond loop_assign stmt) = x $$ nest 2 (ppStatement stmt) where x = text "for" <+> parens (ppAssignment init_assign <> semi <+> ppExpr expr_cond <> semi <+> ppAssignment loop_assign) ppStatement (DelayStmt delay mb_stmt) = ppDelay delay <+> maybe semi ppStatement mb_stmt ppStatement (EventControlStmt ctrl mb_stmt) = case mb_stmt of Just stmt -> ppEventControl ctrl <> char '\n' <> ppStatement stmt Nothing -> ppEventControl ctrl <> semi ppStatement (WaitStmt expr stmt) = (text "wait" <+> parens (ppExpr expr)) `nestStmt` maybe semi ppStatement stmt ppStatement (SeqBlock mb_name decls stmts) = text "begin" <+> x $$ nest 2 (vcat (map ppBlockDecl decls ++ map ppStatement stmts)) $$ text "end" where x = case mb_name of Just name -> colon <+> ppIdent name Nothing -> empty ppStatement (ParBlock mb_name decls stmts) = text "fork" <+> x $$ nest 2 (vcat (map ppBlockDecl decls ++ map ppStatement stmts)) $$ text "join" where x = case mb_name of Just name -> colon <+> ppIdent name Nothing -> empty ppStatement (TaskStmt x mb_es) = char '$' <> ppIdent x <> maybe empty (parens . commasep . map ppExpr) mb_es <> semi ppStatement (TaskEnableStmt name exprs) | null exprs = ppIdent name <> semi | otherwise = ppIdent name <+> parens (commasep (map ppExpr exprs)) {- ppStatement (SystemTaskEnableStmt name exprs) | null exprs = char '$' <> ppIdent name <> semi | otherwise = char '$' <> ppIdent name <+> parens (commasep (map ppExpr exprs)) -} ppStatement (DisableStmt name) = text "disable" <+> ppIdent name <> semi ppStatement (AssignStmt assignment) = text "assign" <+> ppAssignment assignment <> semi ppStatement (DeAssignStmt x) = text "deassign" <+> ppLValue x <> semi ppStatement (ForceStmt assignment) = text "force" <+> ppAssignment assignment <> semi ppStatement (ReleaseStmt x) = text "release" <+> ppLValue x <> semi ppStatement (GenForStmt gvs fs) = text "generate" <> char '\n' <> vcat (map ppItem gvs) <> char '\n' <> vcat (map ppStatement fs) <> char '\n' <> text "endgenerate" ppStatement (GenIfStmt vs) = text "generate" $$ vcat (map ppStatement vs) $$ text "endgenerate" ppStatement (ItemStmt it) = ppItem it -- a helper for pretty-printing statement. 'fsep' chooses whether to put the -- statement on the same line as 'x', or nest it on the next line if it doesn't -- fit on the same line. nestStmt :: Doc -> Doc -> Doc nestStmt x stmt = fsep [x, nest 2 stmt ] ppAssignment :: Assignment -> Doc ppAssignment (Assignment x expr) = ppLValue x <+> equals <+> ppExpr expr ppCaseItem :: CaseItem -> Doc ppCaseItem (CaseItem es mb_stmt) = fsep [ commasep (map ppExpr es) <+> colon, maybe semi ppStatement mb_stmt ] ppCaseItem (CaseDefault mb_stmt) = fsep [ text "default" <+> colon, maybe semi ppStatement mb_stmt ] ppBlockDecl :: BlockDecl -> Doc ppBlockDecl (ParamDeclBlock x) = ppParamDecl x ppBlockDecl (RegDeclBlock x) = ppRegDecl x ppBlockDecl (EventDeclBlock x) = ppEventDecl x -- ----------------------------------------------------------------------------- -- 7. Expressions ppLValue :: LValue -> Doc ppLValue = ppExpr ppExpr :: Expression -> Doc ppExpr = ppExpr' 0 -- precedence-aware expression pretty printer - adds parens when it needs to ppExpr' :: Int -> Expression -> Doc ppExpr' _ (ExprNum x) = text (show x) ppExpr' _ (ExprVar x) = ppIdent x ppExpr' _ (ExprString x) = text (show x) ppExpr' _ (ExprIndex x expr) = ppIdent x <> brackets (ppExpr expr) ppExpr' _ (ExprSlice x e1 e2) = ppIdent x <> brackets (ppExpr e1 <> colon <> ppExpr e2) ppExpr' _ (ExprSlicePlus x e1 e2) = ppIdent x <> brackets (ppExpr e1 <> text "+:" <> ppExpr e2) ppExpr' _ (ExprSliceMinus x e1 e2) = ppIdent x <> brackets (ppExpr e1 <> text "-:" <> ppExpr e2) ppExpr' _ (ExprConcat es) = braces (commasep (map ppExpr es)) ppExpr' _ (ExprMultiConcat e es) = braces (ppExpr e <> braces (commasep (map ppExpr es))) ppExpr' prec (ExprUnary op expr) = if prec >= unary_prec then parens e else e where e = text x <> ppExpr' unary_prec expr x = lookupOp op unary_op_table ppExpr' prec (ExprBinary op expr1 expr2) = if prec > op_prec then parens e else e where e = fsep [ppExpr' op_prec expr1, text x, ppExpr' (op_prec + 1) expr2 ] (x, op_prec) = lookupOp op binary_op_table -- this adds unnecessary parens, but it makes the concrete syntax much easier to -- read {- ppExpr' prec (ExprCond e1 e2 e3) = if prec > cond_prec then parens x else x where x = fsep [ pp e1, char '?', pp e2, colon, pp e3 ] pp e | add_parens e = parens (ppExpr e) | otherwise = ppExpr e add_parens :: Expression -> Bool add_parens ExprCond{} = True add_parens _ = False -} ppExpr' prec (ExprCond e1 e2 e3) = if prec > cond_prec then parens e else e where e = fsep [ ppExpr e1, char '?', ppExpr e2, colon, ppExpr e3 ] ppExpr' _ (ExprFunCall x es) = ppIdent x <+> parens (commasep (map ppExpr es)) cond_prec, unary_prec :: Int cond_prec = 1 unary_prec = 11 lookupOp :: (Eq op, Show op) => op -> [(op, x)] -> x lookupOp op table = fromMaybe (error msg) (lookup op table) where msg = "showOp: cannot find operator: " ++ show op -- precedence tables, also for showing. -- these tables could also be used for parsing operators. unary_op_table :: [(UnaryOp, String)] unary_op_table = [ (UPlus, "+"), (UMinus, "-"), (UBang, "!"), (UTilde, "~") , (UAnd, "&"), (UNand, "~&"), (UOr, "|"), (UNor, "~|") , (UXor, "^"), (UXnor, "~^"), (UXnor, "^~") ] binary_op_table :: [(BinaryOp, (String, Int))] binary_op_table = [ (LOr, ("||", 2)) , (LAnd, ("&&", 3)) , (Or, ("|", 4)), (Nor, ("~|", 4)) , (And, ("&", 5)), (Nand, ("~&", 5)), (Xor, ("^", 5)), (Xnor, ("^~", 5)), (Xnor, ("~^", 5)) , (Equals, ("==", 6)), (NotEquals, ("!=", 6)), (CEquals, ("===", 6)), (CNotEquals, ("!==", 6)) , (LessThan, ("<", 7)), (LessEqual, ("<=", 7)), (GreaterThan, (">", 7)), (GreaterEqual, (">=", 7)) , (ShiftLeft, ("<<", 8)), (ShiftRight, (">>", 8)) , (Plus, ("+", 9)), (Minus, ("-", 9)) , (Times, ("*", 10)), (Divide, ("/", 10)), (Modulo, ("%", 10)) ] -- ----------------------------------------------------------------------------- -- Miscellaneous ppParamAssigns :: [ParamAssign] -> Doc ppParamAssigns paramAssigns = commasep (map ppParamAssign paramAssigns) ppParamAssign :: ParamAssign -> Doc ppParamAssign (ParamAssign ident expr) = ppIdent ident <+> equals <+> ppExpr expr ppExpandRange :: ExpandRange -> Doc ppExpandRange (SimpleRange r) = ppRange r ppExpandRange (ScalaredRange r) = text "scalared" <+> ppRange r ppExpandRange (VectoredRange r) = text "vectored" <+> ppRange r ppRange :: Range -> Doc ppRange (Range e1 e2) = brackets (ppExpr e1 <> colon <> ppExpr e2) ppAssignmentControl :: AssignmentControl -> Doc ppAssignmentControl (DelayControl delay) = ppDelay delay ppAssignmentControl (EventControl ctrl) = ppEventControl ctrl ppAssignmentControl (RepeatControl e ctrl) = text "repear" <> parens (ppExpr e) <+> ppEventControl ctrl ppDelayControl :: DelayControl -> Doc ppDelayControl = ppDelay ppEventControl :: EventControl -> Doc ppEventControl ctrl = char '@' <> case ctrl of EventControlIdent x -> parens $ commasep (map ppIdent x) EventControlExpr e -> parens $ commasep (map ppEventExpr e) EventControlWildCard -> text "(*)" ppDelay :: Delay -> Doc ppDelay x = char '#' <> ppExpr x ppEventExpr :: EventExpr -> Doc ppEventExpr (EventExpr expr) = ppExpr expr ppEventExpr (EventPosedge expr) = text "posedge" <+> ppExpr expr ppEventExpr (EventNegedge expr) = text "negedge" <+> ppExpr expr ppEventExpr (EventOr expr1 expr2) = ppEventExpr expr1 <+> text "or" <+> ppEventExpr expr2 -- TODO: check if the string is a valid Verilog identifier. -- throw error, or convert it into a valid identifier. ppIdent :: Ident -> Doc ppIdent (Ident x) = text x ppIdents :: [Ident] -> Doc ppIdents = commasep . map ppIdent ppDriveStrength :: DriveStrength -> Doc ppDriveStrength (Strength01 s0 s1) = parens (ppStrength0 s0 <> comma <+> ppStrength1 s1) ppDriveStrength (Strength10 s1 s0) = parens (ppStrength1 s1 <> comma <+> ppStrength0 s0) ppStrength0 :: Strength0 -> Doc ppStrength0 = text . show ppStrength1 :: Strength1 -> Doc ppStrength1 = text . show -- -----------------------------------------------------------------------------
githubkleon/ConvenientHDL
src/Language/Verilog/PrettyPrint.hs
bsd-3-clause
21,608
0
16
4,378
7,164
3,580
3,584
452
7
{-# LANGUAGE TemplateHaskell #-} module Test where import Data.Type.Equality import Type import TH _3_4_5 :: Triangle (Succ (Succ (Succ Zero))) (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ (Succ (Succ Zero))))) _3_4_5 = Refl -- Doesn't typecheck. -- _0_4_5 :: -- Triangle Zero -- (Succ (Succ (Succ (Succ Zero)))) -- (Succ (Succ (Succ (Succ (Succ Zero))))) -- _0_4_5 = Refl -- Inferred type: -- 'True :~: 'True _3_4_5' = $(triangle 3 4 5) -- Which is the same as: _3_4_5'' :: Triangle (Succ (Succ (Succ Zero))) (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ (Succ (Succ Zero))))) _3_4_5'' = $(triangle 3 4 5) -- Doesn't typecheck (as before). -- _0_4_5 = $(triangle 0 4 5)
nkaretnikov/triangle-inequality
src/Test.hs
bsd-3-clause
762
0
15
195
233
126
107
16
1
module Internal where import Data.Aeson.TH (Options(..), defaultOptions) import Data.Char (toLower) resultOptions :: Options resultOptions = defaultOptions { fieldLabelModifier = drop 7 } rpcOptions :: Options rpcOptions = defaultOptions { fieldLabelModifier = map toLower . drop 4 }
aspidites/aurse
src/Internal.hs
bsd-3-clause
301
0
8
54
81
48
33
11
1
module Main where import BivarInterpolNewtonSpec as BINS import BodeShootingSpec as BSS import EigenPowerSpec as EPS import FunctionSpec as FS import HeatExplicitSpec as HES import LibrarySpec as LS import ParserSpec as PS import RectIntegralSpec as RIS import SlaeGaussSpec as SGS import SnlaePicardSpec as SPS import SodeRungeKuttaSpec as SRKS import StringifySpec as SS import Test.Hspec main :: IO () main = hspec $ do PS.suite SS.suite LS.suite FS.suite SGS.suite BINS.suite SPS.suite RIS.suite EPS.suite SRKS.suite BSS.suite HES.suite
hrsrashid/nummet
tests/Spec.hs
bsd-3-clause
797
0
8
330
148
88
60
28
1
{-# LANGUAGE BangPatterns #-} module Interpretor ( eval ) where import qualified Data.Map as M import Control.Monad import Control.Monad.Error import Data.Maybe import ParserTypes import Environment import Builtins -- |Evaluate an expression in a certain environment. eval :: Env -> Expr -> ThrowError Expr eval env (AppExpr f s) = --apply env f s do s' <- eval env s apply env f s' --eval env le@(ListExpr es) = return le --liftM ListExpr $ mapM (eval env) es eval env (VarExpr n) = do mEntry <- return $ findEntry env n case mEntry of (Just (SymBinding expr)) -> eval env expr (Just (SymFunc func)) -> return $ FuncCtx (Defined (funcArgCount func) func) [] Nothing -> do case M.lookup n builtins of Just b -> return $ FuncCtx b [] Nothing -> throwError $ SymbolNotFound (n) -- ^ A conditional expression eval env (CondExpr fact alt1 alt2) = do case holds env fact of Left error -> throwError error Right True -> eval env alt1 Right False -> eval env alt2 eval env (LetExpr name definition expr) = do def <- eval env definition computed <- (subs expr name def) eval env computed eval env e | isAtom e = return $ e -- cannot reduce further | otherwise = return $ e apply :: Env -> Expr -> Expr -> ThrowError Expr -- ^ Nested application recursion apply env a@(AppExpr _ _) args = do a' <- (eval env a) apply env a' args -- ^Apply a function context to another arg. Basically there are two options: -- The arguments suffice the function -> function is executed -- There are too little arguemts -> context swallows argument and proceeds apply env c@(FuncCtx bi@(Builtin params f) args) arg | (length args) + 1 == params = do --arg' <- (eval env arg) f (args ++ [arg]) | otherwise = do --arg' <- (eval env arg) return $ FuncCtx bi (args ++ [arg]) -- ^Of course there is a defined function apply env c@(FuncCtx de@(Defined params f) args) arg | (length args) + 1 == params = do --arg' <- (eval env arg) matchAndEvalPatternExpr (funcName f) env (args ++ [arg]) (funcPatterns f) | otherwise = do -- arg' <- (eval env arg) return $ FuncCtx de (args ++ [arg]) -- ^At the bottom of a recursion an AppExpr might contain a Builtin or call any other -- function that is defined within the environment. apply env (VarExpr n) args = case M.lookup n builtins of -- if it is a unary function handle it right away Just (Builtin 1 f) -> do --args <- (eval env args) f [args] -- n-ary function must harvest additional n-1 parameters Just b -> do --args <- (eval env args) return $ FuncCtx b [args] Nothing -> do --args <- (eval env args) applyFromEnv env n args apply env (LamExpr n e) arg = do arg' <- subs e n arg eval env arg' -- ^This is most likely an error. apply env func args = throwError $ CannotApply func args applyFromEnv :: Env -> Name -> Expr -> ThrowError Expr applyFromEnv env name arg = do case findFunc env name of Nothing -> throwError $ SymbolNotFound name Just func -> do case funcArgCount func of 0 -> matchAndEvalPatternExpr name env [] (funcPatterns func) >>= (\expr -> apply env expr arg) 1 -> matchAndEvalPatternExpr name env [arg] (funcPatterns func) n -> return $ FuncCtx (Defined n func) [arg] -- |Evaluate a pattern if it matches the given parameters. matchAndEvalPatternExpr :: Name -> Env -> [Expr] -> [Pattern] -> ThrowError Expr matchAndEvalPatternExpr fname _ es [] = throwError $ PatternFallthrough fname es matchAndEvalPatternExpr fname env es (p:ps) = do case matchPattern p es of Just _ -> do wrapped <- subsBinding fname (patternBindings p) es (patternExpr p) eval env wrapped Nothing -> matchAndEvalPatternExpr fname env es ps subsBinding :: Name -> [Binding] -> [Expr] -> Expr -> ThrowError Expr subsBinding fname [] [] ex = return $ ex subsBinding fname (b@(BVar name):bs) (e:es) ex = do subs' <- (subs ex name e) subsBinding fname bs es subs' subsBinding fname ((BList ((BVar head'),(BVar tail'))):bs) es'@(e:es) ex | isListExpr e = do sub1 <- (subs ex head' (listHead e)) sub2 <- (subs sub1 tail' (listTail e)) subsBinding fname bs es sub2 | otherwise = throwError $ Fallback $ "could not match " ++ (show e) ++ " agains a list or string" subsBinding fname ((BList ((BVar head'),_)):bs) es'@(e:es) ex | isListExpr e = do subs' <- (subs ex head' (listHead e)) subsBinding fname bs es subs' | otherwise = throwError $ Fallback $ "could not match " ++ (show e) ++ " agains a list or string" subsBinding fname ((BList (_,(BVar tail'))):bs) es'@(e:es) ex | isListExpr e = do subs' <- (subs ex tail' (listTail e)) subsBinding fname bs es subs' | otherwise = throwError $ Fallback $ "could not match " ++ (show e) ++ " agains a list or string" subsBinding fname (_:bs) (e:es) ex = subsBinding fname bs es ex -- |Subsitute a variable in an expression with another expression subs :: Expr -> Name -> Expr -> ThrowError Expr subs (AppExpr e1 e2) old new = do s1 <- (subs e1 old new) s2 <- (subs e2 old new) return $ AppExpr s1 s2 subs v@(VarExpr x) old new | old == x = return new -- replace because they really match | otherwise = return v -- OPT (subs e1 old new) >>= (\e1 -> (subs e2 old new) >>= (\e2 -> return $ AppExpr e1 e2)) subs le@(ListExpr es) old new = liftM ListExpr (mapM (\e -> subs e old new) es) subs (LamExpr n e) old new | n == old = return $ (LamExpr n e) | otherwise = do subs' <- (subs e old new) return $ LamExpr n subs' subs (LetExpr name old_def old_expr) old new = do new_def <- subs old_def old new new_expr <- subs old_expr old new return $ LetExpr name new_def new_expr {- OPT (subs old_def old new) >>= (\new_def -> (subs old_expr old new) >>= (\new_expr -> return $ LetExpr name new_def new_expr) )-} subs (CondExpr old_if old_then old_else) old new = do new_if <- (subs old_if old new) new_then <- (subs old_then old new) new_else <- (subs old_else old new) return $ CondExpr new_if new_then new_else {- OPT (subs old_if old new) >>= (\new_if -> (subs old_then old new) >>= (\new_then -> (subs old_else old new) >>= (\new_else -> return $ CondExpr new_if new_then new_else) ) -} subs old _ _ = return old -- |Find out whether an expr is a variable bool literal string or list isAtom :: Expr -> Bool isAtom (VarExpr _) = True isAtom (BoolExpr _) = True isAtom (LitExpr _) = True isAtom (ListExpr _) = True isAtom (StrExpr _) = True isAtom _ = False -- |Does an evaluated expression equal ture? holds :: Env -> Expr -> ThrowError Bool holds env e = do case eval env e of Right (BoolExpr True) -> return $ True Right (BoolExpr False) -> return $ False Right e -> throwError $ ConditionalNotABool e Left error -> throwError $ error
planrich/abstractmachines
src/Interpretor.hs
bsd-3-clause
7,226
0
18
1,940
2,392
1,172
1,220
138
6
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Math.Metric.Taxicab where import Math.Metric.Metric (Metric(..), MetricCoord(..)) import Math.Coordinate.Cartesian (Cartesian(..), Point2(..)) data Taxicab = Taxicab deriving Show -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance MetricCoord Taxicab Cartesian where metricCoord _ = Cartesian instance Num a => Metric Taxicab (Point2 a) a where distanceBase _ (Point2 x1 y1) (Point2 x2 y2) = abs (x2 - x1) + abs (y2 - y1)
wdanilo/algebraic
src/Math/Metric/Taxicab.hs
bsd-3-clause
661
0
9
91
161
93
68
10
0
-- | Types for Web Application Scanning module Qualys.Types.Was where import Data.Text (Text) import qualified Data.ByteString as B import Data.Time (UTCTime) import Qualys.Internal -- | Was scan data WasScan = WasScan { wsId :: Int -- ^ Scan ID , wsName :: Maybe Text -- ^ Scan name , wsRef :: Maybe Text , wsType :: Maybe Text , wsMode :: Maybe Text -- ^ ONDEMAND, SCHEDULED or API , wsMulti :: Maybe Bool , wsProgScan :: Maybe Bool , wsTarget :: Maybe WsTarget -- ^ Target of the web scan , wsProfile :: Maybe WsScanProfile -- ^ Option profile , wsCancAftNHrs :: Maybe Int , wsCancTime :: Maybe Text , wsOptions :: Maybe [(Text,Text)] , wsLaunch :: Maybe UTCTime -- ^ Date and time the scan was launched , wsLaunchBy :: Maybe WsUser -- ^ User who launched the scan , wsStatus :: Maybe Text -- ^ Scan status (SUBMITTED, RUNNING, FINISHED, ERROR or CANCELED). , wsEndDt :: Maybe UTCTime -- ^ Date and time the scan ended , wsScanDur :: Maybe Int -- ^ Duration of the scan in ??? , wsSummary :: Maybe WsSummary , wsStats :: Maybe WsStat , wsVulns :: Maybe [WsScanResult] , wsSensCont :: Maybe [WsScanResult] , wsIgs :: Maybe [WsIg] , wsSendMail :: Maybe Bool } deriving Show -- | Was scan profile data WsScanProfile = WsScanProfile { wspId :: Maybe Int -- ^ ID of the option profile , wspName :: Maybe Text -- ^ Option profile name } deriving Show -- | Was scan target data WsTarget = WsTarget { wstWebApps :: Maybe [WsWebApp] , wstTags :: Maybe [WsTag] , wstWebApp :: WsWebApp , wstAuthRec :: Maybe WsAuthRec , wstScanAppl :: Maybe ScanAppl -- ^ Scanner Appliance , wstCancelOpt :: Maybe Text -- ^ Cancel option , wstProxy :: Maybe WsProxy -- ^ Proxy settings } deriving Show -- | Web application data WsWebApp = WsWebApp { wsWebAppId :: Maybe Int , wsWebAppName :: Maybe Text , wsWebAppUrl :: Maybe Text } deriving Show -- | Tag data data WsTag = WsTag { wstId :: Int , wstName :: Maybe Text } deriving Show -- | Authentication record data WsAuthRec = WsAuthRec { wsaId :: Int , wsaName :: Maybe Text , wsaOwner :: Maybe WsUser , wsaFormRec :: Maybe WaFormRecord , wsaServRec :: Maybe ServRecord , wsaTags :: Maybe [WsTag] , wsaComments :: Maybe [Comment] , wsaCreateDate :: Maybe UTCTime , wsaCreatedBy :: Maybe WsUser , wsaUpdateDate :: Maybe UTCTime , wsaUpdateBy :: Maybe WsUser } deriving Show -- | Proxy information data WsProxy = WsProxy { wsprId :: Maybe Int -- ^ Proxy ID for scanning the app , wsprName :: Maybe Text -- ^ Proxy name , wsprUrl :: Maybe Text -- ^ Proxy URL } deriving Show -- | User data data WsUser = WsUser { wsuId :: Maybe Int , wsuUsername :: Maybe Text , wsuFirstName :: Maybe Text , wsuLastName :: Maybe Text } deriving Show -- | Web scan summary data WsSummary = WsSummary { wssCrawlDur :: Maybe Int , wssTestDur :: Maybe Int , wssLnkCrawl :: Maybe Int , wssRequests :: Maybe Int , wssResStat :: Text , wssAuthStat :: Text , wssOs :: Maybe Text } deriving Show -- | Web scan stats data WsStat = WsStat { wssGlobal :: Maybe WsGlobalStat -- ^ Global stats , wssGroup :: Maybe [WsNameStat] -- ^ Group stats , wssOwasp :: Maybe [WsNameStat] -- ^ OWASP stats () , wssWasc :: Maybe [WsNameStat] -- ^ WASC stats } deriving Show -- | Web scan global stats data WsGlobalStat = WsGlobalStat { wsgVulnTotal :: Int , wsgVulnLev5 :: Int , wsgVulnLev4 :: Int , wsgVulnLev3 :: Int , wsgVulnLev2 :: Int , wsgVulnLev1 :: Int , wsgScsTotal :: Int , wsgScsLev5 :: Int , wsgScsLev4 :: Int , wsgScsLev3 :: Int , wsgScsLev2 :: Int , wsgScsLev1 :: Int , wsgIgsTotal :: Int , wsgIgsLev5 :: Int , wsgIgsLev4 :: Int , wsgIgsLev3 :: Int , wsgIgsLev2 :: Int , wsgIgsLev1 :: Int } deriving Show -- | Named stat data WsNameStat = WsNameStat { wsnName :: Text , wsnTotal :: Int , wsnLev5 :: Int , wsnLev4 :: Int , wsnLev3 :: Int , wsnLev2 :: Int , wsnLev1 :: Int } deriving Show -- | Scan Result data WsScanResult = WsScanResult { wsrQid :: QID , wsrTitle :: Text , wsrUri :: Text , wsrParam :: Maybe Text , wsrContent :: Maybe Text , wsrInsts :: Maybe [WsInstance] } deriving Show -- | Instance data WsInstance = WsInstance { wiAuth :: Bool , wiForm :: Maybe Text , wiPayloads :: Maybe [WsPayload] } deriving Show -- | Payload data WsPayload = WsPayload { wpPayload :: Text , wpResult :: B.ByteString } deriving Show -- | Information gathered data WsIg = WsIg { wigQid :: QID , wigTitle :: Text , wigData :: B.ByteString } deriving Show -- | Scanner appliance data ScanAppl = ScanAppl { saType :: Text , saFriendlyName :: Maybe Text } deriving Show -- | Web application data WebApp = WebApp { waId :: Int , waName :: Maybe Text , waUrl :: Maybe Text , waOs :: Maybe Text , waOwner :: Maybe WsUser , waScope :: Maybe Text , waSubDomain :: Maybe Text , waDomains :: Maybe [Text] , waUris :: Maybe [Text] , waAttrs :: Maybe [(Text,Text)] , waDefProfile :: Maybe WsScanProfile , waDefScanner :: Maybe ScanAppl , waScanLocked :: Maybe Bool , waProgScan :: Maybe Bool , waUrlBlList :: Maybe [UrlEntry] , waUrlWhList :: Maybe [UrlEntry] , waPostBlList :: Maybe [UrlEntry] , waAuthRec :: Maybe [WsAuthRec] , waUseRobots :: Maybe Text , waUseSitemap :: Maybe Bool , waHeaders :: Maybe [Text] , waMalwareMon :: Maybe Bool , waMalwareNot :: Maybe Bool , waMwSchTime :: Maybe UTCTime , waMwSchTz :: Maybe Text -- XXX: , waTags :: Maybe [WsTag] , waComments :: Maybe [Comment] , waIsSched :: Maybe Bool , waLastScan :: Maybe WasScanInfo , waCreatedBy :: Maybe WsUser , waCreateDate :: Maybe UTCTime , waUpdateBy :: Maybe WsUser , waUpdateDate :: Maybe UTCTime , waScreenshot :: Maybe B.ByteString , waProxy :: Maybe WsProxy , waConfig :: Maybe WaConfig } deriving Show -- | Url entry data UrlEntry = UrlText Text | UrlRegex Text deriving Show -- | Comment data Comment = Comment { cmContent :: Text , cmAuthor :: Maybe WsUser , cmDate :: Maybe UTCTime } deriving Show -- | Scan Info data WasScanInfo = WasScanInfo { wsiId :: Int , wsiName :: Maybe Text } deriving Show -- | Web app config data WaConfig = CancelAfterN Int | CancelScanAt Text deriving Show data WaFormRecord = WaFormRecord { wafrType :: Maybe Text , wafrSslOnly :: Maybe Bool , wafrSelScript :: Maybe SelScript , wafrFields :: Maybe [WfrField] } deriving Show data WfrField = WfrField { frId :: Int , frName :: Maybe Text , frSecured :: Maybe Bool , frValue :: Maybe Text } deriving Show data SelScript = SelScript { ssName :: Maybe Text , ssData :: Maybe Text , ssRegex :: Maybe Text } deriving Show data ServRecord = ServRecord { srSslOnly :: Maybe Bool , srCert :: Maybe Certificate , srFields :: Maybe [SrField] } deriving Show data SrField = SrField { srfId :: Int , srfType :: Maybe Text , srfDomain :: Maybe Text , srfUser :: Maybe Text , srfPass :: Maybe Text } deriving Show data Certificate = Certificate { ctName :: Maybe Text , ctContents :: Maybe Text , ctPassphrase :: Maybe Text } deriving Show
ahodgen/qualys
Qualys/Types/Was.hs
bsd-3-clause
8,105
0
11
2,585
1,917
1,139
778
233
0
-- -- | This test reads the current directory and dumps a topologically sorted package list -- import Distribution.ArchLinux.SrcRepo import System.IO import System.Directory import Control.Monad main = do dot <- getCurrentDirectory repo <- getRepoFromDir dot case repo of Nothing -> return () Just r -> foldM (\a -> \s -> putStrLn s) () (dumpContentsTopo r)
archhaskell/archlinux
tests/toposort.hs
bsd-3-clause
374
0
14
71
105
54
51
10
2
module Parse.PatternTest where import Elm.Utils ((|>)) import Test.HUnit (Assertion, assertEqual) import Test.Framework import Test.Framework.Providers.HUnit import qualified Data.Text.Lazy as LazyText import Parse.Pattern import Parse.Helpers (IParser, iParse) import AST.V0_16 import AST.Pattern import AST.Variable hiding (Alias) import Reporting.Annotation hiding (map, at) import Reporting.Region import Text.Parsec.Char (string) import Debug.Trace import Parse.TestHelpers pending = at 0 0 0 0 Anything example name input expected = testCase name $ assertParse expr input expected tests :: Test tests = testGroup "Parse.Pattern" [ example "wildcard" "_" $ at 1 1 1 2 Anything , example "literal" "1" $ at 1 1 1 2 (Literal (IntNum 1)) , example "variable" "a" $ at 1 1 1 2 (Var (VarRef "a")) , testGroup "data" [ example "" "Just x y" $ at 1 1 1 9 (Data "Just" [([],at 1 6 1 7 (Var (VarRef "x"))),([],at 1 8 1 9 (Var (VarRef "y")))]) , example "single parameter" "Just x" $ at 1 1 1 7 (Data "Just" [([],at 1 6 1 7 (Var (VarRef "x")))]) , example "comments" "Just{-A-}x{-B-}y" $ at 1 1 1 17 (Data "Just" [([BlockComment ["A"]],at 1 10 1 11 (Var (VarRef "x"))),([BlockComment ["B"]],at 1 16 1 17 (Var (VarRef "y")))]) , example "newlines" "Just\n x\n y" $ at 1 1 3 3 (Data "Just" [([],at 2 2 2 3 (Var (VarRef "x"))),([],at 3 2 3 3 (Var (VarRef "y")))]) ] , testGroup "unit" [ example "" "()" $ at 1 1 1 3 (UnitPattern []) , example "whitespace" "( )" $ at 1 1 1 4 (UnitPattern []) , example "comments" "({-A-})" $ at 1 1 1 8 (UnitPattern [BlockComment ["A"]]) , example "newlines" "(\n )" $ at 1 1 2 3 (UnitPattern []) ] , testGroup "parentheses" [ example "" "(_)" $ at 1 2 1 3 Anything , example "whitespace" "( _ )" $ at 1 3 1 4 Anything , example "comments" "({-A-}_{-B-})" $ at 1 1 1 14 (PatternParens (Commented [BlockComment ["A"]] (at 1 7 1 8 Anything) [BlockComment ["B"]])) , example "newlines" "(\n _\n )" $ at 2 2 2 3 Anything ] , testGroup "tuple" [ example "" "(x,y)" $ at 1 1 1 6 (Tuple [Commented [] (at 1 2 1 3 (Var (VarRef "x"))) [],Commented [] (at 1 4 1 5 (Var (VarRef "y"))) []]) , example "whitespace" "( x , y )" $ at 1 1 1 10 (Tuple [Commented [] (at 1 3 1 4 (Var (VarRef "x"))) [],Commented [] (at 1 7 1 8 (Var (VarRef "y"))) []]) , example "comments" "({-A-}x{-B-},{-C-}y{-D-})" $ at 1 1 1 26 (Tuple [Commented [BlockComment ["A"]] (at 1 7 1 8 (Var (VarRef "x"))) [BlockComment ["B"]],Commented [BlockComment ["C"]] (at 1 19 1 20 (Var (VarRef "y"))) [BlockComment ["D"]]]) , example "newlines" "(\n x\n ,\n y\n )" $ at 1 1 5 3 (Tuple [Commented [] (at 2 2 2 3 (Var (VarRef "x"))) [],Commented [] (at 4 2 4 3 (Var (VarRef "y"))) []]) ] , testGroup "empty list pattern" [ example "" "[]" $ at 1 1 1 3 (EmptyListPattern []) , example "whitespace" "[ ]" $ at 1 1 1 4 (EmptyListPattern []) , example "comments" "[{-A-}]" $ at 1 1 1 8 (EmptyListPattern [BlockComment ["A"]]) , example "newlines" "[\n ]" $ at 1 1 2 3 (EmptyListPattern []) ] , testGroup "list" [ example "" "[x,y]" $ at 1 1 1 6 (List [Commented [] (at 1 2 1 3 (Var (VarRef "x"))) [],Commented [] (at 1 4 1 5 (Var (VarRef "y"))) []]) , example "single element" "[x]" $ at 1 1 1 4 (List [Commented [] (at 1 2 1 3 (Var (VarRef "x"))) []]) , example "whitespace" "[ x , y ]" $ at 1 1 1 10 (List [Commented [] (at 1 3 1 4 (Var (VarRef "x"))) [],Commented [] (at 1 7 1 8 (Var (VarRef "y"))) []]) , example "comments" "[{-A-}x{-B-},{-C-}y{-D-}]" $ at 1 1 1 26 (List [Commented [BlockComment ["A"]] (at 1 7 1 8 (Var (VarRef "x"))) [BlockComment ["B"]],Commented [BlockComment ["C"]] (at 1 19 1 20 (Var (VarRef "y"))) [BlockComment ["D"]]]) , example "newlines" "[\n x\n ,\n y\n ]" $ at 1 1 5 3 (List [Commented [] (at 2 2 2 3 (Var (VarRef "x"))) [],Commented [] (at 4 2 4 3 (Var (VarRef "y"))) []]) ] , testGroup "cons pattern" [ example "" "a::b::c" $ at 1 1 1 8 (ConsPattern (at 1 1 1 2 (Var (VarRef "a")),[]) [Commented [] (at 1 4 1 5 (Var (VarRef "b"))) []] ([],at 1 7 1 8 (Var (VarRef "c")))) , example "two patterns" "a::b" $ at 1 1 1 5 (ConsPattern (at 1 1 1 2 (Var (VarRef "a")),[]) [] ([],at 1 4 1 5 (Var (VarRef "b")))) , example "whitespace" "a :: b :: c" $ at 1 1 1 12 (ConsPattern (at 1 1 1 2 (Var (VarRef "a")),[]) [Commented [] (at 1 6 1 7 (Var (VarRef "b"))) []] ([],at 1 11 1 12 (Var (VarRef "c")))) , example "comments" "a{-A-}::{-B-}b{-C-}::{-D-}c" $ at 1 1 1 28 (ConsPattern (at 1 1 1 2 (Var (VarRef "a")),[BlockComment ["A"]]) [Commented [BlockComment ["B"]] (at 1 14 1 15 (Var (VarRef "b"))) [BlockComment ["C"]]] ([BlockComment ["D"]],at 1 27 1 28 (Var (VarRef "c")))) , example "newlines" "a\n ::\n b\n ::\n c" $ at 1 1 5 3 (ConsPattern (at 1 1 1 2 (Var (VarRef "a")),[]) [Commented [] (at 3 2 3 3 (Var (VarRef "b"))) []] ([],at 5 2 5 3 (Var (VarRef "c")))) ] , testGroup "record" [ example "" "{a,b}" $ at 1 1 1 6 (Record [Commented [] "a" [],Commented [] "b" []]) , example "single element" "{a}" $ at 1 1 1 4 (Record [Commented [] "a" []]) , example "whitespace" "{ a , b }" $ at 1 1 1 10 (Record [Commented [] "a" [],Commented [] "b" []]) , example "comments" "{{-A-}a{-B-},{-C-}b{-D-}}" $ at 1 1 1 26 (Record [Commented [BlockComment ["A"]] "a" [BlockComment ["B"]],Commented [BlockComment ["C"]] "b" [BlockComment ["D"]]]) , example "newlines" "{\n a\n ,\n b\n }" $ at 1 1 5 3 (Record [Commented [] "a" [],Commented [] "b" []]) , testCase "must have at least one field" $ assertFailure expr "{}" ] , testGroup "alias" [ example "" "_ as x" $ at 1 1 1 7 (Alias (at 1 1 1 2 Anything,[]) ([],"x")) , example "left side has whitespace" "A b as x" $ at 1 1 1 9 (Alias (at 1 1 1 4 (Data "A" [([], at 1 3 1 4 (Var (VarRef "b")))]),[]) ([],"x")) , example "left side ctor without whitespace" "A as x" $ at 1 1 1 7 (Alias (at 1 1 1 2 (Data "A" []),[]) ([],"x")) , example "comments" "_{-A-}as{-B-}x" $ at 1 1 1 15 (Alias (at 1 1 1 2 Anything,[BlockComment ["A"]]) ([BlockComment ["B"]],"x")) , example "newlines" "_\n as\n x" $ at 1 1 3 3 (Alias (at 1 1 1 2 Anything,[]) ([],"x")) , example "nested" "(_ as x)as y" $ at 1 1 1 13 (Alias (at 1 2 1 8 (Alias (at 1 2 1 3 Anything,[]) ([],"x")),[]) ([],"y")) , example "nested (whitespace)" "(_ as x) as y" $ at 1 1 1 14 (Alias (at 1 2 1 8 (Alias (at 1 2 1 3 Anything,[]) ([],"x")),[]) ([],"y")) , testCase "nesting required parentheses" $ assertFailure expr "_ as x as y" ] ]
fredcy/elm-format
tests/Parse/PatternTest.hs
bsd-3-clause
6,860
0
23
1,756
3,664
1,865
1,799
81
1
{-# LANGUAGE TypeSynonymInstances #-} module Network.SiteCheck.URLTests where import Test.Framework import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit hiding (Test) import Data.List (sort) import Network.SiteCheck.URL import Network.SiteCheck.Arbitrary tests = [ testCase "remove params with params" removeParamsWithParams , testCase "remove params without params" removeParamsWithoutParams , testCase "remove params only params" removeParamsOnlyParams , testProperty "params are removed" prop_params_are_removed , testProperty "param is added" prop_param_is_added , testProperty "param is removed" prop_param_is_removed , testProperty "params are ordered" prop_params_are_ordered , testProperty "host is added" prop_host_is_added , testCase "fixed combinations 1" fixedCombinations1 , testCase "fixed combinations 2" fixedCombinations2 , testCase "is in domain" itIsInDomain , testCase "is not in domain" itIsNotInDomain , testCase "is in domain with port" itIsInDomainWithPort , testCase "is not in domain with port" itIsNotInDomainWithPort , testCase "merge paths 1" mergePaths1 , testCase "merge paths 2" mergePaths2 , testCase "merge paths 3" mergePaths3 , testCase "merge paths 4" mergePaths4 , testCase "merge paths 5" mergePaths5 , testCase "merge paths 6" mergePaths6 , testCase "merge paths 7" mergePaths7 ] roundtrip :: (URL -> URL) -> String -> String roundtrip f x = case importURL x of Just u -> exportURL . f $ u Nothing -> x removeParamsWithParams = "http://a.b.c/d" @=? roundtrip removeParams "http://a.b.c/d?e=f" removeParamsWithoutParams = "http://a.b.c/d" @=? roundtrip removeParams "http://a.b.c/d" removeParamsOnlyParams = "" @=? roundtrip removeParams "?e=f" prop_params_are_removed url = (url_params (removeParams url)) == [] where types = (url :: URL) prop_param_is_added url = let url' = (addParam ("name", "joe") url) in (lookup "name" (url_params url')) == (Just "joe") where types = (url :: URL) prop_param_is_removed url | (url_params url) == [] = (url_params (removeParam "name" url)) == [] -- no params | otherwise = let params = (url_params url) count = (length params) (n, v) = head params url' = (removeParam n url) in (length $ url_params url') == count - 1 && lookup n (url_params url') == Nothing prop_params_are_ordered url = (url_params (orderParams url)) == sort (url_params url) prop_host_is_added old = let Just base = importURL "http://www.company.com/some/page?name=dan&age=20" new = (makeAbsolute base old) in case (url_type old) of PathRelative -> (url_type new) == (url_type base) && (url_path new) == (url_path base) >/< (url_path old) && (url_params new) == (url_params old) HostRelative -> (url_type new) == (url_type base) && (url_path new) == (url_path old) && (url_params new) == (url_params old) Absolute _ -> new == old fixedCombinations1 = let Just url = importURL "http://c.c/page?a=1&a=2" in [ [("a","1")] , [("a", "2")] ] @=? (map url_params $ fixedCombinations "a" 1 url) fixedCombinations2 = let Just url = importURL "http://c.c/page?a=1&a=2&a=3" in [ [("a","1"), ("a", "2")] , [("a","1"), ("a", "3")] , [("a", "2"), ("a", "1")] , [("a", "2"), ("a", "3")] , [("a", "3"), ("a", "1")] , [("a", "3"), ("a", "2")] ] @=? (map url_params $ fixedCombinations "a" 2 url) itIsInDomain = let Just url = importURL "http://a.b.c/test" in True @=? isInDomain "a.b.c" url itIsNotInDomain = let Just url = importURL "http://a.b.c/test" in False @=? isInDomain "a.b.d" url itIsInDomainWithPort = let Just url = importURL "http://a.b.c:10/test" in True @=? isInDomain "a.b.c:10" url itIsNotInDomainWithPort = let Just url = importURL "http://a.b.c:30/test" in False @=? isInDomain "a.b.c:10" url mergePaths1 = "" @=? "" >/< "" mergePaths2 = "" @=? "a" >/< "" mergePaths3 = "b" @=? "" >/< "b" mergePaths4 = "b" @=? "a" >/< "b" mergePaths5 = "a/c" @=? "a/b" >/< "c" mergePaths6 = "a/c/d" @=? "a/b" >/< "c/d" mergePaths7 = "a/b/d/e/f" @=? "a/b/c" >/< "d/e/f"
brentonashworth/sitecheck
test/Network/SiteCheck/URLTests.hs
bsd-3-clause
4,514
0
17
1,094
1,289
673
616
101
3
{-# LANGUAGE DoAndIfThenElse #-} module Foreign.HCLR.Parser where import Data.String.HT (trim) import Foreign.HCLR.Ast import Text.Parsec.Char import Text.Parsec.Combinator import Text.Parsec.Pos import Text.Parsec.Prim import Text.Parsec.String parseStringLiteral :: Parser StringLiteral parseStringLiteral = do char '"' s <- ((try $ char '\\' >> anyChar) <|> anyChar) `manyTill` (char '"') return $ StringLiteral s parseSymbol :: Parser Symbol parseSymbol = do sym <- many1 (char '_' <|> alphaNum) return $ Symbol sym parseArg :: Parser Arg parseArg = try (parseStringLiteral >>= return . ArgStringLit) <|> (parseSymbol >>= return . ArgSym) parseArgs :: Parser Args parseArgs = do spaces args <- parseArg `sepBy` space return $ Args args parseNew :: Parser Exp parseNew = do string "new" many1 space typ <- (many (char '_' <|> alphaNum)) `sepBy1` (char '.') args <- parseArgs return $ New (CLRType typ) args parseInvoke :: Parser Exp parseInvoke = do s <- (many (char '_' <|> alphaNum)) `sepBy` (char '.') if length s < 2 then fail "" else do let typ = init s let mth = last s args <- parseArgs return $ Invoke (CLRType typ) (CLRMethod mth) args parseExp :: Parser Exp parseExp = spaces >> (try parseNew <|> parseInvoke) parseBindStmt :: Parser Stmt parseBindStmt = do sym <- (char '_' <|> space <|> alphaNum) `manyTill` bindSymbol >>= return . trim exp <- parseExp return $ BindStmt (Symbol sym) exp parseNoBindStmt :: Parser Stmt parseNoBindStmt = do exp <- parseExp return $ NoBindStmt exp parseStmt :: Parser Stmt parseStmt = spaces >> (try parseBindStmt <|> parseNoBindStmt) parseStmtLine :: Int -> Parser Stmt parseStmtLine n = setPosition (newPos "1" n 1) >> parseStmt bindSymbol :: Parser String bindSymbol = try . string $ "<-"
tim-m89/hclr
Foreign/HCLR/Parser.hs
bsd-3-clause
1,817
0
14
352
674
339
335
59
2
module Test.Integration.Documentation ( spec ) where import Universum import Test.Hspec (Spec, it, shouldSatisfy) import Cardano.Wallet.Client.Http (WalletDocHttpClient) import qualified Cardano.Wallet.Client.Http as Client spec :: WalletDocHttpClient -> Spec spec client = do it "Fetches the documentation from the API" $ do response <- runExceptT $ Client.getSwaggerJson client response `shouldSatisfy` isRight
input-output-hk/pos-haskell-prototype
wallet/test/integration/Test/Integration/Documentation.hs
mit
475
0
13
110
105
61
44
11
1
-- -- -- ----------------- -- Exercise 5.16. ----------------- -- -- -- module E'5'16 where -- [2, 3] contains two items of a type that is defined in the Num typeclass. -- GHCi> :t [2, 3] -- [2, 3] :: Num t => [t] -- [[2, 3]] contains one item of a type that is defined in the Num typeclass. -- [[2, 3]] is of type list of list of numbers of a type that is defined in the Num typeclass. -- GHCi> :t [[2, 3]] -- [[2, 3]] :: Num t => [[t]]
pascal-knodel/haskell-craft
_/links/E'5'16.hs
mit
449
0
2
104
20
19
1
1
0
{- Copyright 2015,2017 Markus Ongyerth, Stephan Guenther This file is part of Monky. Monky is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Monky 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Monky. If not, see <http://www.gnu.org/licenses/>. -} {-| Module : Monky.Disk Description : Allows access to information about a btrfs pool Maintainer : moepi Stability : experimental Portability : Linux This module allows for some support for btrfs devices. This may be renamed in the future when a general block-device module appears. -} module Monky.Disk ( DiskHandle , getDiskReadWrite , getDiskFree , getDiskHandle , getDiskHandleTag ) where import Monky.Utility import Data.Time.Clock.POSIX import Data.IORef import Monky.Disk.Common import Monky.Disk.Btrfs import Monky.Disk.Device -- |The handle xported by this module -- A disk may have multiple physical devices so we use lists for them data DiskHandle = DiskH FSI [File] [IORef Int] [IORef Int] (IORef POSIXTime) sectorSize :: Int sectorSize = 512 -- |Get the read write rates from the disk (in bytes/s) getDiskReadWrite :: DiskHandle -> IO (Int, Int) getDiskReadWrite (DiskH _ fs readrefs writerefs timeref) = do contents <- mapM readValues fs time <- getPOSIXTime let nreads = map (\c -> (c !! 2) * sectorSize) contents let writes = map (\c -> (c !! 6) * sectorSize) contents oreads <- mapM readIORef readrefs owrites <- mapM readIORef writerefs otime <- readIORef timeref let creads = zipWith (-) nreads oreads let cwrites = zipWith (-) writes owrites let ctime = time - otime _ <- sequence $zipWith writeIORef readrefs nreads _ <- sequence $zipWith writeIORef writerefs writes writeIORef timeref time return (sum $map (`sdivBound` round ctime) creads, sum $map (`sdivBound` round ctime) cwrites) -- |Get the space left on the disk getDiskFree :: DiskHandle -> IO Integer getDiskFree (DiskH (FSI h) _ _ _ _) = getFsFree h getBtrfsDH :: (BtrfsHandle, [Dev]) -> IO DiskHandle getBtrfsDH (h, devs) = do -- Open the stat file for each physical device fs <- mapM (\(Dev dev) -> fopen (blBasePath ++ dev ++ "/stat")) devs -- this gets the right number of IORefs without number hacking wfs <- mapM (\_ -> newIORef 0) devs rfs <- mapM (\_ -> newIORef 0) devs t <- newIORef 0 return (DiskH (FSI h) fs wfs rfs t) getBlockDH :: (BlockHandle, Dev) -> IO DiskHandle getBlockDH (h, Dev dev) = do f <- fopen (blBasePath ++ dev ++ "/stat") wf <- newIORef 0 rf <- newIORef 0 t <- newIORef 0 return (DiskH (FSI h) [f] [wf] [rf] t) -- | Get a disk handle from uuid. This special-cases btrfs. getDiskHandle :: String -> IO DiskHandle getDiskHandle uuid = do -- First try btrfs file systems btrfs <- getBtrfsHandle uuid case btrfs of (Just x) -> getBtrfsDH x Nothing -> getDiskHandleTag "UUID" uuid -- | Get the disk handle from a user chosen blkid tag. getDiskHandleTag :: String -> String -> IO DiskHandle getDiskHandleTag t v = do block <- getBlockHandleTag t v case block of Just x -> getBlockDH x Nothing -> error "Disk currently does not support your setup"
Ongy/monky
Monky/Disk.hs
lgpl-3.0
3,628
0
15
757
863
434
429
59
2
-- Test vectors for SHA1 are taken from GEC2: www.secg.org/collateral/gec2.pdf -- Test vectors for SHA224, SHA256, SHA384, SHA512 are taken from RFC 6979 {-# LANGUAGE OverloadedStrings #-} module KAT_PubKey.ECDSA (ecdsaTests) where import Crypto.Number.Serialize import qualified Crypto.PubKey.ECC.ECDSA as ECDSA import qualified Crypto.PubKey.ECC.Types as ECC import Crypto.Hash (SHA1(..), SHA224(..), SHA256(..), SHA384(..), SHA512(..)) import Imports data VectorECDSA = VectorECDSA { curve :: ECC.Curve , msg :: ByteString , d :: Integer , q :: ECC.Point , k :: Integer , r :: Integer , s :: Integer } vectorsSHA1 = [ VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p160r1 , msg = "abc" , d = 971761939728640320549601132085879836204587084162 , q = ECC.Point 466448783855397898016055842232266600516272889280 1110706324081757720403272427311003102474457754220 , k = 702232148019446860144825009548118511996283736794 , r = 1176954224688105769566774212902092897866168635793 , s = 299742580584132926933316745664091704165278518100 } -- from official ECDSA KATs , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_t163k1 , msg = i2osp 0xa2c1a03fdd00521bb08fc88d20344321977aaf637ef9d5470dd7d2c8628fc8d0d1f1d3587c6b3fd02386f8c13db341b14748a9475cc63baf065df64054b27d5c2cdf0f98e3bbb81d0b5dc94f8cdb87acf75720f6163de394c8c6af360bc1acb85b923a493b7b27cc111a257e36337bd94eb0fab9d5e633befb1ae7f1b244bfaa , d = 0x00000011f2626d90d26cb4c0379043b26e64107fc , q = ECC.Point 0x0389fa5ad7f8304325a8c060ef7dcb83042c045bc 0x0eefa094a5054da196943cc80509dcb9f59e5bc2e , k = 0x0000000c3a4ff97286126dab1e5089395fcc47ebb , r = 0x0dbe6c3a1dc851e7f2338b5c26c62b4b37bf8035c , s = 0x1c76458135b1ff9fbd23009b8414a47996126b56a } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_t163k1 , msg = i2osp 0x67048080daaeb77d3ac31babdf8be23dbe75ceb4dfb94aa8113db5c5dcb6fe14b70f717b7b0ed0881835a66a86e6d840ffcb7d976c75ef2d1d4322fbbc86357384e24707aef88cea2c41a01a9a3d1b9e72ce650c7fdecc4f9448d3a77df6cdf13647ab295bb3132de0b1b2c402d8d2de7d452f1e003e0695de1470d1064eee16 , d = 0x00000006a3803301daee9af09bb5b6c991a4f49a4 , q = ECC.Point 0x4b500f555e857da8c299780130c5c3f48f02ee322 0x5c1c0ae25b47f06cc46fb86b12d2d8c0ba6a4bf07 , k = 0x0000002f39fbf77f3e0dc046116de692b6cf91b16 , r = 0x3d3eeda42f65d727f4a564f1415654356c6c57a6c , s = 0x35e4d43c5f08baddf138449db1ad0b7872552b7cd } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_t163k1 , msg = i2osp 0x77e007dc2acd7248256165a4b30e98986f51a81efd926b85f74c81bc2a6d2bcd030060a844091e22fbb0ff3db5a20caaefb5d58ccdcbc27f0ff8a4d940e78f303079ec1ca5b0ca3d4ecc7580f8b34a9f0496c9e719d2ec3e1614b7644bc11179e895d2c0b58a1da204fbf0f6e509f97f983eacb6487092caf6e8e4e6b3c458b2 , d = 0x0000002e28676514bd93fea11b62db0f6e324b18d , q = ECC.Point 0x3f9c90b71f6a1de20a2716f38ef1b5f98c757bd42 0x2ff0a5d266d447ef62d43fbca6c34c08c1ce35a40 , k = 0x00000001233ae699883e74e7f4dfb5279ff22280a , r = 0x39de3cd2cf04145e522b8fba3f23e9218226e0860 , s = 0x2af62bfb3cfa202e2342606ee5bb0934c3b0375b6 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_t163k1 , msg = i2osp 0xfbacfcce4688748406ddf5c3495021eef8fb399865b649eb2395a04a1ab28335da2c236d306fcc59f7b65ea931cf0139571e1538ede5688958c3ac69f47a285362f5ad201f89cc735b7b465408c2c41b310fc8908d0be45054df2a7351fae36b390e842f3b5cdd9ad832940df5b2d25c2ed43ce86eaf2508bcf401ae58bb1d47 , d = 0x000000361dd088e3a6d3c910686c8dce57e5d4d8e , q = ECC.Point 0x064f905c1da9d7e9c32d81890ae6f30dcc7839d32 0x06f1faedb6d9032016d3b681e7cf69c29d29eb27b , k = 0x00000022f723e9f5da56d3d0837d5dca2f937395f , r = 0x374cdc8571083fecfbd4e25e1cd69ecc66b715f2d , s = 0x313b10949222929b2f20b15d446c27d6dcae3f086 } ] rfc6979_vectorsSHA224 = [ VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "sample" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0x4381526b3fc1e7128f202e194505592f01d5ff4c5af015d8 , r = 0xa1f00dad97aeec91c95585f36200c65f3c01812aa60378f5 , s = 0xe07ec1304c7c6c9debbe980b9692668f81d4de7922a0f97a } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "test" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0xf5dc805f76ef851800700cce82e7b98d8911b7d510059fbe , r = 0x6945a1c1d1b2206b8145548f633bb61cef04891baf26ed34 , s = 0xb7fb7fdfc339c0b9bd61a9f5a8eaf9be58fc5cba2cb15293 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "sample" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0xc1d1f2f10881088301880506805feb4825fe09acb6816c36991aa06d , r = 0x1cdfe6662dde1e4a1ec4cdedf6a1f5a2fb7fbd9145c12113e6abfd3e , s = 0xa6694fd7718a21053f225d3f46197ca699d45006c06f871808f43ebc } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "test" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0xdf8b38d40dca3e077d0ac520bf56b6d565134d9b5f2eae0d34900524 , r = 0xc441ce8e261ded634e4cf84910e4c5d1d22c5cf3b732bb204dbef019 , s = 0x902f42847a63bdc5f6046ada114953120f99442d76510150f372a3f4 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "sample" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0x103f90ee9dc52e5e7fb5132b7033c63066d194321491862059967c715985d473 , r = 0x53b2fff5d1752b2c689df257c04c40a587fababb3f6fc2702f1343af7ca9aa3f , s = 0xb9afb64fdc03dc1a131c7d2386d11e349f070aa432a4acc918bea988bf75c74c } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "test" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0x669f4426f2688b8be0db3a6bd1989bdaefff84b649eeb84f3dd26080f667faa7 , r = 0xc37edb6f0ae79d47c3c27e962fa269bb4f441770357e114ee511f662ec34a692 , s = 0xc820053a05791e521fcaad6042d40aea1d6b1a540138558f47d0719800e18f2d } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "sample" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0xa4e4d2f0e729eb786b31fc20ad5d849e304450e0ae8e3e341134a5c1afa03cab8083ee4e3c45b06a5899ea56c51b5879 , r = 0x42356e76b55a6d9b4631c865445dbe54e056d3b3431766d0509244793c3f9366450f76ee3de43f5a125333a6be060122 , s = 0x9da0c81787064021e78df658f2fbb0b042bf304665db721f077a4298b095e4834c082c03d83028efbf93a3c23940ca8d } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "test" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x18fa39db95aa5f561f30fa3591dc59c0fa3653a80daffa0b48d1a4c6dfcbff6e3d33be4dc5eb8886a8ecd093f2935726 , r = 0xe8c9d0b6ea72a0e7837fea1d14a1a9557f29faa45d3e7ee888fc5bf954b5e62464a9a817c47ff78b8c11066b24080e72 , s = 0x07041d4a7a0379ac7232ff72e6f77b6ddb8f09b16cce0ec3286b2bd43fa8c6141c53ea5abef0d8231077a04540a96b66 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "sample" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x121415ec2cd7726330a61f7f3fa5de14be9436019c4db8cb4041f3b54cf31be0493ee3f427fb906393d895a19c9523f3a1d54bb8702bd4aa9c99dab2597b92113f3 , r = 0x1776331cfcdf927d666e032e00cf776187bc9fdd8e69d0dabb4109ffe1b5e2a30715f4cc923a4a5e94d2503e9acfed92857b7f31d7152e0f8c00c15ff3d87e2ed2e , s = 0x050cb5265417fe2320bbb5a122b8e1a32bd699089851128e360e620a30c7e17ba41a666af126ce100e5799b153b60528d5300d08489ca9178fb610a2006c254b41f } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "test" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x040d09fcf3c8a5f62cf4fb223cbbb2b9937f6b0577c27020a99602c25a01136987e452988781484edbbcf1c47e554e7fc901bc3085e5206d9f619cff07e73d6f706 , r = 0x1c7ed902e123e6815546065a2c4af977b22aa8eaddb68b2c1110e7ea44d42086bfe4a34b67ddc0e17e96536e358219b23a706c6a6e16ba77b65e1c595d43cae17fb , s = 0x177336676304fcb343ce028b38e7b4fba76c1c1b277da18cad2a8478b2a9a9f5bec0f3ba04f35db3e4263569ec6aade8c92746e4c82f8299ae1b8f1739f8fd519a4 } ] rfc6979_vectorsSHA256 = [ VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "sample" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0x32b1b6d7d42a05cb449065727a84804fb1a3e34d8f261496 , r = 0x4b0b8ce98a92866a2820e20aa6b75b56382e0f9bfd5ecb55 , s = 0xccdb006926ea9565cbadc840829d8c384e06de1f1e381b85 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "test" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0x5c4ce89cf56d9e7c77c8585339b006b97b5f0680b4306c6c , r = 0x3a718bd8b4926c3b52ee6bbe67ef79b18cb6eb62b1ad97ae , s = 0x5662e6848a4a19b1f1ae2f72acd4b8bbe50f1eac65d9124f } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "sample" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0xad3029e0278f80643de33917ce6908c70a8ff50a411f06e41dedfcdc , r = 0x61aa3da010e8e8406c656bc477a7a7189895e7e840cdfe8ff42307ba , s = 0xbc814050dab5d23770879494f9e0a680dc1af7161991bde692b10101 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "test" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0xff86f57924da248d6e44e8154eb69f0ae2aebaee9931d0b5a969f904 , r = 0xad04dde87b84747a243a631ea47a1ba6d1faa059149ad2440de6fba6 , s = 0x178d49b1ae90e3d8b629be3db5683915f4e8c99fdf6e666cf37adcfd } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "sample" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0xa6e3c57dd01abe90086538398355dd4c3b17aa873382b0f24d6129493d8aad60 , r = 0xefd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716 , s = 0xf7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "test" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0xd16b6ae827f17175e040871a1c7ec3500192c4c92677336ec2537acaee0008e0 , r = 0xf1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d38367 , s = 0x019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "sample" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x180ae9f9aec5438a44bc159a1fcb277c7be54fa20e7cf404b490650a8acc414e375572342863c899f9f2edf9747a9b60 , r = 0x21b13d1e013c7fa1392d03c5f99af8b30c570c6f98d4ea8e354b63a21d3daa33bde1e888e63355d92fa2b3c36d8fb2cd , s = 0xf3aa443fb107745bf4bd77cb3891674632068a10ca67e3d45db2266fa7d1feebefdc63eccd1ac42ec0cb8668a4fa0ab0 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "test" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x0cfac37587532347dc3389fdc98286bba8c73807285b184c83e62e26c401c0faa48dd070ba79921a3457abff2d630ad7 , r = 0x6d6defac9ab64dabafe36c6bf510352a4cc27001263638e5b16d9bb51d451559f918eedaf2293be5b475cc8f0188636b , s = 0x2d46f3becbcc523d5f1a1256bf0c9b024d879ba9e838144c8ba6baeb4b53b47d51ab373f9845c0514eefb14024787265 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "sample" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x0edf38afcaaecab4383358b34d67c9f2216c8382aaea44a3dad5fdc9c32575761793fef24eb0fc276dfc4f6e3ec476752f043cf01415387470bcbd8678ed2c7e1a0 , r = 0x1511bb4d675114fe266fc4372b87682baecc01d3cc62cf2303c92b3526012659d16876e25c7c1e57648f23b73564d67f61c6f14d527d54972810421e7d87589e1a7 , s = 0x04a171143a83163d6df460aaf61522695f207a58b95c0644d87e52aa1a347916e4f7a72930b1bc06dbe22ce3f58264afd23704cbb63b29b931f7de6c9d949a7ecfc } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "test" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x01de74955efaabc4c4f17f8e84d881d1310b5392d7700275f82f145c61e843841af09035bf7a6210f5a431a6a9e81c9323354a9e69135d44ebd2fcaa7731b909258 , r = 0x00e871c4a14f993c6c7369501900c4bc1e9c7b0b4ba44e04868b30b41d8071042eb28c4c250411d0ce08cd197e4188ea4876f279f90b3d8d74a3c76e6f1e4656aa8 , s = 0x0cd52dbaa33b063c3a6cd8058a1fb0a46a4754b034fcc644766ca14da8ca5ca9fde00e88c1ad60ccba759025299079d7a427ec3cc5b619bfbc828e7769bcd694e86 } ] rfc6979_vectorsSHA384 = [ VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "sample" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0x4730005c4fcb01834c063a7b6760096dbe284b8252ef4311 , r = 0xda63bf0b9abcf948fbb1e9167f136145f7a20426dcc287d5 , s = 0xc3aa2c960972bd7a2003a57e1c4c77f0578f8ae95e31ec5e } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "test" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0x5afefb5d3393261b828db6c91fbc68c230727b030c975693 , r = 0xb234b60b4db75a733e19280a7a6034bd6b1ee88af5332367 , s = 0x7994090b2d59bb782be57e74a44c9a1c700413f8abefe77a } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "sample" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0x52b40f5a9d3d13040f494e83d3906c6079f29981035c7bd51e5cac40 , r = 0x0b115e5e36f0f9ec81f1325a5952878d745e19d7bb3eabfaba77e953 , s = 0x830f34ccdfe826ccfdc81eb4129772e20e122348a2bbd889a1b1af1d } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "test" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0x7046742b839478c1b5bd31db2e862ad868e1a45c863585b5f22bdc2d , r = 0x389b92682e399b26518a95506b52c03bc9379a9dadf3391a21fb0ea4 , s = 0x414a718ed3249ff6dbc5b50c27f71f01f070944da22ab1f78f559aab } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "sample" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0x09f634b188cefd98e7ec88b1aa9852d734d0bc272f7d2a47decc6ebeb375aad4 , r = 0x0eafea039b20e9b42309fb1d89e213057cbf973dc0cfc8f129edddc800ef7719 , s = 0x4861f0491e6998b9455193e34e7b0d284ddd7149a74b95b9261f13abde940954 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "test" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0x16aeffa357260b04b1dd199693960740066c1a8f3e8edd79070aa914d361b3b8 , r = 0x83910e8b48bb0c74244ebdf7f07a1c5413d61472bd941ef3920e623fbccebeb6 , s = 0x8ddbec54cf8cd5874883841d712142a56a8d0f218f5003cb0296b6b509619f2c } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "sample" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x94ed910d1a099dad3254e9242ae85abde4ba15168eaf0ca87a555fd56d10fbca2907e3e83ba95368623b8c4686915cf9 , r = 0x94edbb92a5ecb8aad4736e56c691916b3f88140666ce9fa73d64c4ea95ad133c81a648152e44acf96e36dd1e80fabe46 , s = 0x99ef4aeb15f178cea1fe40db2603138f130e740a19624526203b6351d0a3a94fa329c145786e679e7b82c71a38628ac8 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "test" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x015ee46a5bf88773ed9123a5ab0807962d193719503c527b031b4c2d225092ada71f4a459bc0da98adb95837db8312ea , r = 0x8203b63d3c853e8d77227fb377bcf7b7b772e97892a80f36ab775d509d7a5feb0542a7f0812998da8f1dd3ca3cf023db , s = 0xddd0760448d42d8a43af45af836fce4de8be06b485e9b61b827c2f13173923e06a739f040649a667bf3b828246baa5a5 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "sample" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x1546a108bc23a15d6f21872f7ded661fa8431ddbd922d0dcdb77cc878c8553ffad064c95a920a750ac9137e527390d2d92f153e66196966ea554d9adfcb109c4211 , r = 0x1ea842a0e17d2de4f92c15315c63ddf72685c18195c2bb95e572b9c5136ca4b4b576ad712a52be9730627d16054ba40cc0b8d3ff035b12ae75168397f5d50c67451 , s = 0x1f21a3cee066e1961025fb048bd5fe2b7924d0cd797babe0a83b66f1e35eeaf5fde143fa85dc394a7dee766523393784484bdf3e00114a1c857cde1aa203db65d61 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "test" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x1f1fc4a349a7da9a9e116bfdd055dc08e78252ff8e23ac276ac88b1770ae0b5dceb1ed14a4916b769a523ce1e90ba22846af11df8b300c38818f713dadd85de0c88 , r = 0x14bee21a18b6d8b3c93fab08d43e739707953244fdbe924fa926d76669e7ac8c89df62ed8975c2d8397a65a49dcc09f6b0ac62272741924d479354d74ff6075578c , s = 0x133330865c067a0eaf72362a65e2d7bc4e461e8c8995c3b6226a21bd1aa78f0ed94fe536a0dca35534f0cd1510c41525d163fe9d74d134881e35141ed5e8e95b979 } ] rfc6979_vectorsSHA512 = [ VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "sample" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0xa2ac7ab055e4f20692d49209544c203a7d1f2c0bfbc75db1 , r = 0x4d60c5ab1996bd848343b31c00850205e2ea6922dac2e4b8 , s = 0x3f6e837448f027a1bf4b34e796e32a811cbb4050908d8f67 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p192r1 , msg = "test" , d = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4 , q = ECC.Point 0xac2c77f529f91689fea0ea5efec7f210d8eea0b9e047ed56 0x3bc723e57670bd4887ebc732c523063d0a7c957bc97c1c43 , k = 0x0758753a5254759c7cfbad2e2d9b0792eee44136c9480527 , r = 0xfe4f4ae86a58b6507946715934fe2d8ff9d95b6b098fe739 , s = 0x74cf5605c98fba0e1ef34d4b5a1577a7dcf59457cae52290 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "sample" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0x9db103ffededf9cfdba05184f925400c1653b8501bab89cea0fbec14 , r = 0x074bd1d979d5f32bf958ddc61e4fb4872adcafeb2256497cdac30397 , s = 0xa4ceca196c3d5a1ff31027b33185dc8ee43f288b21ab342e5d8eb084 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p224r1 , msg = "test" , d = 0xf220266e1105bfe3083e03ec7a3a654651f45e37167e88600bf257c1 , q = ECC.Point 0x00cf08da5ad719e42707fa431292dea11244d64fc51610d94b130d6c 0xeeab6f3debe455e3dbf85416f7030cbd94f34f2d6f232c69f3c1385a , k = 0xe39c2aa4ea6be2306c72126d40ed77bf9739bb4d6ef2bbb1dcb6169d , r = 0x049f050477c5add858cac56208394b5a55baebbe887fdf765047c17c , s = 0x077eb13e7005929cefa3cd0403c7cdcc077adf4e44f3c41b2f60ecff } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "sample" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0x5fa81c63109badb88c1f367b47da606da28cad69aa22c4fe6ad7df73a7173aa5 , r = 0x8496a60b5e9b47c825488827e0495b0e3fa109ec4568fd3f8d1097678eb97f00 , s = 0x2362ab1adbe2b8adf9cb9edab740ea6049c028114f2460f96554f61fae3302fe } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p256r1 , msg = "test" , d = 0xc9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721 , q = ECC.Point 0x60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 0x7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 , k = 0x6915d11632aca3c40d5d51c08daf9c555933819548784480e93499000d9f0b7f , r = 0x461d93f31b6540894788fd206c07cfa0cc35f46fa3c91816fff1040ad1581a04 , s = 0x39af9f15de0db8d97e72719c74820d304ce5226e32dedae67519e840d1194e55 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "sample" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x92fc3c7183a883e24216d1141f1a8976c5b0dd797dfa597e3d7b32198bd35331a4e966532593a52980d0e3aaa5e10ec3 , r = 0xed0959d5880ab2d869ae7f6c2915c6d60f96507f9cb3e047c0046861da4a799cfe30f35cc900056d7c99cd7882433709 , s = 0x512c8cceee3890a84058ce1e22dbc2198f42323ce8aca9135329f03c068e5112dc7cc3ef3446defceb01a45c2667fdd5 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p384r1 , msg = "test" , d = 0x6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5 , q = ECC.Point 0xec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64def8f0ea9055866064a254515480bc13 0x8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1288b231c3ae0d4fe7344fd2533264720 , k = 0x3780c4f67cb15518b6acae34c9f83568d2e12e47deab6c50a4e4ee5319d1e8ce0e2cc8a136036dc4b9c00e6888f66b6c , r = 0xa0d5d090c9980faf3c2ce57b7ae951d31977dd11c775d314af55f76c676447d06fb6495cd21b4b6e340fc236584fb277 , s = 0x976984e59b4c77b0e8e4460dca3d9f20e07b9bb1f63beefaf576f6b2e8b224634a2092cd3792e0159ad9cee37659c736 } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "sample" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x1dae2ea071f8110dc26882d4d5eae0621a3256fc8847fb9022e2b7d28e6f10198b1574fdd03a9053c08a1854a168aa5a57470ec97dd5ce090124ef52a2f7ecbffd3 , r = 0x0c328fafcbd79dd77850370c46325d987cb525569fb63c5d3bc53950e6d4c5f174e25a1ee9017b5d450606add152b534931d7d4e8455cc91f9b15bf05ec36e377fa , s = 0x0617cce7cf5064806c467f678d3b4080d6f1cc50af26ca209417308281b68af282623eaa63e5b5c0723d8b8c37ff0777b1a20f8ccb1dccc43997f1ee0e44da4a67a } , VectorECDSA { curve = ECC.getCurveByName ECC.SEC_p521r1 , msg = "test" , d = 0x0fad06daa62ba3b25d2fb40133da757205de67f5bb0018fee8c86e1b68c7e75caa896eb32f1f47c70855836a6d16fcc1466f6d8fbec67db89ec0c08b0e996b83538 , q = ECC.Point 0x1894550d0785932e00eaa23b694f213f8c3121f86dc97a04e5a7167db4e5bcd371123d46e45db6b5d5370a7f20fb633155d38ffa16d2bd761dcac474b9a2f5023a4 0x0493101c962cd4d2fddf782285e64584139c2f91b47f87ff82354d6630f746a28a0db25741b5b34a828008b22acc23f924faafbd4d33f81ea66956dfeaa2bfdfcf5 , k = 0x16200813020ec986863bedfc1b121f605c1215645018aea1a7b215a564de9eb1b38a67aa1128b80ce391c4fb71187654aaa3431027bfc7f395766ca988c964dc56d , r = 0x13e99020abf5cee7525d16b69b229652ab6bdf2affcaef38773b4b7d08725f10cdb93482fdcc54edcee91eca4166b2a7c6265ef0ce2bd7051b7cef945babd47ee6d , s = 0x1fbd0013c674aa79cb39849527916ce301c66ea7ce8b80682786ad60f98f7e78a19ca69eff5c57400e3b3a0ad66ce0978214d13baf4e9ac60752f7b155e2de4dce3 } ] vectorToPrivate :: VectorECDSA -> ECDSA.PrivateKey vectorToPrivate vector = ECDSA.PrivateKey (curve vector) (d vector) vectorToPublic :: VectorECDSA -> ECDSA.PublicKey vectorToPublic vector = ECDSA.PublicKey (curve vector) (q vector) doSignatureTest hashAlg i vector = testCase (show i) (expected @=? actual) where expected = Just $ ECDSA.Signature (r vector) (s vector) actual = ECDSA.signWith (k vector) (vectorToPrivate vector) hashAlg (msg vector) doVerifyTest hashAlg i vector = testCase (show i) (True @=? actual) where actual = ECDSA.verify hashAlg (vectorToPublic vector) (ECDSA.Signature (r vector) (s vector)) (msg vector) ecdsaTests = testGroup "ECDSA" [ testGroup "SHA1" [ testGroup "signature" $ zipWith (doSignatureTest SHA1) [katZero..] vectorsSHA1 , testGroup "verify" $ zipWith (doVerifyTest SHA1) [katZero..] vectorsSHA1 ] , testGroup "SHA224" [ testGroup "signature" $ zipWith (doSignatureTest SHA224) [katZero..] rfc6979_vectorsSHA224 , testGroup "verify" $ zipWith (doVerifyTest SHA224) [katZero..] rfc6979_vectorsSHA224 ] , testGroup "SHA256" [ testGroup "signature" $ zipWith (doSignatureTest SHA256) [katZero..] rfc6979_vectorsSHA256 , testGroup "verify" $ zipWith (doVerifyTest SHA256) [katZero..] rfc6979_vectorsSHA256 ] , testGroup "SHA384" [ testGroup "signature" $ zipWith (doSignatureTest SHA384) [katZero..] rfc6979_vectorsSHA384 , testGroup "verify" $ zipWith (doVerifyTest SHA384) [katZero..] rfc6979_vectorsSHA384 ] , testGroup "SHA512" [ testGroup "signature" $ zipWith (doSignatureTest SHA512) [katZero..] rfc6979_vectorsSHA512 , testGroup "verify" $ zipWith (doVerifyTest SHA512) [katZero..] rfc6979_vectorsSHA512 ] ]
vincenthz/cryptonite
tests/KAT_PubKey/ECDSA.hs
bsd-3-clause
35,165
0
12
7,315
3,485
2,062
1,423
447
1
{-# LANGUAGE Haskell2010, CPP, Rank2Types, DeriveDataTypeable, StandaloneDeriving #-} {-# LINE 1 "lib/Data/Time/Clock/Scale.hs" #-} {-# LANGUAGE Trustworthy #-} {-# OPTIONS -fno-warn-unused-imports #-} -- #hide module Data.Time.Clock.Scale ( -- * Universal Time -- | Time as measured by the earth. UniversalTime(..), -- * Absolute intervals DiffTime, secondsToDiffTime, picosecondsToDiffTime, diffTimeToPicoseconds, ) where import Control.DeepSeq import Data.Ratio ((%)) import Data.Fixed import Data.Typeable import Data.Data -- | The Modified Julian Date is the day with the fraction of the day, measured from UT midnight. -- It's used to represent UT1, which is time as measured by the earth's rotation, adjusted for various wobbles. newtype UniversalTime = ModJulianDate {getModJulianDate :: Rational} deriving (Eq,Ord ,Data, Typeable ) -- necessary because H98 doesn't have "cunning newtype" derivation instance NFData UniversalTime where rnf (ModJulianDate a) = rnf a -- | This is a length of time, as measured by a clock. -- Conversion functions will treat it as seconds. -- It has a precision of 10^-12 s. newtype DiffTime = MkDiffTime Pico deriving (Eq,Ord ,Data, Typeable ) -- necessary because H98 doesn't have "cunning newtype" derivation instance NFData DiffTime where -- FIXME: Data.Fixed had no NFData instances yet at time of writing rnf dt = seq dt () -- necessary because H98 doesn't have "cunning newtype" derivation instance Enum DiffTime where succ (MkDiffTime a) = MkDiffTime (succ a) pred (MkDiffTime a) = MkDiffTime (pred a) toEnum = MkDiffTime . toEnum fromEnum (MkDiffTime a) = fromEnum a enumFrom (MkDiffTime a) = fmap MkDiffTime (enumFrom a) enumFromThen (MkDiffTime a) (MkDiffTime b) = fmap MkDiffTime (enumFromThen a b) enumFromTo (MkDiffTime a) (MkDiffTime b) = fmap MkDiffTime (enumFromTo a b) enumFromThenTo (MkDiffTime a) (MkDiffTime b) (MkDiffTime c) = fmap MkDiffTime (enumFromThenTo a b c) instance Show DiffTime where show (MkDiffTime t) = (showFixed True t) ++ "s" -- necessary because H98 doesn't have "cunning newtype" derivation instance Num DiffTime where (MkDiffTime a) + (MkDiffTime b) = MkDiffTime (a + b) (MkDiffTime a) - (MkDiffTime b) = MkDiffTime (a - b) (MkDiffTime a) * (MkDiffTime b) = MkDiffTime (a * b) negate (MkDiffTime a) = MkDiffTime (negate a) abs (MkDiffTime a) = MkDiffTime (abs a) signum (MkDiffTime a) = MkDiffTime (signum a) fromInteger i = MkDiffTime (fromInteger i) -- necessary because H98 doesn't have "cunning newtype" derivation instance Real DiffTime where toRational (MkDiffTime a) = toRational a -- necessary because H98 doesn't have "cunning newtype" derivation instance Fractional DiffTime where (MkDiffTime a) / (MkDiffTime b) = MkDiffTime (a / b) recip (MkDiffTime a) = MkDiffTime (recip a) fromRational r = MkDiffTime (fromRational r) -- necessary because H98 doesn't have "cunning newtype" derivation instance RealFrac DiffTime where properFraction (MkDiffTime a) = let (b',a') = properFraction a in (b',MkDiffTime a') truncate (MkDiffTime a) = truncate a round (MkDiffTime a) = round a ceiling (MkDiffTime a) = ceiling a floor (MkDiffTime a) = floor a -- | Create a 'DiffTime' which represents an integral number of seconds. secondsToDiffTime :: Integer -> DiffTime secondsToDiffTime = fromInteger -- | Create a 'DiffTime' from a number of picoseconds. picosecondsToDiffTime :: Integer -> DiffTime picosecondsToDiffTime x = MkDiffTime (MkFixed x) -- | Get the number of picoseconds in a 'DiffTime'. diffTimeToPicoseconds :: DiffTime -> Integer diffTimeToPicoseconds (MkDiffTime (MkFixed x)) = x {-# RULES "realToFrac/DiffTime->Pico" realToFrac = \ (MkDiffTime ps) -> ps "realToFrac/Pico->DiffTime" realToFrac = MkDiffTime #-}
phischu/fragnix
tests/packages/scotty/Data.Time.Clock.Scale.hs
bsd-3-clause
3,960
0
10
798
936
485
451
64
1
module Snap.Snaplet.Auth.Types.Tests ( tests ) where ------------------------------------------------------------------------------ import Control.Exception (SomeException, evaluate, try) import Control.Monad (liftM) import Data.Aeson (decode, eitherDecode, encode) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit hiding (Test) import qualified Test.QuickCheck as QC import qualified Test.QuickCheck.Monadic as QCM ------------------------------------------------------------------------------ import qualified Snap.Snaplet.Auth as A import Snap.TestCommon (eqTestCase, ordTestCase, readTestCase, showTestCase) ------------------------------------------------------------------------------ tests :: Test tests = testGroup "Auth type tests" [ testCase "Password serialization" dontSerializeClearText , testCase "Fill in [] roles" deserializeDefaultRoles , testCase "Fail deserialization" failDeserialize , testProperty "AuthFailure show instances" authFailureShows , testProperty "Encrypt agrees with password" encryptByteString , testCase "Reject clear encrypted pw check" rejectCheckClearText , testCase "Test Role Show instance" $ showTestCase (A.Role "a") , testCase "Test Role Read instance" $ readTestCase (A.Role "a") , testCase "Test Role Ord instance" $ ordTestCase (A.Role "a") (A.Role "b") , testCase "Test PW Show instance" $ showTestCase (A.ClearText "pw") , testCase "Test PW Read instance" $ readTestCase (A.ClearText "pw") , testCase "Test PW Ord instance" $ ordTestCase (A.ClearText "a") (A.ClearText "b") , testCase "Test AuthFailure Eq instance" $ eqTestCase A.BackendError A.DuplicateLogin --TODO better as property , testCase "Test AuthFailure Show instance" $ showTestCase A.BackendError -- , testCase "Test AuthFailure Read instance" $ -- readTestCase BackendError -- TODO/NOTE: show . read isn't id for , testCase "Test AuthFailure Ord instance" $ ordTestCase A.BackendError A.DuplicateLogin , testCase "Test UserId Show instance" $ showTestCase (A.UserId "1") , testCase "Test UserId Read instance" $ readTestCase (A.UserId "2") , testCase "Test AuthUser Show instance" $ showTestCase A.defAuthUser , testCase "Test AuthUser Eq instance" $ eqTestCase A.defAuthUser A.defAuthUser ] ------------------------------------------------------------------------------ dontSerializeClearText :: Assertion dontSerializeClearText = do let s = encode (A.ClearText "passwordisnthamster") -- Take the length of the ByteString to force it completely, rather than -- using deepseq; BSL.ByteString lacked an NFData instance until -- bytestring-0.10. r <- try $ evaluate (BSL.length s) >> return s case r of Left e -> (e :: SomeException) `seq` return () Right j -> assertFailure $ "Failed to reject ClearText password serialization: " ++ show j ------------------------------------------------------------------------------ sampleUserJson :: T.Text -> T.Text -> T.Text sampleUserJson reqPair optPair = T.intercalate "," [ "{\"uid\":\"1\"" , "\"login\":\"foo\"" , "\"email\":\"[email protected]\"" , "\"pw\":\"sha256|12|gz47sA0OvbVjos51OJRauQ==|Qe5aU2zAH0gIKHP68KrHJkvvwTvTAqA6UgA33BRpNEo=\"" , reqPair , "\"suspended_at\":null" , "\"remember_token\":\"81160620ef9b64865980c2ab760fcf7f14c06e057cbe1e723cba884a9be05547\"" , "\"login_count\":2" , "\"failed_login_count\":1" , "\"locked_until\":null" , "\"current_login_at\":\"2014-06-24T14:43:51.241Z\"" , "\"last_login_at\":null" , "\"current_ip\":\"127.0.0.1\"" , "\"last_ip\":null" , "\"created_at\":\"2014-06-24T14:43:51.236Z\"" , "\"updated_at\":\"2014-06-24T14:43:51.242Z\"" , "\"reset_token\":null" , "\"reset_requested_at\":null" , optPair , "\"meta\":{}}" ] ------------------------------------------------------------------------------ deserializeDefaultRoles :: Assertion deserializeDefaultRoles = either (\e -> assertFailure $ "Failed user deserialization: " ++ e) (\u -> assertEqual "Roles wasn't initialized to empty" [] (A.userRoles u)) (eitherDecode . BSL.fromChunks . (:[]) . encodeUtf8 $ sampleUserJson "\"activated_at\":null" "\"extra\":null") ------------------------------------------------------------------------------ failDeserialize :: Assertion failDeserialize = do case decode . BSL.fromChunks . (:[]) . encodeUtf8 $ t of Nothing -> return () Just a -> assertFailure $ "Expected deserialization failure, got authUser: " ++ show (a :: A.AuthUser) where t = T.replace "login" "loogin" $ sampleUserJson "\"extra\":null" "\"extra2\":null" ------------------------------------------------------------------------------ authFailureShows :: A.AuthFailure -> Bool authFailureShows ae = length (show ae) > 0 ------------------------------------------------------------------------------ instance QC.Arbitrary A.AuthFailure where arbitrary = do s <- (QC.arbitrary `QC.suchThat` (( > 0 ) . length)) tA <- QC.arbitrary tB <- QC.arbitrary let t = UTCTime (ModifiedJulianDay tA) (realToFrac (tB :: Double)) QC.oneof $ map return [A.AuthError s, A.BackendError ,A.DuplicateLogin, A.EncryptedPassword ,A.IncorrectPassword, A.LockedOut t ,A.PasswordMissing, A.UsernameMissing ,A.UserNotFound ] ------------------------------------------------------------------------------ encryptByteString :: QC.Property encryptByteString = QCM.monadicIO testStringEq where clearPw = BS.pack `liftM` (QC.arbitrary `QC.suchThat` ((>0) . length)) testStringEq = QCM.forAllM clearPw $ \s -> do ePW <- A.Encrypted `liftM` (QCM.run $ A.encrypt s) let cPW = A.ClearText s {- ePW' <- QCM.run $ encryptPassword (ClearText s) QCM.assert $ (checkPassword cPW ePW && checkPassword cPW cPW && checkPassword ePW ePW') --TODO/NOTe: This fails. Surpsising? Encrypt twice and get two different password hashes -} QCM.assert $ (A.checkPassword cPW ePW && A.checkPassword cPW (A.ClearText s)) ------------------------------------------------------------------------------ rejectCheckClearText :: Assertion rejectCheckClearText = do let b = A.checkPassword (A.Encrypted "") (A.ClearText "") r <- try $ b `seq` return b case r of Left e -> (e :: SomeException) `seq` return () Right _ -> assertFailure "checkPassword should not accept encripted-clear pair"
snapframework/snap
test/suite/Snap/Snaplet/Auth/Types/Tests.hs
bsd-3-clause
7,695
0
17
2,002
1,406
759
647
128
2
module Shift.Verify where import Shift.Type import Shift.Computer import Util.Faktor import Reporter import ToDoc nth :: [Int] -> Int -> [Bool] nth ps q = zustands_folge ps !! q verify :: Int -> Shift -> Reporter Int verify limit sh = do inform $ text "Ich verifiziere" <+> toDoc sh newline let ps = pins sh let q = vorperiode sh let p = periode sh when ( q > limit || p > limit ) $ reject $ fsep [ text "Eine (Vor-)Periode über", toDoc limit , text "kann ich nicht verifizieren," , text "weil das zuviel Rechenkraft verbraucht." ] -- das rechnen wir zweimal aus, damit es jedesmal (hoffentlich) -- in konstantem space läuft let sq = nth ps q let sqp = nth ps (q + p) inform $ fsep [ text "Stimmen die Zustände zu den Zeiten" , toDoc q, text "und", toDoc (p+q), text "überein?" ] when ( sq /= sqp ) $ reject $ text "Nein." inform $ text "Ja." newline inform $ vcat [ text "Gibt es eine kleinere Periode?" , text "Prüfe für alle echten Primteiler von" <+> toDoc p ] newline sequence $ do t <- map fromIntegral $ primfaktoren $ fromIntegral p guard $ t < p return $ do let pt = p `div` t let sqpt = nth ps (q + pt) let flag = ( sq /= sqpt ) inform $ fsep [ text "Teiler", toDoc t, comma , text "Teilperiode", toDoc pt, comma , text "Z" <> parens (toDoc q) , text "/=", text "Z" <> parens (toDoc (q+pt)) , text "...", toDoc flag ] when ( not flag ) $ reject $ text "also war" <+> toDoc p <+> text "nicht die kürzeste Periode." newline return p
Erdwolf/autotool-bonn
src/Shift/Verify.hs
gpl-2.0
1,645
22
18
488
592
292
300
47
1
{-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -XGeneralizedNewtypeDeriving #-} module Internal.Types where import Control.Monad.Error import Control.Monad.State.Strict import qualified Data.Map as Map import Data.IORef import qualified TclObj as T import qualified EventMgr as Evt import Util import TclErr import TclChan class Runnable t where evalTcl :: t -> TclM T.TclObj newtype TclM a = TclM { unTclM :: ErrorT Err (StateT TclState IO) a } deriving (MonadState TclState, MonadError Err, MonadIO, Monad) data Namespace = TclNS { nsName :: BString, nsCmds :: !CmdMap, nsFrame :: !FrameRef, nsExport :: [BString], nsParent :: Maybe NSRef, nsChildren :: Map.Map BString NSRef, nsPath :: [NSRef], nsPathLinks :: [NSRef], nsUnknown :: Maybe BString } type FrameRef = IORef TclFrame type NSRef = IORef Namespace type UpMap = Map.Map BString (FrameRef,BString) data TclFrame = TclFrame { frVars :: !VarMap, upMap :: !UpMap, frNS :: NSRef, frTag :: !Int, frInfo :: [T.TclObj] } type TclStack = [FrameRef] data Interp = Interp { interpState :: IORef TclState } type InterpMap = Map.Map BString Interp data TclState = TclState { interpSafe :: Bool, tclChans :: ChanMap, tclInterps :: InterpMap, tclEvents :: Evt.EventMgr T.TclObj, tclStack :: !TclStack, tclHidden :: CmdMap, tclGlobalNS :: !NSRef, tclCmdCount :: !Int, tclCmdWatchers :: [IO ()] } type TclCmd = [T.TclObj] -> TclM T.TclObj type CmdRef = IORef TclCmdObj data TclCmdObj = TclCmdObj { cmdName :: BString, cmdOrigNS :: Maybe NSRef, cmdParent :: Maybe CmdRef, cmdKids :: [CmdRef], cmdCore :: !CmdCore } cmdIsProc cmd = case cmdCore cmd of ProcCore {} -> True _ -> False cmdIsEnsem cmd = case cmdCore cmd of EnsemCore {} -> True _ -> False type ArgSpec = Either BString (BString,T.TclObj) type ArgList = [ArgSpec] newtype ParamList = ParamList (BString, Bool, ArgList) data CmdCore = CmdCore !TclCmd | EnsemCore { ensemName :: BString, ensemCmd :: TclCmd } | ProcCore { procBody :: BString, procArgs :: !ParamList, procAction :: !(TclM T.TclObj) } type ProcKey = BString data CmdMap = CmdMap { cmdMapEpoch :: !Int, unCmdMap :: !(Map.Map ProcKey CmdRef) } type TclArray = Map.Map BString T.TclObj data TclVar = ScalarVar !T.TclObj | ArrayVar TclArray | Undefined deriving (Eq,Show) type TraceCB = Maybe (IO ()) type VarMap = Map.Map BString (TraceCB,TclVar) runTclM :: TclM a -> TclState -> IO (Either Err a, TclState) runTclM code env = runStateT (runErrorT (unTclM code)) env execTclM c e = do (r,s) <- runTclM c e case r of Right _ -> return s Left e -> error (show e)
muspellsson/hiccup
Internal/Types.hs
lgpl-2.1
3,033
0
12
909
910
515
395
116
2
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.IO.Handle.Text (module M) where import "base" GHC.IO.Handle.Text as M
Ye-Yong-Chi/codeworld
codeworld-base/src/GHC/IO/Handle/Text.hs
apache-2.0
751
0
4
136
27
21
6
4
0
module Heist.TestCommon where ------------------------------------------------------------------------------ import Blaze.ByteString.Builder import Control.Error import Control.Monad.Trans import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import Data.Map.Syntax import Data.Maybe import Data.Monoid ------------------------------------------------------------------------------ import Heist import qualified Heist.Compiled as C import Heist.Internal.Types import qualified Heist.Interpreted as I import qualified Heist.Interpreted.Internal as I import qualified Text.XmlHtml as X ------------------------------------------------------------------------------ -- | The default doctype given to templates doctype :: ByteString doctype = B.concat [ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " , "'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>" ] loadT :: MonadIO m => FilePath -> Splices (I.Splice m) -> Splices (I.Splice IO) -> Splices (C.Splice m) -> Splices (AttrSplice m) -> IO (Either [String] (HeistState m)) loadT baseDir a b c d = runEitherT $ do let sc = SpliceConfig (defaultInterpretedSplices `mappend` a) (defaultLoadTimeSplices `mappend` b) c d [loadTemplates baseDir] initHeist $ HeistConfig sc "" False ------------------------------------------------------------------------------ loadIO :: FilePath -> Splices (I.Splice IO) -> Splices (I.Splice IO) -> Splices (C.Splice IO) -> Splices (AttrSplice IO) -> IO (Either [String] (HeistState IO)) loadIO baseDir a b c d = runEitherT $ do let sc = SpliceConfig (defaultInterpretedSplices >> a) (defaultLoadTimeSplices >> b) c d [loadTemplates baseDir] initHeist $ HeistConfig sc "" False ------------------------------------------------------------------------------ loadHS :: FilePath -> IO (HeistState IO) loadHS baseDir = do etm <- runEitherT $ do let sc = SpliceConfig defaultInterpretedSplices defaultLoadTimeSplices mempty mempty [loadTemplates baseDir] initHeist $ HeistConfig sc "" False either (error . concat) return etm loadEmpty :: Splices (I.Splice IO) -> Splices (I.Splice IO) -> Splices (C.Splice IO) -> Splices (AttrSplice IO) -> IO (HeistState IO) loadEmpty a b c d = do let sc = SpliceConfig (defaultInterpretedSplices `mappend` a) (defaultLoadTimeSplices `mappend` b) c d mempty res <- runEitherT $ initHeist $ HeistConfig sc "" False either (error . concat) return res testTemplate :: FilePath -> ByteString -> IO ByteString testTemplate tdir tname = do ts <- loadHS tdir Just (resDoc, _) <- I.renderTemplate ts tname return $ toByteString resDoc testTemplateEval :: ByteString -> IO (Maybe Template) testTemplateEval tname = do ts <- loadHS "templates" md <- evalHeistT (I.evalWithDoctypes tname) (X.TextNode "") ts return $ fmap X.docContent md ------------------------------------------------------------------------------ -- | Reloads the templates from disk and renders the specified -- template. (Old convenience code.) quickRender :: FilePath -> ByteString -> IO (Maybe ByteString) quickRender baseDir name = do ts <- loadHS baseDir res <- I.renderTemplate ts name return (fmap (toByteString . fst) res) cRender :: HeistState IO -> ByteString -> IO ByteString cRender hs name = do builder <- fst $ fromJust $ C.renderTemplate hs name return $ toByteString builder iRender :: HeistState IO -> ByteString -> IO ByteString iRender hs name = do builder <- I.renderTemplate hs name return $ toByteString $ fst $ fromJust builder
23Skidoo/heist
test/suite/Heist/TestCommon.hs
bsd-3-clause
4,040
0
16
1,014
1,069
539
530
83
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module TestService_Fuzzer (main) where import Module_Types import qualified TestService_Client as Client import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import Control.Applicative (ZipList(..), (<*>)) import Control.Exception import Control.Monad ( liftM, ap, when ) import Data.ByteString.Lazy (ByteString) import Data.Functor ( (<$>) ) import Data.Hashable import Data.Int import Data.Maybe (catMaybes) import Data.Text.Lazy ( Text ) import Data.Text.Lazy.Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as T import Data.Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import Test.QuickCheck.Arbitrary ( Arbitrary(..) ) import Test.QuickCheck ( elements ) import Thrift hiding (ProtocolExnType(..)) import qualified Thrift (ProtocolExnType(..)) import Thrift.Types import Thrift.Arbitraries import Prelude ((>>), print) import qualified Prelude as P import Control.Monad (forM) import qualified Data.List as L import Data.Maybe (fromJust) import qualified Data.Map as Map import GHC.Int (Int64, Int32) import Data.ByteString.Lazy (ByteString) import System.Environment (getArgs) import Test.QuickCheck (arbitrary) import Test.QuickCheck.Gen (Gen(..)) import Thrift.FuzzerSupport handleOptions :: ([Options -> Options], [String], [String]) -> Options handleOptions (transformers, (serviceName:[]), []) | serviceName `P.elem` serviceNames = (P.foldl (P.flip ($)) defaultOptions transformers) { opt_service = serviceName } handleOptions (_, (serviceName:[]), []) | P.otherwise = P.error $ usage ++ "\nUnknown serviceName " ++ serviceName ++ ", should be one of " ++ (P.show serviceNames) handleOptions (_, [], _) = P.error $ usage ++ "\nMissing mandatory serviceName to fuzz." handleOptions (_, _a, []) = P.error $ usage ++ "\nToo many serviceNames, pick one." handleOptions (_, _, e) = P.error $ usage ++ (P.show e) main :: IO () main = do args <- getArgs let config = handleOptions (getOptions args) fuzz config selectFuzzer :: Options -> (Options -> IO ()) selectFuzzer (Options _host _port service _timeout _framed _verbose) = fromJust $ P.lookup service fuzzerFunctions fuzz :: Options -> IO () fuzz config = (selectFuzzer config) config -- Dynamic content -- Configuration via command-line parsing serviceNames :: [String] serviceNames = ["init"] fuzzerFunctions :: [(String, (Options -> IO ()))] fuzzerFunctions = [("init", init_fuzzer)] -- Random data generation inf_Int64 :: IO [Int64] inf_Int64 = infexamples (arbitrary :: Gen Int64) -- Fuzzers and exception handlers init_fuzzer :: Options -> IO () init_fuzzer opts = do a1 <- ZipList <$> inf_Int64 a2 <- ZipList <$> inf_Int64 a3 <- ZipList <$> inf_Int64 a4 <- ZipList <$> inf_Int64 a5 <- ZipList <$> inf_Int64 a6 <- ZipList <$> inf_Int64 a7 <- ZipList <$> inf_Int64 a8 <- ZipList <$> inf_Int64 a9 <- ZipList <$> inf_Int64 a10 <- ZipList <$> inf_Int64 a11 <- ZipList <$> inf_Int64 a12 <- ZipList <$> inf_Int64 a13 <- ZipList <$> inf_Int64 a14 <- ZipList <$> inf_Int64 a15 <- ZipList <$> inf_Int64 a16 <- ZipList <$> inf_Int64 _ <- P.sequence . getZipList $ init_fuzzFunc <$> a1 <*> a2 <*> a3 <*> a4 <*> a5 <*> a6 <*> a7 <*> a8 <*> a9 <*> a10 <*> a11 <*> a12 <*> a13 <*> a14 <*> a15 <*> a16 return () where init_fuzzFunc a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 = let param = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) in if opt_framed opts then withThriftDo opts (withFramedTransport opts) (init_fuzzOnce param) (init_exceptionHandler param) else withThriftDo opts (withHandle opts) (init_fuzzOnce param) (init_exceptionHandler param) init_exceptionHandler :: (Show a1, Show a2, Show a3, Show a4, Show a5, Show a6, Show a7, Show a8, Show a9, Show a10, Show a11, Show a12, Show a13, Show a14, Show a15, Show a16) => (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) -> IO () init_exceptionHandler (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) = do P.putStrLn $ "Got exception on data:" P.putStrLn $ "(" ++ show a1 ++ show a2 ++ show a3 ++ show a4 ++ show a5 ++ show a6 ++ show a7 ++ show a8 ++ show a9 ++ show a10 ++ show a11 ++ show a12 ++ show a13 ++ show a14 ++ show a15 ++ show a16 ++ ")" init_fuzzOnce (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) client = Client.init client a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 >> return ()
raphaelamorim/fbthrift
thrift/compiler/test/fixtures/service-fuzzer/gen-hs/TestService_Fuzzer.hs
apache-2.0
5,467
0
26
1,032
1,892
1,071
821
102
2
{-# LANGUAGE CPP, GADTs, RankNTypes #-} ----------------------------------------------------------------------------- -- -- Cmm utilities. -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module CmmUtils( -- CmmType primRepCmmType, primRepForeignHint, typeCmmType, typeForeignHint, -- CmmLit zeroCLit, mkIntCLit, mkWordCLit, packHalfWordsCLit, mkByteStringCLit, mkDataLits, mkRODataLits, mkStgWordCLit, -- CmmExpr mkIntExpr, zeroExpr, mkLblExpr, cmmRegOff, cmmOffset, cmmLabelOff, cmmOffsetLit, cmmOffsetExpr, cmmRegOffB, cmmOffsetB, cmmLabelOffB, cmmOffsetLitB, cmmOffsetExprB, cmmRegOffW, cmmOffsetW, cmmLabelOffW, cmmOffsetLitW, cmmOffsetExprW, cmmIndex, cmmIndexExpr, cmmLoadIndex, cmmLoadIndexW, cmmNegate, cmmULtWord, cmmUGeWord, cmmUGtWord, cmmSubWord, cmmNeWord, cmmEqWord, cmmOrWord, cmmAndWord, cmmUShrWord, cmmAddWord, cmmMulWord, cmmQuotWord, cmmToWord, isTrivialCmmExpr, hasNoGlobalRegs, -- Statics blankWord, -- Tagging cmmTagMask, cmmPointerMask, cmmUntag, cmmIsTagged, cmmConstrTag1, -- Liveness and bitmaps mkLiveness, -- * Operations that probably don't belong here modifyGraph, ofBlockMap, toBlockMap, insertBlock, ofBlockList, toBlockList, bodyToBlockList, toBlockListEntryFirst, toBlockListEntryFirstFalseFallthrough, foldGraphBlocks, mapGraphNodes, postorderDfs, mapGraphNodes1, analFwd, analBwd, analRewFwd, analRewBwd, dataflowPassFwd, dataflowPassBwd, dataflowAnalFwd, dataflowAnalBwd, dataflowAnalFwdBlocks, -- * Ticks blockTicks ) where #include "HsVersions.h" import TyCon ( PrimRep(..), PrimElemRep(..) ) import Type ( UnaryType, typePrimRep ) import SMRep import Cmm import BlockId import CLabel import Outputable import Unique import UniqSupply import DynFlags import Util import Data.Word import Data.Maybe import Data.Bits import Hoopl --------------------------------------------------- -- -- CmmTypes -- --------------------------------------------------- primRepCmmType :: DynFlags -> PrimRep -> CmmType primRepCmmType _ VoidRep = panic "primRepCmmType:VoidRep" primRepCmmType dflags PtrRep = gcWord dflags primRepCmmType dflags IntRep = bWord dflags primRepCmmType dflags WordRep = bWord dflags primRepCmmType _ Int64Rep = b64 primRepCmmType _ Word64Rep = b64 primRepCmmType dflags AddrRep = bWord dflags primRepCmmType _ FloatRep = f32 primRepCmmType _ DoubleRep = f64 primRepCmmType _ (VecRep len rep) = vec len (primElemRepCmmType rep) primElemRepCmmType :: PrimElemRep -> CmmType primElemRepCmmType Int8ElemRep = b8 primElemRepCmmType Int16ElemRep = b16 primElemRepCmmType Int32ElemRep = b32 primElemRepCmmType Int64ElemRep = b64 primElemRepCmmType Word8ElemRep = b8 primElemRepCmmType Word16ElemRep = b16 primElemRepCmmType Word32ElemRep = b32 primElemRepCmmType Word64ElemRep = b64 primElemRepCmmType FloatElemRep = f32 primElemRepCmmType DoubleElemRep = f64 typeCmmType :: DynFlags -> UnaryType -> CmmType typeCmmType dflags ty = primRepCmmType dflags (typePrimRep ty) primRepForeignHint :: PrimRep -> ForeignHint primRepForeignHint VoidRep = panic "primRepForeignHint:VoidRep" primRepForeignHint PtrRep = AddrHint primRepForeignHint IntRep = SignedHint primRepForeignHint WordRep = NoHint primRepForeignHint Int64Rep = SignedHint primRepForeignHint Word64Rep = NoHint primRepForeignHint AddrRep = AddrHint -- NB! AddrHint, but NonPtrArg primRepForeignHint FloatRep = NoHint primRepForeignHint DoubleRep = NoHint primRepForeignHint (VecRep {}) = NoHint typeForeignHint :: UnaryType -> ForeignHint typeForeignHint = primRepForeignHint . typePrimRep --------------------------------------------------- -- -- CmmLit -- --------------------------------------------------- -- XXX: should really be Integer, since Int doesn't necessarily cover -- the full range of target Ints. mkIntCLit :: DynFlags -> Int -> CmmLit mkIntCLit dflags i = CmmInt (toInteger i) (wordWidth dflags) mkIntExpr :: DynFlags -> Int -> CmmExpr mkIntExpr dflags i = CmmLit $! mkIntCLit dflags i zeroCLit :: DynFlags -> CmmLit zeroCLit dflags = CmmInt 0 (wordWidth dflags) zeroExpr :: DynFlags -> CmmExpr zeroExpr dflags = CmmLit (zeroCLit dflags) mkWordCLit :: DynFlags -> Integer -> CmmLit mkWordCLit dflags wd = CmmInt wd (wordWidth dflags) mkByteStringCLit :: Unique -> [Word8] -> (CmmLit, GenCmmDecl CmmStatics info stmt) -- We have to make a top-level decl for the string, -- and return a literal pointing to it mkByteStringCLit uniq bytes = (CmmLabel lbl, CmmData ReadOnlyData $ Statics lbl [CmmString bytes]) where lbl = mkStringLitLabel uniq mkDataLits :: Section -> CLabel -> [CmmLit] -> GenCmmDecl CmmStatics info stmt -- Build a data-segment data block mkDataLits section lbl lits = CmmData section (Statics lbl $ map CmmStaticLit lits) mkRODataLits :: CLabel -> [CmmLit] -> GenCmmDecl CmmStatics info stmt -- Build a read-only data block mkRODataLits lbl lits = mkDataLits section lbl lits where section | any needsRelocation lits = RelocatableReadOnlyData | otherwise = ReadOnlyData needsRelocation (CmmLabel _) = True needsRelocation (CmmLabelOff _ _) = True needsRelocation _ = False mkStgWordCLit :: DynFlags -> StgWord -> CmmLit mkStgWordCLit dflags wd = CmmInt (fromStgWord wd) (wordWidth dflags) packHalfWordsCLit :: DynFlags -> StgHalfWord -> StgHalfWord -> CmmLit -- Make a single word literal in which the lower_half_word is -- at the lower address, and the upper_half_word is at the -- higher address -- ToDo: consider using half-word lits instead -- but be careful: that's vulnerable when reversed packHalfWordsCLit dflags lower_half_word upper_half_word = if wORDS_BIGENDIAN dflags then mkWordCLit dflags ((l `shiftL` hALF_WORD_SIZE_IN_BITS dflags) .|. u) else mkWordCLit dflags (l .|. (u `shiftL` hALF_WORD_SIZE_IN_BITS dflags)) where l = fromStgHalfWord lower_half_word u = fromStgHalfWord upper_half_word --------------------------------------------------- -- -- CmmExpr -- --------------------------------------------------- mkLblExpr :: CLabel -> CmmExpr mkLblExpr lbl = CmmLit (CmmLabel lbl) cmmOffsetExpr :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr -- assumes base and offset have the same CmmType cmmOffsetExpr dflags e (CmmLit (CmmInt n _)) = cmmOffset dflags e (fromInteger n) cmmOffsetExpr dflags e byte_off = CmmMachOp (MO_Add (cmmExprWidth dflags e)) [e, byte_off] -- NB. Do *not* inspect the value of the offset in these smart constructors!!! -- because the offset is sometimes involved in a loop in the code generator -- (we don't know the real Hp offset until we've generated code for the entire -- basic block, for example). So we cannot eliminate zero offsets at this -- stage; they're eliminated later instead (either during printing or -- a later optimisation step on Cmm). -- cmmOffset :: DynFlags -> CmmExpr -> Int -> CmmExpr cmmOffset _ e 0 = e cmmOffset _ (CmmReg reg) byte_off = cmmRegOff reg byte_off cmmOffset _ (CmmRegOff reg m) byte_off = cmmRegOff reg (m+byte_off) cmmOffset _ (CmmLit lit) byte_off = CmmLit (cmmOffsetLit lit byte_off) cmmOffset _ (CmmStackSlot area off) byte_off = CmmStackSlot area (off - byte_off) -- note stack area offsets increase towards lower addresses cmmOffset _ (CmmMachOp (MO_Add rep) [expr, CmmLit (CmmInt byte_off1 _rep)]) byte_off2 = CmmMachOp (MO_Add rep) [expr, CmmLit (CmmInt (byte_off1 + toInteger byte_off2) rep)] cmmOffset dflags expr byte_off = CmmMachOp (MO_Add width) [expr, CmmLit (CmmInt (toInteger byte_off) width)] where width = cmmExprWidth dflags expr -- Smart constructor for CmmRegOff. Same caveats as cmmOffset above. cmmRegOff :: CmmReg -> Int -> CmmExpr cmmRegOff reg 0 = CmmReg reg cmmRegOff reg byte_off = CmmRegOff reg byte_off cmmOffsetLit :: CmmLit -> Int -> CmmLit cmmOffsetLit (CmmLabel l) byte_off = cmmLabelOff l byte_off cmmOffsetLit (CmmLabelOff l m) byte_off = cmmLabelOff l (m+byte_off) cmmOffsetLit (CmmLabelDiffOff l1 l2 m) byte_off = CmmLabelDiffOff l1 l2 (m+byte_off) cmmOffsetLit (CmmInt m rep) byte_off = CmmInt (m + fromIntegral byte_off) rep cmmOffsetLit _ byte_off = pprPanic "cmmOffsetLit" (ppr byte_off) cmmLabelOff :: CLabel -> Int -> CmmLit -- Smart constructor for CmmLabelOff cmmLabelOff lbl 0 = CmmLabel lbl cmmLabelOff lbl byte_off = CmmLabelOff lbl byte_off -- | Useful for creating an index into an array, with a staticaly known offset. -- The type is the element type; used for making the multiplier cmmIndex :: DynFlags -> Width -- Width w -> CmmExpr -- Address of vector of items of width w -> Int -- Which element of the vector (0 based) -> CmmExpr -- Address of i'th element cmmIndex dflags width base idx = cmmOffset dflags base (idx * widthInBytes width) -- | Useful for creating an index into an array, with an unknown offset. cmmIndexExpr :: DynFlags -> Width -- Width w -> CmmExpr -- Address of vector of items of width w -> CmmExpr -- Which element of the vector (0 based) -> CmmExpr -- Address of i'th element cmmIndexExpr dflags width base (CmmLit (CmmInt n _)) = cmmIndex dflags width base (fromInteger n) cmmIndexExpr dflags width base idx = cmmOffsetExpr dflags base byte_off where idx_w = cmmExprWidth dflags idx byte_off = CmmMachOp (MO_Shl idx_w) [idx, mkIntExpr dflags (widthInLog width)] cmmLoadIndex :: DynFlags -> CmmType -> CmmExpr -> Int -> CmmExpr cmmLoadIndex dflags ty expr ix = CmmLoad (cmmIndex dflags (typeWidth ty) expr ix) ty -- The "B" variants take byte offsets cmmRegOffB :: CmmReg -> ByteOff -> CmmExpr cmmRegOffB = cmmRegOff cmmOffsetB :: DynFlags -> CmmExpr -> ByteOff -> CmmExpr cmmOffsetB = cmmOffset cmmOffsetExprB :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr cmmOffsetExprB = cmmOffsetExpr cmmLabelOffB :: CLabel -> ByteOff -> CmmLit cmmLabelOffB = cmmLabelOff cmmOffsetLitB :: CmmLit -> ByteOff -> CmmLit cmmOffsetLitB = cmmOffsetLit ----------------------- -- The "W" variants take word offsets cmmOffsetExprW :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr -- The second arg is a *word* offset; need to change it to bytes cmmOffsetExprW dflags e (CmmLit (CmmInt n _)) = cmmOffsetW dflags e (fromInteger n) cmmOffsetExprW dflags e wd_off = cmmIndexExpr dflags (wordWidth dflags) e wd_off cmmOffsetW :: DynFlags -> CmmExpr -> WordOff -> CmmExpr cmmOffsetW dflags e n = cmmOffsetB dflags e (wordsToBytes dflags n) cmmRegOffW :: DynFlags -> CmmReg -> WordOff -> CmmExpr cmmRegOffW dflags reg wd_off = cmmRegOffB reg (wordsToBytes dflags wd_off) cmmOffsetLitW :: DynFlags -> CmmLit -> WordOff -> CmmLit cmmOffsetLitW dflags lit wd_off = cmmOffsetLitB lit (wordsToBytes dflags wd_off) cmmLabelOffW :: DynFlags -> CLabel -> WordOff -> CmmLit cmmLabelOffW dflags lbl wd_off = cmmLabelOffB lbl (wordsToBytes dflags wd_off) cmmLoadIndexW :: DynFlags -> CmmExpr -> Int -> CmmType -> CmmExpr cmmLoadIndexW dflags base off ty = CmmLoad (cmmOffsetW dflags base off) ty ----------------------- cmmULtWord, cmmUGeWord, cmmUGtWord, cmmSubWord, cmmNeWord, cmmEqWord, cmmOrWord, cmmAndWord, cmmUShrWord, cmmAddWord, cmmMulWord, cmmQuotWord :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr cmmOrWord dflags e1 e2 = CmmMachOp (mo_wordOr dflags) [e1, e2] cmmAndWord dflags e1 e2 = CmmMachOp (mo_wordAnd dflags) [e1, e2] cmmNeWord dflags e1 e2 = CmmMachOp (mo_wordNe dflags) [e1, e2] cmmEqWord dflags e1 e2 = CmmMachOp (mo_wordEq dflags) [e1, e2] cmmULtWord dflags e1 e2 = CmmMachOp (mo_wordULt dflags) [e1, e2] cmmUGeWord dflags e1 e2 = CmmMachOp (mo_wordUGe dflags) [e1, e2] cmmUGtWord dflags e1 e2 = CmmMachOp (mo_wordUGt dflags) [e1, e2] --cmmShlWord dflags e1 e2 = CmmMachOp (mo_wordShl dflags) [e1, e2] cmmUShrWord dflags e1 e2 = CmmMachOp (mo_wordUShr dflags) [e1, e2] cmmAddWord dflags e1 e2 = CmmMachOp (mo_wordAdd dflags) [e1, e2] cmmSubWord dflags e1 e2 = CmmMachOp (mo_wordSub dflags) [e1, e2] cmmMulWord dflags e1 e2 = CmmMachOp (mo_wordMul dflags) [e1, e2] cmmQuotWord dflags e1 e2 = CmmMachOp (mo_wordUQuot dflags) [e1, e2] cmmNegate :: DynFlags -> CmmExpr -> CmmExpr cmmNegate _ (CmmLit (CmmInt n rep)) = CmmLit (CmmInt (-n) rep) cmmNegate dflags e = CmmMachOp (MO_S_Neg (cmmExprWidth dflags e)) [e] blankWord :: DynFlags -> CmmStatic blankWord dflags = CmmUninitialised (wORD_SIZE dflags) cmmToWord :: DynFlags -> CmmExpr -> CmmExpr cmmToWord dflags e | w == word = e | otherwise = CmmMachOp (MO_UU_Conv w word) [e] where w = cmmExprWidth dflags e word = wordWidth dflags --------------------------------------------------- -- -- CmmExpr predicates -- --------------------------------------------------- isTrivialCmmExpr :: CmmExpr -> Bool isTrivialCmmExpr (CmmLoad _ _) = False isTrivialCmmExpr (CmmMachOp _ _) = False isTrivialCmmExpr (CmmLit _) = True isTrivialCmmExpr (CmmReg _) = True isTrivialCmmExpr (CmmRegOff _ _) = True isTrivialCmmExpr (CmmStackSlot _ _) = panic "isTrivialCmmExpr CmmStackSlot" hasNoGlobalRegs :: CmmExpr -> Bool hasNoGlobalRegs (CmmLoad e _) = hasNoGlobalRegs e hasNoGlobalRegs (CmmMachOp _ es) = all hasNoGlobalRegs es hasNoGlobalRegs (CmmLit _) = True hasNoGlobalRegs (CmmReg (CmmLocal _)) = True hasNoGlobalRegs (CmmRegOff (CmmLocal _) _) = True hasNoGlobalRegs _ = False --------------------------------------------------- -- -- Tagging -- --------------------------------------------------- -- Tag bits mask --cmmTagBits = CmmLit (mkIntCLit tAG_BITS) cmmTagMask, cmmPointerMask :: DynFlags -> CmmExpr cmmTagMask dflags = mkIntExpr dflags (tAG_MASK dflags) cmmPointerMask dflags = mkIntExpr dflags (complement (tAG_MASK dflags)) -- Used to untag a possibly tagged pointer -- A static label need not be untagged cmmUntag :: DynFlags -> CmmExpr -> CmmExpr cmmUntag _ e@(CmmLit (CmmLabel _)) = e -- Default case cmmUntag dflags e = cmmAndWord dflags e (cmmPointerMask dflags) -- Test if a closure pointer is untagged cmmIsTagged :: DynFlags -> CmmExpr -> CmmExpr cmmIsTagged dflags e = cmmNeWord dflags (cmmAndWord dflags e (cmmTagMask dflags)) (zeroExpr dflags) cmmConstrTag1 :: DynFlags -> CmmExpr -> CmmExpr -- Get constructor tag, but one based. cmmConstrTag1 dflags e = cmmAndWord dflags e (cmmTagMask dflags) -------------------------------------------- -- -- mkLiveness -- --------------------------------------------- mkLiveness :: DynFlags -> [Maybe LocalReg] -> Liveness mkLiveness _ [] = [] mkLiveness dflags (reg:regs) = take sizeW bits ++ mkLiveness dflags regs where sizeW = case reg of Nothing -> 1 Just r -> (widthInBytes (typeWidth (localRegType r)) + wORD_SIZE dflags - 1) `quot` wORD_SIZE dflags -- number of words, rounded up bits = repeat $ is_non_ptr reg -- True <=> Non Ptr is_non_ptr Nothing = True is_non_ptr (Just reg) = not $ isGcPtrType (localRegType reg) -- ============================================== - -- ============================================== - -- ============================================== - --------------------------------------------------- -- -- Manipulating CmmGraphs -- --------------------------------------------------- modifyGraph :: (Graph n C C -> Graph n' C C) -> GenCmmGraph n -> GenCmmGraph n' modifyGraph f g = CmmGraph {g_entry=g_entry g, g_graph=f (g_graph g)} toBlockMap :: CmmGraph -> BlockEnv CmmBlock toBlockMap (CmmGraph {g_graph=GMany NothingO body NothingO}) = body ofBlockMap :: BlockId -> BlockEnv CmmBlock -> CmmGraph ofBlockMap entry bodyMap = CmmGraph {g_entry=entry, g_graph=GMany NothingO bodyMap NothingO} insertBlock :: CmmBlock -> BlockEnv CmmBlock -> BlockEnv CmmBlock insertBlock block map = ASSERT(isNothing $ mapLookup id map) mapInsert id block map where id = entryLabel block toBlockList :: CmmGraph -> [CmmBlock] toBlockList g = mapElems $ toBlockMap g -- | like 'toBlockList', but the entry block always comes first toBlockListEntryFirst :: CmmGraph -> [CmmBlock] toBlockListEntryFirst g | mapNull m = [] | otherwise = entry_block : others where m = toBlockMap g entry_id = g_entry g Just entry_block = mapLookup entry_id m others = filter ((/= entry_id) . entryLabel) (mapElems m) -- | Like 'toBlockListEntryFirst', but we strive to ensure that we order blocks -- so that the false case of a conditional jumps to the next block in the output -- list of blocks. This matches the way OldCmm blocks were output since in -- OldCmm the false case was a fallthrough, whereas in Cmm conditional branches -- have both true and false successors. Block ordering can make a big difference -- in performance in the LLVM backend. Note that we rely crucially on the order -- of successors returned for CmmCondBranch by the NonLocal instance for CmmNode -- defind in cmm/CmmNode.hs. -GBM toBlockListEntryFirstFalseFallthrough :: CmmGraph -> [CmmBlock] toBlockListEntryFirstFalseFallthrough g | mapNull m = [] | otherwise = dfs setEmpty [entry_block] where m = toBlockMap g entry_id = g_entry g Just entry_block = mapLookup entry_id m dfs :: LabelSet -> [CmmBlock] -> [CmmBlock] dfs _ [] = [] dfs visited (block:bs) | id `setMember` visited = dfs visited bs | otherwise = block : dfs (setInsert id visited) bs' where id = entryLabel block bs' = foldr add_id bs (successors block) add_id id bs = case mapLookup id m of Just b -> b : bs Nothing -> bs ofBlockList :: BlockId -> [CmmBlock] -> CmmGraph ofBlockList entry blocks = CmmGraph { g_entry = entry , g_graph = GMany NothingO body NothingO } where body = foldr addBlock emptyBody blocks bodyToBlockList :: Body CmmNode -> [CmmBlock] bodyToBlockList body = mapElems body mapGraphNodes :: ( CmmNode C O -> CmmNode C O , CmmNode O O -> CmmNode O O , CmmNode O C -> CmmNode O C) -> CmmGraph -> CmmGraph mapGraphNodes funs@(mf,_,_) g = ofBlockMap (entryLabel $ mf $ CmmEntry (g_entry g) GlobalScope) $ mapMap (mapBlock3' funs) $ toBlockMap g mapGraphNodes1 :: (forall e x. CmmNode e x -> CmmNode e x) -> CmmGraph -> CmmGraph mapGraphNodes1 f = modifyGraph (mapGraph f) foldGraphBlocks :: (CmmBlock -> a -> a) -> a -> CmmGraph -> a foldGraphBlocks k z g = mapFold k z $ toBlockMap g postorderDfs :: CmmGraph -> [CmmBlock] postorderDfs g = {-# SCC "postorderDfs" #-} postorder_dfs_from (toBlockMap g) (g_entry g) ------------------------------------------------- -- Running dataflow analysis and/or rewrites -- Constructing forward and backward analysis-only pass analFwd :: DataflowLattice f -> FwdTransfer n f -> FwdPass UniqSM n f analBwd :: DataflowLattice f -> BwdTransfer n f -> BwdPass UniqSM n f analFwd lat xfer = analRewFwd lat xfer noFwdRewrite analBwd lat xfer = analRewBwd lat xfer noBwdRewrite -- Constructing forward and backward analysis + rewrite pass analRewFwd :: DataflowLattice f -> FwdTransfer n f -> FwdRewrite UniqSM n f -> FwdPass UniqSM n f analRewBwd :: DataflowLattice f -> BwdTransfer n f -> BwdRewrite UniqSM n f -> BwdPass UniqSM n f analRewFwd lat xfer rew = FwdPass {fp_lattice = lat, fp_transfer = xfer, fp_rewrite = rew} analRewBwd lat xfer rew = BwdPass {bp_lattice = lat, bp_transfer = xfer, bp_rewrite = rew} -- Running forward and backward dataflow analysis + optional rewrite dataflowPassFwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> FwdPass UniqSM n f -> UniqSM (GenCmmGraph n, BlockEnv f) dataflowPassFwd (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = do (graph, facts, NothingO) <- analyzeAndRewriteFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts) return (CmmGraph {g_entry=entry, g_graph=graph}, facts) dataflowAnalFwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> FwdPass UniqSM n f -> BlockEnv f dataflowAnalFwd (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = analyzeFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts) dataflowAnalFwdBlocks :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> FwdPass UniqSM n f -> UniqSM (BlockEnv f) dataflowAnalFwdBlocks (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = do -- (graph, facts, NothingO) <- analyzeAndRewriteFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts) -- return facts return (analyzeFwdBlocks fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts)) dataflowAnalBwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> BwdPass UniqSM n f -> BlockEnv f dataflowAnalBwd (CmmGraph {g_entry=entry, g_graph=graph}) facts bwd = analyzeBwd bwd (JustC [entry]) graph (mkFactBase (bp_lattice bwd) facts) dataflowPassBwd :: NonLocal n => GenCmmGraph n -> [(BlockId, f)] -> BwdPass UniqSM n f -> UniqSM (GenCmmGraph n, BlockEnv f) dataflowPassBwd (CmmGraph {g_entry=entry, g_graph=graph}) facts bwd = do (graph, facts, NothingO) <- analyzeAndRewriteBwd bwd (JustC [entry]) graph (mkFactBase (bp_lattice bwd) facts) return (CmmGraph {g_entry=entry, g_graph=graph}, facts) ------------------------------------------------- -- Tick utilities -- | Extract all tick annotations from the given block blockTicks :: Block CmmNode C C -> [CmmTickish] blockTicks b = reverse $ foldBlockNodesF goStmt b [] where goStmt :: CmmNode e x -> [CmmTickish] -> [CmmTickish] goStmt (CmmTick t) ts = t:ts goStmt _other ts = ts
forked-upstream-packages-for-ghcjs/ghc
compiler/cmm/CmmUtils.hs
bsd-3-clause
22,586
0
18
4,797
5,772
3,040
2,732
361
3
main = putStrLn "oneoneone"
MichielDerhaeg/stack
test/integration/tests/2643-copy-compiler-tool/files/Foo.hs
bsd-3-clause
28
0
5
4
9
4
5
1
1
module Distribution.Client.Dependency.Modular.Message ( Message(..), showMessages ) where import qualified Data.List as L import Prelude hiding (pi) import Distribution.Text -- from Cabal import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.Dependency.Types ( ConstraintSource(..), showConstraintSource ) data Message = Enter -- ^ increase indentation level | Leave -- ^ decrease indentation level | TryP QPN POption | TryF QFN Bool | TryS QSN Bool | Next (Goal QPN) | Success | Failure (ConflictSet QPN) FailReason -- | Transforms the structured message type to actual messages (strings). -- -- Takes an additional relevance predicate. The predicate gets a stack of goal -- variables and can decide whether messages regarding these goals are relevant. -- You can plug in 'const True' if you're interested in a full trace. If you -- want a slice of the trace concerning a particular conflict set, then plug in -- a predicate returning 'True' on the empty stack and if the head is in the -- conflict set. -- -- The second argument indicates if the level numbers should be shown. This is -- recommended for any trace that involves backtracking, because only the level -- numbers will allow to keep track of backjumps. showMessages :: ([Var QPN] -> Bool) -> Bool -> [Message] -> [String] showMessages p sl = go [] 0 where go :: [Var QPN] -> Int -> [Message] -> [String] go _ _ [] = [] -- complex patterns go v l (TryP qpn i : Enter : Failure c fr : Leave : ms) = goPReject v l qpn [i] c fr ms go v l (TryF qfn b : Enter : Failure c fr : Leave : ms) = (atLevel (add (F qfn) v) l $ "rejecting: " ++ showQFNBool qfn b ++ showFR c fr) (go v l ms) go v l (TryS qsn b : Enter : Failure c fr : Leave : ms) = (atLevel (add (S qsn) v) l $ "rejecting: " ++ showQSNBool qsn b ++ showFR c fr) (go v l ms) go v l (Next (Goal (P qpn) gr) : TryP qpn' i : ms@(Enter : Next _ : _)) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn' i ++ showGRs gr) (go (add (P qpn) v) l ms) go v l (Failure c Backjump : ms@(Leave : Failure c' Backjump : _)) | c == c' = go v l ms -- standard display go v l (Enter : ms) = go v (l+1) ms go v l (Leave : ms) = go (drop 1 v) (l-1) ms go v l (TryP qpn i : ms) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn i) (go (add (P qpn) v) l ms) go v l (TryF qfn b : ms) = (atLevel (add (F qfn) v) l $ "trying: " ++ showQFNBool qfn b) (go (add (F qfn) v) l ms) go v l (TryS qsn b : ms) = (atLevel (add (S qsn) v) l $ "trying: " ++ showQSNBool qsn b) (go (add (S qsn) v) l ms) go v l (Next (Goal (P qpn) gr) : ms) = (atLevel (add (P qpn) v) l $ "next goal: " ++ showQPN qpn ++ showGRs gr) (go v l ms) go v l (Next _ : ms) = go v l ms -- ignore flag goals in the log go v l (Success : ms) = (atLevel v l $ "done") (go v l ms) go v l (Failure c fr : ms) = (atLevel v l $ "fail" ++ showFR c fr) (go v l ms) add :: Var QPN -> [Var QPN] -> [Var QPN] add v vs = simplifyVar v : vs -- special handler for many subsequent package rejections goPReject :: [Var QPN] -> Int -> QPN -> [POption] -> ConflictSet QPN -> FailReason -> [Message] -> [String] goPReject v l qpn is c fr (TryP qpn' i : Enter : Failure _ fr' : Leave : ms) | qpn == qpn' && fr == fr' = goPReject v l qpn (i : is) c fr ms goPReject v l qpn is c fr ms = (atLevel (P qpn : v) l $ "rejecting: " ++ L.intercalate ", " (map (showQPNPOpt qpn) (reverse is)) ++ showFR c fr) (go v l ms) -- write a message, but only if it's relevant; we can also enable or disable the display of the current level atLevel v l x xs | sl && p v = let s = show l in ("[" ++ replicate (3 - length s) '_' ++ s ++ "] " ++ x) : xs | p v = x : xs | otherwise = xs showQPNPOpt :: QPN -> POption -> String showQPNPOpt qpn@(Q _pp pn) (POption i linkedTo) = case linkedTo of Nothing -> showPI (PI qpn i) -- Consistent with prior to POption Just pp' -> showQPN qpn ++ "~>" ++ showPI (PI (Q pp' pn) i) showGRs :: QGoalReasonChain -> String showGRs (gr : _) = showGR gr showGRs [] = "" showGR :: GoalReason QPN -> String showGR UserGoal = " (user goal)" showGR (PDependency pi) = " (dependency of " ++ showPI pi ++ ")" showGR (FDependency qfn b) = " (dependency of " ++ showQFNBool qfn b ++ ")" showGR (SDependency qsn) = " (dependency of " ++ showQSNBool qsn True ++ ")" showFR :: ConflictSet QPN -> FailReason -> String showFR _ InconsistentInitialConstraints = " (inconsistent initial constraints)" showFR _ (Conflicting ds) = " (conflict: " ++ L.intercalate ", " (map showDep ds) ++ ")" showFR _ CannotInstall = " (only already installed instances can be used)" showFR _ CannotReinstall = " (avoiding to reinstall a package with same version but new dependencies)" showFR _ Shadowed = " (shadowed by another installed package with same version)" showFR _ Broken = " (package is broken)" showFR _ (GlobalConstraintVersion vr src) = " (" ++ constraintSource src ++ " requires " ++ display vr ++ ")" showFR _ (GlobalConstraintInstalled src) = " (" ++ constraintSource src ++ " requires installed instance)" showFR _ (GlobalConstraintSource src) = " (" ++ constraintSource src ++ " requires source instance)" showFR _ (GlobalConstraintFlag src) = " (" ++ constraintSource src ++ " requires opposite flag selection)" showFR _ ManualFlag = " (manual flag can only be changed explicitly)" showFR _ (BuildFailureNotInIndex pn) = " (unknown package: " ++ display pn ++ ")" showFR c Backjump = " (backjumping, conflict set: " ++ showCS c ++ ")" showFR _ MultipleInstances = " (multiple instances)" showFR c (DependenciesNotLinked msg) = " (dependencies not linked: " ++ msg ++ "; conflict set: " ++ showCS c ++ ")" -- The following are internal failures. They should not occur. In the -- interest of not crashing unnecessarily, we still just print an error -- message though. showFR _ (MalformedFlagChoice qfn) = " (INTERNAL ERROR: MALFORMED FLAG CHOICE: " ++ showQFN qfn ++ ")" showFR _ (MalformedStanzaChoice qsn) = " (INTERNAL ERROR: MALFORMED STANZA CHOICE: " ++ showQSN qsn ++ ")" showFR _ EmptyGoalChoice = " (INTERNAL ERROR: EMPTY GOAL CHOICE)" constraintSource :: ConstraintSource -> String constraintSource src = "constraint from " ++ showConstraintSource src
gridaphobe/cabal
cabal-install/Distribution/Client/Dependency/Modular/Message.hs
bsd-3-clause
6,925
0
19
1,836
2,315
1,171
1,144
83
16
module Capture1 where import Control.Parallel.Strategies (rpar, runEval) fib n | n <= 1 = 1 | otherwise = n1_2 + n2_2 + 1 where n1 = fib (n-1) n2 = fib (n-2) (n1_2, n2_2) = runEval (do n1_2 <- rpar n1 n2_2 <- rpar n2 return (n1_2, n2_2)) n1_2 = fib 42
RefactoringTools/HaRe
old/testing/introThreshold/Capture1_TokOut.hs
bsd-3-clause
384
0
12
184
143
73
70
14
1
module ShowIssue where import qualified Github.Issues as Github main = do possibleIssue <- Github.issue "thoughtbot" "paperclip" 549 putStrLn $ either (\e -> "Error: " ++ show e) formatIssue possibleIssue formatIssue issue = (Github.githubOwnerLogin $ Github.issueUser issue) ++ " opened this issue " ++ (show $ Github.fromGithubDate $ Github.issueCreatedAt issue) ++ "\n" ++ (Github.issueState issue) ++ " with " ++ (show $ Github.issueComments issue) ++ " comments" ++ "\n\n" ++ (Github.issueTitle issue)
kfish/github
samples/Issues/ShowIssue.hs
bsd-3-clause
576
0
17
140
166
85
81
14
1
{-# LANGUAGE RoleAnnotations #-} module Roles6 where data Foo a b = MkFoo (a b) type role Foo nominal representational phantom
urbanslug/ghc
testsuite/tests/roles/should_fail/Roles6.hs
bsd-3-clause
131
0
8
25
32
20
12
4
0
module Main (main) where -- See Trac #149 -- Currently (with GHC 7.0) the CSE works, just, -- but it's delicate. import System.CPUTime main :: IO () main = print $ playerMostOccur1 [1..m] m :: Int m = 22 playerMostOccur1 :: [Int] -> Int playerMostOccur1 [a] = a playerMostOccur1 (x:xs) | numOccur x (x:xs) > numOccur (playerMostOccur1 xs) xs = x | otherwise = playerMostOccur1 xs numOccur :: Int -> [Int] -> Int numOccur i is = length is
oldmanmike/ghc
testsuite/tests/perf/should_run/T149_A.hs
bsd-3-clause
449
0
11
90
166
88
78
13
1
module Kafka.Internal.Shared ( pollEvents , word8PtrToBS , kafkaRespErr , throwOnError , hasError , rdKafkaErrorToEither , kafkaErrorToEither , kafkaErrorToMaybe , maybeToLeft , readPayload , readTopic , readKey , readTimestamp , readBS ) where import Control.Exception (throw) import Control.Monad (void) import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI import Data.Text (Text) import qualified Data.Text as Text import Data.Word (Word8) import Foreign.C.Error (Errno (..)) import Foreign.ForeignPtr (newForeignPtr_) import Foreign.Marshal.Alloc (alloca) import Foreign.Ptr (Ptr, nullPtr) import Foreign.Storable (Storable (peek)) import Kafka.Consumer.Types (Timestamp (..)) import Kafka.Internal.RdKafka (RdKafkaMessageT (..), RdKafkaMessageTPtr, RdKafkaRespErrT (..), RdKafkaTimestampTypeT (..), Word8Ptr, rdKafkaErrno2err, rdKafkaMessageTimestamp, rdKafkaPoll, rdKafkaTopicName) import Kafka.Internal.Setup (HasKafka (..), Kafka (..)) import Kafka.Types (KafkaError (..), Millis (..), Timeout (..)) pollEvents :: HasKafka a => a -> Maybe Timeout -> IO () pollEvents a tm = let timeout = maybe 0 unTimeout tm Kafka k = getKafka a in void (rdKafkaPoll k timeout) word8PtrToBS :: Int -> Word8Ptr -> IO BS.ByteString word8PtrToBS len ptr = BSI.create len $ \bsptr -> BSI.memcpy bsptr ptr len kafkaRespErr :: Errno -> KafkaError kafkaRespErr (Errno num) = KafkaResponseError $ rdKafkaErrno2err (fromIntegral num) {-# INLINE kafkaRespErr #-} throwOnError :: IO (Maybe Text) -> IO () throwOnError action = do m <- action case m of Just e -> throw $ KafkaError e Nothing -> return () hasError :: KafkaError -> Bool hasError err = case err of KafkaResponseError RdKafkaRespErrNoError -> False _ -> True {-# INLINE hasError #-} rdKafkaErrorToEither :: RdKafkaRespErrT -> Either KafkaError () rdKafkaErrorToEither err = case err of RdKafkaRespErrNoError -> Right () _ -> Left (KafkaResponseError err) {-# INLINE rdKafkaErrorToEither #-} kafkaErrorToEither :: KafkaError -> Either KafkaError () kafkaErrorToEither err = case err of KafkaResponseError RdKafkaRespErrNoError -> Right () _ -> Left err {-# INLINE kafkaErrorToEither #-} kafkaErrorToMaybe :: KafkaError -> Maybe KafkaError kafkaErrorToMaybe err = case err of KafkaResponseError RdKafkaRespErrNoError -> Nothing _ -> Just err {-# INLINE kafkaErrorToMaybe #-} maybeToLeft :: Maybe a -> Either a () maybeToLeft = maybe (Right ()) Left {-# INLINE maybeToLeft #-} readPayload :: RdKafkaMessageT -> IO (Maybe BS.ByteString) readPayload = readBS len'RdKafkaMessageT payload'RdKafkaMessageT readTopic :: RdKafkaMessageT -> IO Text readTopic msg = newForeignPtr_ (topic'RdKafkaMessageT msg) >>= (fmap Text.pack . rdKafkaTopicName) readKey :: RdKafkaMessageT -> IO (Maybe BSI.ByteString) readKey = readBS keyLen'RdKafkaMessageT key'RdKafkaMessageT readTimestamp :: RdKafkaMessageTPtr -> IO Timestamp readTimestamp msg = alloca $ \p -> do typeP <- newForeignPtr_ p ts <- fromIntegral <$> rdKafkaMessageTimestamp msg typeP tsType <- peek p return $ case tsType of RdKafkaTimestampCreateTime -> CreateTime (Millis ts) RdKafkaTimestampLogAppendTime -> LogAppendTime (Millis ts) RdKafkaTimestampNotAvailable -> NoTimestamp readBS :: (t -> Int) -> (t -> Ptr Word8) -> t -> IO (Maybe BS.ByteString) readBS flen fdata s = if fdata s == nullPtr then return Nothing else Just <$> word8PtrToBS (flen s) (fdata s)
haskell-works/kafka-client
src/Kafka/Internal/Shared.hs
mit
3,988
0
15
1,053
1,068
569
499
91
3
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.MediaStreamTrackEvent (js_getTrack, getTrack, MediaStreamTrackEvent, castToMediaStreamTrackEvent, gTypeMediaStreamTrackEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"track\"]" js_getTrack :: MediaStreamTrackEvent -> IO (Nullable MediaStreamTrack) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrackEvent.track Mozilla MediaStreamTrackEvent.track documentation> getTrack :: (MonadIO m) => MediaStreamTrackEvent -> m (Maybe MediaStreamTrack) getTrack self = liftIO (nullableToMaybe <$> (js_getTrack (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaStreamTrackEvent.hs
mit
1,428
6
10
160
371
236
135
23
1
module Hpcb.Component.QFP ( qfp_32, qfp_44 ) where import Hpcb.Data.Action import Hpcb.Data.Base import Hpcb.Data.Circuit import Hpcb.Data.Effects import Hpcb.Data.Layer import Hpcb.Data.FpElement import Hpcb.Functions import Data.Monoid -- | QFP32 package qfp_32 :: String -- ^ Reference -> String -- ^ Value -> Circuit qfp_32 ref val = footprint ref "TQFP-32" $ fpText "reference" ref defaultEffects # translate (V2 0 (-6.05)) # layer FSilkS <> fpText "value" val defaultEffects # translate (V2 0 6.05) # layer FFab <> fpText "user" ref defaultEffects # layer FFab <> fpPolygon [ V2 (-3.5) (-2.5), V2 (-2.5) (-3.5), V2 3.5 (-3.5), V2 3.5 3.5, V2 (-3.5) 3.5 ] # layer FFab # width 0.15 <> fpRectangle 10.6 10.6 # layer FCrtYd # width 0.05 <> mconcat [silkCorner # rotate (i*90) | i <- [0..2]] <> ( fpLine (V2 (-3.625) (-3.625)) (V2 (-3.625) (-3.4)) <> fpLine (V2 (-3.625) (-3.625)) (V2 (-3.3) (-3.625)) <> fpLine (V2 (-3.625) (-3.4)) (V2 (-5.05) (-3.4)) ) # layer FSilkS # width 0.15 <> mconcat [padsLine (i*8+1) # rotate (90*fromIntegral i) | i <- [0..3]] where silkCorner = ( fpLine (V2 (-3.625) 3.625) (V2 (-3.625) 3.3) <> fpLine (V2 (-3.625) 3.625) (V2 (-3.3) 3.625) ) # layer FSilkS # width 0.15 padsLine nStart = mconcat [pad (nStart + i) SMD Rect (V2 1.6 0.55) (newNet ref (nStart + i)) # translate (V2 (-4.25) (-2.8+fromIntegral i*0.8)) | i <- [0..7]] # layers [FCu, FPaste, FMask] -- | QFP44 package qfp_44 :: String -- ^ Reference -> String -- ^ Value -> Circuit qfp_44 ref val = footprint ref "TQFP-44" $ fpText "reference" ref defaultEffects # translate (V2 0 (-7.45)) # layer FSilkS <> fpText "value" val defaultEffects # translate (V2 0 7.45) # layer FFab <> fpText "user" ref defaultEffects # layer FFab <> fpPolygon [ V2 (-5) (-4), V2 (-4) (-5), V2 5 (-5), V2 5 5, V2 (-5) 5 ] # layer FFab # width 0.15 <> fpRectangle 13.4 13.4 # layer FCrtYd # width 0.05 <> mconcat [silkCorner # rotate (i*90) | i <- [0..2]] <> ( fpLine (V2 (-5.175) (-5.175)) (V2 (-5.175) (-4.6)) <> fpLine (V2 (-5.175) (-5.175)) (V2 (-4.5) (-5.175)) <> fpLine (V2 (-5.175) (-4.6)) (V2 (-6.45) (-4.6)) ) # layer FSilkS # width 0.15 <> mconcat [padsLine (i*11+1) # rotate (90*fromIntegral i) | i <- [0..3]] where silkCorner = ( fpLine (V2 (-5.175) 5.175) (V2 (-5.175) 4.5) <> fpLine (V2 (-5.175) 5.175) (V2 (-4.5) 5.175) ) # layer FSilkS # width 0.15 padsLine nStart = mconcat [pad (nStart + i) SMD Rect (V2 1.5 0.55) (newNet ref (nStart + i)) # translate (V2 (-5.7) (-4+fromIntegral i*0.8)) | i <- [0..10]] # layers [FCu, FPaste, FMask]
iemxblog/hpcb
src/Hpcb/Component/QFP.hs
mit
2,763
0
27
672
1,435
738
697
65
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.Text.ICU.ExtrasSpec (spec) where import Control.Applicative ((<$>)) import Control.Lens ((&)) import Data.Text (Text) import Data.Text.ICU.Extras (match, findAndReplace, Segment(..), parseReplacement) import Test.Hspec (Spec, describe, it, shouldBe) spec :: Spec spec = do describe "match" $ do it "Should be Nothing if provided an invalid regular expression." $ do match "(" `shouldBe` Nothing it "Should yield a match function if provided a regular expression." $ do ("xa" &) <$> match "x" `shouldBe` Just True ("xa" &) <$> match "y" `shouldBe` Just False describe "parseReplacement" $ do it "Should decompose a replacement string into a sequence [Segment]." $ do parseReplacement "foo$1bar$4$1" `shouldBe` Just [Literal "foo", Reference 1, Literal "bar", Reference 4, Reference 1] it "Should correctly parse successive '$'s" $ do parseReplacement "$$1" `shouldBe` Just [Literal "$", Reference 1] parseReplacement "$$" `shouldBe` Just [Literal "$", Literal "$"] it "Should identity no more than nine capture groups." $ do parseReplacement "$10" `shouldBe` Just [Reference 1, Literal "0"] describe "findAndReplace" $ do it "Should find and replace based upon a regular expression and pattern." $ do ("barqux" &) <$> findAndReplace "(bar)" "$1baz" `shouldBe` Just (Just "barbazqux") ("barqux" &) <$> findAndReplace "(qux)" "baz$1" `shouldBe` Just (Just "barbazqux") ("barqux" &) <$> findAndReplace "u" "uu" `shouldBe` Just (Just "barquux") instance Show (Text -> Bool) where show _ = "Text -> Bool" instance Eq (Text -> Bool) where _ == _ = False
fmap/https-everywhere-rules
test/Data/Text/ICU/ExtrasSpec.hs
mit
1,770
0
16
339
520
269
251
34
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Web.Hastodon.Streaming ( StreamingPayload(..) , StreamingResponse , streamUser , streamPublic , streamLocal , streamHashtag , streamList ) where import Prelude hiding (takeWhile) import Control.Applicative ((<|>), many, some) import Data.Aeson import Data.Attoparsec.ByteString as A import Data.Attoparsec.ByteString.Char8 as C8 import qualified Data.ByteString as BS import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B8 import Data.Maybe (maybeToList) import Conduit import Network.HTTP.Simple import Web.Hastodon.Util import Web.Hastodon.Types ---- -- Public API ---- pStreamUser = "/api/v1/streaming/user" pStreamPublic = "/api/v1/streaming/public" pStreamLocal = "/api/v1/streaming/public/local" pStreamHashtag = "/api/v1/streaming/hashtag" pStreamList = "/api/v1/streaming/list" type StreamingResponse m = forall m. MonadResource m => ConduitT () StreamingPayload m () data StreamingPayload = SUpdate Status | SNotification Notification | SDelete StatusId | Thump deriving (Show) data EventType = EUpdate | ENotification | EDelete streamUser :: HastodonClient -> StreamingResponse m streamUser client = getStreamingResponse pStreamUser client streamPublic :: HastodonClient -> StreamingResponse m streamPublic client = getStreamingResponse pStreamPublic client streamLocal :: HastodonClient -> StreamingResponse m streamLocal client = getStreamingResponse pStreamLocal client streamHashtag :: HastodonClient -> String -> StreamingResponse m streamHashtag client hashtag = getStreamingResponse ph client where ph = pStreamHashtag ++ "?hashtag=" ++ hashtag streamList :: HastodonClient -> String -> StreamingResponse m streamList client list = getStreamingResponse l client where l = pStreamList ++ "?list=" ++ list ---- -- Private stuff ---- stream :: ByteString -> ByteString -> (ByteString, [StreamingPayload]) stream i a | isThump i = ("", [Thump]) | isEvent i = (i, []) | otherwise = parseE a i where parseE et d = case parseET et of (Just EDelete) -> ("", p parseDelete d) (Just ENotification) -> ("", p parseNotification d) (Just EUpdate) -> ("",p parseUpdate d) Nothing -> ("", []) p r s = maybeToList $ maybeResult $ parse r s isThump = (":thump" `B8.isPrefixOf`) isEvent = ("event: " `B8.isPrefixOf`) parseET s = maybeResult $ parse parseEvent s parseEvent :: Parser EventType parseEvent = do string "event: " try ("delete" *> return EDelete) <|> try ("update" *> return EUpdate) <|> try ("notification" *> return ENotification) pd = string "data: " parseDelete :: Parser StreamingPayload parseDelete = do pd i <- StatusId <$> many C8.digit return $ SDelete i eoc :: String -> Char -> Maybe String eoc "\n" '\n' = Nothing eoc acc c = Just (c:acc) parseNotification :: Parser StreamingPayload parseNotification = do pd s <- C8.takeTill (== '\n') case (decodeStrict' s :: Maybe Notification) of Nothing -> fail $ "decode error" (Just n) -> return $ SNotification n parseUpdate :: Parser StreamingPayload parseUpdate = do pd s <- C8.takeTill (== '\n') case (decodeStrict' s :: Maybe Status) of Nothing -> fail $ "decode error" (Just s) -> return $ SUpdate s parseStream :: forall m. MonadResource m => ConduitT ByteString StreamingPayload m () parseStream = concatMapAccumC stream "" getStreamingResponse path client = do req <- liftIO $ mkHastodonRequest path client httpSource req getResponseBody .| parseStream
syucream/hastodon
Web/Hastodon/Streaming.hs
mit
3,895
0
12
945
1,068
568
500
97
4
{-# LANGUAGE CPP #-} module GHCJS.DOM.HTMLCanvasElement ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.HTMLCanvasElement #else module Graphics.UI.Gtk.WebKit.DOM.HTMLCanvasElement #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.HTMLCanvasElement #else import Graphics.UI.Gtk.WebKit.DOM.HTMLCanvasElement #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/HTMLCanvasElement.hs
mit
470
0
5
39
33
26
7
4
0
module Wc where import Data.Int import qualified Data.ByteString.Lazy.Char8 as B import qualified Args as A import qualified Data.Text.Lazy.Encoding as E import qualified Data.Text.Lazy as T import Data.Maybe (isJust, fromJust) import Data.Monoid import Data.List (intersperse) import Data.Char (chr) import Coreutils (split, bsContents) wc :: A.Args -> IO () wc args = case A.files0from args of Just f -> files0from f >>= doFiles args Nothing -> case A.files args of Nothing -> doStdin args Just fs -> doFiles args fs doStdin :: A.Args -> IO () doStdin args = print . wc' args =<< B.getContents doFiles :: A.Args -> [FilePath] -> IO () doFiles args fs = putStr . unlines . label fs . total . map (wc' args) =<< readFiles fs readFiles :: [FilePath] -> IO [B.ByteString] readFiles = mapM bsContents files0from :: FilePath -> IO [FilePath] files0from "-" = fmap (split (chr 0)) getContents files0from f = fmap (split (chr 0)) (readFile f) data Result = Result (Maybe Int64) (Maybe Int64) (Maybe Int64) (Maybe Int64) (Maybe Int64) instance Monoid Result where mempty = Result (Just 0) (Just 0) (Just 0) (Just 0) (Just 0) mappend (Result ls1 ws1 cs1 bs1 ll1) (Result ls2 ws2 cs2 bs2 ll2) = Result ((+) <$> ls1 <*> ls2) ((+) <$> ws1 <*> ws2) ((+) <$> cs1 <*> cs2) ((+) <$> bs1 <*> bs2) ((+) <$> ll1 <*> ll2) instance Show Result where show r = concat . maybePad $ filterShow r where maybePad [s] = [s] maybePad ss = intersperse " " $ map (pad 7 ' ') ss filterShow :: Result -> [String] filterShow (Result ls ws cs bs ll) = map (show . fromJust) (filter isJust [ls,ws,cs,bs,ll]) total :: [Result] -> [Result] total [r] = [r] total rs = rs ++ [foldr (<>) mempty rs] label :: [FilePath] -> [Result] -> [String] label fs rs = map (showFileResult padding) frPairs where padding = widest rs frPairs = zip (fs ++ ["total"]) rs showFileResult :: Int -> (FilePath,Result) -> String showFileResult p (f,r) = (concat . maybePad $ filterShow r) ++ " " ++ f where maybePad [s] = [s] maybePad ss = intersperse " " $ map (pad p ' ') ss pad :: Int -> Char -> String -> String pad w c s = replicate n c ++ s where n = w - length s widest :: [Result] -> Int widest [] = 0 widest rs = maximum . map length . filterShow . last $ rs wc' :: A.Args -> B.ByteString -> Result wc' a xs = let ls = if A.lines a then Just (linecount xs) else Nothing ws = if A.words a then Just (wordcount xs) else Nothing cs = if A.chars a then Just (charcount xs) else Nothing bs = if A.bytes a then Just (bytecount xs) else Nothing ll = if A.longest a then Just (longest xs) else Nothing in Result ls ws cs bs ll linecount :: B.ByteString -> Int64 linecount = B.count '\n' wordcount :: B.ByteString -> Int64 wordcount = fromIntegral . length . B.words charcount :: B.ByteString -> Int64 charcount = T.length . E.decodeUtf8 bytecount :: B.ByteString -> Int64 bytecount = B.length longest :: B.ByteString -> Int64 longest = maximum . map T.length . T.lines . E.decodeUtf8
mrak/coreutils.hs
src/wc/Wc.hs
mit
3,236
0
12
848
1,375
725
650
82
6
{-# LANGUAGE CPP, NoImplicitPrelude, PackageImports #-} module Foreign.Marshal.Compat ( module Base ) where import "base-compat" Foreign.Marshal.Compat as Base
haskell-compat/base-compat
base-compat-batteries/src/Foreign/Marshal/Compat.hs
mit
163
0
4
21
23
17
6
4
0
module LLMH_ExpType where -- Haskell datatypes representing abstract syntax of LLMH types and expressions -- for LLMH allow type variables in types data Type = TypeVar String | TypeConst String | Arrow (Type, Type) | Myb Type | -- Myb t represents Maybe t List Type -- List t represents [t] deriving (Show,Eq) data Exp = Num Integer | Boolean Bool | Var String | Op (String, Exp, Exp) | Cond (Exp, Exp, Exp) | Let (String, Exp, Exp) | Lam (String, Exp) | Jst | Nthg | Nil | Cons (Exp,Exp) | MybCase (Exp, String, Exp, Exp) | ListCase (Exp, Exp, String, String, Exp) deriving Show
jaanos/TPJ-2015-16
homework2/LLMH_ExpType.hs
mit
734
0
7
261
186
118
68
20
0