code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module FunArity where main x y = 0 main x = 1
roberth/uu-helium
test/staticerrors/FunArity.hs
gpl-3.0
51
0
5
17
22
12
10
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.OpsWorks.SetLoadBasedAutoScaling -- 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) -- -- Specify the load-based auto scaling configuration for a specified layer. -- For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-autoscaling.html Managing Load with Time-based and Load-based Instances>. -- -- To use load-based auto scaling, you must create a set of load-based auto -- scaling instances. Load-based auto scaling operates only on the -- instances from that set, so you must ensure that you have created enough -- instances to handle the maximum anticipated load. -- -- __Required Permissions__: To use this action, an IAM user must have a -- Manage permissions level for the stack, or an attached policy that -- explicitly grants permissions. For more information on user permissions, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_SetLoadBasedAutoScaling.html AWS API Reference> for SetLoadBasedAutoScaling. module Network.AWS.OpsWorks.SetLoadBasedAutoScaling ( -- * Creating a Request setLoadBasedAutoScaling , SetLoadBasedAutoScaling -- * Request Lenses , slbasUpScaling , slbasEnable , slbasDownScaling , slbasLayerId -- * Destructuring the Response , setLoadBasedAutoScalingResponse , SetLoadBasedAutoScalingResponse ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'setLoadBasedAutoScaling' smart constructor. data SetLoadBasedAutoScaling = SetLoadBasedAutoScaling' { _slbasUpScaling :: !(Maybe AutoScalingThresholds) , _slbasEnable :: !(Maybe Bool) , _slbasDownScaling :: !(Maybe AutoScalingThresholds) , _slbasLayerId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SetLoadBasedAutoScaling' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'slbasUpScaling' -- -- * 'slbasEnable' -- -- * 'slbasDownScaling' -- -- * 'slbasLayerId' setLoadBasedAutoScaling :: Text -- ^ 'slbasLayerId' -> SetLoadBasedAutoScaling setLoadBasedAutoScaling pLayerId_ = SetLoadBasedAutoScaling' { _slbasUpScaling = Nothing , _slbasEnable = Nothing , _slbasDownScaling = Nothing , _slbasLayerId = pLayerId_ } -- | An 'AutoScalingThresholds' object with the upscaling threshold -- configuration. If the load exceeds these thresholds for a specified -- amount of time, AWS OpsWorks starts a specified number of instances. slbasUpScaling :: Lens' SetLoadBasedAutoScaling (Maybe AutoScalingThresholds) slbasUpScaling = lens _slbasUpScaling (\ s a -> s{_slbasUpScaling = a}); -- | Enables load-based auto scaling for the layer. slbasEnable :: Lens' SetLoadBasedAutoScaling (Maybe Bool) slbasEnable = lens _slbasEnable (\ s a -> s{_slbasEnable = a}); -- | An 'AutoScalingThresholds' object with the downscaling threshold -- configuration. If the load falls below these thresholds for a specified -- amount of time, AWS OpsWorks stops a specified number of instances. slbasDownScaling :: Lens' SetLoadBasedAutoScaling (Maybe AutoScalingThresholds) slbasDownScaling = lens _slbasDownScaling (\ s a -> s{_slbasDownScaling = a}); -- | The layer ID. slbasLayerId :: Lens' SetLoadBasedAutoScaling Text slbasLayerId = lens _slbasLayerId (\ s a -> s{_slbasLayerId = a}); instance AWSRequest SetLoadBasedAutoScaling where type Rs SetLoadBasedAutoScaling = SetLoadBasedAutoScalingResponse request = postJSON opsWorks response = receiveNull SetLoadBasedAutoScalingResponse' instance ToHeaders SetLoadBasedAutoScaling where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.SetLoadBasedAutoScaling" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON SetLoadBasedAutoScaling where toJSON SetLoadBasedAutoScaling'{..} = object (catMaybes [("UpScaling" .=) <$> _slbasUpScaling, ("Enable" .=) <$> _slbasEnable, ("DownScaling" .=) <$> _slbasDownScaling, Just ("LayerId" .= _slbasLayerId)]) instance ToPath SetLoadBasedAutoScaling where toPath = const "/" instance ToQuery SetLoadBasedAutoScaling where toQuery = const mempty -- | /See:/ 'setLoadBasedAutoScalingResponse' smart constructor. data SetLoadBasedAutoScalingResponse = SetLoadBasedAutoScalingResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SetLoadBasedAutoScalingResponse' with the minimum fields required to make a request. -- setLoadBasedAutoScalingResponse :: SetLoadBasedAutoScalingResponse setLoadBasedAutoScalingResponse = SetLoadBasedAutoScalingResponse'
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/SetLoadBasedAutoScaling.hs
mpl-2.0
5,808
0
12
1,136
660
400
260
87
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudTrail.GetTrailStatus -- 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) -- -- Returns a JSON-formatted list of information about the specified trail. -- Fields include information on delivery errors, Amazon SNS and Amazon S3 -- errors, and start and stop logging times for each trail. -- -- /See:/ <http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_GetTrailStatus.html AWS API Reference> for GetTrailStatus. module Network.AWS.CloudTrail.GetTrailStatus ( -- * Creating a Request getTrailStatus , GetTrailStatus -- * Request Lenses , gtsName -- * Destructuring the Response , getTrailStatusResponse , GetTrailStatusResponse -- * Response Lenses , gtsrsLatestDeliveryError , gtsrsStartLoggingTime , gtsrsLatestNotificationError , gtsrsIsLogging , gtsrsLatestDeliveryTime , gtsrsLatestCloudWatchLogsDeliveryTime , gtsrsLatestCloudWatchLogsDeliveryError , gtsrsLatestNotificationTime , gtsrsStopLoggingTime , gtsrsResponseStatus ) where import Network.AWS.CloudTrail.Types import Network.AWS.CloudTrail.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The name of a trail about which you want the current status. -- -- /See:/ 'getTrailStatus' smart constructor. newtype GetTrailStatus = GetTrailStatus' { _gtsName :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetTrailStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gtsName' getTrailStatus :: Text -- ^ 'gtsName' -> GetTrailStatus getTrailStatus pName_ = GetTrailStatus' { _gtsName = pName_ } -- | The name of the trail for which you are requesting the current status. gtsName :: Lens' GetTrailStatus Text gtsName = lens _gtsName (\ s a -> s{_gtsName = a}); instance AWSRequest GetTrailStatus where type Rs GetTrailStatus = GetTrailStatusResponse request = postJSON cloudTrail response = receiveJSON (\ s h x -> GetTrailStatusResponse' <$> (x .?> "LatestDeliveryError") <*> (x .?> "StartLoggingTime") <*> (x .?> "LatestNotificationError") <*> (x .?> "IsLogging") <*> (x .?> "LatestDeliveryTime") <*> (x .?> "LatestCloudWatchLogsDeliveryTime") <*> (x .?> "LatestCloudWatchLogsDeliveryError") <*> (x .?> "LatestNotificationTime") <*> (x .?> "StopLoggingTime") <*> (pure (fromEnum s))) instance ToHeaders GetTrailStatus where toHeaders = const (mconcat ["X-Amz-Target" =# ("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.GetTrailStatus" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON GetTrailStatus where toJSON GetTrailStatus'{..} = object (catMaybes [Just ("Name" .= _gtsName)]) instance ToPath GetTrailStatus where toPath = const "/" instance ToQuery GetTrailStatus where toQuery = const mempty -- | Returns the objects or data listed below if successful. Otherwise, -- returns an error. -- -- /See:/ 'getTrailStatusResponse' smart constructor. data GetTrailStatusResponse = GetTrailStatusResponse' { _gtsrsLatestDeliveryError :: !(Maybe Text) , _gtsrsStartLoggingTime :: !(Maybe POSIX) , _gtsrsLatestNotificationError :: !(Maybe Text) , _gtsrsIsLogging :: !(Maybe Bool) , _gtsrsLatestDeliveryTime :: !(Maybe POSIX) , _gtsrsLatestCloudWatchLogsDeliveryTime :: !(Maybe POSIX) , _gtsrsLatestCloudWatchLogsDeliveryError :: !(Maybe Text) , _gtsrsLatestNotificationTime :: !(Maybe POSIX) , _gtsrsStopLoggingTime :: !(Maybe POSIX) , _gtsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetTrailStatusResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gtsrsLatestDeliveryError' -- -- * 'gtsrsStartLoggingTime' -- -- * 'gtsrsLatestNotificationError' -- -- * 'gtsrsIsLogging' -- -- * 'gtsrsLatestDeliveryTime' -- -- * 'gtsrsLatestCloudWatchLogsDeliveryTime' -- -- * 'gtsrsLatestCloudWatchLogsDeliveryError' -- -- * 'gtsrsLatestNotificationTime' -- -- * 'gtsrsStopLoggingTime' -- -- * 'gtsrsResponseStatus' getTrailStatusResponse :: Int -- ^ 'gtsrsResponseStatus' -> GetTrailStatusResponse getTrailStatusResponse pResponseStatus_ = GetTrailStatusResponse' { _gtsrsLatestDeliveryError = Nothing , _gtsrsStartLoggingTime = Nothing , _gtsrsLatestNotificationError = Nothing , _gtsrsIsLogging = Nothing , _gtsrsLatestDeliveryTime = Nothing , _gtsrsLatestCloudWatchLogsDeliveryTime = Nothing , _gtsrsLatestCloudWatchLogsDeliveryError = Nothing , _gtsrsLatestNotificationTime = Nothing , _gtsrsStopLoggingTime = Nothing , _gtsrsResponseStatus = pResponseStatus_ } -- | Displays any Amazon S3 error that CloudTrail encountered when attempting -- to deliver log files to the designated bucket. For more information see -- the topic -- <http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html Error Responses> -- in the Amazon S3 API Reference. gtsrsLatestDeliveryError :: Lens' GetTrailStatusResponse (Maybe Text) gtsrsLatestDeliveryError = lens _gtsrsLatestDeliveryError (\ s a -> s{_gtsrsLatestDeliveryError = a}); -- | Specifies the most recent date and time when CloudTrail started -- recording API calls for an AWS account. gtsrsStartLoggingTime :: Lens' GetTrailStatusResponse (Maybe UTCTime) gtsrsStartLoggingTime = lens _gtsrsStartLoggingTime (\ s a -> s{_gtsrsStartLoggingTime = a}) . mapping _Time; -- | Displays any Amazon SNS error that CloudTrail encountered when -- attempting to send a notification. For more information about Amazon SNS -- errors, see the -- <http://docs.aws.amazon.com/sns/latest/dg/welcome.html Amazon SNS Developer Guide>. gtsrsLatestNotificationError :: Lens' GetTrailStatusResponse (Maybe Text) gtsrsLatestNotificationError = lens _gtsrsLatestNotificationError (\ s a -> s{_gtsrsLatestNotificationError = a}); -- | Whether the CloudTrail is currently logging AWS API calls. gtsrsIsLogging :: Lens' GetTrailStatusResponse (Maybe Bool) gtsrsIsLogging = lens _gtsrsIsLogging (\ s a -> s{_gtsrsIsLogging = a}); -- | Specifies the date and time that CloudTrail last delivered log files to -- an account\'s Amazon S3 bucket. gtsrsLatestDeliveryTime :: Lens' GetTrailStatusResponse (Maybe UTCTime) gtsrsLatestDeliveryTime = lens _gtsrsLatestDeliveryTime (\ s a -> s{_gtsrsLatestDeliveryTime = a}) . mapping _Time; -- | Displays the most recent date and time when CloudTrail delivered logs to -- CloudWatch Logs. gtsrsLatestCloudWatchLogsDeliveryTime :: Lens' GetTrailStatusResponse (Maybe UTCTime) gtsrsLatestCloudWatchLogsDeliveryTime = lens _gtsrsLatestCloudWatchLogsDeliveryTime (\ s a -> s{_gtsrsLatestCloudWatchLogsDeliveryTime = a}) . mapping _Time; -- | Displays any CloudWatch Logs error that CloudTrail encountered when -- attempting to deliver logs to CloudWatch Logs. gtsrsLatestCloudWatchLogsDeliveryError :: Lens' GetTrailStatusResponse (Maybe Text) gtsrsLatestCloudWatchLogsDeliveryError = lens _gtsrsLatestCloudWatchLogsDeliveryError (\ s a -> s{_gtsrsLatestCloudWatchLogsDeliveryError = a}); -- | Specifies the date and time of the most recent Amazon SNS notification -- that CloudTrail has written a new log file to an account\'s Amazon S3 -- bucket. gtsrsLatestNotificationTime :: Lens' GetTrailStatusResponse (Maybe UTCTime) gtsrsLatestNotificationTime = lens _gtsrsLatestNotificationTime (\ s a -> s{_gtsrsLatestNotificationTime = a}) . mapping _Time; -- | Specifies the most recent date and time when CloudTrail stopped -- recording API calls for an AWS account. gtsrsStopLoggingTime :: Lens' GetTrailStatusResponse (Maybe UTCTime) gtsrsStopLoggingTime = lens _gtsrsStopLoggingTime (\ s a -> s{_gtsrsStopLoggingTime = a}) . mapping _Time; -- | The response status code. gtsrsResponseStatus :: Lens' GetTrailStatusResponse Int gtsrsResponseStatus = lens _gtsrsResponseStatus (\ s a -> s{_gtsrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-cloudtrail/gen/Network/AWS/CloudTrail/GetTrailStatus.hs
mpl-2.0
9,254
0
20
1,893
1,282
756
526
141
1
{-# LANGUAGE TypeOperators #-} module TypeOperator where -- - @"+" defines/binding SumTypeOp data a + b = Sum a b -- - @"+" ref SumTypeOp mkSum :: a -> b -> a + b mkSum x y = Sum x y
google/haskell-indexer
kythe-verification/testdata/basic/TypeOperators.hs
apache-2.0
186
0
7
44
53
30
23
5
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Edward Kmett and Dan Doel 2014 -- License : BSD2 -- Maintainer: Dan Doel <[email protected]> -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Ermine.Interpreter ( Address , Closure(..) , closureCode , closureEnv , papArity , allocPrimOp , allocGlobal , Env(..) , Frame(..) , MachineState(..) , trace , eval , defaultMachineState , primOpNZ , primOpNN , primOpUN , primOpNU , primOpNNN , primOpUUU ) where import Control.Applicative hiding (empty) import Control.Monad.Primitive import Control.Monad.State import Control.Lens hiding (au) import Data.Default import Data.HashMap.Strict (HashMap) import qualified Data.Foldable as F import Data.Maybe import qualified Data.Map as Map import Data.Monoid hiding (Any) import Data.Primitive.MutVar import Data.Vector (Vector) import qualified Data.Vector as B import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as GM import qualified Data.Vector.Mutable as BM import qualified Data.Vector.Primitive as P import qualified Data.Vector.Primitive.Mutable as PM import Data.Word import Ermine.Core.Compiler (SortRef, compileBinding) import Ermine.Syntax.Convention (Convention) import Ermine.Syntax.Core (Core) import Ermine.Syntax.G import Ermine.Syntax.Id import Ermine.Syntax.Sort import Prelude hiding (log) import Unsafe.Coerce newtype Address m = Address (MutVar (PrimState m) (Closure m)) deriving Eq data Env m = Env { _envB :: Vector (Address m) , _envU :: P.Vector Word64 , _envN :: Vector Native } instance Default (Env m) where def = Env mempty mempty mempty data Closure m = Closure { _closureCode :: !LambdaForm , _closureEnv :: !(Env m) } | PartialApplication { _closureCode :: !LambdaForm , _closureEnv :: !(Env m) , _papArity :: !(Sorted Int) -- remaining args } | BlackHole | PrimClosure (MachineState m -> m ()) data Frame m = Branch !Continuation !(Env m) | Update !(Address m) data MachineState m = MachineState { _sp :: !(Sorted Int) , _fp :: !(Sorted Int) , _stackF :: [(Sorted Int, Frame m)] , _genv :: HashMap Id (Address m) , _trace :: String -> m () , _stackB :: BM.MVector (PrimState m) (Address m) , _stackU :: PM.MVector (PrimState m) Word64 , _stackN :: BM.MVector (PrimState m) Native } makeClassy ''Env makeLenses ''MachineState makeLenses ''Closure log :: MachineState m -> String -> m () log = view trace note :: (Monad m, Show a) => MachineState m -> String -> a -> m () note ms n a = log ms (n ++ ": " ++ show a) {- watch :: (Monad m, Show a) => MachineState m -> String -> m a -> m a watch ms n m = do a <- m note ms n a return a -} nargs :: MachineState m -> Sorted Int nargs ms = ms^.fp -ms^.sp sentinel :: a sentinel = error "PANIC: access past end of stack" allocPrimOp :: (Functor m, PrimMonad m) => (MachineState m -> m ()) -> m (Address m) allocPrimOp f = Address <$> newMutVar (PrimClosure f) allocGlobal :: (Eq c, Functor m, PrimMonad m) => (c -> SortRef) -> Core Convention c -> m (Address m) allocGlobal cxt core = case compileBinding cxt core of PreClosure rs co | F.all G.null rs -> Address <$> newMutVar (Closure co def) | otherwise -> error "PANIC: allocating global with captures" defaultMachineState :: (Applicative m, PrimMonad m) => Int -> HashMap Id (Address m) -> m (MachineState m) defaultMachineState stackSize ge = MachineState (pure stackSize) (pure stackSize) [] ge (const $ return ()) <$> GM.replicate stackSize sentinel <*> GM.replicate stackSize 0 <*> GM.replicate stackSize sentinel poke :: PrimMonad m => Address m -> Closure m -> m () poke (Address r) c = writeMutVar r c peek :: PrimMonad m => Address m -> m (Closure m) peek (Address r) = readMutVar r resolveEnv :: (Applicative m, PrimMonad m) => Env m -> Sorted (Vector Ref) -> MachineState m -> m (Env m) resolveEnv le (Sorted bs us ns) ms = Env <$> G.mapM (resolveClosure le ms) bs <*> (G.convert <$> G.mapM (resolveUnboxed le ms) us) <*> G.mapM (resolveNative le ms) ns resolveClosure :: PrimMonad m => Env m -> MachineState m -> Ref -> m (Address m) resolveClosure le _ (Local l) = return $ le^?!envB.ix (fromIntegral l) resolveClosure _ ms (Stack s) = GM.read (ms^.stackB) (fromIntegral s + ms^.sp.sort B) resolveClosure _ ms (Global g) = return $ ms^?!genv.ix g resolveClosure _ _ Lit{} = error "resolveClosure: Lit" resolveClosure _ _ Native{} = error "resolveClosure: Native" resolveUnboxed :: PrimMonad m => Env m -> MachineState m -> Ref -> m Word64 resolveUnboxed le _ (Local l) = return $ le^?!envU.ix (fromIntegral l) resolveUnboxed _ ms (Stack s) = GM.read (ms^.stackU) (fromIntegral s + ms^.sp.sort U) resolveUnboxed _ _ (Lit l) = return l resolveUnboxed _ _ Global{} = error "resolveUnboxed: Global" resolveUnboxed _ _ Native{} = error "resolveUnboxed: Native" resolveNative :: PrimMonad m => Env m -> MachineState m -> Ref -> m Native resolveNative _ _ (Native a) = return a resolveNative le _ (Local l) = return $ le^?!envN.ix (fromIntegral l) resolveNative _ ms (Stack s) = GM.read (ms^.stackN) (fromIntegral s + ms^.sp.sort N) resolveNative _ _ Lit{} = error "resolveNative: Lit" resolveNative _ _ Global{} = error "resolveNative: Global" buildClosure :: (PrimMonad m, Applicative m) => Env m -> PreClosure -> MachineState m -> m (Closure m) buildClosure le (PreClosure captures code) ms = Closure code <$> resolveEnv le captures ms allocClosure :: (Applicative m, PrimMonad m) => Env m -> PreClosure -> MachineState m -> m (Address m) allocClosure le cc ms = Address <$> (buildClosure le cc ms >>= newMutVar) allocRecursive :: (Applicative m, PrimMonad m) => Env m -> Vector PreClosure -> MachineState m -> m (MachineState m) allocRecursive lo ccs ms = do let n = B.length ccs (sb, ms') = ms & sp.sort B <-~ n stk = ms^.stackB ifor_ ccs $ \ i _ -> do mv <- newMutVar (error "PANIC: allocRecursive: closure isn't") GM.write stk (sb + i) (Address mv) ifor_ ccs $ \ i pc -> do addr <- GM.read stk (sb + i) buildClosure lo pc ms' >>= poke addr return ms' pushArgs :: (Applicative m, PrimMonad m) => Env m -> Sorted (Vector Ref) -> MachineState m -> m (MachineState m) pushArgs le refs@(Sorted bs us ns) ms = do note ms "pushArgs" (B.length <$> refs) let (Sorted sb su sn, ms') = ms & sp <-~ fmap B.length refs stkB = ms^.stackB stkU = ms^.stackU stkN = ms^.stackN ifor_ bs $ \i -> resolveClosure le ms >=> GM.write stkB (sb + i) ifor_ us $ \i -> resolveUnboxed le ms >=> GM.write stkU (su + i) ifor_ ns $ \i -> resolveNative le ms >=> GM.write stkN (sn + i) return $ ms' push :: Frame m -> MachineState m -> MachineState m push fr ms | F.or ((>) <$> ms^.sp <*> ms^.fp) = error "push inverts stack and frame pointers" | otherwise = ms & fp .~ ms^.sp & stackF %~ ((ms^.fp,fr):) copyArgs :: (PrimMonad m, GM.MVector v a) => v (PrimState m) a -> Int -> Int -> Int -> m () copyArgs stk frm off len = GM.move (GM.slice (frm+off-len) len stk) (GM.slice frm len stk) pop :: PrimMonad m => MachineState m -> m (Maybe (Frame m, MachineState m)) pop = popWith 0 popWith :: PrimMonad m => Sorted Int -> MachineState m -> m (Maybe (Frame m, MachineState m)) popWith args ms = case ms^.stackF of (ofp,fr):fs -> do let f = ms^.fp ms' <- squash (f - ms^.sp) args ms return $ Just (fr,ms' & fp .~ ofp & stackF .~ fs) [] -> return Nothing -- for tail calls or return -- -- In @squash sz args ms@ -- -- @sz@ is the number of local variables and arguments we just pushed -- @args@ is the number of those local variables that are arguments we had pushed -- We then squash the variables so that the local variables that were pushed on the end -- are pushed at the front of this frame and 'suck the air' out of the frame removing -- all the others -- -- @ -- Before (w/ stack growing down to the right) -- -- fp sp -- | | -- v v -- <-----sz------> -- <-args-> -- -- After -- -- fp sp' -- | | -- v v -- <-args-> -- @ squash :: PrimMonad m => Sorted Int -> Sorted Int -> MachineState m -> m (MachineState m) squash sz@(Sorted zb zu zn) args@(Sorted ab au an) ms = do note ms "squash" (sz, args) let Sorted sb su sn = ms^.sp stkB = ms^.stackB stkU = ms^.stackU stkN = ms^.stackN copyArgs stkB sb zb ab copyArgs stkU su zu au copyArgs stkN sn zn an when (zb > ab) $ GM.set (GM.slice sb (zb-ab) stkB) sentinel when (zn > an) $ GM.set (GM.slice sn (zn-an) stkN) sentinel return $ ms & sp +~ sz - args select :: Continuation -> Tag -> G select (Continuation bs df) t = fromMaybe (error "PANIC: missing default case in branch") $ snd <$> Map.lookup t bs <|> df extendPayload :: (PrimMonad m, G.Vector v a) => v a -> G.Mutable v (PrimState m) a -> Int -> Int -> m (v a) extendPayload d stk stp n = do let m = G.length d me <- GM.new (m + n) G.copy (GM.slice 0 m me) d GM.copy (GM.slice m n me) (GM.slice stp n stk) G.unsafeFreeze me pushPayload :: (PrimMonad m, G.Vector v a) => Int -> v a -> G.Mutable v (PrimState m) a -> Int -> m () pushPayload f e stk stp = G.copy (GM.slice stp (G.length e - f) stk) (G.drop f e) pushPayloads :: PrimMonad m => Sorted Int -> Env m -> MachineState m -> m (MachineState m) pushPayloads (Sorted fb fu fn) (Env db du dn) ms = do let Sorted sb su sn = ms^.sp pushPayload fb db (ms^.stackB) sb pushPayload fu du (ms^.stackU) su pushPayload fn dn (ms^.stackN) sn return $ ms & sp -~ Sorted (G.length db - fb) (G.length du - fu) (G.length dn - fn) extendPayloads :: (Applicative m, PrimMonad m) => Env m -> MachineState m -> m (Env m) extendPayloads (Env db du dn) ms = Env <$> extendPayload db (ms^.stackB) sb arb <*> extendPayload du (ms^.stackU) su aru <*> extendPayload dn (ms^.stackN) sn arn where Sorted sb su sn = ms^.sp Sorted arb aru arn = nargs ms payload :: (PrimMonad m, G.Vector v a) => G.Mutable v (PrimState m) a -> Int -> Int -> m (v a) payload mv s n = do me <- GM.new n GM.copy me (GM.slice s n mv) G.unsafeFreeze me ------------------------------------------------------------------------------ -- * The Spineless Tagless G-Machine ------------------------------------------------------------------------------ eval :: (Applicative m, PrimMonad m) => G -> Env m -> MachineState m -> m () eval (App sz f xs) le ms = case f of Ref r -> do addr <- resolveClosure le ms r ms' <- pushArgs le xs ms let lxs = G.length <$> xs let lsz = fromIntegral <$> sz ms'' <- squash (lsz + lxs) lxs ms' enter addr ms'' Con t -> pushArgs le xs ms >>= returnCon t (G.length <$> xs) eval (Let bs e) le ms = do let stk = ms^.stackB (sb, ms') = ms & sp.sort B <-~ G.length bs ifor_ bs $ \i pc -> allocClosure le pc ms >>= GM.write stk (sb + i) eval e le ms' eval (LetRec bs e) le ms = allocRecursive le bs ms >>= eval e le eval (Case co k) le ms = do log ms "pushBranch: Case" ; eval co le $ push (Branch k le) ms eval (CaseLit ref k) le ms = do l <- resolveUnboxed le ms ref returnLit l $ push (Branch k le) ms eval Slot le ms = do pos <- resolveUnboxed le ms (Stack 0) slot <- resolveClosure le ms (Local pos) squash (Sorted 0 1 0) 0 ms >>= enter slot enter :: (Applicative m, PrimMonad m) => Address m -> MachineState m -> m () enter addr ms = do note ms "enter" args peek addr >>= \case BlackHole -> fail "ermine <<loop>> detected" w@(PartialApplication co da arity) | F.sum args < F.sum arity -> pap co da arity w | otherwise -> pushPayloads (fmap fromIntegral (co^.free)) da ms >>= eval (co^.body) da w@(Closure co da) | co^.update -> do log ms "pushUpdate" ; eval (co^.body) da $ push (Update addr) ms | arity <- fmap fromIntegral (co^.bound), argcount < F.sum arity -> pap co da arity w | otherwise -> eval (co^.body) da ms PrimClosure k -> k ms where args = nargs ms argcount = F.sum args pap co da arity w | argcount == 0 = go w -- entering a function with 0 args | otherwise = do e <- extendPayloads da ms go $ PartialApplication co e (arity - args) where go k = pop ms >>= \case Just (Update ad, ms') -> do poke ad k enter ad ms' Just (Branch (Continuation m (Just dflt)) le', ms') | Map.null m -> eval dflt le' ms' Just _ -> error "bad frame after partial application" Nothing -> return () returnCon :: (Applicative m, PrimMonad m) => Tag -> Sorted Int -> MachineState m -> m () returnCon t args@(Sorted ab au an) ms = popWith args ms >>= \case Just (Branch k le, ms') -> log ms "popBranch" >> eval (select k t) le ms' Just (Update ad, ms') -> do log ms "popUpdate" let Sorted sb su sn = ms'^.sp e <- Env <$> payload (ms'^.stackB) sb ab <*> payload (ms'^.stackU) su au <*> payload (ms'^.stackN) sn an poke ad $ Closure (standardConstructor (fromIntegral <$> args) t) e returnCon t args ms' Nothing -> return () returnLit :: (Applicative m, PrimMonad m) => Word64 -> MachineState m -> m () returnLit w ms = pop ms >>= \case Just (Branch k le, ms') -> eval (select k w) le ms' Just _ -> error "PANIC: literal update frame" Nothing -> return () ------------------------------------------------------------------------------ -- Primops ------------------------------------------------------------------------------ primOpNZ :: PrimMonad m => (a -> m ()) -> MachineState m -> m () primOpNZ f ms = GM.read nstk np >>= f . unsafeCoerce where np = ms^.sp.sort N nstk = ms^.stackN primOpUN :: (Applicative m, PrimMonad m) => (Word64 -> m b) -> MachineState m -> m () primOpUN f ms = GM.read ustk up >>= f >>= GM.write nstk np . unsafeCoerce >> returnCon 0 (Sorted 0 0 1) ms' where (Sorted _ up np, ms') = ms & sp <-~ Sorted 0 0 1 nstk = ms^.stackN ustk = ms^.stackU primOpNU :: (Applicative m, PrimMonad m) => (a -> m Word64) -> MachineState m -> m () primOpNU f ms = GM.read nstk np >>= f . unsafeCoerce >>= GM.write ustk up >> returnCon 0 (Sorted 0 1 0) ms' where (Sorted _ up np, ms') = ms & sp <-~ Sorted 0 1 0 nstk = ms^.stackN ustk = ms^.stackU primOpNN :: (Applicative m, PrimMonad m) => (a -> m b) -> MachineState m -> m () primOpNN f ms = GM.read nstk np >>= f . unsafeCoerce >>= GM.write nstk (np-1) . unsafeCoerce >> returnCon 0 (Sorted 0 0 1) ms' where (np, ms') = ms & sp.sort N <-~ 1 nstk = ms^.stackN primOpNNN :: (Applicative m, PrimMonad m) => (a -> b -> m c) -> MachineState m -> m () primOpNNN f ms = do a <- GM.read nstk (np+1) b <- GM.read nstk (np+2) GM.write nstk np . unsafeCoerce =<< f (unsafeCoerce a) (unsafeCoerce b) returnCon 0 (Sorted 0 0 1) ms' where (np, ms') = ms & sp.sort N <-~ 1 nstk = ms^.stackN primOpUUU :: (Applicative m, PrimMonad m) => (Word64 -> Word64 -> Word64) -> MachineState m -> m () primOpUUU f ms = do w1 <- GM.read ustk (up+1) w2 <- GM.read ustk (up+2) GM.write ustk up $ f w1 w2 returnCon 0 (Sorted 0 1 0) ms' where (up, ms') = ms & sp.sort U <-~ 1 ustk = ms^.stackU
PipocaQuemada/ermine
src/Ermine/Interpreter.hs
bsd-2-clause
15,554
0
19
3,448
6,651
3,302
3,349
-1
-1
module Data.STM.Bag ( Impl, module Data.STM.Bag.Class ) where import Data.STM.Bag.Class import Data.STM.Bag.Internal.PTLB -- | The default implementation type Impl = PTLB
Alllex/stm-data-collection
src/Data/STM/Bag.hs
bsd-3-clause
182
0
5
32
42
30
12
6
0
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.PackageIndex -- Copyright : (c) David Himmelstrup 2005, -- Bjorn Bringert 2007, -- Duncan Coutts 2008 -- -- Maintainer : [email protected] -- Portability : portable -- -- An index of packages. -- module Distribution.Client.PackageIndex ( -- * Package index data type PackageIndex, -- * Fine-grained package dependencies PackageFixedDeps(..), -- * Creating an index fromList, -- * Updates merge, insert, deletePackageName, deletePackageId, deleteDependency, -- * Queries -- ** Precise lookups elemByPackageId, elemByPackageName, lookupPackageName, lookupPackageId, lookupDependency, -- ** Case-insensitive searches searchByName, SearchResult(..), searchByNameSubstring, -- ** Bulk queries allPackages, allPackagesByName, ) where import Prelude hiding (lookup) import Control.Exception (assert) import qualified Data.Map as Map import Data.Map (Map) import Data.List (groupBy, sortBy, isInfixOf) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (Monoid(..)) #endif import Data.Maybe (isJust, fromMaybe) import Distribution.Package ( PackageName(..), PackageIdentifier(..) , Package(..), packageName, packageVersion , Dependency(Dependency) , InstalledPackageId, installedDepends ) import Distribution.Version ( withinRange ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo_ ) import Distribution.Simple.Utils ( lowercase, comparing ) -- | Subclass of packages that have specific versioned dependencies. -- -- So for example a not-yet-configured package has dependencies on version -- ranges, not specific versions. A configured or an already installed package -- depends on exact versions. Some operations or data structures (like -- dependency graphs) only make sense on this subclass of package types. -- class Package pkg => PackageFixedDeps pkg where depends :: pkg -> [InstalledPackageId] instance PackageFixedDeps (InstalledPackageInfo_ str) where depends info = installedDepends info -- | The collection of information about packages from one or more 'PackageDB's. -- -- It can be searched efficiently by package name and version. -- newtype PackageIndex pkg = PackageIndex -- This index package names to all the package records matching that package -- name case-sensitively. It includes all versions. -- -- This allows us to find all versions satisfying a dependency. -- Most queries are a map lookup followed by a linear scan of the bucket. -- (Map PackageName [pkg]) deriving (Show, Read, Functor) instance Package pkg => Monoid (PackageIndex pkg) where mempty = PackageIndex Map.empty mappend = merge --save one mappend with empty in the common case: mconcat [] = mempty mconcat xs = foldr1 mappend xs invariant :: Package pkg => PackageIndex pkg -> Bool invariant (PackageIndex m) = all (uncurry goodBucket) (Map.toList m) where goodBucket _ [] = False goodBucket name (pkg0:pkgs0) = check (packageId pkg0) pkgs0 where check pkgid [] = packageName pkgid == name check pkgid (pkg':pkgs) = packageName pkgid == name && pkgid < pkgid' && check pkgid' pkgs where pkgid' = packageId pkg' -- -- * Internal helpers -- mkPackageIndex :: Package pkg => Map PackageName [pkg] -> PackageIndex pkg mkPackageIndex index = assert (invariant (PackageIndex index)) (PackageIndex index) internalError :: String -> a internalError name = error ("PackageIndex." ++ name ++ ": internal error") -- | Lookup a name in the index to get all packages that match that name -- case-sensitively. -- lookup :: PackageIndex pkg -> PackageName -> [pkg] lookup (PackageIndex m) name = fromMaybe [] $ Map.lookup name m -- -- * Construction -- -- | Build an index out of a bunch of packages. -- -- If there are duplicates, later ones mask earlier ones. -- fromList :: Package pkg => [pkg] -> PackageIndex pkg fromList pkgs = mkPackageIndex . Map.map fixBucket . Map.fromListWith (++) $ [ (packageName pkg, [pkg]) | pkg <- pkgs ] where fixBucket = -- out of groups of duplicates, later ones mask earlier ones -- but Map.fromListWith (++) constructs groups in reverse order map head -- Eq instance for PackageIdentifier is wrong, so use Ord: . groupBy (\a b -> EQ == comparing packageId a b) -- relies on sortBy being a stable sort so we -- can pick consistently among duplicates . sortBy (comparing packageId) -- -- * Updates -- -- | Merge two indexes. -- -- Packages from the second mask packages of the same exact name -- (case-sensitively) from the first. -- merge :: Package pkg => PackageIndex pkg -> PackageIndex pkg -> PackageIndex pkg merge i1@(PackageIndex m1) i2@(PackageIndex m2) = assert (invariant i1 && invariant i2) $ mkPackageIndex (Map.unionWith mergeBuckets m1 m2) -- | Elements in the second list mask those in the first. mergeBuckets :: Package pkg => [pkg] -> [pkg] -> [pkg] mergeBuckets [] ys = ys mergeBuckets xs [] = xs mergeBuckets xs@(x:xs') ys@(y:ys') = case packageId x `compare` packageId y of GT -> y : mergeBuckets xs ys' EQ -> y : mergeBuckets xs' ys' LT -> x : mergeBuckets xs' ys -- | Inserts a single package into the index. -- -- This is equivalent to (but slightly quicker than) using 'mappend' or -- 'merge' with a singleton index. -- insert :: Package pkg => pkg -> PackageIndex pkg -> PackageIndex pkg insert pkg (PackageIndex index) = mkPackageIndex $ Map.insertWith (\_ -> insertNoDup) (packageName pkg) [pkg] index where pkgid = packageId pkg insertNoDup [] = [pkg] insertNoDup pkgs@(pkg':pkgs') = case compare pkgid (packageId pkg') of LT -> pkg : pkgs EQ -> pkg : pkgs' GT -> pkg' : insertNoDup pkgs' -- | Internal delete helper. -- delete :: Package pkg => PackageName -> (pkg -> Bool) -> PackageIndex pkg -> PackageIndex pkg delete name p (PackageIndex index) = mkPackageIndex $ Map.update filterBucket name index where filterBucket = deleteEmptyBucket . filter (not . p) deleteEmptyBucket [] = Nothing deleteEmptyBucket remaining = Just remaining -- | Removes a single package from the index. -- deletePackageId :: Package pkg => PackageIdentifier -> PackageIndex pkg -> PackageIndex pkg deletePackageId pkgid = delete (packageName pkgid) (\pkg -> packageId pkg == pkgid) -- | Removes all packages with this (case-sensitive) name from the index. -- deletePackageName :: Package pkg => PackageName -> PackageIndex pkg -> PackageIndex pkg deletePackageName name = delete name (\pkg -> packageName pkg == name) -- | Removes all packages satisfying this dependency from the index. -- deleteDependency :: Package pkg => Dependency -> PackageIndex pkg -> PackageIndex pkg deleteDependency (Dependency name verstionRange) = delete name (\pkg -> packageVersion pkg `withinRange` verstionRange) -- -- * Bulk queries -- -- | Get all the packages from the index. -- allPackages :: PackageIndex pkg -> [pkg] allPackages (PackageIndex m) = concat (Map.elems m) -- | Get all the packages from the index. -- -- They are grouped by package name, case-sensitively. -- allPackagesByName :: PackageIndex pkg -> [[pkg]] allPackagesByName (PackageIndex m) = Map.elems m -- -- * Lookups -- elemByPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Bool elemByPackageId index = isJust . lookupPackageId index elemByPackageName :: Package pkg => PackageIndex pkg -> PackageName -> Bool elemByPackageName index = not . null . lookupPackageName index -- | Does a lookup by package id (name & version). -- -- Since multiple package DBs mask each other case-sensitively by package name, -- then we get back at most one package. -- lookupPackageId :: Package pkg => PackageIndex pkg -> PackageIdentifier -> Maybe pkg lookupPackageId index pkgid = case [ pkg | pkg <- lookup index (packageName pkgid) , packageId pkg == pkgid ] of [] -> Nothing [pkg] -> Just pkg _ -> internalError "lookupPackageIdentifier" -- | Does a case-sensitive search by package name. -- lookupPackageName :: Package pkg => PackageIndex pkg -> PackageName -> [pkg] lookupPackageName index name = [ pkg | pkg <- lookup index name , packageName pkg == name ] -- | Does a case-sensitive search by package name and a range of versions. -- -- We get back any number of versions of the specified package name, all -- satisfying the version range constraint. -- lookupDependency :: Package pkg => PackageIndex pkg -> Dependency -> [pkg] lookupDependency index (Dependency name versionRange) = [ pkg | pkg <- lookup index name , packageName pkg == name , packageVersion pkg `withinRange` versionRange ] -- -- * Case insensitive name lookups -- -- | Does a case-insensitive search by package name. -- -- If there is only one package that compares case-insensitively to this name -- then the search is unambiguous and we get back all versions of that package. -- If several match case-insensitively but one matches exactly then it is also -- unambiguous. -- -- If however several match case-insensitively and none match exactly then we -- have an ambiguous result, and we get back all the versions of all the -- packages. The list of ambiguous results is split by exact package name. So -- it is a non-empty list of non-empty lists. -- searchByName :: PackageIndex pkg -> String -> [(PackageName, [pkg])] searchByName (PackageIndex m) name = [ pkgs | pkgs@(PackageName name',_) <- Map.toList m , lowercase name' == lname ] where lname = lowercase name data SearchResult a = None | Unambiguous a | Ambiguous [a] -- | Does a case-insensitive substring search by package name. -- -- That is, all packages that contain the given string in their name. -- searchByNameSubstring :: PackageIndex pkg -> String -> [(PackageName, [pkg])] searchByNameSubstring (PackageIndex m) searchterm = [ pkgs | pkgs@(PackageName name, _) <- Map.toList m , lsearchterm `isInfixOf` lowercase name ] where lsearchterm = lowercase searchterm
seereason/cabal
cabal-install/Distribution/Client/PackageIndex.hs
bsd-3-clause
10,633
0
13
2,364
2,241
1,221
1,020
153
4
-- | Regression tests for specific bugs. -- {-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Tests.Regressions ( tests ) where {- import Control.Exception (SomeException, handle) import System.IO import Test.HUnit (assertBool, assertEqual, assertFailure) import qualified Data.ByteString as B import Data.ByteString.Char8 () import qualified Data.ByteString.Lazy as LB import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LE import qualified Data.Text.Unsafe as T -} import qualified Test.Framework as F import qualified Test.Framework.Providers.HUnit as F {- import Tests.Utils (withTempFile) -- Reported by Michael Snoyman: UTF-8 encoding a large lazy bytestring -- caused either a segfault or attempt to allocate a negative number -- of bytes. lazy_encode_crash :: IO () lazy_encode_crash = withTempFile $ \ _ h -> LB.hPut h . LE.encodeUtf8 . LT.pack . replicate 100000 $ 'a' -- Reported by Pieter Laeremans: attempting to read an incorrectly -- encoded file can result in a crash in the RTS (i.e. not merely an -- exception). hGetContents_crash :: IO () hGetContents_crash = withTempFile $ \ path h -> do B.hPut h (B.pack [0x78, 0xc4 ,0x0a]) >> hClose h h' <- openFile path ReadMode hSetEncoding h' utf8 handle (\(_::SomeException) -> return ()) $ T.hGetContents h' >> assertFailure "T.hGetContents should crash" -- Reported by Ian Lynagh: attempting to allocate a sufficiently large -- string (via either Array.new or Text.replicate) could result in an -- integer overflow. replicate_crash :: IO () replicate_crash = handle (\(_::SomeException) -> return ()) $ T.replicate (2^power) "0123456789abcdef" `seq` assertFailure "T.replicate should crash" where power | maxBound == (2147483647::Int) = 28 | otherwise = 60 :: Int -- Reported by John Millikin: a UTF-8 decode error handler could -- return a bogus substitution character, which we would write without -- checking. utf8_decode_unsafe :: IO () utf8_decode_unsafe = do let t = TE.decodeUtf8With (\_ _ -> Just '\xdc00') "\x80" assertBool "broken error recovery shouldn't break us" (t == "\xfffd") -- Reported by Eric Seidel: we mishandled mapping Chars that fit in a -- single Word16 to Chars that require two. mapAccumL_resize :: IO () mapAccumL_resize = do let f a _ = (a, '\65536') count = 5 val = T.mapAccumL f (0::Int) (T.replicate count "a") assertEqual "mapAccumL should correctly fill buffers for two-word results" (0, T.replicate count "\65536") val assertEqual "mapAccumL should correctly size buffers for two-word results" (count * 2) (T.lengthWord16 (snd val)) -} tests :: F.Test tests = F.testGroup "Regressions" [] {- F.testGroup "Regressions" [ F.testCase "hGetContents_crash" hGetContents_crash , F.testCase "lazy_encode_crash" lazy_encode_crash , F.testCase "mapAccumL_resize" mapAccumL_resize , F.testCase "replicate_crash" replicate_crash , F.testCase "utf8_decode_unsafe" utf8_decode_unsafe ] -}
ghcjs/ghcjs-base
test/Tests/Regressions.hs
mit
3,214
0
6
615
56
38
18
8
1
module GoToSymbolFunction_ReferenceLeftMostFunctionWithoutTypeSig where test 1 = a test 2 = b test 3 = c t<caret>est 4 = d
charleso/intellij-haskforce
tests/gold/codeInsight/GoToSymbolFunction_ReferenceLeftMostFunctionWithoutTypeSig.hs
apache-2.0
123
1
6
19
46
23
23
-1
-1
{-| External data loader. This module holds the external data loading, and thus is the only one depending (via the specialized Text\/Rapi\/Luxi modules) on the actual libraries implementing the low-level protocols. -} {- Copyright (C) 2009, 2010, 2011, 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.HTools.ExtLoader ( loadExternalData , commonSuffix , maybeSaveData ) where import Control.Monad import Control.Monad.Writer (runWriterT) import Control.Exception import Data.Maybe (isJust, fromJust) import Data.Monoid (getAll) import System.FilePath import System.IO import System.Time (getClockTime) import Text.Printf (hPrintf) import Ganeti.BasicTypes import qualified Ganeti.HTools.Backend.Luxi as Luxi import qualified Ganeti.HTools.Backend.Rapi as Rapi import qualified Ganeti.HTools.Backend.Simu as Simu import qualified Ganeti.HTools.Backend.Text as Text import qualified Ganeti.HTools.Backend.IAlloc as IAlloc import qualified Ganeti.HTools.Backend.MonD as MonD import Ganeti.HTools.CLI import Ganeti.HTools.Loader (mergeData, checkData, ClusterData(..) , commonSuffix, clearDynU) import Ganeti.HTools.Types import Ganeti.Utils (sepSplit, tryRead, exitIfBad, exitWhen) -- | Error beautifier. wrapIO :: IO (Result a) -> IO (Result a) wrapIO = handle (\e -> return . Bad . show $ (e::IOException)) -- | Parses a user-supplied utilisation string. parseUtilisation :: String -> Result (String, DynUtil) parseUtilisation line = case sepSplit ' ' line of [name, cpu, mem, dsk, net] -> do rcpu <- tryRead name cpu rmem <- tryRead name mem rdsk <- tryRead name dsk rnet <- tryRead name net let du = DynUtil { cpuWeight = rcpu, memWeight = rmem , dskWeight = rdsk, netWeight = rnet } return (name, du) _ -> Bad $ "Cannot parse line " ++ line -- | External tool data loader from a variety of sources. loadExternalData :: Options -> IO ClusterData loadExternalData opts = do let mhost = optMaster opts lsock = optLuxi opts tfile = optDataFile opts simdata = optNodeSim opts iallocsrc = optIAllocSrc opts setRapi = mhost /= "" setLuxi = isJust lsock setSim = (not . null) simdata setFile = isJust tfile setIAllocSrc = isJust iallocsrc allSet = filter id [setRapi, setLuxi, setFile] exTags = case optExTags opts of Nothing -> [] Just etl -> map (++ ":") etl selInsts = optSelInst opts exInsts = optExInst opts exitWhen (length allSet > 1) "Only one of the rapi, luxi, and data\ \ files options should be given." util_contents <- maybe (return "") readFile (optDynuFile opts) util_data <- exitIfBad "can't parse utilisation data" . mapM parseUtilisation $ lines util_contents input_data <- case () of _ | setRapi -> wrapIO $ Rapi.loadData mhost | setLuxi -> wrapIO . Luxi.loadData (optSoR opts) $ fromJust lsock | setSim -> Simu.loadData simdata | setFile -> wrapIO . Text.loadData $ fromJust tfile | setIAllocSrc -> wrapIO . IAlloc.loadData $ fromJust iallocsrc | otherwise -> return $ Bad "No backend selected! Exiting." now <- getClockTime let ignoreDynU = optIgnoreDynu opts startIdle = ignoreDynU || optIdleDefault opts eff_u = if ignoreDynU then [] else util_data ldresult = input_data >>= (if startIdle then clearDynU else return) >>= mergeData eff_u exTags selInsts exInsts now cdata <- exitIfBad "failed to load data, aborting" ldresult (cdata', ok) <- runWriterT $ if optMonD opts then MonD.queryAllMonDDCs cdata opts else return cdata exitWhen (optMonDExitMissing opts && not (getAll ok)) "Not all required data available" let (fix_msgs, nl) = checkData (cdNodes cdata') (cdInstances cdata') unless (optVerbose opts == 0) $ maybeShowWarnings fix_msgs return cdata' {cdNodes = nl} -- | Function to save the cluster data to a file. maybeSaveData :: Maybe FilePath -- ^ The file prefix to save to -> String -- ^ The suffix (extension) to add -> String -- ^ Informational message -> ClusterData -- ^ The cluster data -> IO () maybeSaveData Nothing _ _ _ = return () maybeSaveData (Just path) ext msg cdata = do let adata = Text.serializeCluster cdata out_path = path <.> ext writeFile out_path adata hPrintf stderr "The cluster state %s has been written to file '%s'\n" msg out_path
leshchevds/ganeti
src/Ganeti/HTools/ExtLoader.hs
bsd-2-clause
5,938
0
16
1,414
1,182
622
560
98
5
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fil-PH"> <title>Selenium add-on</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/selenium/resources/help_fil_PH/helpset_fil_PH.hs
apache-2.0
962
79
67
157
413
209
204
-1
-1
-- Operations on the global state of the vectorisation monad. module Vectorise.Monad.Global ( readGEnv, setGEnv, updGEnv, -- * Configuration isVectAvoidanceAggressive, -- * Vars defGlobalVar, undefGlobalVar, -- * Vectorisation declarations lookupVectDecl, -- * Scalars globalParallelVars, globalParallelTyCons, -- * TyCons lookupTyCon, defTyConName, defTyCon, globalVectTyCons, -- * Datacons lookupDataCon, defDataCon, -- * PA Dictionaries lookupTyConPA, defTyConPAs, -- * PR Dictionaries lookupTyConPR ) where import Vectorise.Monad.Base import Vectorise.Env import CoreSyn import Type import TyCon import DataCon import DynFlags import NameEnv import NameSet import Name import VarEnv import VarSet import Var as Var import Outputable -- Global Environment --------------------------------------------------------- -- |Project something from the global environment. -- readGEnv :: (GlobalEnv -> a) -> VM a readGEnv f = VM $ \_ genv lenv -> return (Yes genv lenv (f genv)) -- |Set the value of the global environment. -- setGEnv :: GlobalEnv -> VM () setGEnv genv = VM $ \_ _ lenv -> return (Yes genv lenv ()) -- |Update the global environment using the provided function. -- updGEnv :: (GlobalEnv -> GlobalEnv) -> VM () updGEnv f = VM $ \_ genv lenv -> return (Yes (f genv) lenv ()) -- Configuration -------------------------------------------------------------- -- |Should we avoid as much vectorisation as possible? -- -- Set by '-f[no]-vectorisation-avoidance' -- isVectAvoidanceAggressive :: VM Bool isVectAvoidanceAggressive = readGEnv global_vect_avoid -- Vars ----------------------------------------------------------------------- -- |Add a mapping between a global var and its vectorised version to the state. -- defGlobalVar :: Var -> Var -> VM () defGlobalVar v v' = do { traceVt "add global var mapping:" (ppr v <+> text "-->" <+> ppr v') -- check for duplicate vectorisation ; currentDef <- readGEnv $ \env -> lookupVarEnv (global_vars env) v ; case currentDef of Just old_v' -> do dflags <- getDynFlags cantVectorise dflags "Variable is already vectorised:" $ ppr v <+> moduleOf v old_v' Nothing -> return () ; updGEnv $ \env -> env { global_vars = extendVarEnv (global_vars env) v v' } } where moduleOf var var' | var == var' = text "vectorises to itself" | Just mod <- nameModule_maybe (Var.varName var') = text "in module" <+> ppr mod | otherwise = text "in the current module" -- |Remove the mapping of a variable in the vectorisation map. -- undefGlobalVar :: Var -> VM () undefGlobalVar v = do { traceVt "REMOVING global var mapping:" (ppr v) ; updGEnv $ \env -> env { global_vars = delVarEnv (global_vars env) v } } -- Vectorisation declarations ------------------------------------------------- -- |Check whether a variable has a vectorisation declaration. -- -- The first component of the result indicates whether the variable has a 'NOVECTORISE' declaration. -- The second component contains the given type and expression in case of a 'VECTORISE' declaration. -- lookupVectDecl :: Var -> VM (Bool, Maybe (Type, CoreExpr)) lookupVectDecl var = readGEnv $ \env -> case lookupVarEnv (global_vect_decls env) var of Nothing -> (False, Nothing) Just Nothing -> (True, Nothing) Just vectDecl -> (False, vectDecl) -- Parallel entities ----------------------------------------------------------- -- |Get the set of global parallel variables. -- globalParallelVars :: VM DVarSet globalParallelVars = readGEnv global_parallel_vars -- |Get the set of all parallel type constructors (those that may embed parallelism) including both -- both those parallel type constructors declared in an imported module and those declared in the -- current module. -- globalParallelTyCons :: VM NameSet globalParallelTyCons = readGEnv global_parallel_tycons -- TyCons --------------------------------------------------------------------- -- |Determine the vectorised version of a `TyCon`. The vectorisation map in the global environment -- contains a vectorised version if the original `TyCon` embeds any parallel arrays. -- lookupTyCon :: TyCon -> VM (Maybe TyCon) lookupTyCon tc = readGEnv $ \env -> lookupNameEnv (global_tycons env) (tyConName tc) -- |Add a mapping between plain and vectorised `TyCon`s to the global environment. -- -- The second argument is only to enable tracing for (mutually) recursively defined type -- constructors, where we /must not/ pull at the vectorised type constructors (because that would -- pull too early at the recursive knot). -- defTyConName :: TyCon -> Name -> TyCon -> VM () defTyConName tc nameOfTc' tc' = do { traceVt "add global tycon mapping:" (ppr tc <+> text "-->" <+> ppr nameOfTc') -- check for duplicate vectorisation ; currentDef <- readGEnv $ \env -> lookupNameEnv (global_tycons env) (tyConName tc) ; case currentDef of Just old_tc' -> do dflags <- getDynFlags cantVectorise dflags "Type constructor or class is already vectorised:" $ ppr tc <+> moduleOf tc old_tc' Nothing -> return () ; updGEnv $ \env -> env { global_tycons = extendNameEnv (global_tycons env) (tyConName tc) tc' } } where moduleOf tc tc' | tc == tc' = text "vectorises to itself" | Just mod <- nameModule_maybe (tyConName tc') = text "in module" <+> ppr mod | otherwise = text "in the current module" -- |Add a mapping between plain and vectorised `TyCon`s to the global environment. -- defTyCon :: TyCon -> TyCon -> VM () defTyCon tc tc' = defTyConName tc (tyConName tc') tc' -- |Get the set of all vectorised type constructors. -- globalVectTyCons :: VM (NameEnv TyCon) globalVectTyCons = readGEnv global_tycons -- DataCons ------------------------------------------------------------------- -- |Lookup the vectorised version of a `DataCon` from the global environment. -- lookupDataCon :: DataCon -> VM (Maybe DataCon) lookupDataCon dc | isTupleTyCon (dataConTyCon dc) = return (Just dc) | otherwise = readGEnv $ \env -> lookupNameEnv (global_datacons env) (dataConName dc) -- |Add the mapping between plain and vectorised `DataCon`s to the global environment. -- defDataCon :: DataCon -> DataCon -> VM () defDataCon dc dc' = updGEnv $ \env -> env { global_datacons = extendNameEnv (global_datacons env) (dataConName dc) dc' } -- 'PA' dictionaries ------------------------------------------------------------ -- |Lookup the 'PA' dfun of a vectorised type constructor in the global environment. -- lookupTyConPA :: TyCon -> VM (Maybe Var) lookupTyConPA tc = readGEnv $ \env -> lookupNameEnv (global_pa_funs env) (tyConName tc) -- |Associate vectorised type constructors with the dfun of their 'PA' instances in the global -- environment. -- defTyConPAs :: [(TyCon, Var)] -> VM () defTyConPAs ps = updGEnv $ \env -> env { global_pa_funs = extendNameEnvList (global_pa_funs env) [(tyConName tc, pa) | (tc, pa) <- ps] } -- PR Dictionaries ------------------------------------------------------------ lookupTyConPR :: TyCon -> VM (Maybe Var) lookupTyConPR tc = readGEnv $ \env -> lookupNameEnv (global_pr_funs env) (tyConName tc)
snoyberg/ghc
compiler/vectorise/Vectorise/Monad/Global.hs
bsd-3-clause
7,644
0
14
1,718
1,545
816
729
113
3
{-# LANGUAGE TypeFamilies #-} module T10836 where type family Foo a = r | r -> a where Foo Int = Int Foo Bool = Int type family Bar a = r | r -> a where Bar Int = Int Bar Bool = Int
acowley/ghc
testsuite/tests/typecheck/should_fail/T10836.hs
bsd-3-clause
202
0
6
65
67
42
25
8
0
{-# LANGUAGE RankNTypes, MonoLocalBinds #-} module T13804 where f periph = let sr :: forall a. [a] -> [a] sr = if periph then reverse else id sr2 = sr -- The question: is sr2 generalised? -- It should be, because sr has a type sig -- even though it has periph free in (sr2 [True], sr2 "c")
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T13804.hs
bsd-3-clause
390
0
11
158
75
44
31
6
2
import Control.Concurrent import Control.Exception import System.Mem ( performGC ) import System.Mem.Weak ( addFinalizer ) data P = P (MVar Bool) -- Bug reported by Manuel Chakravarty, namely that we weren't checking -- for runnable finalizers before declaring that the program is -- deadlocked. main = do -- gcThread -- with this thread enabled, no error mv <- newEmptyMVar let p = P mv addFinalizer p (set p) takeMVar mv >>= print putStrLn "End." where set (P mv) = putMVar mv True -- -- this is just to demonstrate that it is only about the GC timing -- gcThread = forkIO $ let gc = do putStrLn "delay" threadDelay 100000 putStrLn "gc" performGC gc in gc
hferreiro/replay
testsuite/tests/concurrent/should_run/conc031.hs
bsd-3-clause
734
0
14
191
173
85
88
19
1
-- !!! Importing unknown name module M where import Prelude(f)
urbanslug/ghc
testsuite/tests/module/mod80.hs
bsd-3-clause
64
0
5
11
13
9
4
2
0
/* Copyright (C) 2007 Free Software Foundation Contributed by Ollie Wild <[email protected]> */ static unsigned offset[] = {__COUNTER__, __COUNTER__, __COUNTER__}; #define counter __COUNTER__
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.dg/pch/counter-1.hs
gpl-2.0
193
5
7
27
60
34
26
-1
-1
module KNXd.Client.Internal.Serialize where import Data.ByteString (ByteString) import Data.HList import Data.Serialize import Data.Word import KNXd.Client.Internal.Types -- |Some types need nonstandard serialization, -- so it's easier to just serialize in a special class. class ConvertWire a where putWire :: Putter a default putWire :: Serialize a => Putter a putWire = put getWire :: Get a default getWire :: Serialize a => Get a getWire = get instance ConvertWire Word8 where putWire = putWord8 getWire = getWord8 instance ConvertWire Word16 where putWire = putWord16be getWire = getWord16be instance ConvertWire Word32 where putWire = putWord32be getWire = getWord32be instance ConvertWire Bool where putWire True = putWord8 0xff putWire False = putWord8 0 getWire = (>0) <$> getWord8 -- |This instance assumes an isolate block and that every 'ByteString' comes last instance ConvertWire ByteString where -- |Note that this uses 'putByteString' to avoid writing length putWire = putByteString getWire = remaining >>= getByteString instance ConvertWire e => ConvertWire [e] where putWire = mapM_ putWire getWire = do len <- remaining let count = len `div` 2 replicateM count getWire instance ConvertWire e => ConvertWire (Maybe e) where putWire = mapM_ putWire getWire = do len <- remaining case len of 0 -> return Nothing _ -> Just <$> getWire instance ConvertWire (HList '[]) where putWire _ = return () getWire = return HNil instance (ConvertWire e, ConvertWire (HList l)) => ConvertWire (HList (e ': l)) where putWire (HCons e l) = putWire e >> putWire l getWire = HCons <$> getWire <*> getWire deriving instance ConvertWire IndividualAddress deriving instance ConvertWire GroupAddress instance ConvertWire ProgCommand where putWire = putWord8 . fromIntegral . fromEnum getWire = (toEnum . fromIntegral) <$> getWord8
KaneTW/knxd-native-client
src/KNXd/Client/Internal/Serialize.hs
mit
1,944
0
11
393
535
279
256
-1
-1
module P11 where import P10(encode) data Item a = Single a | Multiple Int a deriving(Show) -- | Modified run-length encoding -- >>> encodeModified "aaaabccaadeeee" -- [Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e'] encodeModified :: Eq a => [a] -> [Item a] encodeModified = fmap toItem . encode where toItem (1, x) = Single x toItem (n, x) = Multiple n x
briancavalier/h99
p11.hs
mit
404
0
8
79
114
64
50
7
2
{-# LANGUAGE OverloadedStrings #-} module CoinApi.Types.Quote where import CoinApi.Types.Internal import CoinApi.Types.Trade import Data.Aeson.Types data Quote = Quote { symbol_id :: !Text , time_exchange :: !UTCTime , time_coinapi :: !UTCTime , ask_price :: !Scientific , ask_size :: !Scientific , bid_price :: !Scientific , bid_size :: !Scientific , last_trade :: Maybe Trade } deriving (Show, Eq) instance FromJSON Quote where parseJSON = withObject "Quote" $ \o -> do symbol_id <- o .: "symbol_id" Quote symbol_id <$> fmap fromTime (o .: "time_exchange") <*> fmap fromTime (o .: "time_coinapi") <*> o .: "ask_price" <*> o .: "ask_size" <*> o .: "bid_price" <*> o .: "bid_size" <*> (parseLastTrade symbol_id =<< (o .:? "last_trade")) where parseLastTrade _ Nothing = return Nothing parseLastTrade symbol_id (Just o) = Just <$> (Trade symbol_id <$> fmap fromTime (o .: "time_exchange") <*> fmap fromTime (o .: "time_coinapi") <*> o .: "uuid" <*> o .: "price" <*> o .: "size" <*> o .: "taker_side")
coinapi/coinapi-sdk
data-api/haskell-rest/CoinApi/Types/Quote.hs
mit
1,892
0
23
1,044
336
177
159
46
0
-- Remove duplicates from list -- https://www.codewars.com/kata/57a5b0dfcf1fa526bb000118 module RemoveDuplicates where import Data.List (nub) distinct :: [Int] -> [Int] distinct = nub
gafiatulin/codewars
src/8 kyu/RemoveDuplicates.hs
mit
187
0
6
24
36
23
13
4
1
module Ecma.Prims where import Data.Int import Data.Word import Data.Binary.IEEE754 (doubleToWord) nan :: Double nan = read "NaN" infinity :: Double infinity = read "Infinity" -- 8.6.1 class Value a where --value :: (Typeable b) => a -> b value :: a -> a class Writable a where writable :: a -> Bool class Enumerable a where enumerable :: a -> Bool class Configurable a where configurable :: a -> Bool {-class Get a where get :: a -> a class Set a where set :: a -> a class (Enumerable a, Configurable a) => CommonProperties a where class (CommonProperties a, Writable a) => NamedDataProperties a where class (CommonProperties a, Get a, Set a) => NamedDataAccessorProperties a where-} -- 8.10.2 isDataDescriptor :: (Coerce a, Value a, Writable a, Queryable a) => a -> Bool isDataDescriptor desc = not (is_undefined desc) && (to_boolean (value desc) || writable desc) -- 8.12.1 getOwnProperty = undefined -- 9 class Coerce a where -- 9.1 to_primitive :: a -> Maybe a -> a to_primitive = undefined -- 9.2 to_boolean :: a -> Bool to_boolean a = False -- 9.3 to_number :: a -> Double to_number a = 0 -- 9.4 to_integer :: a -> Integer to_integer a | num == nan = 0 | num == infinity = to_integer' num | otherwise = to_integer' num where num = to_number a to_integer' = fromIntegral . doubleToWord -- 9.5 to_int32 :: a -> Int32 to_int32 = fromIntegral . to_integer -- 9.6 to_uint32 :: a -> Word32 to_uint32 = fromIntegral . to_integer -- 9.8 to_string :: a -> String to_string a = "" {- not sure what to do with these so far it seems that types need to be inspectable in a number of ways in addition to inspecting what's in them -} class (Coerce a) => Typeable a where -- basically need to cast to the type and return if it succeeds class (Coerce a) => Queryable a where is_undefined :: a -> Bool is_null :: a -> Bool
phylake/avm3
ecma/prims.hs
mit
1,954
0
10
474
466
248
218
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} -- | CmdItem is a tool to build command lines. module Data.CmdItem where import Control.Applicative ((<$>)) import Data.Either (either, partitionEithers) import Data.List (intercalate) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Monoid import Data.Text (Text, pack) import qualified Data.Text as T import GHC.Exts import Text.Templater (template) data CmdItem = CmdItem { fragments :: [Text] -- pieces of command line , localVars :: Map Text Text -- context of substitution } deriving (Show, Eq) -- | Renders a command line item to a @Text@ string -- This will throw an error if anything goes wrong render :: CmdItem -> IO Text render c = either error return (renderEither c) -- | Renders a command line item to a @Maybe Text@ renderMaybe :: CmdItem -> Maybe Text renderMaybe c = either (const Nothing) return (renderEither c) -- | Renders a command line item to a @Either String Text@ renderEither :: CmdItem -> Either String Text renderEither (CmdItem {..}) = let (lefts, rights) = partitionEithers $ (\x -> template x (`M.lookup` localVars)) <$> fragments isOk = null lefts in if isOk then Right $ T.intercalate " " rights else Left $ intercalate ", " lefts instance Monoid CmdItem where mempty = CmdItem mempty mempty mappend (CmdItem cmdA localA) (CmdItem cmdB localB) = CmdItem (cmdA <> cmdB) (localA <> localB) instance IsString CmdItem where fromString "" = mempty fromString st = CmdItem [pack st] mempty #if MIN_VERSION_base(4,7,0) instance IsList CmdItem where type Item CmdItem = (Text, Text) fromList [] = mempty fromList lst = CmdItem mempty (M.fromList lst) toList (CmdItem _ m) = M.toList m #endif
geraud/cmd-item
src/Data/CmdItem.hs
mit
2,040
0
14
551
514
284
230
38
2
module NinetyNine.Parser (module X) where import NinetyNine.Parser.Char as X import NinetyNine.Parser.Combinator as X import NinetyNine.Parser.Prim as X import NinetyNine.Parser.Token as X import NinetyNine.Parser.Example.Expr as X
airt/Haskell-99
src/NinetyNine/Parser.hs
mit
233
0
4
26
53
39
14
6
0
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveGeneric #-} module Models.ComicList (ComicList(..)) where import BasicPrelude import Data.Aeson (FromJSON(..), ToJSON(..)) import GHC.Generics (Generic) import Models.ComicSummary (ComicSummary) data ComicList = ComicList { available :: Int , items :: [ComicSummary] } deriving (Show, Generic) instance FromJSON ComicList instance ToJSON ComicList
nicolashery/example-marvel-haskell
Models/ComicList.hs
mit
414
0
9
58
110
67
43
13
0
module Language.UHC.JScript.Assorted where import Language.UHC.JScript.ECMA.String import Language.UHC.JScript.Types import Language.UHC.JScript.Primitives alert :: String -> IO () alert = _alert . toJS foreign import js "alert(%*)" _alert :: JSString -> IO ()
kjgorman/melchior
Language/UHC/JScript/Assorted.hs
mit
266
1
7
35
67
42
25
8
1
module Settings.Packages.Cabal where import GHC import Expression cabalPackageArgs :: Args cabalPackageArgs = package cabal ? -- Cabal is a rather large library and quite slow to compile. Moreover, we -- build it for stage0 only so we can link ghc-pkg against it, so there is -- little reason to spend the effort to optimize it. stage0 ? builder Ghc ? arg "-O0"
izgzhen/hadrian
src/Settings/Packages/Cabal.hs
mit
380
0
8
80
47
27
20
6
1
module Language.Brainfuck.Py2Bf.Bfprim ( Bfprim (..) , isBfprimNonIO , isBfWhile , BfState , runPrim , runPrimIO ) where import Data.Word (Word8) import Data.Functor ((<$>)) import Codec.Binary.UTF8.String (decode, encode) data Bfprim = BfIncr | BfDecr | BfNext | BfPrev | BfPut | BfGet | BfWhile [Bfprim] deriving Eq instance Show Bfprim where show BfIncr = "+" show BfDecr = "-" show BfNext = ">" show BfPrev = "<" show BfPut = "." show BfGet = "," show (BfWhile bf) = '[' : concatMap show bf ++ "]" showList = (++) . concatMap show instance Read Bfprim where readsPrec _ str = case snd (parse str) of bfprim:_ -> [(bfprim, "")] _ -> [] readList str = [(snd (parse str), "")] parse :: String -> (String, [Bfprim]) parse ('+':bf) = (BfIncr:) <$> parse bf parse ('-':bf) = (BfDecr:) <$> parse bf parse ('>':bf) = (BfNext:) <$> parse bf parse ('<':bf) = (BfPrev:) <$> parse bf parse ('.':bf) = (BfPut:) <$> parse bf parse (',':bf) = (BfGet:) <$> parse bf parse ('[':bf) = (\(s, bff) -> (BfWhile bff:) <$> parse s) (parse bf) parse (']':bf) = (bf, []) parse (_:bf) = parse bf parse [] = ("", []) isBfprimNonIO :: Bfprim -> Bool isBfprimNonIO BfPut = False isBfprimNonIO BfGet = False isBfprimNonIO (BfWhile bf) = all isBfprimNonIO bf isBfprimNonIO _ = True isBfWhile :: Bfprim -> Bool isBfWhile (BfWhile _) = True isBfWhile _ = False type BfState = ([Word8], Word8, [Word8], [Word8], [Word8]) runPrim :: [Bfprim] -> BfState -> Either String BfState runPrim (BfIncr:bf) (xs, x, ys, os, is) = runPrim bf (xs, x + 1, ys, os, is) runPrim (BfDecr:bf) (xs, x, ys, os, is) = runPrim bf (xs, x - 1, ys, os, is) runPrim (BfNext:bf) (xs, x, [], os, is) = runPrim bf (x:xs, 0, [], os, is) runPrim (BfNext:bf) (xs, x, y:ys, os, is) = runPrim bf (x:xs, y, ys, os, is) runPrim (BfPrev:_) ([], _, _, _, _) = Left negativeAddressError runPrim (BfPrev:bf) (x:xs, y, ys, os, is) = runPrim bf (xs, x, y:ys, os, is) runPrim (BfWhile _:bf) s@(_, 0, _, _, _) = runPrim bf s runPrim bf@(BfWhile bff:_) s = runPrim bff s >>= runPrim bf runPrim (BfPut:bf) (xs, x, ys, os, is) = runPrim bf (xs, x, ys, os ++ [x], is) runPrim (BfGet:bf) (xs, _, ys, os, []) = runPrim bf (xs, 0, ys, os, []) runPrim (BfGet:bf) (xs, _, ys, os, i:is) = runPrim bf (xs, i, ys, os, is) runPrim [] s = Right s runPrimIO :: [Bfprim] -> BfState -> IO BfState runPrimIO (BfIncr:bf) (xs, x, ys, os, is) = runPrimIO bf (xs, x + 1, ys, os, is) runPrimIO (BfDecr:bf) (xs, x, ys, os, is) = runPrimIO bf (xs, x - 1, ys, os, is) runPrimIO (BfNext:bf) (xs, x, [], os, is) = runPrimIO bf (x:xs, 0, [], os, is) runPrimIO (BfNext:bf) (xs, x, y:ys, os, is) = runPrimIO bf (x:xs, y, ys, os, is) runPrimIO (BfPrev:_) ([], _, _, _, _) = error negativeAddressError runPrimIO (BfPrev:bf) (x:xs, y, ys, os, is) = runPrimIO bf (xs, x, y:ys, os, is) runPrimIO (BfWhile _:bf) s@(_, 0, _, _, _) = runPrimIO bf s runPrimIO bf@(BfWhile bff:_) s = runPrimIO bff s >>= runPrimIO bf runPrimIO (BfPut:bf) (xs, x, ys, os, is) | x > 0xbf = putStr (decode os) >> runPrimIO bf (xs, x, ys, [x], is) | null os || l == 5 && 0xfb < h && h <= 0xff || l == 4 && 0xf7 < h && h <= 0xfb || l == 3 && 0xef < h && h <= 0xf7 || l == 2 && 0xdf < h && h <= 0xef || l == 1 && 0xc1 < h && h <= 0xdf = putStr str >> runPrimIO bf (xs, x, ys, [], is) | otherwise = runPrimIO bf (xs, x, ys, os ++ [x], is) where str = decode (os ++ [x]) l = length os h = head os runPrimIO (BfGet:bf) (xs, _, ys, os, []) = encode . return <$> getChar >>= \inp -> case inp of [] -> runPrimIO bf (xs, 0, ys, os, []) i:is -> runPrimIO bf (xs, i, ys, os, is) runPrimIO (BfGet:bf) (xs, _, ys, os, i:is) = runPrimIO bf (xs, i, ys, os, is) runPrimIO [] s = return s negativeAddressError :: String negativeAddressError = "negative address access"
itchyny/py2bf.hs
Language/Brainfuck/Py2Bf/Bfprim.hs
mit
4,210
0
38
1,219
2,231
1,248
983
94
2
module Control.Flower.Functor ( module Control.Flower.Functor.Lazy, module Control.Flower.Functor.Strict ) where import Control.Flower.Functor.Lazy import Control.Flower.Functor.Strict
expede/flower
src/Control/Flower/Functor.hs
mit
190
0
5
18
39
28
11
5
0
module Chattp.Relay.Config where import System.Environment (getEnv, lookupEnv) import qualified Data.ByteString.Lazy.Char8 as BS data Family = Inet | Unix deriving (Show,Eq) data RelayConfig = RelayConfig { publishHost :: String, publishPort :: Int, publishBasePath :: String, publishChanIdParam :: String, myHost :: String, myFamily :: Family, myPort :: Int, brokerHost :: String, brokerPort :: Int, nThreads :: Int, publishURL :: BS.ByteString } deriving Show publish_host_env_var, publish_port_env_var, publish_base_path_env_var :: String publish_chan_id_env_var, broker_addr_env_var, broker_port_env_var, nthreads_env_var :: String self_bind_addr_env_var, self_bind_family_env_var, self_bind_port_env_var :: String publish_host_env_var = "CHATTP_MSGRELAY_PUBLISH_HOST" publish_port_env_var = "CHATTP_MSGRELAY_PUBLISH_PORT" publish_base_path_env_var = "CHATTP_MSGRELAY_PUBLISH_BASE_PATH" publish_chan_id_env_var = "CHATTP_MSGRELAY_PUBLISH_CHAN_ID_PARAMETER" broker_addr_env_var = "CHATTP_MSGBROKER_MSGRELAY_BIND_ADDR" broker_port_env_var = "CHATTP_MSGBROKER_MSGRELAY_BIND_PORT" self_bind_addr_env_var = "CHATTP_MESG_RELAY_ADDR" self_bind_family_env_var = "CHATTP_MESG_RELAY_FAMILY" self_bind_port_env_var = "CHATTP_MESG_RELAY_PORT" nthreads_env_var = "CHATTP_MSGRELAY_NUMBER_THREADS" makeConfig :: IO RelayConfig makeConfig = do -- web server info p_host <- getEnv publish_host_env_var p_port_raw <- lookupEnv publish_port_env_var p_base <- getEnv publish_base_path_env_var p_chanid <- getEnv publish_chan_id_env_var let p_port = maybe 80 read p_port_raw -- self bind info my_family_raw <- getEnv self_bind_family_env_var let my_family = case my_family_raw of "UNIX" -> Unix "INET" -> Inet my_addr <- getEnv self_bind_addr_env_var my_port <- if my_family == Inet then fmap read (getEnv self_bind_port_env_var) else return 0 -- broker info broker_addr <- getEnv broker_addr_env_var broker_port <- if my_family == Inet then fmap read (getEnv broker_port_env_var) else return 0 -- nthreads_raw <- lookupEnv nthreads_env_var let nthreads = maybe 2 read nthreads_raw return RelayConfig { publishHost = p_host, publishPort = p_port, publishBasePath = p_base, publishChanIdParam = p_chanid, myHost = my_addr, myFamily = my_family, myPort = my_port, brokerHost = broker_addr, brokerPort = broker_port, nThreads = nthreads, publishURL = BS.pack $ "http://" ++ p_host ++ p_base ++ "/pub?" ++ p_chanid ++ "=" }
Spheniscida/cHaTTP
mesg-relay/Chattp/Relay/Config.hs
mit
2,842
0
16
700
530
299
231
58
4
{-# LANGUAGE TemplateHaskell #-} module Parser where import Control.Monad import Control.Monad.State import Control.Lens import Data.List import Data.Map as M hiding (map) type RuleName = String type RulePair = (RuleName, Pattern) type RuleMap = M.Map RuleName Pattern data RepTime = RTInt Integer -- n-times | RTInf -- infinity deriving (Show,Eq) manyTimes :: Pattern -> Pattern manyTimes a = Repetition a (RTInt 1) RTInf -- + anyTimes :: Pattern -> Pattern anyTimes a = Repetition a (RTInt 0) RTInf -- * optional :: Pattern -> Pattern optional a = Repetition a (RTInt 0) (RTInt 1) -- ? rtZerop :: RepTime -> Bool rtZerop (RTInt 0) = True rtZerop _ = False rtPred :: RepTime -> RepTime rtPred (RTInt 0) = RTInt 0 rtPred (RTInt n) = RTInt (n - 1) rtPred RTInf = RTInf data Pattern = Atom String | Rule String | RuleX String -- rule that only do matching but ignoring the result -- TODO: RepetitionL : Lazy repetition | Repetition Pattern RepTime RepTime -- pat, minTime, maxTime | Choice [Pattern] | Sequence [Pattern] | NegativeLookahead Pattern | PositiveLookahead Pattern deriving (Eq) instance Show Pattern where show (Atom x) = show x show (Rule x) = x show (RuleX x) = "@" ++ x show (Repetition p a b) = show p ++ mark a b where mark (RTInt 0) (RTInt 1) = "?" mark (RTInt 1) RTInf = "+" mark (RTInt 0) RTInf = "*" mark (RTInt l) (RTInt u) = "{" ++ show l ++ "," ++ show u ++ "}" mark _ _ = undefined show (Choice xs) = intercalate " | " $ map show xs show (Sequence xs) = unwords $ map show xs show (NegativeLookahead p) = '!' : show p show (PositiveLookahead p) = '=' : show p data MatchData = MAtom String | MList [MatchData] | MPair (RuleName, MatchData) deriving (Eq) instance Show MatchData where show (MPair (name,md)) = "{" ++ show md ++ "}:" ++ name show (MList xs) = join $ map show xs show (MAtom x) = x isMPair :: MatchData -> Bool isMPair (MPair (_,_)) = True isMPair _ = False getMPair :: MatchData -> (RuleName, MatchData) getMPair (MPair (r,m)) = (r,m) getMPair _ = error "not a MPair" isMList :: MatchData -> Bool isMList (MList _) = True isMList _ = False getMList :: MatchData -> [MatchData] getMList (MList xs) = xs getMList _ = error "not a MList" isMAtom :: MatchData -> Bool isMAtom (MAtom _) = True isMAtom _ = False getMAtom :: MatchData -> String getMAtom (MAtom s) = s getMAtom _ = error "not a MAtom" mInspect :: MatchData -> String mInspect (MPair (n,md)) = n ++ "=>" ++ mInspect md mInspect (MList xs) = "[" ++ intercalate "/" (map mInspect xs) ++ "]" mInspect (MAtom s) = s mToString :: MatchData -> String mToString (MPair (_,md)) = mToString md mToString (MList xs) = join $ map mToString xs mToString (MAtom s) = s data ParsingState = ParsingState { _restString :: String, _ruleMap :: RuleMap } makeLenses ''ParsingState type ParseState = State ParsingState type ParseResult = ParseState (Maybe MatchData) getRestString :: ParseState String getRestString = liftM (view restString) get putRestString :: String -> ParseState () putRestString st = modify (restString .~ st) -- read only state getRuleMap :: ParseState RuleMap getRuleMap = liftM (view ruleMap) get lookupRule :: RuleName -> ParseState (Maybe Pattern) lookupRule name = liftM (M.lookup name) getRuleMap parseI :: Pattern -> ParseResult parseI (Atom x) = do rest <- getRestString let len = length x if len <= length rest && take len rest == x then do putRestString (drop len rest) return $ Just $ MAtom x else return Nothing parseI (Rule name) = do pat' <- lookupRule name case pat' of Nothing -> return Nothing Just pat -> do result <- parseI pat case result of Nothing -> return Nothing Just m -> return $ Just $ MPair (name, m) parseI (RuleX name) = do pat' <- lookupRule name case pat' of Nothing -> return Nothing Just pat -> do result <- parseI pat case result of Nothing -> return Nothing Just m -> return $ Just $ MAtom $ mToString m parseI (Repetition pat l' u') = if rtZerop u' then return $ Just $ MList [] else do oldST <- get m' <- parseI pat case m' of Nothing -> if rtZerop l' then do put oldST return (Just $ MList []) else return Nothing -- error Just m -> do ms' <- parseI (Repetition pat (rtPred l') (rtPred u')) case ms' of Nothing -> return Nothing Just (MList ms) -> return $ Just $ MList (m : ms) Just _ -> error "impossible" parseI (Choice []) = return Nothing -- impossible case parseI (Choice [p]) = do m' <- parseI p case m' of Nothing -> return Nothing Just _ -> return m' parseI (Choice (p:ps)) = do oldST <- get m' <- parseI p case m' of Just _ -> return m' Nothing -> do put oldST parseI (Choice ps) parseI (Sequence []) = return $ Just $ MList [] parseI (Sequence (p:ps)) = do m' <- parseI p case m' of Nothing -> return Nothing Just m -> do ms' <- parseI (Sequence ps) case ms' of Nothing -> return Nothing Just ms'' -> case ms'' of MList ms -> return $ Just $ MList (m:ms) _ -> error "impossible!" parseI (NegativeLookahead p) = do oldST <- get m' <- parseI p put oldST case m' of Nothing -> return $ Just $ MAtom "" Just _ -> return Nothing parseI (PositiveLookahead p) = do oldST <- get m' <- parseI p put oldST case m' of Just _ -> return $ Just $ MAtom "" Nothing -> return Nothing
shouya/gximemo
GxiMemo/Parser.hs
mit
5,934
0
21
1,771
2,288
1,130
1,158
177
18
module Hitly.Map ( appMap, mkMap, atomicIO, newLink, getLink, getAndTickCounter ) where import BasePrelude hiding (insert, lookup, delete) import Control.Monad.IO.Class import STMContainers.Map import Hitly.Types appMap :: STM AppMap appMap = new mkMap :: MonadIO m => m AppMap mkMap = liftIO $ atomically $ appMap atomicIO :: MonadIO m => STM a -> m a atomicIO = liftIO . atomically newLink :: (Hashable k, Eq k) => v -> k -> Map k v -> STM () newLink = insert getLink :: (Hashable k, Eq k) => k -> Map k v -> STM (Maybe v) getLink urlHash smap = lookup urlHash smap getAndTickCounter :: (Hashable k, Eq k) => k -> Map k HitlyRequest -> STM (Maybe HitlyRequest) getAndTickCounter urlHash smap = do orig <- getLink urlHash smap case orig of Nothing -> return Nothing Just (HitlyRequest user' url' cnt') -> do let ticked = HitlyRequest user' url' (cnt' + 1) delete urlHash smap insert ticked urlHash smap return $ Just ticked
buckie/hitly
src/Hitly/Map.hs
mit
1,044
0
17
281
384
195
189
31
2
{-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DataKinds #-} module Language.HLC.HighLevelC.PrimFunctions where import Language.HLC.Util.Names import Data.Typeable import Language.HLC.HighLevelC.HLC import Language.HLC.HighLevelC.HLCTypes import Language.HLC.HighLevelC.BasicTypes import Language.HLC.HighLevelC.CWriter import Language.HLC.HighLevelC.Operators import Language.HLC.HighLevelC.HLCCalls import Language.HLC.HighLevelC.LangConstructs malloc :: ExtFunction '[HLCInt] (HLCPtr HLCVoid) False malloc = ExtFunction (ExactSymbol "malloc") [PreprocessorDirective "#include <stdlib.h>"] call_malloc :: forall a intTy ptrTy. (HLCBasicIntType intTy, RHSExpression a intTy, HLCTypeable ptrTy) => a -> HLC (TypedExpr (HLCPtr ptrTy)) call_malloc n = let n' = fromIntType $ rhsExpr n :: HLC (TypedExpr HLCInt) in castPtr $ callExtFunction malloc (n' :+: HNil) freeMem :: ExtFunction '[HLCPtr a] HLCVoid False freeMem = ExtFunction (ExactSymbol "free") [PreprocessorDirective "#include <stdlib.h>"] call_freeMem :: forall a obj. (RHSExpression a (HLCPtr obj), HLCTypeable obj) => a -> HLC (TypedExpr HLCVoid) call_freeMem ptr = callExtFunction (freeMem :: ExtFunction '[HLCPtr obj] HLCVoid False) ((rhsExpr ptr) :+: HNil) printf :: ExtFunction '[HLCString] HLCVoid True printf = ExtFunction (ExactSymbol "printf") [PreprocessorDirective "#include <stdio.h>"]
alexstachnik/High-Level-C
src/Language/HLC/HighLevelC/PrimFunctions.hs
gpl-2.0
1,811
0
12
302
409
229
180
43
1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Haskell.Data where import Autolib.ToDoc import Autolib.Reader import Autolib.Size import Data.Typeable import Test.QuickCheck ( Args (..)) import System.Random ( StdGen ) import qualified Language.Haskell.Exts.Parser as Pa import qualified Language.Haskell.Exts.Pretty as Pr -- TODO: the ToDoc method should -- definitely not print the String quotes -- and maybe do prettyprinting -- the Reader Method should not need the string quotes -- and call a real Haskell parser instead data Code = Code String deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc] [''Code]) data Display = Display instance Size Code where -- FIXME: should use the size of the syntax tree size ( Code cs ) = length cs code_example :: Code code_example = Code "\\ n -> (0,n)" data Driver = QuickCheck -- Args | SmallCheck { tests_run :: Int , failures_shown :: Int } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Driver]) instance Reader StdGen instance ToDoc StdGen data Instance = Instance { global :: Code -- | an Haskell expression, -- will be applied to student's solution -- and must then represent a Quick/Smallcheck property , specification :: Code , driver :: Driver , testing_time_seconds :: Int } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Instance]) instance_example :: Instance instance_example = Instance { global = Code "data Foo = Bar" , specification = Code "\\ f -> \\ n -> let (x,y) = f n in if n > 0 then 2^x * y == n && odd y else True " , driver = SmallCheck { tests_run = 1000, failures_shown = 10 } , testing_time_seconds = 1 }
marcellussiegburg/autotool
collection/src/Haskell/Data.hs
gpl-2.0
1,859
0
9
500
360
214
146
37
1
module DarkPlaces.Demo ( getDemoMessage, getDemoMessages, iterDemoMessages, demoFileMessages, demoFilePackets ) where import Control.Applicative import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as B import Data.Binary.Get import DarkPlaces.Types import DarkPlaces.Binary import DarkPlaces.PacketParser getDemoMessage :: Get (QVector, BL.ByteString) getDemoMessage = do size <- fromIntegral <$> getWord32le angls <- getQVector32f msg <- getLazyByteString size return (angls, msg) getDemoMessages :: Get [(QVector, BL.ByteString)] getDemoMessages = do empty <- isEmpty if empty then return [] else (:) <$> getDemoMessage <*> getDemoMessages iterDemoMessages :: BL.ByteString -> [Either ErrorInfo (QVector, BL.ByteString)] iterDemoMessages demo_data = go decoder $ BL.toChunks demo_data where decoder = runGetIncremental getDemoMessage go (Fail _ offset msg) _ = [Left (offset, msg)] go (Partial k) [] = go (k Nothing) [] go (Partial k) (x:xs) = go (k $ Just x) xs go (Done left _ res) xs = Right res : if empty then [] else go decoder xs' where empty = B.null left && null xs xs' = left:xs demoFileMessages :: BL.ByteString -> [Either ErrorInfo (QVector, BL.ByteString)] demoFileMessages file_data = either (\l -> [Left l]) iterDemoMessages either_demo where either_demo = skipTrack file_data demoFilePackets :: BL.ByteString -> [Either ErrorInfo PacketOrError] demoFilePackets file_data = parse (demoFileMessages file_data) defaultDemoState where parse (x:xs) s = case x of Left l -> [Left l] Right (_, ps) -> case listPackets ps s of Left l -> [Left l] Right (pls, s') -> (Right <$> pls) ++ parse xs s' parse [] _ = []
bacher09/darkplaces-demo
src/DarkPlaces/Demo.hs
gpl-2.0
1,818
0
15
406
638
335
303
45
5
module TS.Page.YoYo where import TS.Logic import TS.Utils import TS.App import Yesod --Improve Elm loading method. Find a way to embed the code. Link the the .elm here rather than the .js yoyoPage :: WidgetT TS IO() yoyoPage = sendFile "text/html" "Resources/yoyo.html"
Sheerfreeze/thoughtspread
TS/Page/YoYo.hs
gpl-2.0
272
0
6
43
50
29
21
7
1
module Data.Chemistry.Parser ( xyzParser , xyzTrajParser , moldenParser , nwBasisParser , gmsBasisParser , numericalMatrixParser ) where import Control.Applicative import Data.Attoparsec.Text.Lazy import Data.Chemistry.Types import Data.Chemistry.Wavefunction import Data.Maybe import qualified Data.Text as T import qualified Numeric.LinearAlgebra as BLAS import Numeric.LinearAlgebra ((><)) import Data.List -- | Make a parser optional, return Nothing if there is no match maybeOption :: Parser a -> Parser (Maybe a) maybeOption p = option Nothing (Just <$> p) -- | give a element and a list. Checks if every element in this list ist the given element allequal :: (Eq a) => a -> [a] -> Bool allequal e elist = foldl (\acc x -> if x /= e then False else acc) True elist -------------------------------------------------------------------------------- -- chemical data formats -------------------------------------------------------------------------------- {- === -} {- XYZ -} {- === -} xyzParser :: Parser XYZ xyzParser = do skipSpace nAtoms_parse <- decimal _ <- manyTill anyChar endOfLine comment_parse <- manyTill anyChar endOfLine --coordinates <- many' xyzCoordLineParser coordinates <- count nAtoms_parse xyzCoordLineParser -- _ <- endOfLine <|> endOfInput return XYZ { _xyz_nAtoms = nAtoms_parse , _xyz_comment = comment_parse , _xyz_xyzcontent = coordinates } where xyzCoordLineParser :: Parser (String,Double,Double,Double) xyzCoordLineParser = do skipSpace element_p <- manyTill anyChar (char ' ') skipSpace x <- double skipSpace y <- double skipSpace z <- double skipSpace _ <- many' endOfLine return (element_p,x,y,z) xyzTrajParser :: Parser [XYZ] xyzTrajParser = do trajectory <- many' xyzParser return trajectory {- ====== -} {- Molden -} {- ====== -} -- | Parse interesting parts of a Molden file (Atoms, GTO, MOs) moldenParser :: Parser Molden moldenParser = do -- it all began with "[Molden Format]" ... _ <- asciiCI $ T.pack "[Molden Format]" -- parse the "[Atoms]" block, containing the geometry informations atoms_p <- moldenATOMS -- parse the "[GTO]" block basfuns_p <- moldenGTO -- parse the "[MO]" block mmos_p <- moldenMO -- return the results return Molden { _molden_atoms = atoms_p , _molden_basfuns = basfuns_p , _molden_mos = mmos_p } where moldenTITLE :: Parser String moldenTITLE = do -- it starts with the "[Title]" _ <- manyTill anyChar (asciiCI $ T.pack "[Title]") skipSpace title_p <- manyTill anyChar endOfLine return title_p moldenATOMS :: Parser (MoldenUnits, [MoldenCoord]) moldenATOMS = do -- it starts with the "[Atoms]" block _ <- manyTill anyChar (asciiCI $ T.pack "[Atoms]") -- parse the units. Maybe AU/(AU) or Angs/(Angs) skipSpace units_p <- do units_raw <- manyTill anyChar endOfLine if T.isInfixOf (T.toLower . T.pack $ units_raw) (T.pack "(au)") then return Bohr else return Angstrom -- the geometry line by line skipSpace geom <- many1 moldenCoordLineParser -- return the results return (units_p, geom) where -- parse a coordinate line in a [Atoms] block moldenCoordLineParser :: Parser MoldenCoord moldenCoordLineParser = do -- parse the atomic symbol skipSpace element_p <- manyTill anyChar (char ' ') -- parse the number of the atom in the molecule skipSpace natom_p <- decimal -- parse the atomic number (aka number of protons) skipSpace nproton_p <- decimal -- the x coordinate skipSpace x_p <- double -- the y coordinate skipSpace y_p <- double -- the z coordinate skipSpace z_p <- double -- return the results return MoldenCoord { _moldenCoord_element = element_p , _moldenCoord_natom = natom_p , _moldenCoord_nproton = nproton_p , _moldenCoord_coord = (x_p, y_p, z_p) } moldenGTO :: Parser [[BasFun]] moldenGTO = do -- it starts with the "[GTO]" block _ <- manyTill anyChar (asciiCI $ T.pack "[GTO]") -- possibly there is also a unit here _ <- manyTill anyChar endOfLine -- parse the basis functions of an atom skipSpace basfuns_p <- many1 moldenGTOAtomParser -- parse the informations about coordinate system skipSpace _ <- maybeOption (asciiCI $ T.pack "[5D]") skipSpace _ <- maybeOption (asciiCI $ T.pack "[7F]") skipSpace _ <- maybeOption (asciiCI $ T.pack "[9G]") skipSpace -- return the results (basis functions atomwise) return basfuns_p where {- parse the basis functions for a complete atom, for example 2 0 s 3 0 13.0100000000 0.0334987264 1.9620000000 0.2348008012 0.4446000000 0.8136829579 s 1 0 0.1220000000 1.0000000000 p 1 0 0.7270000000 1.0000000000 -} moldenGTOAtomParser :: Parser [BasFun] moldenGTOAtomParser = do -- parse the atom number, on which the basis functions are centred skipSpace _ <- (decimal :: Parser Int) -- the zero at the end skipSpace _ <- maybeOption (char '0') skipSpace -- parse the basis functions of the given atom basfunsAtom_p <- many1 moldenGTOAtomBFParser --return the result return basfunsAtom_p {- parse a single basis function for a given atom s 3 0 13.0100000000 0.0334987264 1.9620000000 0.2348008012 0.4446000000 0.8136829579 -} moldenGTOAtomBFParser :: Parser BasFun moldenGTOAtomBFParser = do -- parse the angular momentum of this basis function skipSpace angular_p <- do angular_char <- letter return $ orb2AngMom angular_char -- number of PGTOs to experct skipSpace npgto_p <- decimal -- parse the zero or other number till the endOfLine skipSpace _ <- maybeOption (manyTill anyChar $ char ' ' <|> char '\n') -- parse the PGTOs line by line and make a CGTO of them skipSpace cgto_p <- count npgto_p pgto_and_ContrCoeff return $ BasFun { _basfun_angular = angular_p , _basfun_radial = cgto_p } -- parse a single pgto and its contraction coefficient pgto_and_ContrCoeff :: Parser (PGTO, ContrCoeff) pgto_and_ContrCoeff = do -- parse the exponent skipSpace pgto_p <- double -- parse the contraction coefficient skipSpace contrcoeff_p <- double -- return the result return $ (pgto_p, contrcoeff_p) moldenMO :: Parser [MoldenMO] moldenMO = do -- it starts with the "[Atoms]" block skipSpace _ <- manyTill anyChar (asciiCI $ T.pack "[MO]") -- parse the MOs skipSpace mmos <- many1 singleMMOParser -- return the results return mmos where singleMMOParser :: Parser MoldenMO singleMMOParser = do -- parse the "Sym" statement skipSpace sym_p <- do sym_temp <- maybeOption symParse if (isNothing sym_temp == True) then return "e" else return $ fromJust sym_temp -- parse the "Ene" statement skipSpace _ <- asciiCI $ T.pack "Ene=" skipSpace ene_p <- double -- parse the "Spin" statement skipSpace _ <- asciiCI $ T.pack "Spin=" skipSpace spin_p <- do spin_raw <- manyTill anyChar $ (char ' ') <|> (char '\n') if (spin_raw == "Alpha") then return Alpha else return Beta -- parse the "Occup" statement skipSpace _ <- asciiCI $ T.pack "Occup=" skipSpace occup_p <- double -- parse the MO coefficients in the AO expansion skipSpace coeffs_p <- do coeffs_raw <- many1 coeff_lineParser return $ BLAS.fromList coeffs_raw -- return the results return MoldenMO { _moldenMO_sym = sym_p , _moldenMO_energy = ene_p , _moldenMO_spin = spin_p , _moldenMO_occup = occup_p , _moldenMO_coeffs = coeffs_p } -- wrap the symmetry parser in an optional statement, so it can be optional symParse :: Parser String symParse = do _ <- asciiCI $ T.pack "Sym=" skipSpace sym_p <- manyTill anyChar $ char ' ' <|> char '\n' return $ sym_p -- parse a single line of the coefficients in the [MO] block for a single MO coeff_lineParser :: Parser Double coeff_lineParser = do -- not interested in the first number (label of basis function) skipSpace _ <- (decimal :: Parser Int) -- but parse the mo coefficient skipSpace single_mo_coeff_p <- double -- return the result return single_mo_coeff_p -------------------------------------------------------------------------------- -- basis sets -------------------------------------------------------------------------------- -- | NWChem format as obtained from Basis set exchange -- | parse complete basis set file nwBasisParser :: Parser [Basis] nwBasisParser = do _ <- manyTill anyChar (string $ T.pack "BASIS \"ao basis\" PRINT") --_ <- string $ T.pack "BASIS \"ao basis\" PRINT" endOfLine basises <- many1 nwSingleBasisParser _ <- string $ T.pack "END" return basises where -- parse basis for a single element nwSingleBasisParser :: Parser Basis nwSingleBasisParser = do _ <- string $ T.pack "#BASIS SET: " _ <- manyTill anyChar endOfLine parsedGauss <- many1 nwConGaussParser let elements = map fst parsedGauss conGaussians = map snd parsedGauss if (allequal (head elements) elements) then do return Basis { element = head elements , basFuns = concat conGaussians } else do return Basis { element = "X" , basFuns = [ConGauss {angMom = 0, expoCoeff_pairs = [(0.0, 0.0)]}] } {- parse o complete block of a contracted gaussian SP and other contractions as in the pople basis sets are recognized and flattened general contractions are also recognized and flattened example: C S 3047.5249000 0.0018347 457.3695100 0.0140373 would give ("C", [ConGauss {angMom = 0, expoCoeff_pairs = [(3047.5249000, 0.0018347), (457.3695100, 0.0140373)]}]) example: C SP 7.8682724 -0.1193324 0.0689991 would give ("C", [ConGauss {angMom = 0, expoCoeff_pairs = [(7.8682724, -0.1193324)]}, ConGauss {angMom = 1, expoCoeff_pairs = [(7.8682724, 0.0689991)]}]) example: C S 0.1687144 1.0000000 2.0000000 would give ("C", [ConGauss {angMom = 1, expoCoeff_pairs = [(0.1687144, 1.0)], ConGauss {angMom = 0, expoCoeff_pairs = [(0.1687144,1.0)]}]) -} nwConGaussParser :: Parser (String, [ConGauss]) nwConGaussParser = do atom <- manyTill anyChar (char ' ') _ <- many1 (char ' ') angMom_raw <- manyTill anyChar (char ' ' <|> char '\n') expoCoeffs_pairs_raw <- many1 nwConGaussLineParser conGauss_list <- if (length angMom_raw == 1) then do if ((length . snd $ head expoCoeffs_pairs_raw) == 1) then do let expoList = map fst expoCoeffs_pairs_raw coeffList = concat . (map snd) $ expoCoeffs_pairs_raw return [ ConGauss { angMom = orb2AngMom $ head angMom_raw , expoCoeff_pairs = zip expoList coeffList } ] else do let expoList = map fst expoCoeffs_pairs_raw manyCoeffList = map snd expoCoeffs_pairs_raw return [ ConGauss { angMom = orb2AngMom $ head angMom_raw , expoCoeff_pairs = zip expoList (map (!! ind) manyCoeffList) } | ind <- [0..(length (head manyCoeffList) - 1)] ] else do let angMoms = map orb2AngMom angMom_raw expoList = map fst expoCoeffs_pairs_raw manyCoeffList = map snd expoCoeffs_pairs_raw return [ ConGauss { angMom = angMoms !! ind , expoCoeff_pairs = zip expoList (map (!! ind) manyCoeffList) } | ind <- [0..(length angMom_raw -1)] ] return (atom, conGauss_list) {- parse single line of gaussians in NWChem style example: exponent1 coefficient1a coefficient1b would give (exponent, [coefficient1a, coefficient1b]) -} nwConGaussLineParser :: Parser (Double, [Double]) nwConGaussLineParser = do _ <- many' (char ' ') expo <- double _ <- many' (char ' ') coefflist <- many1 coeffparser endOfLine let pairs = (expo, coefflist) return pairs where coeffparser :: Parser Double coeffparser = do coeff <- double _ <- many' (char ' ') return coeff -- | parse a basis set for GAMESS-US gmsBasisParser :: Parser [Basis] gmsBasisParser = do _ <- manyTill anyChar (string $ T.pack "$DATA") endOfLine basises <- many1 gmsSingleBasisParser _ <- string $ T.pack "$END" return basises where gmsSingleBasisParser :: Parser Basis gmsSingleBasisParser = do skipSpace fullElemName <- manyTill anyChar endOfLine parsedGauss <- many1 gmsConGaussParser return Basis { element = fullElemName , basFuns = concat parsedGauss } gmsConGaussParser :: Parser [ConGauss] gmsConGaussParser = do skipSpace angMom_raw <- anyChar skipSpace _ <- (decimal :: Parser Int) _ <- many' (char ' ') endOfLine expoCoeffs_pairs_raw <- many1 gmsConGaussLineParser conGauss_list <- if (angMom_raw /= 'L') then do if (length . snd $ head expoCoeffs_pairs_raw) == 1 then do let expoList = map fst expoCoeffs_pairs_raw coeffList = concat . (map snd) $ expoCoeffs_pairs_raw return [ ConGauss { angMom = orb2AngMom angMom_raw , expoCoeff_pairs = zip expoList coeffList } ] else do let expoList = map fst expoCoeffs_pairs_raw manyCoeffList = map snd expoCoeffs_pairs_raw return [ ConGauss { angMom = orb2AngMom angMom_raw , expoCoeff_pairs = zip expoList (map (!! ind) manyCoeffList) } | ind <- [0..(length (head manyCoeffList) - 1)] ] else do let angMoms = [0, 1] expoList = map fst expoCoeffs_pairs_raw manyCoeffList = map snd expoCoeffs_pairs_raw return [ ConGauss { angMom = angMoms !! ind , expoCoeff_pairs = zip expoList (map (!! ind) manyCoeffList) } | ind <- [0, 1] ] return conGauss_list gmsConGaussLineParser :: Parser (Double, [Double]) gmsConGaussLineParser = do skipSpace _ <- (decimal :: Parser Int) skipSpace expo <- double skipSpace coefflist <- many1 coeffparser _ <- many' (char ' ') endOfLine let pairs = (expo, coefflist) return pairs where coeffparser :: Parser Double coeffparser = do coeff <- double _ <- many' (char ' ') return coeff -------------------------------------------------------------------------------- -- Simple data formats -------------------------------------------------------------------------------- -- | A simple parser for many fixed column data, numericalMatrixParser :: [Char] -> Parser (Maybe (BLAS.Matrix Double)) numericalMatrixParser commentChar = do _ <- many' commentLineParser numLines <- many1 numLineParser if (length . nub $ [length (numLines !! i) | i <- [0 .. length numLines - 1]]) /= 1 then return Nothing else return $ Just $ ((length numLines) >< (length . head $ numLines)) (concat numLines) where commentLineParser = do skipSpace _ <- satisfy (`elem` commentChar) commentLine <- manyTill anyChar endOfLine return commentLine numLineParser = do _ <- many' (char ' ' <|> char '\t') numLine <- many1 $ do n <- double _ <- many' (satisfy (`elem` ";, \t")) return n endOfLine return numLine
sheepforce/Haskell_Data.Chemistry
src/modules/Data/Chemistry/Parser.hs
gpl-3.0
19,530
0
25
7,880
3,525
1,756
1,769
-1
-1
module Model.Light where import Model.Object import Model.Types data PointLight = PointLight { plPosition :: Translation , plStrength :: GLfloat , plColor :: ColorRGB , plrelativeTo :: Maybe Object }
halvorgb/AO2D
src/Model/Light.hs
gpl-3.0
295
0
9
124
52
32
20
8
0
{-# LANGUAGE TemplateHaskell #-} module Tic.LocationSelectionResult where import ClassyPrelude import Control.Lens (makePrisms) import Tic.GeoCoord data LocationSelectionResult a = LocationClicked (GeoCoord a) | LocationTimedOut deriving(Show) $(makePrisms ''LocationSelectionResult)
pmiddend/tic
lib/Tic/LocationSelectionResult.hs
gpl-3.0
380
0
8
122
63
36
27
9
0
module Main where import Test.Tasty (TestTree, testGroup, defaultMain) import Test.Tasty.HUnit (testCase, assertBool, (@?=)) import Control.Monad(when) import Data.Functor.Foldable (Fix(..), Recursive(..), Corecursive(..)) import Data.Maybe(fromMaybe) import Data.Monoid ((<>)) import MLSB parsesM' :: (Monad m, Eq x, Show x) => (String -> Either ParserError x) -> String -> String -> (x -> m Bool) -> m () parsesM' p msg s mchk = let err details = fail $ "Failed to parse '" <> s <> "': " <> details <> ". " <> msg in case p s of Right e -> do ok <- mchk e when (not ok) $ err $ "Unexpected: " <> show e Left (ParserError report) -> err report parses' :: (Monad m, Eq x, Show x) => (String -> Either ParserError x) -> String -> String -> (x -> Bool) -> m () parses' p msg s1 f = parsesM' p msg s1 (return . f) parsesSame' :: (Monad m, Eq x, Show x) => (String -> Either ParserError x) -> String -> String -> m () parsesSame' p s1 s2 = parsesM' p "" s1 (\x1 -> do parsesM' p "" s2 (\x2 -> do return (x1 == x2)) return True) parsesExpr :: (Monad m) => String -> m () parsesExpr s = parses' parseExpr "Expected any Right-result" s (const True) parsesExprAs :: (Monad m) => String -> Expr -> m () parsesExprAs s ans = parses' parseExpr ("Expected: (" <> show ans <> ") expr") s (==ans) parsesType :: (Monad m) => String -> m () parsesType s = parses' parseType "Expected any Right-result" s (const True) parsesTypeAs :: (Monad m) => String -> (Type,Shape) -> m () parsesTypeAs s ans = parses' parseType ("Expected: (" <> show ans <> ") type") s (==ans) parsesShape :: (Monad m) => String -> m () parsesShape s = parses' parseShape "Expected any Right-result" s (const True) parsesShapeAs :: (Monad m) => String -> Shape -> m () parsesShapeAs s ans = parses' parseShape ("Expected: (" <> show ans <> ") type") s (==ans) parsesExprSame :: (Monad m) => String -> String -> m () parsesExprSame s1 s2 = parsesSame' parseExpr s1 s2 parsesTypeSame :: (Monad m) => String -> String -> m () parsesTypeSame s1 s2 = parsesSame' parseType s1 s2 closeVal :: Val -> Val -> Bool closeVal = eqVal (1e-5) evals :: (Monad m) => String -> Const -> m () evals s ans = case parseExpr s of Right e -> let res = evalExpr initEnv e in case (ValC ans) `closeVal` res of True -> return () False -> fail $ "Mismatching resutls: expected "<>show ans<>", got: "<> printVal res Left report -> fail $ show report main :: IO () main = defaultMain $ testGroup "All" [ testCase "Tokenize" $ do tokenize "asdas<>111+8" @?= [Cd "asdas",Cd "<>",Cd "111",Cd "+",Cd "8"] tokenize "x (=<>=) y" @?= [Cd "x", Ws " ", Cd"(",Cd "=<>=",Cd ")",Ws " ", Cd "y"] tokenize "x==y" @?= [Cd "x",Cd "==",Cd "y"] tokenize "x;23+(zzz)" @?= [Cd "x",Cd ";",Cd "23",Cd "+",Cd "(",Cd "zzz",Cd ")"] , testCase "Parse shapes" $ do parsesShapeAs "" (STail) parsesShapeAs " [ ]" (STail) parsesShapeAs " [ 10 ]" (SConsC 10 STail) parsesShapeAs " [ 10, 20 , 30 ,40 ]" (SConsC 10 (SConsC 20 (SConsC 30 (SConsC 40 STail)))) , testCase "Parse types" $ do let tc x = TConst x parsesTypeAs " a" (tc "a", STail) parsesTypeAs "a b" (TApp (tc "a") (tc "b"), STail) parsesTypeAs " a -> b" (TApp (TApp (TIdent "->") (tc "a")) (tc "b"), STail) parsesTypeAs " ( a ) -> b" (TApp (TApp (TIdent "->") (tc "a")) (tc "b"), STail) parsesTypeAs "a -> b -> c" (TApp (TApp (TIdent "->") (tc "a")) (TApp (TApp (TIdent "->") (tc "b")) (tc "c")), STail) parsesTypeSame "a -> b -> c" "a -> (b -> c)" parsesTypeAs " a [ 3 , 2 ]" (TConst "a", SConsC 3 (SConsC 2 STail)) parsesTypeAs " a[ 3 , x ]" (TConst "a", SConsC 3 (SConsI "x" STail)) , testCase "Parse unlabeled expression" $ do parsesExprAs " a " (Ident "a") parsesExprAs "a b" (App (Ident "a") (Ident "b")) parsesExprAs "let x = y ; in z" (Let (Pat "x") (Ident "y") (Ident "z")) parsesExprAs "let x = y . f ; in z" (Let (Pat "x") (Lam (Pat "y") (Ident "f")) (Ident "z")) parsesExprAs "let x = a . b . c; in z" (Let (Pat "x") (Lam (Pat "a") (Lam (Pat "b") (Ident "c"))) (Ident "z")) parsesExprAs "let x = a . b . (c d); in z" (Let (Pat "x") (Lam (Pat "a") (Lam (Pat "b") (App (Ident "c") (Ident "d")))) (Ident "z")) parsesExprAs "10" (Const (ConstR (10))) parsesExprAs "10 + 20" (App (App (Ident "+") (Const (ConstR (10)))) (Const (ConstR (20)))) parsesExprAs "x . x + x" (Lam (Pat "x") (App (App (Ident "+") (Ident "x")) (Ident "x"))) parsesExprAs "let x = y ; in y + z" (Let (Pat "x") (Ident "y") (App (App (Ident "+") (Ident "y")) (Ident "z"))) parsesExprAs "a b + c" (App (Ident "a") (App (App (Ident "+") (Ident "b")) (Ident "c"))) parsesExprAs "a [b + c, 10]" (Slice (Ident "a") [App (App (Ident "+") (Ident "b")) (Ident "c"),Const (ConstR (10))]) parsesExprAs "x + y[10]" (App (App (Ident "+") (Ident "x")) (Slice (Ident "y") [Const (ConstR (10))])) parsesExprAs "x y[10]" (App (Ident "x") (Slice (Ident "y") [Const (ConstR (10))])) , testCase "Parse labeled expression" $ do {- FIXME: check type label correctness -} parsesExprAs "let x : int = y ; in z" (Let (Pat "x") (Ident "y") (Ident "z")) , testCase "Eval" $ do evals "33" (ConstR 33) evals "10 + 20" (ConstR 30) evals "10 + (let x = 20 ;in x)" (ConstR 30) evals "10 + 20 * 2" (ConstR 50) evals "(10 + 20) * 2" (ConstR 60) evals "let f = x . (x + x); in (f 2)" (ConstR 4) return () ]
grwlf/ml-df
test/Main.hs
gpl-3.0
5,721
0
21
1,494
2,575
1,269
1,306
115
3
import System.IO import System.Directory import Data.List import System.Environment import Data.Time import Data.Maybe import Utils type Note = String getNotefilePath :: IO (String) getNotefilePath = getEnv "NOTE_FILE" main :: IO () main = do args <- getArgs runWith args where runWith :: [String] -> IO () runWith [] = helpMode [] runWith args@(('-':cmd:_):_) | cmd == 'w' = writeMode args | cmd == 'p' = pipeMode args | cmd == 'r' = readMode args | cmd == 'f' = findMode args | otherwise = helpMode args runWith args = writeMode args writeMode :: [String] -> IO () writeMode (('-':_):nonCommandArgs) = writeMode nonCommandArgs writeMode args = do notefilePath <- getNotefilePath time <- getZonedTime let note = makeNote args time appendFile notefilePath note putStr note pipeMode :: [String] -> IO () pipeMode (('-':_):nonCommandArgs) = pipeMode nonCommandArgs pipeMode args = do notefilePath <- getNotefilePath time <- getZonedTime contents <- getContents let note = makeNote args time let formattedContents = "\t+---\n" ++ (unlines $ map ("\t| " ++) $ lines contents) ++ "\t+---\n" let noteAndContents = note ++ formattedContents appendFile notefilePath noteAndContents putStr noteAndContents findMode :: [String] -> IO () findMode ((_:_:subcommands):params) = do notes <- getNotes let findPattern = head params putStr . concat . filterAction findPattern $ notes where filterAction | elem 'm' subcommands = filterByMessage | otherwise = filterBySubject filterBySubject :: String -> [Note] -> [Note] filterBySubject patt = filter ((isInfixOf patt) . getSubjectFromNote) filterByMessage :: String -> [Note] -> [Note] filterByMessage patt = filter ((isInfixOf patt) . getMessageFromNote) getSubjectFromNote :: Note -> String getSubjectFromNote = snd . splitOnFirst ' ' . fst . splitOnFirst ':' . snd . splitOnFirst ':' getMessageFromNote :: Note -> String getMessageFromNote = tail . snd . splitOnNth 2 ':' readMode :: [String] -> IO () readMode args@((_:_:n):params) = do let numNotes = tryParseInt n 1 notes <- getNotes if numNotes < 0 then putStr $ concat $ take (-numNotes) notes else putStr $ concat $ takeLast numNotes notes getNotes :: IO ([Note]) getNotes = do notefilePath <- getNotefilePath handle <- openFile notefilePath ReadMode contents <- hGetContents handle return $ parseNotes contents parseNotes :: String -> [Note] parseNotes contents = nonEmptyNotes where nonEmptyNotes = filter (/= "") notes notes = map unlines linesByNote linesByNote = splitInclusiveWhen (not . isPrefixOf "\t") $ lines contents helpMode :: [String] -> IO () helpMode _ = putStrLn "Help message" -- todo make useful makeNote :: [String] -> ZonedTime -> Note makeNote [] time = (makeTimestamp time) ++ " MISC: \n" makeNote (subject:msgParts) time = indentedNote where subject' = filter (/= ':') subject msg = intercalate " " msgParts note = (makeTimestamp time) ++ " " ++ subject' ++ ": " ++ msg ++ "\n" noteLines = lines note indentedNote = unlines $ head noteLines : (map ('\t':) $ tail noteLines) makeTimestamp :: ZonedTime -> String makeTimestamp time = formatTime defaultTimeLocale "%F %R" time
apvanzanten/learningMeAHaskell
note.hs
gpl-3.0
3,294
0
16
676
1,187
590
597
88
3
module DL3048 (tests) where import Helpers import Test.Hspec tests :: SpecWith () tests = do let ?rulesConfig = mempty describe "DL3048 - Invalid Label Key Rule" $ do it "not ok with reserved namespace" $ do ruleCatches "DL3048" "LABEL com.docker.label=\"foo\"" ruleCatches "DL3048" "LABEL io.docker.label=\"foo\"" ruleCatches "DL3048" "LABEL org.dockerproject.label=\"foo\"" onBuildRuleCatches "DL3048" "LABEL com.docker.label=\"foo\"" onBuildRuleCatches "DL3048" "LABEL io.docker.label=\"foo\"" onBuildRuleCatches "DL3048" "LABEL org.dockerproject.label=\"foo\"" it "not ok with invalid character" $ do ruleCatches "DL3048" "LABEL invalid$character=\"foo\"" onBuildRuleCatches "DL3048" "LABEL invalid$character=\"foo\"" it "not ok with invalid start and end characters" $ do ruleCatches "DL3048" "LABEL .invalid =\"foo\"" ruleCatches "DL3048" "LABEL -invalid =\"foo\"" ruleCatches "DL3048" "LABEL 1invalid =\"foo\"" onBuildRuleCatches "DL3048" "LABEL .invalid=\"foo\"" onBuildRuleCatches "DL3048" "LABEL -invalid=\"foo\"" onBuildRuleCatches "DL3048" "LABEL 1invalid=\"foo\"" it "not ok with consecutive dividers" $ do ruleCatches "DL3048" "LABEL invalid..character=\"foo\"" ruleCatches "DL3048" "LABEL invalid--character=\"foo\"" onBuildRuleCatches "DL3048" "LABEL invalid..character=\"foo\"" onBuildRuleCatches "DL3048" "LABEL invalid--character=\"foo\"" it "ok with valid labels" $ do ruleCatchesNot "DL3048" "LABEL org.valid-key.label3=\"foo\"" ruleCatchesNot "DL3048" "LABEL validlabel=\"foo\"" onBuildRuleCatchesNot "DL3048" "LABEL org.valid-key.label3=\"foo\"" onBuildRuleCatchesNot "DL3048" "LABEL validlabel=\"foo\""
lukasmartinelli/hadolint
test/DL3048.hs
gpl-3.0
1,786
0
13
320
277
113
164
-1
-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.Run.Namespaces.Services.ReplaceService -- 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) -- -- Replace a service. Only the spec and metadata labels and annotations are -- modifiable. After the Update request, Cloud Run will work to make the -- \'status\' match the requested \'spec\'. May provide -- metadata.resourceVersion to enforce update from last read for optimistic -- concurrency control. -- -- /See:/ <https://cloud.google.com/run/ Cloud Run Admin API Reference> for @run.namespaces.services.replaceService@. module Network.Google.Resource.Run.Namespaces.Services.ReplaceService ( -- * REST Resource NamespacesServicesReplaceServiceResource -- * Creating a Request , namespacesServicesReplaceService , NamespacesServicesReplaceService -- * Request Lenses , nsrsXgafv , nsrsUploadProtocol , nsrsAccessToken , nsrsUploadType , nsrsPayload , nsrsName , nsrsDryRun , nsrsCallback ) where import Network.Google.Prelude import Network.Google.Run.Types -- | A resource alias for @run.namespaces.services.replaceService@ method which the -- 'NamespacesServicesReplaceService' request conforms to. type NamespacesServicesReplaceServiceResource = "apis" :> "serving.knative.dev" :> "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "dryRun" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Service :> Put '[JSON] Service -- | Replace a service. Only the spec and metadata labels and annotations are -- modifiable. After the Update request, Cloud Run will work to make the -- \'status\' match the requested \'spec\'. May provide -- metadata.resourceVersion to enforce update from last read for optimistic -- concurrency control. -- -- /See:/ 'namespacesServicesReplaceService' smart constructor. data NamespacesServicesReplaceService = NamespacesServicesReplaceService' { _nsrsXgafv :: !(Maybe Xgafv) , _nsrsUploadProtocol :: !(Maybe Text) , _nsrsAccessToken :: !(Maybe Text) , _nsrsUploadType :: !(Maybe Text) , _nsrsPayload :: !Service , _nsrsName :: !Text , _nsrsDryRun :: !(Maybe Text) , _nsrsCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NamespacesServicesReplaceService' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nsrsXgafv' -- -- * 'nsrsUploadProtocol' -- -- * 'nsrsAccessToken' -- -- * 'nsrsUploadType' -- -- * 'nsrsPayload' -- -- * 'nsrsName' -- -- * 'nsrsDryRun' -- -- * 'nsrsCallback' namespacesServicesReplaceService :: Service -- ^ 'nsrsPayload' -> Text -- ^ 'nsrsName' -> NamespacesServicesReplaceService namespacesServicesReplaceService pNsrsPayload_ pNsrsName_ = NamespacesServicesReplaceService' { _nsrsXgafv = Nothing , _nsrsUploadProtocol = Nothing , _nsrsAccessToken = Nothing , _nsrsUploadType = Nothing , _nsrsPayload = pNsrsPayload_ , _nsrsName = pNsrsName_ , _nsrsDryRun = Nothing , _nsrsCallback = Nothing } -- | V1 error format. nsrsXgafv :: Lens' NamespacesServicesReplaceService (Maybe Xgafv) nsrsXgafv = lens _nsrsXgafv (\ s a -> s{_nsrsXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). nsrsUploadProtocol :: Lens' NamespacesServicesReplaceService (Maybe Text) nsrsUploadProtocol = lens _nsrsUploadProtocol (\ s a -> s{_nsrsUploadProtocol = a}) -- | OAuth access token. nsrsAccessToken :: Lens' NamespacesServicesReplaceService (Maybe Text) nsrsAccessToken = lens _nsrsAccessToken (\ s a -> s{_nsrsAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). nsrsUploadType :: Lens' NamespacesServicesReplaceService (Maybe Text) nsrsUploadType = lens _nsrsUploadType (\ s a -> s{_nsrsUploadType = a}) -- | Multipart request metadata. nsrsPayload :: Lens' NamespacesServicesReplaceService Service nsrsPayload = lens _nsrsPayload (\ s a -> s{_nsrsPayload = a}) -- | The name of the service being replaced. For Cloud Run (fully managed), -- replace {namespace_id} with the project ID or number. nsrsName :: Lens' NamespacesServicesReplaceService Text nsrsName = lens _nsrsName (\ s a -> s{_nsrsName = a}) -- | Indicates that the server should validate the request and populate -- default values without persisting the request. Supported values: \`all\` nsrsDryRun :: Lens' NamespacesServicesReplaceService (Maybe Text) nsrsDryRun = lens _nsrsDryRun (\ s a -> s{_nsrsDryRun = a}) -- | JSONP nsrsCallback :: Lens' NamespacesServicesReplaceService (Maybe Text) nsrsCallback = lens _nsrsCallback (\ s a -> s{_nsrsCallback = a}) instance GoogleRequest NamespacesServicesReplaceService where type Rs NamespacesServicesReplaceService = Service type Scopes NamespacesServicesReplaceService = '["https://www.googleapis.com/auth/cloud-platform"] requestClient NamespacesServicesReplaceService'{..} = go _nsrsName _nsrsXgafv _nsrsUploadProtocol _nsrsAccessToken _nsrsUploadType _nsrsDryRun _nsrsCallback (Just AltJSON) _nsrsPayload runService where go = buildClient (Proxy :: Proxy NamespacesServicesReplaceServiceResource) mempty
brendanhay/gogol
gogol-run/gen/Network/Google/Resource/Run/Namespaces/Services/ReplaceService.hs
mpl-2.0
6,448
0
19
1,434
873
511
362
126
1
{-# LANGUAGE TypeFamilies, OverloadedStrings #-} module Model.Token.Types ( Token(..) , AccountToken(..) , LoginToken(..) , Session(..) , Upload(..) , makeUpload ) where import qualified Data.ByteString as BS import Data.Int (Int64) import Has (Has(..)) import Model.Kind import Model.Time import Model.Id.Types import Model.Party.Types import Model.Permission.Types type instance IdType Token = BS.ByteString data Token = Token { tokenId :: Id Token , tokenExpires :: Timestamp } instance Has (Id Token) Token where view = tokenId data AccountToken = AccountToken { accountToken :: !Token , tokenAccount :: SiteAuth } instance Has (Id Token) AccountToken where view = view . accountToken instance Has SiteAuth AccountToken where view = tokenAccount instance Has Access AccountToken where view = view . tokenAccount instance Has (Id Party) AccountToken where view = view . tokenAccount instance Has Account AccountToken where view = view . tokenAccount data LoginToken = LoginToken { loginAccountToken :: !AccountToken , loginPasswordToken :: Bool } -- these are signed version of Id Token type instance IdType LoginToken = BS.ByteString instance Kinded LoginToken where kindOf _ = "token" instance Has (Id Token) LoginToken where view = view . loginAccountToken instance Has SiteAuth LoginToken where view = view . loginAccountToken data Session = Session { sessionAccountToken :: !AccountToken , sessionVerf :: !BS.ByteString , sessionSuperuser :: Bool } instance Has (Id Token) Session where view = view . sessionAccountToken instance Has Access Session where view = view . sessionAccountToken instance Has (Id Party) Session where view = view . sessionAccountToken instance Has Account Session where view = view . sessionAccountToken data Upload = Upload { uploadAccountToken :: AccountToken , uploadFilename :: BS.ByteString , uploadSize :: Int64 } instance Has (Id Token) Upload where view = view . uploadAccountToken makeUpload :: Token -> BS.ByteString -> Int64 -> SiteAuth -> Upload makeUpload t n z u = Upload (AccountToken t u) n z
databrary/databrary
src/Model/Token/Types.hs
agpl-3.0
2,135
0
10
392
608
344
264
-1
-1
{-# OPTIONS_GHC -Wall -} {- - Module to parse .emod files - - - Copyright 2013 -- name removed for blind review, all rights reserved! Please push a git request to receive author's name! -- - 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. -} module EParser(parse,tbrfun,pGetEMOD,pGetLisp,pGetTerms,LispTree(..),TermBuilder (..) ,QueueAssignment(..),FlopAssignment(..),InputAssignment(..),OutputAssignment(..),Term(..) ,OutputWire(..),names,HasName(name),AssignmentOrWire(..)) where import LispParser (parse,pGetLisp,LispTree(..),LispPrimitive(..),SourcePos) import Terms(Term(..),(.+.)) import qualified Data.Set as Set (fromList, singleton) type EStructure = ([QueueAssignment],[FlopAssignment],[InputAssignment],[OutputAssignment],[OutputWire]) -- lisp terms without lambda functions, since we do not use lambda functions in E data LispTerm = LispTerm SourcePos String [LispTerm] | LispTermPrimitive SourcePos LispPrimitive deriving (Show) data GetTermError = GetTermError String SourcePos data QueueAssignment = QueueAssignment String -- | Queue name Int -- | Queue size Term -- | input-channel irdy [Term] -- | input-channel data Term -- | output-channel trdy deriving Show data FlopAssignment = FlopAssignment String -- | register name Term -- | register value deriving Show data InputAssignment = InputAssignment String -- | input name Term -- | trdy value deriving Show data OutputAssignment = OutputAssignment String -- | output name Term -- | irdy value [Term] -- | data value deriving Show data OutputWire = OutputWire String Term deriving Show data AssignmentOrWire = AssignQ QueueAssignment | AssignF FlopAssignment | AssignI InputAssignment | AssignO OutputAssignment | Wire OutputWire class HasName a where name :: a -> String instance HasName QueueAssignment where name (QueueAssignment n _ _ _ _) = n instance HasName FlopAssignment where name (FlopAssignment n _) = n instance HasName InputAssignment where name (InputAssignment n _) = n instance HasName OutputAssignment where name (OutputAssignment n _ _) = n instance HasName OutputWire where name (OutputWire n _) = n names :: (HasName a) => [a] -> [String] names = map name sortOutAssignments :: [AssignmentOrWire] -> ([QueueAssignment],[FlopAssignment],[InputAssignment],[OutputAssignment],[OutputWire]) sortOutAssignments xs = ([a|AssignQ a<-xs],[a|AssignF a<-xs],[a|AssignI a<-xs],[a|AssignO a<-xs],[a|Wire a<-xs]) data TermBuilder a b = TBError a | TB b Int -- .. and warnings? data TBR a b = TBR{tbrfun::(Int -> TermBuilder a b)} instance Monad (TBR a) where return b = TBR (TB b) (>>=) (TBR f1) f2 = TBR (\x -> case f1 x of {TBError a -> TBError a; TB b y -> (tbrfun (f2 b)) y}) instance Show GetTermError where show (GetTermError s p) = s ++ "\n on "++ (show p) getTermPos :: LispTerm -> SourcePos getTermPos (LispTerm p _ _) = p getTermPos (LispTermPrimitive p _) = p firstLeft :: [TBR a' a] -> TBR a' [a] firstLeft [] = return [] firstLeft (r:rs) = r >>= (\x -> tbrDo ((:) x) (firstLeft rs)) tbrDo :: (b1 -> b) -> TBR a b1 -> TBR a b tbrDo f arg = TBR (\y -> case (tbrfun arg) y of {TBError a -> TBError a;TB b i -> TB (f b) i}) firstLeftMap :: (a1 -> TBR a b) -> [a1] -> TBR a [b] firstLeftMap f xs = firstLeft (map f xs) pGetTerms :: [LispTree] -> TBR GetTermError [LispTerm] pGetTerms xs = firstLeftMap pGetTerm xs -- data LispTree = LispCons SourcePos LispTree LispTree | LispTreePrimitive SourcePos LispPrimitive deriving (Show) -- the TBR monoid takes failures on the left and return values on the right pGetTerm :: LispTree -> TBR GetTermError LispTerm pGetTerm (LispCons p a b) = do { h <- pGetSymbol a ; t' <- pGetList b ; t <- firstLeft (map pGetTerm t') ; return (LispTerm p h t) } pGetTerm (LispTreePrimitive p p') = return (LispTermPrimitive p p') pGetCons :: LispTree -> TBR GetTermError (LispTree, LispTree) pGetCons (LispCons _ a b) = return (a,b) pGetCons (LispTreePrimitive p _) = makeError p "Expecting CONS" pGetList :: LispTree -> TBR GetTermError [LispTree] pGetList (LispCons _ a b) = do {b' <-pGetList b;return$ a:b'} pGetList (LispTreePrimitive _ (LispSymbol "NIL")) = return [] pGetList (LispTreePrimitive p _) = makeError p "Expecting end of list marker NIL (perhaps you should omit the . ?)" pGetAList :: LispTree -> TBR GetTermError [(String,LispTerm)] pGetAList x = pGetList x >>= firstLeftMap pGetAssignment pGetEMOD :: LispTree -> TBR GetTermError ([QueueAssignment],[FlopAssignment],[InputAssignment],[OutputAssignment],[OutputWire]) pGetEMOD x = do { alist <- pGetAList x ; assignments <- firstLeftMap getAssignment alist ; return (sortOutAssignments assignments) } repeatN :: Int -> (TBR GetTermError a) -> (TBR GetTermError [a]) repeatN n f = if n<=0 then return [] else do{v<-f;r<-repeatN (n-1) f;return (v:r)} getAssignment :: (String,LispTerm) -> TBR GetTermError AssignmentOrWire getAssignment (name,LispTerm p "FLOP" lts) = case lts of { (clk : LispTermPrimitive _ (LispSymbol name') : val : []) -> do{ trm <- getTerm val ; _ <- getClk clk ; _ <- (if name/=name' then makeError p ("the name in the flop should be itself: "++name++" /= "++name') else return ()) ; return$ AssignF (FlopAssignment name trm) } ; _ -> makeError p "FLOP should have the arguments: |clk| name value, where name must be a symbol." } getAssignment (name,LispTerm p "GET-QUEUE-STATE" lts) = case lts of { (LispTermPrimitive _ (LispInt size) : LispTermPrimitive _ (LispInt dsize) : irdy : d : trdy : []) -> do{ irdy' <- getTerm irdy ; d' <- getData d ; trdy' <- getTerm trdy ; unknowns <- (repeatN (dsize - length d') (getTerm (LispTerm p "X" []))) ; return$ AssignQ (QueueAssignment name size irdy' (d'++unknowns) trdy') } ; _ -> makeError p "QUEUE should have the arguments: size data-size irdy data trdy, where size and data-size are integers"} getAssignment (name,LispTerm p "GET-SOURCE-STATE" lts) = case lts of { (trdy : []) -> do{ trdy' <- getTerm trdy ; return$ AssignI (InputAssignment name trdy') } ; _ -> makeError p "SOURCE should have one argument: trdy"} getAssignment (name,LispTerm p "GET-SINK-STATE" lts) = case lts of { (irdy : d : []) -> do{ d' <- getData d ; irdy' <- getTerm irdy ; return$ AssignO (OutputAssignment name irdy' d') } ; _ -> makeError p "SINK should have two argument: irdy data"} getAssignment (name,LispTerm p "OUTPUT" lts) = case lts of { (irdy : []) -> do{ irdy' <- getTerm irdy ; return$ Wire (OutputWire name irdy') } ; _ -> makeError p "OUTPUT should have one argument: the term it represents"} getAssignment (name,t) = makeError (getTermPos t) ("Not a valid assignment for "++name++",\n should be either FLOP, OUTPUT or GET-*-STATE where * = SINK, SOURCE or QUEUE") getData :: LispTerm -> TBR GetTermError [Term] getData (LispTerm _ "LIST" lst) = firstLeftMap getTerm lst getData (LispTerm _ "X" []) = return [] -- cheat a little by putting X this way getData t = makeError (getTermPos t) ("Not a valid list, lists should start with the function symbol LIST") getTerm :: LispTerm -> TBR GetTermError Term getTerm (LispTerm p "AND" lst) = do {(a,b)<-get2 p "arguments for AND" lst;a'<-getTerm a;b'<-getTerm b;return (T_AND a' b')} getTerm (LispTerm p "OR" lst) = do {(a,b)<-get2 p "arguments for OR" lst;a'<-getTerm a;b'<-getTerm b;return (T_OR a' b')} getTerm (LispTerm p "NOT" lst) = do {a<-get1 p "argument for NOT" lst;a'<-getTerm a;return (T_NOT a')} getTerm (LispTerm p "XOR" lst) = do {(a,b)<-get2 p "arguments for OR" lst;a'<-getTerm a;b'<-getTerm b;return (T_XOR a' b')} getTerm (LispTerm p "FLOPVAL" lst) = do {(a,b)<-get2 p "arguments for FLOPVAL" lst;_<-getClk a;b'<-getSymbol b;return (T_FLOPV b')} getTerm (LispTerm p "VALUE" lst) = case lst of { (LispTermPrimitive _ (LispSymbol "O.IRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_QIRDY s ; (LispTermPrimitive _ (LispSymbol "I.TRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_QTRDY s ; (LispTermPrimitive _ (LispSymbol "O.DATA") : LispTermPrimitive _ (LispInt i) : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_QDATA s i ; (LispTermPrimitive _ (LispSymbol "S.IRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_IIRDY s ; (LispTermPrimitive _ (LispSymbol "S.TRDY") : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_OTRDY s ; (LispTermPrimitive _ (LispSymbol "S.DATA") : LispTermPrimitive _ (LispInt i) : LispTermPrimitive _ (LispSymbol s) : []) -> return$ T_IDATA s i ; _ -> makeError p "VALUE should either get O.IRDY, I.TRDY or O.DATA with a queue-name (or an integer + queue name for O.DATA), or S.* similarly" } getTerm (LispTerm p "X" lst) = do {_<-get0 p "arguments for X" lst;increment (\x -> T_UNKNOWN x)} getTerm (LispTerm p "F" lst) = do {_<-get0 p "arguments for F" lst;return (T_VALUE False)} getTerm (LispTerm p "T" lst) = do {_<-get0 p "arguments for T" lst;return (T_VALUE True)} getTerm (LispTermPrimitive p p') = do {_<-getRst p p';return T_RESET} getTerm (LispTerm p "INPUT" lst) = do {a<-get1 p "argument for INPUT" lst;a'<-getSymbol a;return (T_INPUT a')} getTerm (LispTerm p s _) = makeError p ("unexpected function symbol: "++s++"\n Recognised function symbols are: AND, OR, NOT, XOR, FLOPVAL, INPUT and VALUE") -- like return, only allows for an integer too increment :: (Int -> b) -> TBR a b increment f = (TBR (\x -> TB (f x) (x + 1))) getRst :: SourcePos -> LispPrimitive -> TBR GetTermError () getRst _ (LispSymbol "rst") = return () getRst p _ = makeError p "the only free symbol allowed is the reset: |rst|" getClk :: LispTerm -> TBR GetTermError () getClk (LispTermPrimitive _ (LispSymbol "clk")) = return () getClk t = makeError (getTermPos t) "expecting clock symbol |clk|" get2 :: SourcePos -> [Char] -> [t] -> TBR GetTermError (t, t) get2 _ _ (a:b:[]) = return (a,b) get2 p s _ = makeError p ("Expecting two "++s) get1 :: SourcePos -> [Char] -> [a] -> TBR GetTermError a get1 _ _ (a:[]) = return a get1 p s _ = makeError p ("Expecting one "++s) get0 :: SourcePos -> [Char] -> [a] -> TBR GetTermError () get0 _ _ [] = return () get0 p s _ = makeError p ("Expecting no "++s) (<?>) :: TBR GetTermError b -> String -> TBR GetTermError b (<?>) tbr msg = TBR (\x -> case (tbrfun tbr) x of {TBError (GetTermError _ p) -> makeError' msg p;v -> v}) pGetAssignment :: LispTree -> TBR GetTermError (String,LispTerm) pGetAssignment x = do { (a,b) <- (pGetCons x <?> "Expecting assignment") ; s <- pGetSymbol a <?> "Assignment requires its first item to be a symbol" ; t <- pGetTerm b ; return (s,t) } makeError :: SourcePos -> String -> TBR GetTermError b makeError pos str = TBR (\_ -> makeError' str pos) makeError' :: String -> SourcePos -> TermBuilder GetTermError b makeError' str pos = TBError (GetTermError str pos) getSymbol :: LispTerm -> TBR GetTermError String getSymbol (LispTermPrimitive _ (LispSymbol p)) = return$ p getSymbol (LispTermPrimitive p _) = makeError p "Expecting primitive of Symbol type, consider putting ||'s around the primitive" getSymbol (LispTerm p _ _) = makeError p "Expecting primitive of Symbol type, got a Cons" pGetSymbol :: LispTree -> TBR GetTermError String pGetSymbol (LispTreePrimitive _ (LispSymbol p)) = return$ p pGetSymbol (LispTreePrimitive p _) = makeError p "Expecting primitive of Symbol type, consider putting ||'s around the primitive" pGetSymbol (LispCons p _ _) = makeError p "Expecting primitive of Symbol type, got a Cons"
DatePaper616/code
EParser.hs
apache-2.0
13,249
53
17
3,377
4,468
2,308
2,160
-1
-1
-- | Schedule program for execution. At the moment it schedule for -- exact number of threads module DNA.Compiler.Scheduler where import Control.Monad import Data.Graph.Inductive.Graph import qualified Data.IntMap as IntMap import Data.IntMap ((!)) import DNA.AST import DNA.Actor import DNA.Compiler.Types ---------------------------------------------------------------- -- Simple scheduler ---------------------------------------------------------------- -- | Number of nodes in the cluster type CAD = Int -- | Simple scheduler. It assumes that all optimization passes are -- done and will not try to transform graph. schedule :: CAD -> DataflowGraph -> Compile DataflowGraph schedule nTotal gr = do let nMust = nMandatory gr nVar = nVarGroups gr nFree = nTotal - nMust - nVar -- We need at least 1 node per group when (nFree < 0) $ compError ["Not enough nodes to schedule algorithm"] -- Schedule for mandatory nodes. For each node we let mandSched = IntMap.fromList $ mandatoryNodes gr `zip` [0..] -- Now we should schedule remaining nodes. let varGroups = contiguosChunks nMust (splitChunks nVar (nTotal - nMust)) varSched = IntMap.fromList $ variableNodes gr `zip` varGroups -- Build schedule for every let sched i (ANode _ a@(RealActor _ act)) = case act of StateM{} -> ANode (Single n) a Producer{} -> ANode (Single n) a ScatterGather{} -> ANode (MasterSlaves n (varSched ! i)) a where n = mandSched ! i return $ gmap (\(a1, i, a, a2) -> (a1, i, sched i a, a2)) gr -- | Total number of processes that we must spawn. nMandatory :: DataflowGraph -> Int nMandatory gr = sum [ getN $ lab' $ context gr n | n <- nodes gr] where getN (ANode _ _) = 1 -- | List of all actors for which we must allocate separate cluster node. mandatoryNodes :: DataflowGraph -> [Node] mandatoryNodes gr = [ n | n <- nodes gr] variableNodes :: DataflowGraph -> [Node] variableNodes gr = [ n | n <- nodes gr , isSG (lab' $ context gr n) ] where isSG (ANode _ (RealActor _ (ScatterGather{}))) = True isSG _ = False -- | Number of groups for which we can vary number of allocated nodes nVarGroups :: DataflowGraph -> Int nVarGroups gr = sum [ get $ lab' $ context gr n | n <- nodes gr] where get (ANode _ (RealActor _ (ScatterGather{}))) = 1 get _ = 0 -- Split N items to k groups. splitChunks :: Int -> Int -> [Int] splitChunks nChunks nTot = map (+1) toIncr ++ rest where (chunk,n) = nTot `divMod` nChunks (toIncr,rest) = splitAt n (replicate nChunks chunk) contiguosChunks :: Int -> [Int] -> [[Int]] contiguosChunks off = go [off ..] where go _ [] = [] go xs (n:ns) = case splitAt n xs of (a,rest) -> a : go rest ns
SKA-ScienceDataProcessor/RC
MS1/dna/DNA/Compiler/Scheduler.hs
apache-2.0
2,911
0
17
764
869
464
405
54
3
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} ---------------------------------------------------------------------------- -- | -- Module : Web.Skroutz.Model.Base.SkuReview -- Copyright : (c) 2016 Remous-Aris Koutsiamanis -- License : Apache License 2.0 -- Maintainer : Remous-Aris Koutsiamanis <[email protected]> -- Stability : alpha -- Portability : non-portable -- -- Provides the 'SkuReview' type, a user review of an 'Web.Skroutz.Model.Base.Sku.Sku'. ---------------------------------------------------------------------------- module Web.Skroutz.Model.Base.SkuReview where import Control.DeepSeq (NFData) import Data.Data (Data, Typeable) import Data.Text (Text) import GHC.Generics (Generic) import Web.Skroutz.Model.Base.ISO8601Time import Web.Skroutz.TH data SkuReview = SkuReview { _skuReviewId :: Int , _skuReviewUserId :: Int , _skuReviewReview :: Text , _skuReviewRating :: Int , _skuReviewCreatedAt :: ISO8601Time , _skuReviewDemoted :: Bool , _skuReviewVotesCount :: Int , _skuReviewHelpfulVotesCount :: Int } deriving (Eq, Ord, Typeable, Data, Generic, Show, NFData) makeLensesAndJSON ''SkuReview "_skuReview"
ariskou/skroutz-haskell-api
src/Web/Skroutz/Model/Base/SkuReview.hs
apache-2.0
1,492
0
8
410
179
115
64
22
0
----------------------------------------------------------------------------- -- -- Module : Graphics.UI.Hieroglyph.Cache -- Copyright : -- License : BSD3 -- -- Maintainer : J.R. Heard -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Graphics.UI.Hieroglyph.Cache where import qualified Data.Map as Map import qualified Data.IntMap as IntMap data Cache k a = Cache { store :: Map.Map k a, times :: IntMap.IntMap k, now :: Int, maxsize :: Int, size :: Int, decimation :: Int } empty mxsz dec = Cache Map.empty IntMap.empty 0 mxsz 0 dec get :: Ord k => k -> Cache k a -> (Cache k a,Maybe a) get key cache = (cache',value) where value = Map.lookup key (store cache) cache' = maybe (cache{ now = now cache + 1 }) (\_ -> cache{ now = now cache + 1, times = IntMap.insert (now cache) key (times cache) }) value put :: Ord k => k -> a -> Cache k a -> Cache k a put key value cache | size cache < maxsize cache && (not $ Map.member key (store cache)) = cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) , size = size cache + 1 } | size cache < maxsize cache = cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) } | size cache >= maxsize cache && (Map.member key (store cache)) = cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) } | size cache >= maxsize cache = cache{ now = now cache + 1, times = IntMap.insert (now cache) key times', store = Map.insert key value store', size = size cache - decimation cache } where times' = foldr IntMap.delete (times cache) lowtimes (lowtimes,lowtimekeys) = unzip . take (decimation cache) . IntMap.toAscList . times $ cache store' = foldr Map.delete (store cache) lowtimekeys put' :: Ord k => k -> a -> Cache k a -> ([a], Cache k a) put' key value cache | size cache < maxsize cache && (not $ Map.member key (store cache)) = ([],cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) , size = size cache + 1 }) | size cache < maxsize cache = ([],cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) }) | size cache >= maxsize cache && (Map.member key (store cache)) = ([],cache { now = now cache + 1, times = IntMap.insert (now cache) key (times cache), store = Map.insert key value (store cache) }) | size cache >= maxsize cache = (freed, cache{ now = now cache + 1, times = IntMap.insert (now cache) key times', store = Map.insert key value store', size = size cache - decimation cache }) where times' = foldr IntMap.delete (times cache) lowtimes (lowtimes,lowtimekeys) = unzip . take (decimation cache) . IntMap.toAscList . times $ cache store' = foldr Map.delete (store cache) lowtimekeys freed = map (store cache Map.!) lowtimekeys free :: Ord k => Cache k a -> ((k,a),Cache k a) free cache = ((minkey,minval),cache') where minkey = IntMap.findMin (times cache) minval = store cache Map.! minkey cache' = cache{ now = now cache + 1, times = IntMap.deleteMin (times cache), store = Map.delete minkey (store cache), size = (size cache) } member :: Ord k => k -> Cache k a -> Bool member key cache = Map.member key (store cache)
JeffHeard/Hieroglyph
Graphics/UI/Hieroglyph/Cache.hs
bsd-2-clause
3,561
0
14
767
1,568
816
752
35
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGradient.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGradient ( QqGradient(..) ,QqGradient_nf(..) ,coordinateMode ,setColorAt ,setCoordinateMode ,setSpread ,spread ,qGradient_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QGradient import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqGradient x1 where qGradient :: x1 -> IO (QGradient ()) instance QqGradient (()) where qGradient () = withQGradientResult $ qtc_QGradient foreign import ccall "qtc_QGradient" qtc_QGradient :: IO (Ptr (TQGradient ())) instance QqGradient ((QGradient t1)) where qGradient (x1) = withQGradientResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGradient1 cobj_x1 foreign import ccall "qtc_QGradient1" qtc_QGradient1 :: Ptr (TQGradient t1) -> IO (Ptr (TQGradient ())) class QqGradient_nf x1 where qGradient_nf :: x1 -> IO (QGradient ()) instance QqGradient_nf (()) where qGradient_nf () = withObjectRefResult $ qtc_QGradient instance QqGradient_nf ((QGradient t1)) where qGradient_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QGradient1 cobj_x1 coordinateMode :: QGradient a -> (()) -> IO (CoordinateMode) coordinateMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_coordinateMode cobj_x0 foreign import ccall "qtc_QGradient_coordinateMode" qtc_QGradient_coordinateMode :: Ptr (TQGradient a) -> IO CLong setColorAt :: QGradient a -> ((Double, QColor t2)) -> IO () setColorAt x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGradient_setColorAt cobj_x0 (toCDouble x1) cobj_x2 foreign import ccall "qtc_QGradient_setColorAt" qtc_QGradient_setColorAt :: Ptr (TQGradient a) -> CDouble -> Ptr (TQColor t2) -> IO () setCoordinateMode :: QGradient a -> ((CoordinateMode)) -> IO () setCoordinateMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_setCoordinateMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGradient_setCoordinateMode" qtc_QGradient_setCoordinateMode :: Ptr (TQGradient a) -> CLong -> IO () setSpread :: QGradient a -> ((Spread)) -> IO () setSpread x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_setSpread cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGradient_setSpread" qtc_QGradient_setSpread :: Ptr (TQGradient a) -> CLong -> IO () spread :: QGradient a -> (()) -> IO (Spread) spread x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_spread cobj_x0 foreign import ccall "qtc_QGradient_spread" qtc_QGradient_spread :: Ptr (TQGradient a) -> IO CLong instance Qqtype (QGradient a) (()) (IO (QGradientType)) where qtype x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_type cobj_x0 foreign import ccall "qtc_QGradient_type" qtc_QGradient_type :: Ptr (TQGradient a) -> IO CLong qGradient_delete :: QGradient a -> IO () qGradient_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QGradient_delete cobj_x0 foreign import ccall "qtc_QGradient_delete" qtc_QGradient_delete :: Ptr (TQGradient a) -> IO ()
keera-studios/hsQt
Qtc/Gui/QGradient.hs
bsd-2-clause
3,662
0
12
608
1,057
552
505
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QUdpSocket_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Network.QUdpSocket_h where import Qtc.Enums.Base import Qtc.Enums.Core.QIODevice import Qtc.Enums.Network.QAbstractSocket import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Network_h import Qtc.ClassTypes.Network import Foreign.Marshal.Array instance QunSetUserMethod (QUdpSocket ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QUdpSocket_unSetUserMethod" qtc_QUdpSocket_unSetUserMethod :: Ptr (TQUdpSocket a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QUdpSocketSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QUdpSocket ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QUdpSocketSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QUdpSocket ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QUdpSocketSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QUdpSocket_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QUdpSocket ()) (QUdpSocket x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setUserMethod" qtc_QUdpSocket_setUserMethod :: Ptr (TQUdpSocket a) -> CInt -> Ptr (Ptr (TQUdpSocket x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QUdpSocket :: (Ptr (TQUdpSocket x0) -> IO ()) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QUdpSocket_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QUdpSocketSc a) (QUdpSocket x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QUdpSocket ()) (QUdpSocket x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setUserMethodVariant" qtc_QUdpSocket_setUserMethodVariant :: Ptr (TQUdpSocket a) -> CInt -> Ptr (Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QUdpSocket :: (Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QUdpSocket_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QUdpSocketSc a) (QUdpSocket x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QUdpSocket setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QUdpSocket_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QUdpSocket_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QUdpSocket ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QUdpSocket_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QUdpSocket_unSetHandler" qtc_QUdpSocket_unSetHandler :: Ptr (TQUdpSocket a) -> CWString -> IO (CBool) instance QunSetHandler (QUdpSocketSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QUdpSocket_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler1" qtc_QUdpSocket_setHandler1 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket1 :: (Ptr (TQUdpSocket x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QatEnd_h (QUdpSocket ()) (()) where atEnd_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_atEnd cobj_x0 foreign import ccall "qtc_QUdpSocket_atEnd" qtc_QUdpSocket_atEnd :: Ptr (TQUdpSocket a) -> IO CBool instance QatEnd_h (QUdpSocketSc a) (()) where atEnd_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_atEnd cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CLLong) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCLLong rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler2" qtc_QUdpSocket_setHandler2 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> IO (CLLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket2 :: (Ptr (TQUdpSocket x0) -> IO (CLLong)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO (CLLong))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO (CLLong) setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCLLong rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QbytesAvailable_h (QUdpSocket ()) (()) where bytesAvailable_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesAvailable cobj_x0 foreign import ccall "qtc_QUdpSocket_bytesAvailable" qtc_QUdpSocket_bytesAvailable :: Ptr (TQUdpSocket a) -> IO CLLong instance QbytesAvailable_h (QUdpSocketSc a) (()) where bytesAvailable_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesAvailable cobj_x0 instance QbytesToWrite_h (QUdpSocket ()) (()) where bytesToWrite_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesToWrite cobj_x0 foreign import ccall "qtc_QUdpSocket_bytesToWrite" qtc_QUdpSocket_bytesToWrite :: Ptr (TQUdpSocket a) -> IO CLLong instance QbytesToWrite_h (QUdpSocketSc a) (()) where bytesToWrite_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_bytesToWrite cobj_x0 instance QcanReadLine_h (QUdpSocket ()) (()) where canReadLine_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_canReadLine cobj_x0 foreign import ccall "qtc_QUdpSocket_canReadLine" qtc_QUdpSocket_canReadLine :: Ptr (TQUdpSocket a) -> IO CBool instance QcanReadLine_h (QUdpSocketSc a) (()) where canReadLine_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_canReadLine cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler3" qtc_QUdpSocket_setHandler3 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket3 :: (Ptr (TQUdpSocket x0) -> IO ()) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> IO () setHandlerWrapper x0 = do x0obj <- qUdpSocketFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qclose_h (QUdpSocket ()) (()) where close_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_close cobj_x0 foreign import ccall "qtc_QUdpSocket_close" qtc_QUdpSocket_close :: Ptr (TQUdpSocket a) -> IO () instance Qclose_h (QUdpSocketSc a) (()) where close_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_close cobj_x0 instance QisSequential_h (QUdpSocket ()) (()) where isSequential_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_isSequential cobj_x0 foreign import ccall "qtc_QUdpSocket_isSequential" qtc_QUdpSocket_isSequential :: Ptr (TQUdpSocket a) -> IO CBool instance QisSequential_h (QUdpSocketSc a) (()) where isSequential_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_isSequential cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler4" qtc_QUdpSocket_setHandler4 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> CInt -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket4 :: (Ptr (TQUdpSocket x0) -> CInt -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> CInt -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> Int -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CInt -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1int rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QwaitForBytesWritten_h (QUdpSocket ()) (()) where waitForBytesWritten_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten cobj_x0 foreign import ccall "qtc_QUdpSocket_waitForBytesWritten" qtc_QUdpSocket_waitForBytesWritten :: Ptr (TQUdpSocket a) -> IO CBool instance QwaitForBytesWritten_h (QUdpSocketSc a) (()) where waitForBytesWritten_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten cobj_x0 instance QwaitForBytesWritten_h (QUdpSocket ()) ((Int)) where waitForBytesWritten_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten1 cobj_x0 (toCInt x1) foreign import ccall "qtc_QUdpSocket_waitForBytesWritten1" qtc_QUdpSocket_waitForBytesWritten1 :: Ptr (TQUdpSocket a) -> CInt -> IO CBool instance QwaitForBytesWritten_h (QUdpSocketSc a) ((Int)) where waitForBytesWritten_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForBytesWritten1 cobj_x0 (toCInt x1) instance QwaitForReadyRead_h (QUdpSocket ()) (()) where waitForReadyRead_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead cobj_x0 foreign import ccall "qtc_QUdpSocket_waitForReadyRead" qtc_QUdpSocket_waitForReadyRead :: Ptr (TQUdpSocket a) -> IO CBool instance QwaitForReadyRead_h (QUdpSocketSc a) (()) where waitForReadyRead_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead cobj_x0 instance QwaitForReadyRead_h (QUdpSocket ()) ((Int)) where waitForReadyRead_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead1 cobj_x0 (toCInt x1) foreign import ccall "qtc_QUdpSocket_waitForReadyRead1" qtc_QUdpSocket_waitForReadyRead1 :: Ptr (TQUdpSocket a) -> CInt -> IO CBool instance QwaitForReadyRead_h (QUdpSocketSc a) ((Int)) where waitForReadyRead_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_waitForReadyRead1 cobj_x0 (toCInt x1) instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> OpenMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1flags = qFlags_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1flags rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler5" qtc_QUdpSocket_setHandler5 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket5 :: (Ptr (TQUdpSocket x0) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> CLong -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> OpenMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 let x1flags = qFlags_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1flags rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qopen_h (QUdpSocket ()) ((OpenMode)) where open_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_open cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QUdpSocket_open" qtc_QUdpSocket_open :: Ptr (TQUdpSocket a) -> CLong -> IO CBool instance Qopen_h (QUdpSocketSc a) ((OpenMode)) where open_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_open cobj_x0 (toCLong $ qFlags_toInt x1) instance Qpos_h (QUdpSocket ()) (()) where pos_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_pos cobj_x0 foreign import ccall "qtc_QUdpSocket_pos" qtc_QUdpSocket_pos :: Ptr (TQUdpSocket a) -> IO CLLong instance Qpos_h (QUdpSocketSc a) (()) where pos_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_pos cobj_x0 instance Qreset_h (QUdpSocket ()) (()) (IO (Bool)) where reset_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_reset cobj_x0 foreign import ccall "qtc_QUdpSocket_reset" qtc_QUdpSocket_reset :: Ptr (TQUdpSocket a) -> IO CBool instance Qreset_h (QUdpSocketSc a) (()) (IO (Bool)) where reset_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_reset cobj_x0 instance Qseek_h (QUdpSocket ()) ((Int)) where seek_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_seek cobj_x0 (toCLLong x1) foreign import ccall "qtc_QUdpSocket_seek" qtc_QUdpSocket_seek :: Ptr (TQUdpSocket a) -> CLLong -> IO CBool instance Qseek_h (QUdpSocketSc a) ((Int)) where seek_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_seek cobj_x0 (toCLLong x1) instance Qqsize_h (QUdpSocket ()) (()) where qsize_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_size cobj_x0 foreign import ccall "qtc_QUdpSocket_size" qtc_QUdpSocket_size :: Ptr (TQUdpSocket a) -> IO CLLong instance Qqsize_h (QUdpSocketSc a) (()) where qsize_h x0 () = withLongLongResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QUdpSocket_size cobj_x0 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler6" qtc_QUdpSocket_setHandler6 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket6 :: (Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QUdpSocket ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QUdpSocket_event cobj_x0 cobj_x1 foreign import ccall "qtc_QUdpSocket_event" qtc_QUdpSocket_event :: Ptr (TQUdpSocket a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QUdpSocketSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QUdpSocket_event cobj_x0 cobj_x1 instance QsetHandler (QUdpSocket ()) (QUdpSocket x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QUdpSocket_setHandler7" qtc_QUdpSocket_setHandler7 :: Ptr (TQUdpSocket a) -> CWString -> Ptr (Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QUdpSocket7 :: (Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QUdpSocket7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QUdpSocketSc a) (QUdpSocket x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QUdpSocket7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QUdpSocket7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QUdpSocket_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQUdpSocket x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qUdpSocketFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QUdpSocket ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QUdpSocket_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QUdpSocket_eventFilter" qtc_QUdpSocket_eventFilter :: Ptr (TQUdpSocket a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QUdpSocketSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QUdpSocket_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Network/QUdpSocket_h.hs
bsd-2-clause
38,699
0
18
8,838
12,713
6,089
6,624
-1
-1
module Data.Drasil.Concepts.PhysicalProperties where import Language.Drasil import Utils.Drasil import Data.Drasil.Concepts.Documentation (material_, property) import Data.Drasil.Concepts.Math (centre) physicalcon :: [ConceptChunk] physicalcon = [gaseous, liquid, solid, ctrOfMass, density, specWeight, mass, len, dimension, vol, flexure] gaseous, liquid, solid, ctrOfMass, density, specWeight, mass, len, dimension, vol, flexure :: ConceptChunk gaseous = dcc "gaseous" (cn''' "gas" ) "gaseous state" liquid = dcc "liquid" (cn' "liquid" ) "liquid state" solid = dcc "solid" (cn' "solid" ) "solid state" ctrOfMass = dcc "ctrOfMass" (centre `of_''` mass ) "the mean location of the distribution of mass of the object" dimension = dcc "dimension" (cn' "dimension" ) "any of a set of basic kinds of quantity, as mass, length, and time" density = dcc "density" (cnIES "density" ) "the mass per unit volume" specWeight = dcc "specWeight" (cn' "specific weight") "the weight per unit volume" flexure = dcc "flexure" (cn' "flexure" ) "a bent or curved part" len = dcc "length" (cn' "length" ) ("the straight-line distance between two points along an object, " ++ "typically used to represent the size of an object from one end to the other") mass = dcc "mass" (cn''' "mass" ) "the quantity of matter in a body" vol = dcc "volume" (cn' "volume" ) "the amount of space that a substance or object occupies" materialProprty :: NamedChunk materialProprty = compoundNC material_ property
JacquesCarette/literate-scientific-software
code/drasil-data/Data/Drasil/Concepts/PhysicalProperties.hs
bsd-2-clause
1,681
0
7
425
339
197
142
24
1
{-# LANGUAGE OverloadedStrings #-} module Network.WebSockets.Protocol.Hybi10.Internal ( Hybi10_ (..) , encodeFrameHybi10 ) where import Control.Applicative (pure, (<$>)) import Data.Bits ((.&.), (.|.)) import Data.Maybe (maybeToList) import Data.Monoid (mempty, mappend, mconcat) import Data.Attoparsec (anyWord8) import Data.Binary.Get (runGet, getWord16be, getWord64be) import Data.ByteString (ByteString) import Data.ByteString.Char8 () import Data.Digest.Pure.SHA (bytestringDigest, sha1) import Data.Int (Int64) import Data.Enumerator ((=$)) import qualified Blaze.ByteString.Builder as B import qualified Data.Attoparsec as A import qualified Data.Attoparsec.Enumerator as A import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.CaseInsensitive as CI import qualified Data.Enumerator as E import qualified Data.Enumerator.List as EL import Network.WebSockets.Handshake.Http import Network.WebSockets.Protocol import Network.WebSockets.Protocol.Hybi10.Demultiplex import Network.WebSockets.Protocol.Hybi10.Mask import Network.WebSockets.Types data Hybi10_ = Hybi10_ instance Protocol Hybi10_ where version Hybi10_ = "hybi10" headerVersions Hybi10_ = ["13", "8", "7"] encodeMessages Hybi10_ = EL.map encodeMessageHybi10 decodeMessages Hybi10_ = decodeMessagesHybi10 finishRequest Hybi10_ = handshakeHybi10 implementations = [Hybi10_] instance TextProtocol Hybi10_ instance BinaryProtocol Hybi10_ encodeMessageHybi10 :: Message p -> B.Builder encodeMessageHybi10 msg = builder where mkFrame = Frame True False False False builder = encodeFrameHybi10 $ case msg of (ControlMessage (Close pl)) -> mkFrame CloseFrame pl (ControlMessage (Ping pl)) -> mkFrame PingFrame pl (ControlMessage (Pong pl)) -> mkFrame PongFrame pl (DataMessage (Text pl)) -> mkFrame TextFrame pl (DataMessage (Binary pl)) -> mkFrame BinaryFrame pl -- | Encode a frame encodeFrameHybi10 :: Frame -> B.Builder encodeFrameHybi10 f = B.fromWord8 byte0 `mappend` B.fromWord8 byte1 `mappend` len `mappend` B.fromLazyByteString (framePayload f) where byte0 = fin .|. rsv1 .|. rsv2 .|. rsv3 .|. opcode fin = if frameFin f then 0x80 else 0x00 rsv1 = if frameRsv1 f then 0x40 else 0x00 rsv2 = if frameRsv2 f then 0x20 else 0x00 rsv3 = if frameRsv3 f then 0x10 else 0x00 opcode = case frameType f of ContinuationFrame -> 0x00 TextFrame -> 0x01 BinaryFrame -> 0x02 CloseFrame -> 0x08 PingFrame -> 0x09 PongFrame -> 0x0a byte1 = lenflag len' = BL.length (framePayload f) (lenflag, len) | len' < 126 = (fromIntegral len', mempty) | len' < 0x10000 = (126, B.fromWord16be (fromIntegral len')) | otherwise = (127, B.fromWord64be (fromIntegral len')) decodeMessagesHybi10 :: Monad m => E.Enumeratee ByteString (Message p) m a decodeMessagesHybi10 = (E.sequence (A.iterParser parseFrame) =$) . demultiplexEnum demultiplexEnum :: Monad m => E.Enumeratee Frame (Message p) m a demultiplexEnum = EL.concatMapAccum step emptyDemultiplexState where step s f = let (m, s') = demultiplex s f in (s', maybeToList m) -- | Parse a frame parseFrame :: A.Parser Frame parseFrame = do byte0 <- anyWord8 let fin = byte0 .&. 0x80 == 0x80 rsv1 = byte0 .&. 0x40 == 0x40 rsv2 = byte0 .&. 0x20 == 0x20 rsv3 = byte0 .&. 0x10 == 0x10 opcode = byte0 .&. 0x0f let ft = case opcode of 0x00 -> ContinuationFrame 0x01 -> TextFrame 0x02 -> BinaryFrame 0x08 -> CloseFrame 0x09 -> PingFrame 0x0a -> PongFrame _ -> error "Unknown opcode" byte1 <- anyWord8 let mask = byte1 .&. 0x80 == 0x80 lenflag = fromIntegral (byte1 .&. 0x7f) len <- case lenflag of 126 -> fromIntegral . runGet' getWord16be <$> A.take 2 127 -> fromIntegral . runGet' getWord64be <$> A.take 8 _ -> return lenflag masker <- maskPayload <$> if mask then Just <$> A.take 4 else pure Nothing chunks <- take64 len return $ Frame fin rsv1 rsv2 rsv3 ft (masker $ BL.fromChunks chunks) where runGet' g = runGet g . BL.fromChunks . return take64 :: Int64 -> A.Parser [ByteString] take64 n | n <= 0 = return [] | otherwise = do let n' = min intMax n chunk <- A.take (fromIntegral n') (chunk :) <$> take64 (n - n') where intMax :: Int64 intMax = fromIntegral (maxBound :: Int) handshakeHybi10 :: Monad m => RequestHttpPart -> E.Iteratee ByteString m Request handshakeHybi10 reqHttp@(RequestHttpPart path h _) = do key <- getHeader "Sec-WebSocket-Key" let hash = unlazy $ bytestringDigest $ sha1 $ lazy $ key `mappend` guid let encoded = B64.encode hash return $ Request path h $ response101 [("Sec-WebSocket-Accept", encoded)] "" where guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" lazy = BL.fromChunks . return unlazy = mconcat . BL.toChunks getHeader k = case lookup k h of Just t -> return t Nothing -> E.throwError $ MalformedRequest reqHttp $ "Header missing: " ++ BC.unpack (CI.original k)
0xfaded/websockets
src/Network/WebSockets/Protocol/Hybi10/Internal.hs
bsd-3-clause
5,497
0
14
1,403
1,668
886
782
127
10
module Hchain.Client (start) where import qualified Control.Distributed.Backend.P2P as P2P import Control.Distributed.Process as DP import Control.Distributed.Process.Node as DPN import Data.Binary import Data.Typeable import Network.Socket import Hchain.BlockChain import Hchain.Client.Chain as Chain import Hchain.Client.CommandLineInterface as CommandLine import Control.Concurrent.MVar import Control.Distributed.Process.Extras.SystemLog start :: (Show a, Typeable a, Binary a, BContent a) => HostName -> ServiceName -> [String] -> BlockChain (Block a) -> MVar (BlockChain (Block a)) -> IO () start host port seeds chain storage = P2P.bootstrap host port (map P2P.makeNodeId seeds) initRemoteTable mainProcess where mainProcess = do _ <- systemLogFile ("log/application_" ++ host ++ port ++ ".log") Info return loopPid <- spawnLocal $ Chain.spawnProcess chain storage -- _commandLinePid <- spawnLocal $ CommandLine.spawnProcess loopPid return ()
jesuspc/hchain
src/hchain/Client.hs
bsd-3-clause
1,163
0
15
325
274
153
121
18
1
-- | A module that implements a dictionary/hash table module Text.Regex.Deriv.Dictionary where import qualified Data.IntMap as IM import Data.Char import Prelude hiding (all, words) class Key a where hash :: a -> [Int] instance Key Int where hash i = [i] instance Key Char where hash c = [(ord c)] instance (Key a, Key b) => Key (a,b) where hash (a,b) = hash a ++ hash b instance (Key a, Key b, Key c) => Key (a,b,c) where hash (a,b,c) = hash a ++ hash b ++ hash c instance Key a => Key [a] where hash as = concatMap hash as -- an immutable dictionary newtype Dictionary a = Dictionary (Trie a) primeL :: Int primeL = 757 primeR :: Int primeR = 577 empty :: Dictionary a empty = Dictionary emptyTrie -- insert and overwrite insert :: Key k => k -> a -> Dictionary a -> Dictionary a insert key val (Dictionary trie) = let key_hash = hash key in key_hash `seq` Dictionary (insertTrie True key_hash val trie) -- insert not overwrite insertNotOverwrite :: Key k => k -> a -> Dictionary a -> Dictionary a insertNotOverwrite key val (Dictionary trie) = let key_hash = hash key in key_hash `seq` Dictionary (insertTrie False key_hash val trie) lookup :: Key k => k -> Dictionary a -> Maybe a lookup key (Dictionary trie) = let key_hash = hash key in key_hash `seq` case lookupTrie key_hash trie of Just (Trie (x:_) _) -> Just x _ -> Nothing lookupAll :: Key k => k -> Dictionary a -> [a] lookupAll key (Dictionary trie) = let key_hash = hash key in key_hash `seq` case lookupTrie key_hash trie of Just (Trie xs _) -> xs _ -> [] member :: Key k => k -> Dictionary a -> Bool member key d = case Text.Regex.Deriv.Dictionary.lookup key d of { Just _ -> True ; Nothing -> False } fromList :: Key k => [(k,a)] -> Dictionary a fromList l = foldl (\d (key,val) -> insert key val d) empty l fromListNotOverwrite :: Key k => [(k,a)] -> Dictionary a fromListNotOverwrite l = foldl (\d (key,val) -> insertNotOverwrite key val d) empty l update :: Key k => k -> a -> Dictionary a -> Dictionary a update key val (Dictionary trie) = let key_hash = hash key trie' = key_hash `seq` updateTrie key_hash val trie in Dictionary trie' -- The following are some special functions we implemented for -- an special instance of the dictionary 'Dictionary (k,a)' -- in which we store both the key k together with the actual value a, -- i.e. we map (hash k) to list of (k,a) value pairs -- ^ the dictionary (k,a) version of elem isIn :: (Key k, Eq k) => k -> Dictionary (k,a) -> Bool isIn k dict = let all = lookupAll (hash k) dict in k `elem` (map fst all) nub :: (Key k, Eq k) => [k] -> [k] nub ks = nubSub ks empty nubSub :: (Key k, Eq k) => [k] -> Dictionary (k,()) -> [k] nubSub [] _ = [] nubSub (x:xs) d | x `isIn` d = nubSub xs d | otherwise = let d' = insertNotOverwrite x (x,()) d in x:(nubSub xs d') -- An internal trie which we use to implement the dictoinar data Trie a = Trie ![a] !(IM.IntMap (Trie a)) emptyTrie :: Trie a emptyTrie = Trie [] (IM.empty) insertTrie :: Bool -> [Int] -> a -> Trie a -> Trie a insertTrie overwrite [] i (Trie is maps) | overwrite = Trie [i] maps | otherwise = Trie (i:is) maps insertTrie overwrite (word:words) i (Trie is maps) = let key = word in key `seq` case IM.lookup key maps of { Just trie -> let trie' = insertTrie overwrite words i trie maps' = trie' `seq` IM.update (\_ -> Just trie') key maps in maps' `seq` Trie is maps' ; Nothing -> let trie = emptyTrie trie' = insertTrie overwrite words i trie maps' = trie' `seq` IM.insert key trie' maps in maps' `seq` Trie is maps' } lookupTrie :: [Int] -> Trie a -> Maybe (Trie a) lookupTrie [] trie = Just trie lookupTrie (word:words) (Trie _ maps) = let key = word in case IM.lookup key maps of Just trie -> lookupTrie words trie Nothing -> Nothing -- we only update the first one, not the collided ones updateTrie :: [Int] -> a -> Trie a -> Trie a updateTrie [] y (Trie (_:xs) maps) = Trie (y:xs) maps updateTrie (word:words) v (Trie is maps) = let key = word in case IM.lookup key maps of Just trie -> let trie' = updateTrie words v trie maps' = IM.update (\_ -> Just trie') key maps in Trie is maps' Nothing -> Trie is maps
awalterschulze/xhaskell-regex-deriv
Text/Regex/Deriv/Dictionary.hs
bsd-3-clause
4,562
0
19
1,269
1,860
952
908
108
2
module Publish where import Control.Monad.Error.Class (throwError) import qualified Data.Maybe as Maybe import qualified Bump import qualified Catalog import qualified CommandLine.Helpers as Cmd import qualified Docs import qualified Elm.Docs as Docs import qualified Elm.Package.Description as Desc import qualified Elm.Package as Package import qualified Elm.Package.Paths as P import qualified GitHub import qualified Manager publish :: Manager.Manager () publish = do description <- Desc.read P.description let name = Desc.name description let version = Desc.version description Cmd.out $ unwords [ "Verifying", Package.toString name, Package.versionToString version, "..." ] verifyMetadata description docs <- Docs.generate validity <- verifyVersion docs description newVersion <- case validity of Bump.Valid -> return version Bump.Invalid -> throwError "Cannot publish with an invalid version!" Bump.Changed v -> return v verifyTag name newVersion Catalog.register name newVersion Cmd.out "Success!" verifyMetadata :: Desc.Description -> Manager.Manager () verifyMetadata deps = case problems of [] -> return () _ -> throwError $ "Some of the fields in " ++ P.description ++ " have not been filled in yet:\n\n" ++ unlines problems ++ "\nFill these in and try to publish again!" where problems = Maybe.catMaybes [ verify Desc.repo " repository - must refer to a valid repo on GitHub" , verify Desc.summary " summary - a quick summary of your project, 80 characters or less" , verify Desc.exposed " exposed-modules - list modules your project exposes to users" ] verify getField msg = if getField deps == getField Desc.defaultDescription then Just msg else Nothing verifyVersion :: [Docs.Documentation] -> Desc.Description -> Manager.Manager Bump.Validity verifyVersion docs description = let name = Desc.name description version = Desc.version description in do maybeVersions <- Catalog.versions name case maybeVersions of Just publishedVersions -> Bump.validateVersion docs name version publishedVersions Nothing -> Bump.validateInitialVersion description verifyTag :: Package.Name -> Package.Version -> Manager.Manager () verifyTag name version = do publicVersions <- GitHub.getVersionTags name if version `elem` publicVersions then return () else throwError (tagMessage version) tagMessage :: Package.Version -> String tagMessage version = let v = Package.versionToString version in unlines [ "Libraries must be tagged in git, but tag " ++ v ++ " was not found." , "These tags make it possible to find this specific version on github." , "To tag the most recent commit and push it to github, run this:" , "" , " git tag -a " ++ v ++ " -m \"release version " ++ v ++ "\"" , " git push origin " ++ v , "" ]
laszlopandy/elm-package
src/Publish.hs
bsd-3-clause
3,146
0
13
828
705
360
345
77
3
module Algebra.Structures.PID ( module Algebra.Structures.UFD , PID(..) ) where import Algebra.Structures.UFD class UFD a => PID a
Alex128/abstract-math
src/Algebra/Structures/PID.hs
bsd-3-clause
148
0
6
34
43
26
17
-1
-1
{- Find things that are unsafe <TEST> {-# NOINLINE entries #-}; entries = unsafePerformIO newIO entries = unsafePerformIO Multimap.newIO -- {-# NOINLINE entries #-} ; entries = unsafePerformIO Multimap.newIO entries = unsafePerformIO $ f y where foo = 1 -- {-# NOINLINE entries #-} ; entries = unsafePerformIO $ f y where foo = 1 entries v = unsafePerformIO $ Multimap.newIO where foo = 1 entries v = x where x = unsafePerformIO $ Multimap.newIO entries = x where x = unsafePerformIO $ Multimap.newIO -- {-# NOINLINE entries #-} ; entries = x where x = unsafePerformIO $ Multimap.newIO entries = unsafePerformIO . bar entries = unsafePerformIO . baz $ x -- {-# NOINLINE entries #-} ; entries = unsafePerformIO . baz $ x entries = unsafePerformIO . baz $ x -- {-# NOINLINE entries #-} ; entries = unsafePerformIO . baz $ x </TEST> -} module Hint.Unsafe(unsafeHint) where import Hint.Type(DeclHint,ModuleEx(..),Severity(..),rawIdea,toSSA) import Data.List.Extra import Refact.Types hiding(Match) import Data.Generics.Uniplate.DataOnly import GHC.Hs import GHC.Types.Name.Occurrence import GHC.Types.Name.Reader import GHC.Data.FastString import GHC.Types.Basic import GHC.Types.SourceText import GHC.Types.SrcLoc import Language.Haskell.GhclibParserEx.GHC.Hs.Expr import Language.Haskell.GhclibParserEx.GHC.Utils.Outputable -- The conditions on which to fire this hint are subtle. We are -- interested exclusively in application constants involving -- 'unsafePerformIO'. For example, -- @ -- f = \x -> unsafePerformIO x -- @ -- is not such a declaration (the right hand side is a lambda, not an -- application) whereas, -- @ -- f = g where g = unsafePerformIO Multimap.newIO -- @ -- is. We advise that such constants should have a @NOINLINE@ pragma. unsafeHint :: DeclHint unsafeHint _ (ModuleEx (L _ m)) = \ld@(L loc d) -> [rawIdea Hint.Type.Warning "Missing NOINLINE pragma" (locA loc) (unsafePrettyPrint d) (Just $ trimStart (unsafePrettyPrint $ gen x) ++ "\n" ++ unsafePrettyPrint d) [] [InsertComment (toSSA ld) (unsafePrettyPrint $ gen x)] -- 'x' does not declare a new function. | d@(ValD _ FunBind {fun_id=L _ (Unqual x) , fun_matches=MG{mg_origin=FromSource,mg_alts=L _ [L _ Match {m_pats=[]}]}}) <- [d] -- 'x' is a synonym for an appliciation involing 'unsafePerformIO' , isUnsafeDecl d -- 'x' is not marked 'NOINLINE'. , x `notElem` noinline] where gen :: OccName -> LHsDecl GhcPs gen x = noLocA $ SigD noExtField (InlineSig EpAnnNotUsed (noLocA (mkRdrUnqual x)) (InlinePragma (SourceText "{-# NOINLINE") NoInline Nothing NeverActive FunLike)) noinline :: [OccName] noinline = [q | L _(SigD _ (InlineSig _ (L _ (Unqual q)) (InlinePragma _ NoInline Nothing NeverActive FunLike)) ) <- hsmodDecls m] isUnsafeDecl :: HsDecl GhcPs -> Bool isUnsafeDecl (ValD _ FunBind {fun_matches=MG {mg_origin=FromSource,mg_alts=L _ alts}}) = any isUnsafeApp (childrenBi alts) || any isUnsafeDecl (childrenBi alts) isUnsafeDecl _ = False -- Am I equivalent to @unsafePerformIO x@? isUnsafeApp :: HsExpr GhcPs -> Bool isUnsafeApp (OpApp _ (L _ l) op _ ) | isDol op = isUnsafeFun l isUnsafeApp (HsApp _ (L _ x) _) = isUnsafeFun x isUnsafeApp _ = False -- Am I equivalent to @unsafePerformIO . x@? isUnsafeFun :: HsExpr GhcPs -> Bool isUnsafeFun (HsVar _ (L _ x)) | x == mkVarUnqual (fsLit "unsafePerformIO") = True isUnsafeFun (OpApp _ (L _ l) op _) | isDot op = isUnsafeFun l isUnsafeFun _ = False
ndmitchell/hlint
src/Hint/Unsafe.hs
bsd-3-clause
3,600
0
24
727
817
441
376
45
1
module Hhhhoard.Creds ( userEmail , userPassword) where userEmail :: String; userEmail = "[email protected]" userPassword :: String; userPassword = "password"
yan/hhhhoard
Hhhhoard/Creds.hs
bsd-3-clause
168
0
4
28
36
23
13
5
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.DebugLabel -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/EXT/debug_label.txt EXT_debug_label> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.DebugLabel ( -- * Enums gl_BUFFER_OBJECT_EXT, gl_PROGRAM_OBJECT_EXT, gl_PROGRAM_PIPELINE_OBJECT_EXT, gl_QUERY_OBJECT_EXT, gl_SAMPLER, gl_SHADER_OBJECT_EXT, gl_TRANSFORM_FEEDBACK, gl_VERTEX_ARRAY_OBJECT_EXT, -- * Functions glGetObjectLabelEXT, glLabelObjectEXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/DebugLabel.hs
bsd-3-clause
923
0
4
112
73
56
17
13
0
-- The Timber compiler <timber-lang.org> -- -- Copyright 2008-2009 Johan Nordlander <[email protected]> -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the names of the copyright holder and any identified -- contributors, nor the names of their affiliations, may be used to -- endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. {- ************************************************************************** ** This file is based on sources distributed as the haskell-src package ** ************************************************************************** The Glasgow Haskell Compiler License Copyright 2004, The University Court of the University of Glasgow. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Lexer (Token(..), lexer, readInteger, readNumber, readRational) where import ParseMonad import Data.Char import Data.Ratio import Token import Common {- The source location, (y,x), is the coordinates of the previous token. col is the current column in the source file. If col is 0, we are somewhere at the beginning of the line before the first token. Setting col to 0 is used in two places: just after emitting a virtual close brace due to layout, so that next time through we check whether we also need to emit a semi-colon, and at the beginning of the file, to kick off the lexer. -} lexer :: (Token -> PM a) -> PM a lexer cont = PM $ \input (y,x) col -> if col == 0 then tab y x True input col else tab y col False input col -- throw away old x where -- move past whitespace and comments tab y x bol [] col = (unPM $ cont EOF) [] (y,x) col tab y x bol ('\t':s) col = tab y (nextTab x) bol s col tab y x bol ('\n':s) col = newLine s y col tab y x bol ('-':'-':s) col = newLine (drop 1 (dropWhile (/= '\n') s)) y col tab y x bol ('{':'-':s) col = nestedComment tab y x bol s col tab y x bol (c:s) col | isSpace c = tab y (x + 1) bol s col | otherwise = if bol then (unPM $ lexBOL cont) (c:s) (y,x) x else (unPM $ lexToken cont) (c:s) (y,x) x newLine s y col = tab (y + 1) 1 True s col nextTab x = x + (tab_length - (x - 1) `mod` tab_length) {- When we are lexing the first token of a line, check whether we need to insert virtual semicolons or close braces due to layout. -} lexBOL :: (Token -> PM a) -> PM a lexBOL cont = PM $ \ s loc@(y,x) col ctx -> if need_close_curly x ctx then -- tr' ("layout: inserting '}' at " ++ show loc ++ "\n") $ -- Set col to 0, indicating that we're still at the -- beginning of the line, in case we need a semi-colon too. -- Also pop the context here, so that we don't insert -- another close brace before the parser can pop it. (unPM $ cont VRightCurly) s loc 0 (tail ctx) else if need_semi_colon x ctx then -- tr' ("layout: inserting ';' at " ++ show loc ++ "\n") $ (unPM $ cont SemiColon) s loc col ctx else (unPM $ lexToken cont) s loc col ctx where need_close_curly x [] = False need_close_curly x (Layout n:Layout m:_) | n <= m = True need_close_curly x (i:_) = case i of NoLayout -> False Layout n -> x < n RecLayout n -> False need_semi_colon x [] = False need_semi_colon x (i:_) = case i of NoLayout -> False Layout n -> x == n RecLayout n -> x == n lexToken :: (Token -> PM a) -> PM a lexToken cont = PM lexToken' where lexToken' (c:s) loc@(y,x') x = -- trace ("lexer: y = " ++ show y ++ " x = " ++ show x ++ "\n") $ case c of -- First the special symbols '(' -> special LeftParen ')' -> special RightParen ',' -> special Comma ';' -> special SemiColon '[' -> special LeftSquare ']' -> special RightSquare '`' -> special BackQuote '{' -> special LeftCurly '}' -> \state -> case state of (_:ctxt) -> special RightCurly ctxt -- pop context on } [] -> (unPM $ parseError "parse error (possibly incorrect indentation)") s loc x [] '\'' -> (unPM $ lexChar cont) s loc (x + 1) '\"' -> (unPM $ lexString cont) s loc (x + 1) '_' | null s || not (isIdent (head s)) -> special Wildcard c | isDigit c -> case lexInt (c:s) of Decimal (n, rest) -> case rest of ('.':c2:rest2) | isDigit c2 -> case lexFloatRest (c2:rest2) of Nothing -> (unPM $ parseError "illegal float.") s loc x Just (n2,rest3) -> let f = n ++ ('.':n2) in forward (length f) (FloatTok f) rest3 _ -> forward (length n) (IntTok n) rest Octal (n,rest) -> forward (length n) (IntTok n) rest Hexadecimal (n,rest) -> forward (length n) (IntTok n) rest | isLower c -> lexVarId "" c s | isUpper c -> lexQualName "" c s | isSymbol c -> lexSymbol "" c s | otherwise -> (unPM $ parseError ("illegal character \'" ++ showLitChar c "" ++ "\'\n")) s loc x where special t = forward 1 t s forward n t s = (unPM $ cont t) s loc (x + n) join "" n = n join q n = q ++ '.' : n len "" n = length n len q n = length q + length n + 1 lexFloatRest r = case span isDigit r of (r2, 'e':r3) -> lexFloatExp (r2 ++ "e") r3 (r2, 'E':r3) -> lexFloatExp (r2 ++ "e") r3 f@(r2, r3) -> Just f lexFloatExp r1 ('-':r2) = lexFloatExp2 (r1 ++ "-") r2 lexFloatExp r1 ('+':r2) = lexFloatExp2 (r1 ++ "+") r2 lexFloatExp r1 r2 = lexFloatExp2 r1 r2 lexFloatExp2 r1 r2 = case span isDigit r2 of ("", _ ) -> Nothing (ds, r3) -> Just (r1++ds,r3) lexVarId q c s = let (vidtail, rest) = span isIdent s vid = c:vidtail l_vid = len q vid in case lookup vid reserved_ids of Just keyword -> case q of "" -> forward l_vid keyword rest _ -> (unPM $ parseError "illegal qualified name") s loc x Nothing -> forward l_vid (VarId (q,vid)) rest lexQualName q c s = let (contail, rest) = span isIdent s con = join q (c:contail) l_con = length con in case rest of '.': c' : rest' | isUpper c' -> lexQualName con c' rest' | isLower c' -> lexVarId con c' rest' | isSymbol c' -> lexSymbol con c' rest' | otherwise -> (unPM $ parseError "illegal qualified name") s loc x _ -> forward l_con (ConId (q,c:contail)) rest lexSymbol q c s = let (symtail, rest) = span isSymbol s sym = c:symtail l_sym = len q sym in case lookup sym reserved_ops of Just t -> case q of "" -> forward l_sym t rest _ -> (unPM $ parseError "illegal qualified name") s loc x Nothing -> case c of ':' -> forward l_sym (ConSym (q,sym)) rest _ -> forward l_sym (VarSym (q,sym)) rest lexToken' _ _ _ = internalError0 "Lexer.lexToken: empty input stream." lexInt ('0':o:d:r) | toLower o == 'o' && isOctDigit d = let (ds, rs) = span isOctDigit r in Octal ('0':'o':d:ds, rs) lexInt ('0':x:d:r) | toLower x == 'x' && isHexDigit d = let (ds, rs) = span isHexDigit r in Hexadecimal ('0':'x':d:ds, rs) lexInt r = Decimal (span isDigit r) lexChar :: (Token -> PM a) -> PM a lexChar cont = PM lexChar' where lexChar' s loc@(y,_) x = case s of '\\':s -> let (e, s2, i) = runPM (escapeChar s) "" loc x [] in charEnd e s2 loc (x + i) c:s -> charEnd c s loc (x + 1) [] -> internalError0 "Lexer.lexChar: empty list." charEnd c ('\'':s) = \loc x -> (unPM $ cont (Character c)) s loc (x + 1) charEnd c s = (unPM $ parseError "improperly terminated character constant.") s lexString :: (Token -> PM a) -> PM a lexString cont = PM lexString' where lexString' s loc@(y',_) x = loop "" s x y' where loop e s x y = case s of '\\':'&':s -> loop e s (x+2) y '\\':c:s | isSpace c -> stringGap e s (x + 2) y | otherwise -> let (e', sr, i) = runPM (escapeChar (c:s)) "" loc x [] in loop (e':e) sr (x+i) y '\"':s{-"-} -> (unPM $ cont (StringTok (reverse e))) s loc (x + 1) c:s -> loop (c:e) s (x + 1) y [] -> (unPM $ parseError "improperly terminated string.") s loc x stringGap e s x y = case s of '\n':s -> stringGap e s 1 (y + 1) '\\':s -> loop e s (x + 1) y c:s' | isSpace c -> stringGap e s' (x + 1) y | otherwise -> (unPM $ parseError "illegal character in string gap.") s loc x [] -> internalError0 "Lexer.stringGap: empty list." escapeChar :: String -> PM (Char, String, Int) escapeChar s = case s of 'a':s -> return ('\a', s, 2) 'b':s -> return ('\b', s, 2) 'f':s -> return ('\f', s, 2) 'n':s -> return ('\n', s, 2) 'r':s -> return ('\r', s, 2) 't':s -> return ('\t', s, 2) 'v':s -> return ('\v', s, 2) '\\':s -> return ('\\', s, 2) '"':s -> return ('\"', s, 2) -- " '\'':s -> return ('\'', s, 2) '^':x@(c:s) -> cntrl x 'N':'U':'L':s -> return ('\NUL', s, 4) 'S':'O':'H':s -> return ('\SOH', s, 4) 'S':'T':'X':s -> return ('\STX', s, 4) 'E':'T':'X':s -> return ('\ETX', s, 4) 'E':'O':'T':s -> return ('\EOT', s, 4) 'E':'N':'Q':s -> return ('\ENQ', s, 4) 'A':'C':'K':s -> return ('\ACK', s, 4) 'B':'E':'L':s -> return ('\BEL', s, 4) 'B':'S':s -> return ('\BS', s, 3) 'H':'T':s -> return ('\HT', s, 3) 'L':'F':s -> return ('\LF', s, 3) 'V':'T':s -> return ('\VT', s, 3) 'F':'F':s -> return ('\FF', s, 3) 'C':'R':s -> return ('\CR', s, 3) 'S':'O':s -> return ('\SO', s, 3) 'S':'I':s -> return ('\SI', s, 3) 'D':'L':'E':s -> return ('\DLE', s, 4) 'D':'C':'1':s -> return ('\DC1', s, 4) 'D':'C':'2':s -> return ('\DC2', s, 4) 'D':'C':'3':s -> return ('\DC3', s, 4) 'D':'C':'4':s -> return ('\DC4', s, 4) 'N':'A':'K':s -> return ('\NAK', s, 4) 'S':'Y':'N':s -> return ('\SYN', s, 4) 'E':'T':'B':s -> return ('\ETB', s, 4) 'C':'A':'N':s -> return ('\CAN', s, 4) 'E':'M':s -> return ('\EM', s, 3) 'S':'U':'B':s -> return ('\SUB', s, 4) 'E':'S':'C':s -> return ('\ESC', s, 4) 'F':'S':s -> return ('\FS', s, 3) 'G':'S':s -> return ('\GS', s, 3) 'R':'S':s -> return ('\RS', s, 3) 'U':'S':s -> return ('\US', s, 3) 'S':'P':s -> return ('\SP', s, 3) 'D':'E':'L':s -> return ('\DEL', s, 4) -- Depending upon the compiler/interpreter's Char type, these yield either -- just 8-bit ISO-8859-1 or 2^16 UniCode. -- Octal representation of a character 'o':s -> let (ds, s') = span isOctDigit s n = readNumber 8 ds in numberToChar n s' (length ds + 1) -- Hexadecimal representation of a character 'x':s -> let (ds, s') = span isHexDigit s n = readNumber 16 ds in numberToChar n s' (length ds + 1) -- Base 10 representation of a character d:s | isDigit d -> let (ds, s') = span isDigit s n = readNumber 10 (d:ds) in numberToChar n s' (length ds + 1) _ -> parseError "illegal escape sequence." where numberToChar n s l_n = if n < (toInteger $ fromEnum (minBound :: Char)) || n > (toInteger $ fromEnum (maxBound :: Char)) then parseError "illegal character literal (number out of range)." else return (chr $ fromInteger n, s, l_n) cntrl :: String -> PM (Char, String, Int) cntrl (c :s) | isUpper c = return (chr (ord c - ord 'A'), s, 2) cntrl ('@' :s) = return ('\^@', s, 2) cntrl ('[' :s) = return ('\^[', s, 2) cntrl ('\\':s) = return ('\^\', s, 2) cntrl (']' :s) = return ('\^]', s, 2) cntrl ('^' :s) = return ('\^^', s, 2) cntrl ('_' :s) = return ('\^_', s, 2) cntrl _ = parseError "illegal control character" nestedComment cont y x bol s col = case s of '-':'}':s -> cont y (x + 2) bol s col '{':'-':s -> nestedComment (nestedComment cont) y (x + 2) bol s col '\t':s -> nestedComment cont y (nextTab x) bol s col '\n':s -> nestedComment cont (y + 1) 1 True s col c:s -> nestedComment cont y (x + 1) bol s col [] -> compileError "Open comment at end of file" readInteger :: String -> Integer readInteger ('0':'o':ds) = readInteger2 8 isOctDigit ds readInteger ('0':'O':ds) = readInteger2 8 isOctDigit ds readInteger ('0':'x':ds) = readInteger2 16 isHexDigit ds readInteger ('0':'X':ds) = readInteger2 16 isHexDigit ds readInteger ds = readInteger2 10 isDigit ds readNumber :: Integer -> String -> Integer readNumber radix ds = readInteger2 radix (const True) ds readInteger2 :: Integer -> (Char -> Bool) -> String -> Integer readInteger2 radix isDig ds = foldl1 (\n d -> n * radix + d) (map (fromIntegral . digitToInt) (takeWhile isDig ds)) readRational :: String -> Rational readRational xs = (readInteger (i ++ m))%1 * 10^^((case e of "" -> 0 ('+':e2) -> read e2 _ -> read e) - length m) where (i, r1) = span isDigit xs (m, r2) = span isDigit (dropWhile (== '.') r1) e = dropWhile (== 'e') r2
UBMLtonGroup/timberc
src/Lexer.hs
bsd-3-clause
18,665
50
27
6,972
5,642
2,901
2,741
282
50
{-# LANGUAGE CPP, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Array.Class -- Copyright : (C) 2011 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : type families, MPTCs -- ---------------------------------------------------------------------------- module Control.Monad.Array.Class ( MonadArray(..) , MonadUArray(..) ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Concurrent.STM import Control.Monad (liftM) import Control.Monad.ST import Control.Monad.Trans.Class import Data.Array.Base import Data.Array.IO import Data.Array.ST import Data.Array.MArray.Extras import Foreign.Ptr import Foreign.StablePtr import Data.Int import Data.Word -- | Arr m serves as a canonical choice of boxed MArray class Monad m => MonadArray m where data Arr m :: * -> * -> * getBoundsM :: Ix i => Arr m i e -> m (i, i) getNumElementsM :: Ix i => Arr m i e -> m Int newArrayM :: Ix i => (i, i) -> e -> m (Arr m i e) newArrayM_ :: Ix i => (i, i) -> m (Arr m i e) unsafeNewArrayM_ :: Ix i => (i, i) -> m (Arr m i e) unsafeReadM :: Ix i => Arr m i e -> Int -> m e unsafeWriteM :: Ix i => Arr m i e -> Int -> e -> m () instance MonadArray m => MArray (Arr m) e m where getBounds = getBoundsM getNumElements = getNumElementsM newArray = newArrayM unsafeNewArray_ = unsafeNewArrayM_ newArray_ = newArrayM_ unsafeRead = unsafeReadM unsafeWrite = unsafeWriteM instance MonadArray IO where newtype Arr IO i e = ArrIO { runArrIO :: IOArray i e } getBoundsM = getBounds . runArrIO getNumElementsM = getNumElements . runArrIO newArrayM bs e = ArrIO <$> newArray bs e newArrayM_ bs = ArrIO <$> newArray_ bs unsafeNewArrayM_ bs = ArrIO <$> unsafeNewArray_ bs unsafeReadM (ArrIO a) i = unsafeRead a i unsafeWriteM (ArrIO a) i e = unsafeWrite a i e instance MonadArray (ST s) where newtype Arr (ST s) i e = ArrST { runArrST :: STArray s i e } getBoundsM = getBounds . runArrST getNumElementsM = getNumElements . runArrST newArrayM bs e = ArrST <$> newArray bs e newArrayM_ bs = ArrST <$> newArray_ bs unsafeNewArrayM_ bs = ArrST <$> unsafeNewArray_ bs unsafeReadM (ArrST a) i = unsafeRead a i unsafeWriteM (ArrST a) i e = unsafeWrite a i e instance MonadArray STM where newtype Arr STM i e = ArrSTM { runArrSTM :: TArray i e } getBoundsM = getBounds . runArrSTM getNumElementsM = getNumElements . runArrSTM newArrayM bs e = ArrSTM <$> newArray bs e newArrayM_ bs = ArrSTM <$> newArray_ bs unsafeNewArrayM_ bs = ArrSTM <$> unsafeNewArray_ bs unsafeReadM (ArrSTM a) i = unsafeRead a i unsafeWriteM (ArrSTM a) i e = unsafeWrite a i e instance (MonadTrans t, Monad (t m), MonadArray m) => MonadArray (t m) where newtype Arr (t m) i e = ArrT { runArrT :: Arr m i e } getBoundsM = lift . getBounds . runArrT getNumElementsM = lift . getNumElements . runArrT newArrayM bs e = lift $ ArrT `liftM` newArray bs e newArrayM_ bs = lift $ ArrT `liftM` newArray_ bs unsafeNewArrayM_ bs = lift $ ArrT `liftM` unsafeNewArray_ bs unsafeReadM (ArrT a) i = lift $ unsafeRead a i unsafeWriteM (ArrT a) i e = lift $ unsafeWrite a i e -- | UArr m provides unboxed arrays, and can be used on the primitive data types: -- -- 'Bool', 'Char', 'Int', 'Word', 'Double', 'Float', 'Int8', 'Int16', 'Int32', 'Int64', 'Word8', -- 'Word16', 'Word32', and 'Word64' -- -- It can be used via 'MArray1' to store values of types @'StablePtr' a@, @'FunPtr' a@ and @'Ptr a'@ as well. class ( MonadArray m , MArray (UArr m) Bool m , MArray (UArr m) Char m , MArray (UArr m) Int m , MArray (UArr m) Word m , MArray (UArr m) Double m , MArray (UArr m) Float m , MArray (UArr m) Int8 m , MArray (UArr m) Int16 m , MArray (UArr m) Int32 m , MArray (UArr m) Int64 m , MArray (UArr m) Word8 m , MArray (UArr m) Word16 m , MArray (UArr m) Word32 m , MArray (UArr m) Word64 m , MArray1 (UArr m) StablePtr m , MArray1 (UArr m) FunPtr m , MArray1 (UArr m) Ptr m ) => MonadUArray m where data UArr m :: * -> * -> * instance MArray IOUArray e IO => MArray (UArr IO) e IO where getBounds = getBounds . runUArrIO getNumElements = getNumElements . runUArrIO newArray bs e = UArrIO <$> newArray bs e newArray_ bs = UArrIO <$> newArray_ bs unsafeNewArray_ bs = UArrIO <$> unsafeNewArray_ bs unsafeRead (UArrIO a) i = unsafeRead a i unsafeWrite (UArrIO a) i e = unsafeWrite a i e instance MArray1 IOUArray e IO => MArray1 (UArr IO) e IO where getBounds1 = getBounds1 . runUArrIO getNumElements1 = getNumElements1 . runUArrIO newArray1 bs e = UArrIO <$> newArray1 bs e newArray1_ bs = UArrIO <$> newArray1_ bs unsafeNewArray1_ bs = UArrIO <$> unsafeNewArray1_ bs unsafeRead1 (UArrIO a) i = unsafeRead1 a i unsafeWrite1 (UArrIO a) i e = unsafeWrite1 a i e instance MonadUArray IO where newtype UArr IO i e = UArrIO { runUArrIO :: IOUArray i e } instance MArray (STUArray s) e (ST s) => MArray (UArr (ST s)) e (ST s) where getBounds = getBounds . runUArrST getNumElements = getNumElements . runUArrST newArray bs e = UArrST <$> newArray bs e newArray_ bs = UArrST <$> newArray_ bs unsafeNewArray_ bs = UArrST <$> unsafeNewArray_ bs unsafeRead (UArrST a) i = unsafeRead a i unsafeWrite (UArrST a) i e = unsafeWrite a i e instance MArray1 (STUArray s) e (ST s) => MArray1 (UArr (ST s)) e (ST s) where getBounds1 = getBounds1 . runUArrST getNumElements1 = getNumElements1 . runUArrST newArray1 bs e = UArrST <$> newArray1 bs e newArray1_ bs = UArrST <$> newArray1_ bs unsafeNewArray1_ bs = UArrST <$> unsafeNewArray1_ bs unsafeRead1 (UArrST a) i = unsafeRead1 a i unsafeWrite1 (UArrST a) i e = unsafeWrite1 a i e instance MonadUArray (ST s) where newtype UArr (ST s) i e = UArrST { runUArrST :: STUArray s i e } instance (MonadTrans t, Monad (t m), MonadUArray m, MArray (UArr m) e m) => MArray (UArr (t m)) e (t m) where getBounds = lift . getBounds . runUArrT getNumElements = lift . getNumElements . runUArrT newArray bs e = lift $ UArrT `liftM` newArray bs e newArray_ bs = lift $ UArrT `liftM` newArray_ bs unsafeNewArray_ bs = lift $ UArrT `liftM` unsafeNewArray_ bs unsafeRead (UArrT a) i = lift $ unsafeRead a i unsafeWrite (UArrT a) i e = lift $ unsafeWrite a i e instance (MonadTrans t, Monad (t m), MonadUArray m, MArray1 (UArr m) f m) => MArray1 (UArr (t m)) f (t m) where getBounds1 = lift . getBounds1 . runUArrT getNumElements1 = lift . getNumElements1 . runUArrT newArray1 bs e = lift $ UArrT `liftM` newArray1 bs e newArray1_ bs = lift $ UArrT `liftM` newArray1_ bs unsafeNewArray1_ bs = lift $ UArrT `liftM` unsafeNewArray1_ bs unsafeRead1 (UArrT a) i = lift $ unsafeRead1 a i unsafeWrite1 (UArrT a) i e = lift $ unsafeWrite1 a i e instance (MonadTrans t, Monad (t m), MonadUArray m) => MonadUArray (t m) where newtype UArr (t m) i e = UArrT { runUArrT :: UArr m i e }
ekmett/monadic-arrays
Control/Monad/Array/Class.hs
bsd-3-clause
7,851
0
12
2,183
2,643
1,353
1,290
145
0
{-# LANGUAGE CPP #-} module Language.Sh.Glob ( expandGlob, matchPattern, removePrefix, removeSuffix ) where import Control.Monad.Trans ( MonadIO, liftIO ) import Control.Monad.State ( runState, put ) import Data.Char ( ord, chr ) import Data.List ( isPrefixOf, partition ) import Data.Maybe ( isJust, listToMaybe ) import System.Directory ( getCurrentDirectory ) import System.FilePath ( pathSeparator, isPathSeparator, isExtSeparator ) import Text.Regex.PCRE.Light.Char8 ( Regex, compileM, match, ungreedy ) import Language.Sh.Syntax ( Lexeme(..), Word ) -- we might get a bit fancier if older glob libraries will support -- a subset of what we want to do...? #ifdef HAVE_GLOB import System.FilePath.Glob ( tryCompile, globDir, factorPath ) #endif expandGlob :: MonadIO m => Word -> m [FilePath] #ifdef HAVE_GLOB expandGlob w = case mkGlob w of Nothing -> return [] Just g -> case tryCompile g of Right g' -> liftIO $ do let (dir,g'') = factorPath g' liftIO $ putStrLn $ show (dir,g'') hits <- globDir [g''] dir return $ head $ fst $ hits _ -> return [] #else expandGlob = const $ return [] #endif -- By the time this is called, we should only have quotes and quoted -- literals to worry about. In the event of finding an unquoted glob -- char (and if the glob matches) we'll automatically remove quotes, etc. -- (since the next stage is, after all, quote removal). mkGlob :: Word -> Maybe String mkGlob w = case runState (mkG w) False of (s,True) -> Just s _ -> Nothing where mkG [] = return [] mkG (Literal '[':xs) = case mkClass xs of Just (g,xs') -> fmap (g++) $ mkG xs' Nothing -> fmap ((mkLit '[')++) $ mkG xs mkG (Literal '*':Literal '*':xs) = mkG $ Literal '*':xs mkG (Literal '*':xs) = put True >> fmap ('*':) (mkG xs) mkG (Literal '?':xs) = put True >> fmap ('?':) (mkG xs) mkG (Literal c:xs) = fmap (mkLit c++) $ mkG xs mkG (Quoted (Literal c):xs) = fmap (mkLit c++) $ mkG xs mkG (Quoted q:xs) = mkG $ q:xs mkG (Quote _:xs) = mkG xs mkLit c | c `elem` "[*?<" = ['[',c,']'] | otherwise = [c] -- This is basically gratuitously copied from Glob's internals. mkClass :: Word -> Maybe (String,Word) mkClass xs = let (range, rest) = break (isLit ']') xs in if null rest then Nothing else if null range then let (range', rest') = break (isLit ']') (tail rest) in if null rest' then Nothing else do x <- cr' range' return (x,tail rest') else do x <- cr' range return (x,tail rest) where cr' s = Just $ "["++movedash (filter (not . isQuot) s)++"]" isLit c x = case x of { Literal c' -> c==c'; _ -> False } isQuot x = case x of { Quote _ -> True; _ -> False } quoted c x = case x of Quoted (Quoted x) -> quoted c $ Quoted x Quoted (Literal c') -> c==c' _ -> False movedash s = let (d,nd) = partition (quoted '-') s bad = null d || (isLit '-' $ head $ reverse s) in map fromLexeme $ if bad then nd else nd++d fromLexeme x = case x of { Literal c -> c; Quoted q -> fromLexeme q } {- expandGlob :: MonadIO m => Word -> m [FilePath] expandGlob w = case mkGlob w of Nothing -> return [] Just g -> case G.unPattern g of (G.PathSeparator:_) -> liftIO $ do hits <- G.globDir [g] "/" -- unix...? let ps = [pathSeparator] return $ head $ fst $ hits _ -> liftIO $ do cwd <- getCurrentDirectory hits <- G.globDir [g] cwd let ps = [pathSeparator] return $ map (removePrefix $ cwd++ps) $ head $ fst $ hits where removePrefix pre s | pre `isPrefixOf` s = drop (length pre) s | otherwise = s -} -- Two issues: we can deal with them here... -- 1. if glob starts with a dirsep then we need to go relative to root... -- (what about in windows?) -- 2. if not, then we should remove the absolute path from the beginning of -- the results (should be easy w/ a map) {- -- This is a sort of default matcher, but needn't be used... matchGlob :: MonadIO m => Glob -> m [FilePath] matchGlob g = matchG' [] $ splitDir return $ do -- now we're in the list monad... where d = splitDir g splitDir (c:xs) | ips c = []:splitDir (dropWhile ips xs) splitDir xs = filter (not . null) $ filter (not . all ips) $ groupBy ((==) on ips) xs ips x = case x of { Lit c -> isPathSeparator c; _ -> False } -} ---------------------------------------------------------------------- -- This is copied from above, but it's used separately for non-glob -- -- pattern matching. Maybe we'll combine them someday. -- ---------------------------------------------------------------------- match' :: Regex -> String -> Maybe String match' regex s = listToMaybe =<< match regex s [] matchPattern :: Word -> String -> Bool matchPattern w s = case mkRegex False False "^" "$" w of Just r -> isJust $ match r s [] Nothing -> fromLit w == s removePrefix :: Bool -- ^greediness -> Word -- ^pattern -> String -- ^haystack -> String removePrefix g n h = case mkRegex g False "^" "" n of Just r -> case match' r h of Just m -> drop (length m) h Nothing -> h Nothing -> if l `isPrefixOf` h then drop (length l) h else h where l = fromLit n removeSuffix :: Bool -- ^greediness -> Word -- ^pattern -> String -- ^haystack -> String removeSuffix g n h = case mkRegex g True "^" "" n of Just r -> case match' r hr of Just m -> reverse $ drop (length m) hr Nothing -> h Nothing -> if l `isPrefixOf` hr then reverse $ drop (length l) hr else h where l = reverse $ fromLit n hr = reverse h mkRegex :: Bool -- ^greedy? -> Bool -- ^reverse? (before adding pre/suff) -> String -- ^prefix -> String -- ^suffix -> Word -- ^pattern -> Maybe Regex mkRegex g r pre suf w = case runState (mkG w) False of (s,True) -> mk' $ concat $ affix $ (if r then reverse else id) s _ -> Nothing where mkG [] = return [] mkG (Literal '[':xs) = case mkClass xs of Just (g,xs') -> fmap (g:) $ mkG xs' Nothing -> fmap ((mkLit '['):) $ mkG xs mkG (Literal '*':Literal '*':xs) = mkG $ Literal '*':xs mkG (Literal '*':xs) = put True >> fmap (".*":) (mkG xs) mkG (Literal '?':xs) = put True >> fmap (".":) (mkG xs) mkG (Literal c:xs) = fmap (mkLit c:) $ mkG xs mkG (Quoted (Literal c):xs) = fmap (mkLit c:) $ mkG xs mkG (Quoted q:xs) = mkG $ q:xs mkG (Quote _:xs) = mkG xs mkLit c | c `elem` "[](){}|^$.*+?\\" = ['\\',c] | otherwise = [c] affix s = pre:s++[suf] mk' s = case compileM s (if g then [] else [ungreedy]) of Left _ -> Nothing Right regex -> Just regex fromLit :: Word -> String fromLit = concatMap $ \l -> case l of Literal c -> [c] Quoted q -> fromLit [q] _ -> []
MgaMPKAy/language-sh
Language/Sh/Glob.hs
bsd-3-clause
8,582
0
17
3,513
2,262
1,163
1,099
113
14
-- {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} -- we are deriving Monoid instance for Config type -- {-# OPTIONS_GHC -fno-warn-missing-methods #-} module System.EtCetera.Redis.V2_8 where import Control.Applicative (Alternative) import Control.Arrow (first) import Control.Category (Category, id, (.)) import Control.Error (note) import Control.Lens (DefName(..), Lens', lensField, lensRules, makeLensesWith, over, set, view, (&), (.~), (??)) import Data.List (foldl') import Data.Monoid ((<>)) import qualified Data.Set as Set import Generics.Deriving.Base (Generic) import Generics.Deriving.Monoid (gmappend, gmempty, GMonoid) import Generics.Deriving.Show (gshow, GShow) import Language.Haskell.TH (mkName, Name, nameBase) import Prelude hiding ((.), id) import Text.Boomerang.Combinators (manyl, manyr, opt, push, rCons, rList, rList1, rListSep, rNil, somel, somer) import Text.Boomerang.HStack (arg, (:-)(..)) import Text.Boomerang.Prim (Boomerang(..), Parser(..), prs, xpure) import Text.Boomerang.String (anyChar, digit, lit, int, StringBoomerang, StringError) import System.EtCetera.Internal (Optional(..), repeatableScalar, scalar, vector) import System.EtCetera.Internal.Prim (Ser(..), toPrs) import System.EtCetera.Internal.Boomerangs (eol, ignoreWhen, noneOf, oneOf, parseString, simpleSumBmg, whiteSpace, word, (<?>)) type IP = String type Port = Int data SizeUnit = K | M | G | Kb | Mb | Gb deriving (Eq, Read, Show) data Size = Size Int SizeUnit deriving (Eq, Show) sizeBmg :: StringBoomerang r (Size :- r) sizeBmg = xpure (arg (arg (:-)) Size) (\(Size i u :- r) -> Just (i :- u :- r)) . int . simpleSumBmg ["k", "m", "g", "kb", "mb", "gb"] data RenameCommand = RenameCommand String String | DisableCommand String deriving (Eq, Show) renameCommandBmg :: StringBoomerang r (RenameCommand :- r) renameCommandBmg = c . string . ws . string where c = xpure (arg (arg (:-)) (\c n -> if n == "\"\"" then DisableCommand c else RenameCommand c n)) (\case (DisableCommand c :- r) -> Just (c :- "\"\"" :- r) (RenameCommand o n :- r) -> Just (o :- n :- r)) data MemoryPolicy = VolatileLru | AllkeysLru | VolatileRandom | AllkeysRandom | VolatileTtl | Noeviction deriving (Eq, Show) memoryPolicyBmg :: StringBoomerang r (MemoryPolicy :- r) memoryPolicyBmg = xpure (arg (:-) p) (\(mp :- r) -> (Just (s mp :- r))) . (word "volatile-lru" <> word "allkeys-lru" <> word "volatile-random" <> word "allkeys-random" <> word "volatile-ttl" <> word "noeviction") where p "volatile-lru" = VolatileLru p "allkeys-lru" = AllkeysLru p "volatile-random" = VolatileRandom p "allkeys-random" = AllkeysRandom p "volatile-ttl" = VolatileTtl p "noeviction" = Noeviction s VolatileLru = "volatile-lru" s AllkeysLru = "allkeys-lru" s VolatileRandom = "volatile-random" s AllkeysRandom = "allkeys-random" s VolatileTtl = "volatile-ttl" s Noeviction = "noeviction" data LogLevel = Debug | Verbose | Notice | Warning deriving (Eq, Read, Show) logLevelBmg :: StringBoomerang r (LogLevel :- r) logLevelBmg = simpleSumBmg ["debug", "verbose", "notice", "warning"] data SyslogFacility = User | Local0 | Local1 | Local2 | Local3 | Local4 | Local5 | Local6 | Local7 deriving (Eq, Read, Show) syslogFacilityBmg :: StringBoomerang r (SyslogFacility :- r) syslogFacilityBmg = simpleSumBmg [ "user", "local0", "local1", "local2", "local3" , "local4", "local5", "local6" , "local7"] data Save = Save Int Int | SaveReset deriving (Eq, Show) saveBmg = s <> sr where s = xpure (arg (arg (:-)) Save) (\case (Save s c :- r) -> Just (s :- c :- r) otherwise -> Nothing) . int . ws . int sr = push SaveReset . lit "\"\"" string :: StringBoomerang r (String :- r) string = rList1 (noneOf "\n \t") slaveOfBmg :: StringBoomerang r ((IP, Port) :- r) slaveOfBmg = xpure (arg (arg (:-)) (\ip port -> (ip, port))) (\((ip, port) :- r) -> Just (ip :- port :- r)) . string . ws . int data AppendFsync = Always | No | Everysec deriving (Eq, Read, Show) appendFsyncBmg :: StringBoomerang r (AppendFsync :- r) appendFsyncBmg = simpleSumBmg ["always", "no", "everysec"] data KeyspaceEvnType = KeyspaceEvns | KeyeventEvns | GenericCmds | StringCmds | ListCmds | SetCmds | HashCmds | SortedSetCmds | ExpiredEvns | EvictedEvns deriving (Eq, Ord, Show) -- can be used as a A keyspaceEvnA = Set.fromList [ GenericCmds, StringCmds, ListCmds , SetCmds , HashCmds, SortedSetCmds , ExpiredEvns, EvictedEvns ] data KeyspaceEvn = SetKespaceEvns (Set.Set KeyspaceEvnType) | DisableKeyspaceEvns deriving (Eq, Show) keyspaceEvnTypeBmg :: StringBoomerang (String :- r) (Set.Set KeyspaceEvnType :- r) keyspaceEvnTypeBmg = xpure (arg (:-) parse) (\(es :- r) -> Just (serialize es :- r)) where serialize = foldl' (\r e -> s e : r) "" where s KeyspaceEvns = 'K' s KeyeventEvns = 'E' s GenericCmds = 'g' s StringCmds = '$' s ListCmds = 'l' s SetCmds = 's' s HashCmds = 'h' s SortedSetCmds = 'z' s ExpiredEvns = 'x' s EvictedEvns = 'e' parse = foldl' (flip p) Set.empty where p 'K' = Set.insert KeyspaceEvns p 'E' = Set.insert KeyeventEvns p 'g' = Set.insert GenericCmds p '$' = Set.insert StringCmds p 'l' = Set.insert ListCmds p 's' = Set.insert SetCmds p 'h' = Set.insert HashCmds p 'z' = Set.insert SortedSetCmds p 'x' = Set.insert ExpiredEvns p 'e' = Set.insert EvictedEvns p 'A' = Set.union keyspaceEvnA keyspaceEvnBmg :: StringBoomerang r (KeyspaceEvn :- r) keyspaceEvnBmg = (d . word "\"\"") <> (e . keyspaceEvnTypeBmg . rList1 (oneOf "KEg$lshzxeA")) where d = xpure (arg (:-) (const DisableKeyspaceEvns)) (\case (DisableKeyspaceEvns :- r) -> Just ("\"\"" :- r) otherwise -> Nothing) e = xpure (arg (:-) SetKespaceEvns) (\case (SetKespaceEvns s :- r) -> Just (s :- r) otherwise -> Nothing) data ClientOutputBufferLimitSize = ClientOutputBufferLimitSize { soft :: Size , hard :: Size , softSecods :: Int } deriving (Eq, Show) clientOutputBufferLimitBmg :: StringBoomerang r (ClientOutputBufferLimitSize :- r) clientOutputBufferLimitBmg = c . sizeBmg . ws . sizeBmg . ws . int where c = xpure (arg (arg (arg (:-))) ClientOutputBufferLimitSize) (\(ClientOutputBufferLimitSize s h ss :- r) -> Just (s :- h :- ss :- r)) strings :: StringBoomerang r ([String] :- r) strings = rListSep string (somer whiteSpace) bool :: StringBoomerang r (Bool :- r) bool = xpure (arg (:-) (\case "no" -> False "yes" -> True)) (\case (True :- r) -> Just ("yes" :- r) (False :- r) -> Just ("no" :- r)) . (word "yes" <> word "no") ws = somel whiteSpace data RedisConfig = RedisConfig { include :: [FilePath] , daemonize :: Optional Bool , port :: Optional Int , pidFile :: Optional FilePath , tcpBacklog :: Optional Int , bind :: [String] , unixSocket :: Optional FilePath -- XXX: add more type safety , unixSocketPerm :: Optional String , timeout :: Optional Int , tcpKeepAlive :: Optional Int , logLevel :: Optional LogLevel , logFile :: Optional FilePath , syslogEnabled :: Optional Bool , syslogIdent :: Optional String , syslogFacility :: Optional SyslogFacility , databases :: Optional Int , save :: [Save] , stopWritesOnBgsaveError :: Optional Bool , rdbCompression :: Optional Bool , rdbChecksum :: Optional Bool , dbFilename :: Optional FilePath , dir :: Optional FilePath , slaveOf :: Optional (IP, Port) , masterAuth :: Optional String , slaveServeStaleData :: Optional Bool , slaveReadOnly :: Optional Bool , replDisklessSync :: Optional Bool , replDisklessSyncDelay :: Optional Int , replPingSlavePeriod :: Optional Int , replTimeout :: Optional Int , replDisableTcpNoDelay :: Optional Bool , replBacklogSize :: Optional Size , replBacklogTtl :: Optional Int , slavePriority :: Optional Int , minSlavesToWrite :: Optional Int , minSlavesMaxLag :: Optional Int , requirePass :: Optional String , renameCommand :: [RenameCommand] , maxClients :: Optional Int , maxMemory :: Optional Int , maxMemoryPolicy :: Optional MemoryPolicy , maxMemorySamples :: Optional Int , appendOnly :: Optional Bool , appendFilename :: Optional String , appendFsync :: Optional AppendFsync , noAppendFsyncOnRewrite :: Optional Bool , autoAofRewritePercentage :: Optional Int , autoAofRewriteMinSize :: Optional Size , aofLoadTruncated :: Optional Bool , luaTimeLimit :: Optional Int , slowlogLogSlowerThan :: Optional Int , slowlogMaxLen :: Optional Int , latencyMonitorThreshold :: Optional Int , notifyKeyspaceEvents :: Optional KeyspaceEvn , hashMaxZiplistEntries :: Optional Int , hashMaxZiplistValue :: Optional Int , listMaxZiplistEntries :: Optional Int , listMaxZiplistValue :: Optional Int , setMaxIntsetEntries :: Optional Int , zsetMaxZiplistEntries :: Optional Int , zsetMaxZiplistValue :: Optional Int , hllSparseMaxBytes :: Optional Int , activeRehashing :: Optional Bool -- split client-output-buffer-limit into -- three differnet fields , clientOutputBufferLimitNormal :: Optional ClientOutputBufferLimitSize , clientOutputBufferLimitSlave :: Optional ClientOutputBufferLimitSize , clientOutputBufferLimitPubSub :: Optional ClientOutputBufferLimitSize , hz :: Optional Int , aofRewriteIncrementalFsync :: Optional Bool } deriving (Eq, Generic, Show) instance GMonoid RedisConfig instance Monoid RedisConfig where mempty = gmempty mappend = gmappend makeLensesWith ?? ''RedisConfig $ lensRules & lensField .~ \_ _ name -> [TopName (mkName $ nameBase name ++ "Lens")] emptyConfig = mempty data ParsingError = ParserError StringError deriving (Eq, Show) data SerializtionError = SerializtionError deriving (Eq, Show) optionBoomerang label valueBoomerang = lit label . ws . valueBoomerang (anyOptionParser, serializer) = repeatableScalar includeLens (optionBoomerang "include" string) . scalar daemonizeLens (optionBoomerang "daemonize" bool) . scalar portLens (optionBoomerang "port" int) . scalar pidFileLens (optionBoomerang "pidfile" string) . scalar tcpBacklogLens (optionBoomerang "tcp-backlog" int) . vector bindLens (optionBoomerang "bind" strings) . scalar unixSocketLens (optionBoomerang "unixsocket" string) . scalar unixSocketPermLens (optionBoomerang "unixsocketperm" string) . scalar timeoutLens (optionBoomerang "timeout" int) . scalar tcpKeepAliveLens (optionBoomerang "tcp-keepalive" int) . scalar logLevelLens (optionBoomerang "loglevel" logLevelBmg) . scalar logFileLens (optionBoomerang "logfile" string) . scalar syslogEnabledLens (optionBoomerang "syslog-enabled" bool) . scalar syslogIdentLens (optionBoomerang "syslog-ident" string) . scalar syslogFacilityLens (optionBoomerang "syslog-facility" syslogFacilityBmg) . scalar databasesLens (optionBoomerang "databases" int) . repeatableScalar saveLens (optionBoomerang "save" saveBmg) . scalar stopWritesOnBgsaveErrorLens (optionBoomerang "stop-writes-on-bg-save-error" bool) . scalar rdbCompressionLens (optionBoomerang "rdbcompression" bool) . scalar rdbChecksumLens (optionBoomerang "rdbchecksum" bool) . scalar dbFilenameLens (optionBoomerang "dbfilename" string) . scalar dirLens (optionBoomerang "dir" string) . scalar slaveOfLens (optionBoomerang "slaveof" slaveOfBmg) . scalar masterAuthLens (optionBoomerang "masterauth" string) . scalar slaveServeStaleDataLens (optionBoomerang "slave-serve-stale-data" bool) . scalar slaveReadOnlyLens (optionBoomerang "slave-read-only" bool) . scalar replDisklessSyncLens (optionBoomerang "repl-diskless-sync" bool) . scalar replDisklessSyncDelayLens (optionBoomerang "repl-diskless-sync-delay" int) . scalar replPingSlavePeriodLens (optionBoomerang "repl-ping-slave-period" int) . scalar replTimeoutLens (optionBoomerang "repl-timeout" int) . scalar replDisableTcpNoDelayLens (optionBoomerang "repl-disable-tcp-no-delay" bool) . scalar replBacklogSizeLens (optionBoomerang "repl-backlog-size" sizeBmg) . scalar replBacklogTtlLens (optionBoomerang "repl-backlog-ttl" int) . scalar slavePriorityLens (optionBoomerang "slave-priority" int) . scalar minSlavesToWriteLens (optionBoomerang "min-slaves-to-write" int) . scalar minSlavesMaxLagLens (optionBoomerang "min-slaves-max-lag" int) . scalar requirePassLens (optionBoomerang "requirepass" string) . repeatableScalar renameCommandLens (optionBoomerang "rename-command" renameCommandBmg) . scalar maxClientsLens (optionBoomerang "maxclients" int) . scalar maxMemoryLens (optionBoomerang "maxmemory" int) . scalar maxMemoryPolicyLens (optionBoomerang "maxmemory-policy" memoryPolicyBmg) . scalar maxMemorySamplesLens (optionBoomerang "maxmemory-samples" int) . scalar appendOnlyLens (optionBoomerang "appendonly" bool) . scalar appendFilenameLens (optionBoomerang "appendfilename" string) . scalar appendFsyncLens (optionBoomerang "appendfsync" appendFsyncBmg) . scalar noAppendFsyncOnRewriteLens (optionBoomerang "no-appendfsync-on-rewrite" bool) . scalar autoAofRewritePercentageLens (optionBoomerang "auto-aof-rewrite-percentage" int) . scalar autoAofRewriteMinSizeLens (optionBoomerang "auto-aof-rewrite-min-size" sizeBmg) . scalar aofLoadTruncatedLens (optionBoomerang "aof-load-truncated" bool) . scalar luaTimeLimitLens (optionBoomerang "lua-time-limit" int) . scalar slowlogLogSlowerThanLens (optionBoomerang "slowlog-log-slower-than" int) . scalar slowlogMaxLenLens (optionBoomerang "slowlog-max-len" int) . scalar latencyMonitorThresholdLens (optionBoomerang "latency-monitor-threshold" int) . scalar notifyKeyspaceEventsLens (optionBoomerang "notify-keyspace-events" keyspaceEvnBmg) . scalar hashMaxZiplistEntriesLens (optionBoomerang "hash-max-ziplist-entries" int) . scalar hashMaxZiplistValueLens (optionBoomerang "hash-max-ziplist-value" int) . scalar listMaxZiplistEntriesLens (optionBoomerang "list-max-ziplist-entries" int) . scalar listMaxZiplistValueLens (optionBoomerang "list-max-ziplist-value" int) . scalar setMaxIntsetEntriesLens (optionBoomerang "set-max-intset-entries" int) . scalar zsetMaxZiplistEntriesLens (optionBoomerang "zset-max-ziplist-entries" int) . scalar zsetMaxZiplistValueLens (optionBoomerang "zset-max-ziplist-value" int) . scalar hllSparseMaxBytesLens (optionBoomerang "hll-sparse-max-bytes" int) . scalar activeRehashingLens (optionBoomerang "activerehashing" bool) . scalar clientOutputBufferLimitNormalLens (optionBoomerang "client-output-buffer-limit" (lit "normal" . ws . clientOutputBufferLimitBmg)) . scalar clientOutputBufferLimitSlaveLens (optionBoomerang "client-output-buffer-limit" (lit "slave" . ws . clientOutputBufferLimitBmg)) . scalar clientOutputBufferLimitPubSubLens (optionBoomerang "client-output-buffer-limit" (lit "pubsub" . ws . clientOutputBufferLimitBmg)) . scalar hzLens (optionBoomerang "hz" int) . scalar aofRewriteIncrementalFsyncLens (optionBoomerang "aof-rewrite-incremental-fsync" bool) $ (mempty, id) parser = -- comment ((toPrs (lit "#" . manyr (ignoreWhen (/= '\n'))) -- only white characters line <> toPrs ws -- option <> anyOptionParser <?> (\t -> "can't parse any option from this line: " ++ takeWhile (/= '\n') t)) -- end of line and more options -- or optinal end of line . (id <> eol' <> (eol' . parser))) -- completely empty line (I don't want to handle this -- above with `manyl witeSpace` because always matches -- and causes errors information loss <> (eol' . (parser <> id)) where -- used only for parser generation eol' = toPrs eol parse :: String -> Either ParsingError RedisConfig parse conf = either (Left . ParserError) Right (parseString (parser . toPrs (push emptyConfig)) conf) serialize :: RedisConfig -> Either SerializtionError String serialize redisConfig = note SerializtionError . fmap (($ "") . fst) . s $ (redisConfig :- ()) where Ser s = serializer
paluh/et-cetera
src/System/EtCetera/Redis/V2_8.hs
bsd-3-clause
17,130
0
75
3,650
4,747
2,542
2,205
367
20
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module DFAMin (minimizeDFA) where import AbsSyn import Data.Map (Map) import qualified Data.Map as Map import Data.IntSet (IntSet) import qualified Data.IntSet as IS import Data.IntMap (IntMap) import qualified Data.IntMap as IM import qualified Data.List as List -- % Hopcroft's Algorithm for DFA minimization (cut/pasted from Wikipedia): -- % X refines Y into Y1 and Y2 means -- % Y1 := Y ∩ X -- % Y2 := Y \ X -- % where both Y1 and Y2 are nonempty -- -- P := {{all accepting states}, {all nonaccepting states}}; -- Q := {{all accepting states}}; -- while (Q is not empty) do -- choose and remove a set A from Q -- for each c in ∑ do -- let X be the set of states for which a transition on c leads to a state in A -- for each set Y in P for which X refines Y into Y1 and Y2 do -- replace Y in P by the two sets Y1 and Y2 -- if Y is in Q -- replace Y in Q by the same two sets -- else -- add the smaller of the two sets to Q -- end; -- end; -- end; -- -- % X is a preimage of A under transition function. -- % observation : Q is always subset of P -- % let R = P \ Q. then following algorithm is the equivalent of the Hopcroft's Algorithm -- -- R := {{all nonaccepting states}}; -- Q := {{all accepting states}}; -- while (Q is not empty) do -- choose a set A from Q -- remove A from Q and add it to R -- for each c in ∑ do -- let X be the set of states for which a transition on c leads to a state in A -- for each set Y in R for which X refines Y into Y1 and Y2 do -- replace Y in R by the greater of the two sets Y1 and Y2 -- add the smaller of the two sets to Q -- end; -- for each set Y in Q for which X refines Y into Y1 and Y2 do -- replace Y in Q by the two sets Y1 and Y2 -- end; -- end; -- end; -- -- % The second for loop that iterates over R mutates Q, -- % but it does not affect the third for loop that iterates over Q. -- % Because once X refines Y into Y1 and Y2, Y1 and Y2 can't be more refined by X. minimizeDFA :: forall a. Ord a => DFA Int a -> DFA Int a minimizeDFA dfa@(DFA { dfa_start_states = starts, dfa_states = statemap }) = DFA { dfa_start_states = starts, dfa_states = Map.fromList states } where equiv_classes :: [EquivalenceClass] equiv_classes = groupEquivStates dfa numbered_states :: [(Int, EquivalenceClass)] numbered_states = number (length starts) equiv_classes -- assign each state in the minimized DFA a number, making -- sure that we assign the numbers [0..] to the start states. number :: Int -> [EquivalenceClass] -> [(Int, EquivalenceClass)] number _ [] = [] number n (ss:sss) = case filter (`IS.member` ss) starts of [] -> (n,ss) : number (n+1) sss starts' -> map (,ss) starts' ++ number n sss -- if one of the states of the minimized DFA corresponds -- to multiple starts states, we just have to duplicate -- that state. states :: [(Int, State Int a)] states = [ let old_states = map (lookup statemap) (IS.toList equiv) accs = map fix_acc (state_acc (head old_states)) -- accepts should all be the same out = IM.fromList [ (b, get_new old) | State _ out <- old_states, (b,old) <- IM.toList out ] in (n, State accs out) | (n, equiv) <- numbered_states ] fix_acc :: Accept a -> Accept a fix_acc acc = acc { accRightCtx = fix_rctxt (accRightCtx acc) } fix_rctxt :: RightContext SNum -> RightContext SNum fix_rctxt (RightContextRExp s) = RightContextRExp (get_new s) fix_rctxt other = other lookup :: Ord k => Map k v -> k -> v lookup m k = Map.findWithDefault (error "minimizeDFA") k m get_new :: Int -> Int get_new = lookup old_to_new old_to_new :: Map Int Int old_to_new = Map.fromList [ (s,n) | (n,ss) <- numbered_states, s <- IS.toList ss ] type EquivalenceClass = IntSet groupEquivStates :: forall a. Ord a => DFA Int a -> [EquivalenceClass] groupEquivStates DFA { dfa_states = statemap } = go init_r init_q where accepting, nonaccepting :: Map Int (State Int a) (accepting, nonaccepting) = Map.partition acc statemap where acc (State as _) = not (List.null as) nonaccepting_states :: EquivalenceClass nonaccepting_states = IS.fromList (Map.keys nonaccepting) -- group the accepting states into equivalence classes accept_map :: Map [Accept a] [Int] accept_map = {-# SCC "accept_map" #-} List.foldl' (\m (n,s) -> Map.insertWith (++) (state_acc s) [n] m) Map.empty (Map.toList accepting) accept_groups :: [EquivalenceClass] accept_groups = map IS.fromList (Map.elems accept_map) init_r, init_q :: [EquivalenceClass] init_r -- Issue #71: each EquivalenceClass needs to be a non-empty set | IS.null nonaccepting_states = [] | otherwise = [nonaccepting_states] init_q = accept_groups -- a map from token T to -- a map from state S to the set of states that transition to -- S on token T -- bigmap is an inversed transition function classified by each input token. -- the codomain of each inversed function is a set of states rather than single state -- since a transition function might not be an injective. -- This is a cache of the information needed to compute xs below bigmap :: IntMap (IntMap EquivalenceClass) bigmap = IM.fromListWith (IM.unionWith IS.union) [ (i, IM.singleton to (IS.singleton from)) | (from, state) <- Map.toList statemap, (i,to) <- IM.toList (state_out state) ] -- The outer loop: recurse on each set in R and Q go :: [EquivalenceClass] -> [EquivalenceClass] -> [EquivalenceClass] go r [] = r go r (a:q) = uncurry go $ List.foldl' go0 (a:r,q) xs where preimage :: IntMap EquivalenceClass -- inversed transition function -> EquivalenceClass -- subset of codomain of original transition function -> EquivalenceClass -- preimage of given subset #if MIN_VERSION_containers(0, 6, 0) preimage invMap a = IS.unions (IM.restrictKeys invMap a) #else preimage invMap a = IS.unions [IM.findWithDefault IS.empty s invMap | s <- IS.toList a] #endif xs :: [EquivalenceClass] xs = [ x | invMap <- IM.elems bigmap , let x = preimage invMap a , not (IS.null x) ] refineWith :: EquivalenceClass -- preimage set that bisects the input equivalence class -> EquivalenceClass -- input equivalence class -> Maybe (EquivalenceClass, EquivalenceClass) -- refined equivalence class refineWith x y = if IS.null y1 || IS.null y2 then Nothing else Just (y1, y2) where y1 = IS.intersection y x y2 = IS.difference y x go0 (r,q) x = go1 r [] [] where -- iterates over R go1 [] r' q' = (r', go2 q q') go1 (y:r) r' q' = case refineWith x y of Nothing -> go1 r (y:r') q' Just (y1, y2) | IS.size y1 <= IS.size y2 -> go1 r (y2:r') (y1:q') | otherwise -> go1 r (y1:r') (y2:q') -- iterates over Q go2 [] q' = q' go2 (y:q) q' = case refineWith x y of Nothing -> go2 q (y:q') Just (y1, y2) -> go2 q (y1:y2:q')
simonmar/alex
src/DFAMin.hs
bsd-3-clause
8,226
0
19
2,757
1,724
946
778
109
7
module Main where eight = 1 + ( 2 * 2 ) + 3
YoshikuniJujo/toyhaskell_haskell
examples/eight.hs
bsd-3-clause
45
0
8
15
24
14
10
2
1
{-# language CPP #-} -- | = Name -- -- VK_GOOGLE_surfaceless_query - instance extension -- -- == VK_GOOGLE_surfaceless_query -- -- [__Name String__] -- @VK_GOOGLE_surfaceless_query@ -- -- [__Extension Type__] -- Instance extension -- -- [__Registered Extension Number__] -- 434 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_surface@ -- -- [__Special Use__] -- -- - <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse OpenGL \/ ES support> -- -- [__Contact__] -- -- - Shahbaz Youssefi -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_GOOGLE_surfaceless_query] @syoussefi%0A<<Here describe the issue or question you have about the VK_GOOGLE_surfaceless_query extension>> > -- -- [__Extension Proposal__] -- <https://github.com/KhronosGroup/Vulkan-Docs/tree/main/proposals/VK_GOOGLE_surfaceless_query.asciidoc VK_GOOGLE_surfaceless_query> -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2021-12-14 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Ian Elliott, Google -- -- - Shahbaz Youssefi, Google -- -- - James Jones, NVIDIA -- -- == Description -- -- This extension allows the -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfaceFormatsKHR' -- and -- 'Vulkan.Extensions.VK_KHR_surface.getPhysicalDeviceSurfacePresentModesKHR' -- functions to accept 'Vulkan.Core10.APIConstants.NULL_HANDLE' as their -- @surface@ parameter, allowing potential surface formats, colorspaces and -- present modes to be queried without providing a surface. Identically, -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.getPhysicalDeviceSurfaceFormats2KHR' -- and -- 'Vulkan.Extensions.VK_EXT_full_screen_exclusive.getPhysicalDeviceSurfacePresentModes2EXT' -- would accept 'Vulkan.Core10.APIConstants.NULL_HANDLE' in -- 'Vulkan.Extensions.VK_KHR_get_surface_capabilities2.PhysicalDeviceSurfaceInfo2KHR'::@surface@. -- __This can only be supported on platforms where the results of these -- queries are surface-agnostic and a single presentation engine is the -- implicit target of all present operations__. -- -- == New Enum Constants -- -- - 'GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME' -- -- - 'GOOGLE_SURFACELESS_QUERY_SPEC_VERSION' -- -- == Version History -- -- - Revision 1, 2021-12-14 (Shahbaz Youssefi) -- -- - Internal revisions -- -- == See Also -- -- No cross-references are available -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_GOOGLE_surfaceless_query Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_GOOGLE_surfaceless_query ( GOOGLE_SURFACELESS_QUERY_SPEC_VERSION , pattern GOOGLE_SURFACELESS_QUERY_SPEC_VERSION , GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME , pattern GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME ) where import Data.String (IsString) type GOOGLE_SURFACELESS_QUERY_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_GOOGLE_SURFACELESS_QUERY_SPEC_VERSION" pattern GOOGLE_SURFACELESS_QUERY_SPEC_VERSION :: forall a . Integral a => a pattern GOOGLE_SURFACELESS_QUERY_SPEC_VERSION = 1 type GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME = "VK_GOOGLE_surfaceless_query" -- No documentation found for TopLevel "VK_GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME" pattern GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME = "VK_GOOGLE_surfaceless_query"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_GOOGLE_surfaceless_query.hs
bsd-3-clause
3,978
0
8
695
205
159
46
-1
-1
module Language.Asdf.Lexer ( symbol , parens , brackets , natural , naturalOrFloat , rational , stringLiteral , operator , identifier , reserved , reservedOp , whiteSpace , comma , lexer ) where import Control.Monad import Text.Parsec import Text.Parsec.Language import qualified Text.Parsec.Token as Token lexerStyle :: (Monad m) => GenLanguageDef String u m lexerStyle = Token.LanguageDef { Token.commentStart = "{-" , Token.commentEnd = "-}" , Token.commentLine = "//" , Token.nestedComments = True , Token.identStart = letter , Token.identLetter = alphaNum <|> oneOf "_'#" , Token.opStart = Token.opLetter lexerStyle , Token.opLetter = oneOf "~!@$%^&*-+/?|=<>" , Token.reservedOpNames= ["::"] , Token.reservedNames = [ "return", "struct", "union" , "for", "while", "if", "else" , "do", "var", "foreign", "def"] , Token.caseSensitive = True } lexer :: (Monad m) => Token.GenTokenParser String u m lexer = Token.makeTokenParser lexerStyle symbol :: (Monad m) => String -> ParsecT String u m String symbol = Token.symbol lexer parens, brackets :: (Monad m) => ParsecT String u m a -> ParsecT String u m a parens = Token.parens lexer brackets = Token.brackets lexer natural :: (Monad m) => ParsecT String u m Integer natural = Token.natural lexer naturalOrFloat :: (Monad m) => ParsecT String u m (Either Integer Double) naturalOrFloat = Token.naturalOrFloat lexer rational :: (Monad m) => ParsecT String u m Rational rational = liftM (either toRational toRational) naturalOrFloat stringLiteral, identifier, operator, comma :: (Monad m) => ParsecT String u m String stringLiteral = Token.stringLiteral lexer operator = Token.operator lexer identifier = Token.identifier lexer comma = Token.comma lexer reservedOp :: (Monad m) => String -> ParsecT String u m () reservedOp = Token.reservedOp lexer reserved :: (Monad m) => String -> ParsecT String u m () reserved = Token.reserved lexer whiteSpace :: (Monad m) => ParsecT String u m () whiteSpace = Token.whiteSpace lexer
sw17ch/Asdf
src/Language/Asdf/Lexer.hs
bsd-3-clause
2,688
0
8
1,010
670
373
297
57
1
module Main where fibs = 0 : 1 : zipWith (+) fibs (tail fibs) fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) f :: Int -> Int f x = if fib 100 > 10 then f (x + 1) else 0 main :: IO () main = if fib 10 == fibs !! 10 then putStrLn "Yay!" else putStrLn "Boo!"
yav/sequent-core
examples/Example.hs
bsd-3-clause
264
0
8
74
162
84
78
9
2
module NestedIO where import Data.Time.Calendar import Data.Time.Clock import System.Random huehue :: IO (Either (IO Int) (IO ())) huehue = do t <- getCurrentTime let (_, _, dayOfMonth) = toGregorian (utctDay t) case even dayOfMonth of True -> return $ Left randomIO False -> return $ Right (putStrLn "no soup for you") {- blah <- huehue either (>>= print) id blah -}
chengzh2008/hpffp
src/ch29-IO/nestedIO.hs
bsd-3-clause
385
0
13
78
134
69
65
11
2
{-| Module : $Header$ Description : Adapter for communicating with Slack via its real time messaging API Copyright : (c) Justus Adam, 2016 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : POSIX See http://marvin.readthedocs.io/en/latest/adapters.html#real-time-messaging-api for documentation of this adapter. -} module Marvin.Adapter.Slack.RTM ( SlackAdapter, RTM , SlackUserId(..), SlackChannelId(..) , MkSlack , SlackRemoteFile(..), SlackLocalFile(..) , HasTitle(..), HasPublicPermalink(..), HasEditable(..), HasPublic(..), HasUser(..), HasPrivateUrl(..), HasComment(..) ) where import Control.Concurrent.Async.Lifted (async, link) import Control.Concurrent.Chan.Lifted import Control.Concurrent.MVar.Lifted import Control.Exception.Lifted import Control.Monad import Control.Monad.Except import Control.Monad.Logger import Data.Aeson hiding (Error) import Data.Aeson.Types hiding (Error) import qualified Data.ByteString.Lazy.Char8 as BS import Data.IORef.Lifted import Data.Maybe (fromMaybe) import qualified Data.Text as T import Lens.Micro.Platform hiding ((.=)) import Marvin.Adapter import Marvin.Adapter.Slack.Internal.Common import Marvin.Adapter.Slack.Internal.Types import Marvin.Interpolate.Text import Network.URI import Network.WebSockets import Network.Wreq import Text.Read (readMaybe) import Wuss runConnectionLoop :: Chan (InternalType RTM) -> MVar Connection -> AdapterM (SlackAdapter RTM) () runConnectionLoop eventChan connectionTracker = do messageChan <- newChan a <- async $ forever $ do msg <- readChan messageChan case eitherDecode msg >>= parseEither eventParser of -- changed it do logDebug for now as we still have events that we do not handle -- all those will show up as errors and I want to avoid polluting the log -- once we are sure that all events are handled in some way we can make this as error again -- (which it should be) Left e -> logDebugN $(isT "Error parsing json: #{e} original data: #{rawBS msg}") Right v -> writeChan eventChan v link a forever $ do token <- requireFromAdapterConfig "token" logDebugN "initializing socket" r <- liftIO $ post "https://slack.com/api/rtm.start" [ "token" := (token :: T.Text) ] case eitherDecode (r^.responseBody) of Left err -> do logErrorN $(isT "Error decoding rtm json #{err}") logDebugN $(isT "#{r^.responseBody}") Right js -> do port <- case uriPort authority_ of v@(':':rest_) -> maybe (portOnErr v) return $ readMaybe rest_ v -> portOnErr v logDebugN $(isT "connecting to socket '#{uri}'") logFn <- askLoggerIO liftIO $ runSecureClient host port path_ $ \conn -> flip runLoggingT logFn $ do logInfoN "Connection established" d <- liftIO $ receiveData conn case eitherDecode d >>= parseEither helloParser of Right True -> logDebugN "Recieved hello packet" Left _ -> error $ "Hello packet not readable: " ++ BS.unpack d _ -> error $ "First packet was not hello packet: " ++ BS.unpack d putMVar connectionTracker conn forever $ do data_ <- liftIO $ receiveData conn writeChan messageChan data_ `catch` \e -> do void $ takeMVar connectionTracker logErrorN $(isT "#{e :: ConnectionException}") where uri = url js authority_ = fromMaybe (error "URI lacks authority") (uriAuthority uri) host = uriUserInfo authority_ ++ uriRegName authority_ path_ = uriPath uri portOnErr v = do logWarnN $(isT "Port unreadable \"#{v}\", trying standard port 443") return 443 senderLoop :: MVar Connection -> AdapterM (SlackAdapter a) () senderLoop connectionTracker = do outChan <- view (adapter.outChannel) midTracker <- newIORef (0 :: Int) forever $ do (SlackChannelId sid, msg) <- readChan outChan mid <- atomicModifyIORef' midTracker (\i -> (i+1, i)) let encoded = encode $ object [ "id" .= mid , "type" .= ("message" :: T.Text) , "channel" .= sid , "text" .= msg ] tryConn = withMVar connectionTracker (liftIO . flip sendTextData encoded) `catch` \e -> do logErrorN $(isT "#{e :: ConnectionException}") throwError () either (const $ logErrorN "Connection error, quitting retry.") return =<< runExceptT (msum (replicate 3 tryConn)) -- | Recieve events by opening a websocket to the Real Time Messaging API data RTM instance MkSlack RTM where mkAdapterId = "slack-rtm" initIOConnections inChan = do connTracker <- newEmptyMVar a <- async $ runConnectionLoop inChan connTracker link a senderLoop connTracker
JustusAdam/marvin
src/Marvin/Adapter/Slack/RTM.hs
bsd-3-clause
5,717
0
26
1,995
1,207
621
586
-1
-1
{-#LANGUAGE ScopedTypeVariables, NoImplicitPrelude#-} module Base ( -- Classes Eq (..), Ord (..), Bounded (..), Num (..), Real (..), Integral (..), Fractional (..), Floating (..), RealFrac (..), RealFloat (..), Enum (..), Functor (..), Monad (..), Show (..), Read (..), -- Types Bool (..), Maybe (..), Either (..), Ordering (..), Ratio (..), (%), Char, Int, String, Integer, Float, Double, IO, ShowS, ReadS, Rational, IO , -- dangerous functions asTypeOf, error, undefined, seq, ($!), -- functions on specific types -- Bool (&&), (||), not, otherwise, -- Char isSpace, isUpper, isLower, isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum, showLitChar, readLitChar, lexLitChar, -- Ratio numerator, denominator, -- Maybe maybe, -- Either either, -- overloaded functions mapM, mapM_, sequence, sequence_, (=<<), subtract, even, odd, gcd, lcm, (^), (^^), absReal, signumReal, fromIntegral, realToFrac, boundedSucc, boundedPred, boundedEnumFrom, boundedEnumFromTo, boundedEnumFromThen, boundedEnumFromThenTo, shows, showChar, showString, showParen, reads, read, lex, readParen, readSigned, readInt, readDec, readOct, readHex, readFloat, lexDigits, fromRat, -- standard functions fst, snd, curry, uncurry, id, const, (.), flip, ($), until, map, (++), concat, filter, head, last, tail, init, null, length, (!!), foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1, iterate, repeat, replicate, cycle, take, drop, splitAt, takeWhile, dropWhile, span, break, lines, words, unlines, unwords, reverse, and, or, any, all, elem, notElem, lookup, sum, product, maximum, minimum, concatMap, zip, zip3, zipWith, zipWith3, unzip, unzip3, -- standard functions for Char ord, chr, ) where import BuiltIn -------------------------------------------------------------- -- Operator precedences -------------------------------------------------------------- infixr 9 . infixl 9 !! infixr 8 ^, ^^, ** infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, % infixl 6 +, - infixr 5 ++ infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem` infixr 3 && infixr 2 || infixl 1 >>, >>= infixr 1 =<< infixr 0 $, $!, `seq` -------------------------------------------------------------- -- Dangerous functions -------------------------------------------------------------- asTypeOf :: a -> a -> a asTypeOf = const seq :: a -> b -> b seq = primSeq f $! x = x `seq` f x error :: String -> a error = primError undefined :: a undefined = error "Prelude.undefined" -------------------------------------------------------------- -- class Eq, Ord, Bounded -------------------------------------------------------------- class Eq a where (==), (/=) :: a -> a -> Bool -- Minimal complete definition: (==) or (/=) x == y = not (x/=y) x /= y = not (x==y) class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a -- Minimal complete definition: (<=) or compare -- using compare can be more efficient for complex types compare x y | x==y = EQ | x<=y = LT | otherwise = GT x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT max x y | x <= y = y | otherwise = x min x y | x <= y = x | otherwise = y class Bounded a where minBound, maxBound :: a -- Minimal complete definition: All boundedSucc, boundedPred :: (Num a, Bounded a, Enum a) => a -> a boundedSucc x | x == maxBound = error "succ: applied to maxBound" | otherwise = x+1 boundedPred x | x == minBound = error "pred: applied to minBound" | otherwise = x-1 boundedEnumFrom :: (Ord a, Bounded a, Enum a) => a -> [a] boundedEnumFromTo :: (Ord a, Bounded a, Enum a) => a -> a -> [a] boundedEnumFromThenTo :: (Ord a, Num a, Bounded a, Enum a) => a -> a -> a -> [a] boundedEnumFromThen :: (Ord a, Bounded a, Enum a) => a -> a -> [a] boundedEnumFrom n = takeWhile1 (/= maxBound) (iterate succ n) boundedEnumFromTo n m = takeWhile (<= m) (boundedEnumFrom n) boundedEnumFromThen n m = enumFromThenTo n m (if n <= m then maxBound else minBound) boundedEnumFromThenTo n n' m | n' >= n = if n <= m then takeWhile1 (<= m - delta) ns else [] | otherwise = if n >= m then takeWhile1 (>= m - delta) ns else [] where delta = n'-n ns = iterate (+delta) n -- takeWhile and one more takeWhile1 :: (a -> Bool) -> [a] -> [a] takeWhile1 p (x:xs) = x : if p x then takeWhile1 p xs else [] numericEnumFrom :: Num a => a -> [a] numericEnumFromThen :: Num a => a -> a -> [a] numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a] numericEnumFrom n = iterate (+1) n numericEnumFromThen n m = iterate (+(m-n)) n numericEnumFromTo n m = takeWhile (<= m+1/2) (numericEnumFrom n) numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n') where p | n' >= n = (<= m + (n'-n)/2) | otherwise = (>= m + (n'-n)/2) -------------------------------------------------------------- -- Numeric classes: Num, Real, Integral, -- Fractional, Floating, -- RealFrac, RealFloat -------------------------------------------------------------- -- class (Eq a, Show a) => Num a where class (Eq a) => Num a where (+), (-), (*) :: a -> a -> a negate :: a -> a abs, signum :: a -> a fromInteger :: Integer -> a fromInt :: Int -> a -- Minimal complete definition: All, except negate or (-) x - y = x + negate y fromInt = fromIntegral negate x = 0 - x class (Num a, Ord a) => Real a where toRational :: a -> Rational class (Real a, Enum a) => Integral a where quot, rem, div, mod :: a -> a -> a quotRem, divMod :: a -> a -> (a,a) toInteger :: a -> Integer toInt :: a -> Int -- Minimal complete definition: quotRem and toInteger n `quot` d = q where (q,r) = quotRem n d n `rem` d = r where (q,r) = quotRem n d n `div` d = q where (q,r) = divMod n d n `mod` d = r where (q,r) = divMod n d divMod n d = if signum r == - signum d then (q-1, r+d) else qr where qr@(q,r) = quotRem n d toInt = toInt . toInteger class (Num a) => Fractional a where (/) :: a -> a -> a recip :: a -> a fromRational :: Rational -> a fromDouble :: Double -> a -- Minimal complete definition: fromRational and ((/) or recip) recip x = 1 / x fromDouble x = fromRational (fromDouble x) x / y = x * recip y class (Fractional a) => Floating a where pi :: a exp, log, sqrt :: a -> a (**), logBase :: a -> a -> a sin, cos, tan :: a -> a asin, acos, atan :: a -> a sinh, cosh, tanh :: a -> a asinh, acosh, atanh :: a -> a -- Minimal complete definition: pi, exp, log, sin, cos, sinh, cosh, -- asinh, acosh, atanh pi = 4 * atan 1 x ** y = exp (log x * y) logBase x y = log y / log x sqrt x = x ** 0.5 tan x = sin x / cos x sinh x = (exp x - exp (-x)) / 2 cosh x = (exp x + exp (-x)) / 2 tanh x = sinh x / cosh x asinh x = log (x + sqrt (x*x + 1)) acosh x = log (x + sqrt (x*x - 1)) atanh x = (log (1 + x) - log (1 - x)) / 2 class (Real a, Fractional a) => RealFrac a where properFraction :: (Integral b) => a -> (b,a) truncate, round :: (Integral b) => a -> b ceiling, floor :: (Integral b) => a -> b -- Minimal complete definition: properFraction truncate x = m where (m,_) = properFraction x round x = let (n,r) = properFraction x m = if r < 0 then n - 1 else n + 1 in case signum (abs r - 0.5) of -1 -> n 0 -> if even n then n else m 1 -> m ceiling x = if r > 0 then n + 1 else n where (n,r) = properFraction x floor x = if r < 0 then n - 1 else n where (n,r) = properFraction x {----------------------------- -- Minimal complete definition: properFraction truncate x :: xt = m where (m::xt,_) = properFraction x round x :: xt = let (n::xt,r) = properFraction x m = if r < 0 then n - 1 else n + 1 in case signum (abs r - 0.5) of -1 -> n 0 -> if even n then n else m 1 -> m ceiling x :: xt = if r > 0 then n + 1 else n where (n::xt,r) = properFraction x floor x :: xt = if r < 0 then n - 1 else n where (n::xt,r) = properFraction x -----------------------------} class (RealFrac a, Floating a) => RealFloat a where floatRadix :: a -> Integer floatDigits :: a -> Int floatRange :: a -> (Int,Int) decodeFloat :: a -> (Integer,Int) encodeFloat :: Integer -> Int -> a exponent :: a -> Int significand :: a -> a scaleFloat :: Int -> a -> a isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE :: a -> Bool atan2 :: a -> a -> a -- Minimal complete definition: All, except exponent, signficand, -- scaleFloat, atan2 exponent x = if m==0 then 0 else n + floatDigits x where (m,n) = decodeFloat x significand x = encodeFloat m (negate (floatDigits x)) where (m,_) = decodeFloat x scaleFloat k x = encodeFloat m (n+k) where (m,n) = decodeFloat x atan2 y x | x>0 = atan (y/x) | x==0 && y>0 = pi/2 | x<0 && y>0 = pi + atan (y/x) | (x<=0 && y<0) || (x<0 && isNegativeZero y) || (isNegativeZero x && isNegativeZero y) = - atan2 (-y) x | y==0 && (x<0 || isNegativeZero x) = pi -- must be after the previous test on zero y | x==0 && y==0 = y -- must be after the other double zero tests | otherwise = x + y -- x or y is a NaN, return a NaN (via +) -------------------------------------------------------------- -- Overloaded numeric functions -------------------------------------------------------------- subtract :: Num a => a -> a -> a subtract = flip (-) even, odd :: (Integral a) => a -> Bool even n = n `rem` 2 == 0 odd = not . even gcd :: Integral a => a -> a -> a gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined" gcd x y = gcd' (abs x) (abs y) where gcd' x 0 = x gcd' x y = gcd' y (x `rem` y) lcm :: (Integral a) => a -> a -> a lcm _ 0 = 0 lcm 0 _ = 0 lcm x y = abs ((x `quot` gcd x y) * y) (^) :: (Num a, Integral b) => a -> b -> a x ^ 0 = 1 x ^ n | n > 0 = f x (n-1) x where f _ 0 y = y f x n y = g x n where g x n | even n = g (x*x) (n`quot`2) | otherwise = f x (n-1) (x*y) _ ^ _ = error "Prelude.^: negative exponent" (^^) :: (Fractional a, Integral b) => a -> b -> a x ^^ n = if n >= 0 then x ^ n else recip (x^(-n)) fromIntegral :: (Integral a, Num b) => a -> b fromIntegral = fromInteger . toInteger realToFrac :: (Real a, Fractional b) => a -> b realToFrac = fromRational . toRational absReal :: (Ord a,Num a) => a -> a absReal x | x >= 0 = x | otherwise = -x signumReal :: (Ord a,Num a) => a -> a signumReal x | x == 0 = 0 | x > 0 = 1 | otherwise = -1 -------------------------------------------------------------- -- class Enum -------------------------------------------------------------- class Enum a where succ, pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] -- [n..] enumFromThen :: a -> a -> [a] -- [n,m..] enumFromTo :: a -> a -> [a] -- [n..m] enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m] -- Minimal complete definition: toEnum, fromEnum succ = toEnum . (1+) . fromEnum pred = toEnum . subtract 1 . fromEnum enumFrom x = map toEnum [ fromEnum x ..] enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ] enumFromThen x y = map toEnum [ fromEnum x, fromEnum y ..] enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ] -------------------------------------------------------------- -- class Read, Show -------------------------------------------------------------- type ReadS a = String -> [(a,String)] type ShowS = String -> String class Read a where readsPrec :: Int -> ReadS a readList :: ReadS [a] -- Minimal complete definition: readsPrec readList :: ReadS [a] = readParen False (\r -> [pr | ("[",s) <- lex r, pr <- readl s ]) readl :: ReadS [a] readl s = [([],t) | ("]",t) <- lex s] ++ [(x:xs,u) | (x,t) <- reads s, (xs,u) <- readl' t] readl' :: ReadS [a] readl' s = [([],t) | ("]",t) <- lex s] ++ [(x:xs,v) | (",",t) <- lex s, (x,u) <- reads t, (xs,v) <- readl' u] class Show a where show :: a -> String showsPrec :: Int -> a -> ShowS showList :: [a] -> ShowS -- Minimal complete definition: show or showsPrec show x = showsPrec 0 x "" showsPrec _ x s = show x ++ s showList [] = showString "[]" showList (x:xs) = showChar '[' . shows x . showl xs where showl [] = showChar ']' showl (x:xs) = showChar ',' . shows x . showl xs -------------------------------------------------------------- -- class Functor, Monad -------------------------------------------------------------- class Functor f where fmap :: (a -> b) -> (f a -> f b) class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b fail :: String -> m a -- Minimal complete definition: (>>=), return p >> q = p >>= \ _ -> q fail s = error s sequence :: Monad m => [m a] -> m [a] sequence [] = return [] sequence (c:cs) = do x <- c xs <- sequence cs return (x:xs) -- overloaded Functor and Monad function -- sequence_ :: forall a . Monad m => [m a] -> m () sequence_ :: Monad m => [m a] -> m () sequence_ = foldr (>>) (return ()) --mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM f = sequence . map f --mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ f = sequence_ . map f (=<<) :: Monad m => (a -> m b) -> m a -> m b f =<< x = x >>= f -------------------------------------------------------------- -- Boolean type -------------------------------------------------------------- data Bool = False | True deriving (Eq, Ord, Enum, Show, Read) (&&), (||) :: Bool -> Bool -> Bool False && x = False True && x = x False || x = x True || x = True not :: Bool -> Bool not True = False not False = True otherwise :: Bool otherwise = True instance Bounded Bool where minBound = False maxBound = True -------------------------------------------------------------- -- Char type -------------------------------------------------------------- isUpper :: Char -> Bool isUpper = primCharIsUpper isLower :: Char -> Bool isLower = primCharIsLower instance Eq Char where (==) = primEqChar instance Ord Char where compare = primCmpChar instance Enum Char where toEnum = primIntToChar fromEnum = primCharToInt --enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)] --enumFromThen = boundedEnumFromThen instance Read Char where readsPrec p = readParen False (\r -> [(c,t) | ('\'':s,t) <- lex r, (c,"\'") <- readLitChar s ]) readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r, (l,_) <- readl s ]) where readl ('"':s) = [("",s)] readl ('\\':'&':s) = readl s readl s = [(c:cs,u) | (c ,t) <- readLitChar s, (cs,u) <- readl t ] instance Show Char where showsPrec p '\'' = showString "'\\''" showsPrec p c = showChar '\'' . showLitChar c . showChar '\'' showList cs = showChar '"' . showl cs where showl "" = showChar '"' showl ('"':cs) = showString "\\\"" . showl cs showl (c:cs) = showLitChar c . showl cs instance Bounded Char where minBound = '\0' maxBound = '\xff' -- primMaxChar isSpace :: Char -> Bool isSpace c = c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' || c == '\xa0' isDigit :: Char -> Bool isDigit c = c >= '0' && c <= '9' isAlpha :: Char -> Bool isAlpha c = isUpper c || isLower c isAlphaNum :: Char -> Bool isAlphaNum c = isAlpha c || isDigit c ord :: Char -> Int ord = fromEnum chr :: Int -> Char chr = toEnum -------------------------------------------------------------- -- Maybe type -------------------------------------------------------------- data Maybe a = Nothing | Just a deriving (Eq, Ord, Show, Read) -- TODO: Read instance Functor Maybe where fmap f Nothing = Nothing fmap f (Just x) = Just (f x) instance Monad Maybe where Just x >>= k = k x Nothing >>= k = Nothing return = Just fail s = Nothing maybe :: b -> (a -> b) -> Maybe a -> b maybe n f Nothing = n maybe n f (Just x) = f x -------------------------------------------------------------- -- Either type -------------------------------------------------------------- data Either a b = Left a | Right b deriving (Eq, Ord, Show) -- TODO: Read either :: (a -> c) -> (b -> c) -> Either a b -> c either l r (Left x) = l x either l r (Right y) = r y -------------------------------------------------------------- -- Ordering type -------------------------------------------------------------- data Ordering = LT | EQ | GT deriving (Eq, Ord, Enum, Show) -- TODO: Ix, Read, Bounded -------------------------------------------------------------- -- Lists -------------------------------------------------------------- instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = x==y && xs==ys _ == _ = False [] /= [] = False (x:xs) /= (y:ys) = x/=y || xs/=ys _ /= _ = True instance Ord a => Ord [a] where compare [] (_:_) = LT compare [] [] = EQ compare (_:_) [] = GT compare (x:xs) (y:ys) = primCompAux x y (compare xs ys) instance Functor [] where fmap = map instance Monad [] where (x:xs) >>= f = f x ++ (xs >>= f) [] >>= f = [] return x = [x] fail s = [] instance Read a => Read [a] where readsPrec p = readList instance Show a => Show [a] where showsPrec p = showList -------------------------------------------------------------- -- Int type -------------------------------------------------------------- instance Bounded Int where minBound = primMinInt maxBound = primMaxInt instance Eq Int where (==) = primEqInt instance Ord Int where (<=) = primLeInt (>=) = primGeInt instance Num Int where (+) = primPlusInt (-) = primMinusInt (*) = primMultInt negate = primNegateInt fromInteger = primIntegerToInt instance Integral Int where divMod x y = (primDivInt x y, primModInt x y) quotRem x y = (primQuotInt x y, primRemInt x y) div = primDivInt quot = primQuotInt rem = primRemInt mod = primModInt toInteger = primIntToInteger toInt x = x instance Enum Int where succ = boundedSucc pred = boundedPred toEnum = id fromEnum = id enumFrom = boundedEnumFrom enumFromTo = boundedEnumFromTo enumFromThen = boundedEnumFromThen enumFromThenTo = boundedEnumFromThenTo instance Read Int where readsPrec p = readSigned readDec instance Real Int where toRational x = x % 1 showInt :: Int -> String showInt x | x<0 = '-' : showInt(-x) | x==0 = "0" | otherwise = (map primIntToChar . map (+48) . reverse . map (`rem`10) . takeWhile (/=0) . iterate (`div`10)) x instance Show Int where show = showInt -------------------------------------------------------------- -- Integer type -------------------------------------------------------------- instance Eq Integer where (==) = primEqInteger instance Ord Integer where compare = primCmpInteger instance Num Integer where (+) = primAddInteger (-) = primSubInteger negate = primNegInteger (*) = primMulInteger abs = absReal signum = signumReal fromInteger x = x fromInt = primIntToInteger instance Real Integer where toRational x = x % 1 instance Integral Integer where divMod = primDivModInteger quotRem = primQuotRemInteger div = primDivInteger quot = primQuotInteger rem = primRemInteger mod = primModInteger toInteger x = x toInt = primIntegerToInt instance Enum Integer where succ x = x + 1 pred x = x - 1 toEnum = primIntToInteger fromEnum = primIntegerToInt enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo n m = takeWhile (<= m) (numericEnumFrom n) enumFromThenTo n n2 m = takeWhile p (numericEnumFromThen n n2) where p | n2 >= n = (<= m) | otherwise = (>= m) showInteger :: Integer -> String showInteger x | x<0 = '-' : showInteger(-x) | x==0 = "0" | otherwise = (map primIntToChar . map (+48) . reverse . map primIntegerToInt . map (`rem`10) . takeWhile (/=0) . iterate (`div`10)) x instance Show Integer where show = showInteger instance Read Integer where readsPrec p = readSigned readDec -------------------------------------------------------------- -- Float and Double type -------------------------------------------------------------- instance Eq Float where (==) = primEqFloat instance Eq Double where (==) = primEqDouble instance Ord Float where compare = primCmpFloat instance Ord Double where compare = primCmpDouble instance Num Float where (+) = primAddFloat (-) = primSubFloat negate = primNegFloat (*) = primMulFloat abs = absReal signum = signumReal fromInteger = primIntegerToFloat fromInt = primIntToFloat instance Num Double where (+) = primAddDouble (-) = primSubDouble negate = primNegDouble (*) = primMulDouble abs = absReal signum = signumReal fromInteger = primIntegerToDouble fromInt = primIntToDouble instance Real Float where toRational = floatToRational instance Real Double where toRational = doubleToRational -- TODO: Calls to these functions should be optimised when passed as arguments to fromRational floatToRational :: Float -> Rational floatToRational x = fromRat x doubleToRational :: Double -> Rational doubleToRational x = fromRat x fromRat :: RealFloat a => a -> Rational fromRat x = (m%1)*(b%1)^^n where (m,n) = decodeFloat x b = floatRadix x instance Fractional Float where (/) = primDivideFloat recip = primRecipFloat fromRational = primRationalToFloat fromDouble = primDoubleToFloat instance Fractional Double where (/) = primDivideDouble recip = primRecipDouble fromRational = primRationalToDouble fromDouble x = x instance Floating Float where exp = primExpFloat log = primLogFloat sqrt = primSqrtFloat sin = primSinFloat cos = primCosFloat tan = primTanFloat asin = primAsinFloat acos = primAcosFloat atan = primAtanFloat sinh = primSinhFloat instance Floating Double where exp = primExpDouble log = primLogDouble sqrt = primSqrtDouble sin = primSinDouble cos = primCosDouble tan = primTanDouble asin = primAsinDouble acos = primAcosDouble atan = primAtanDouble sinh = primSinhDouble cosh = primCoshDouble tanh = primTanhDouble instance RealFrac Float where properFraction = floatProperFraction instance RealFrac Double where properFraction = floatProperFraction floatProperFraction x | n >= 0 = (fromInteger m * fromInteger b ^ n, 0) | otherwise = (fromInteger w, encodeFloat r n) where (m,n) = decodeFloat x b = floatRadix x (w,r) = quotRem m (b^(-n)) instance RealFloat Float where floatRadix _ = toInteger primRadixDoubleFloat floatDigits _ = primDigitsFloat floatRange _ = (primMinExpFloat, primMaxExpFloat) encodeFloat = primEncodeFloat decodeFloat = primDecodeFloat isNaN = primIsNaNFloat isInfinite = primIsInfiniteFloat isDenormalized= primIsDenormalizedFloat isNegativeZero= primIsNegativeZeroFloat isIEEE _ = primIsIEEE atan2 = primAtan2Float instance RealFloat Double where floatRadix _ = toInteger primRadixDoubleFloat floatDigits _ = primDigitsDouble floatRange _ = (primMinExpDouble, primMaxExpDouble) encodeFloat = primEncodeDouble decodeFloat = primDecodeDouble isNaN = primIsNaNDouble isInfinite = primIsInfiniteDouble isDenormalized= primIsDenormalizedDouble isNegativeZero= primIsNegativeZeroDouble isIEEE _ = primIsIEEE atan2 = primAtan2Double instance Enum Float where succ x = x+1 pred x = x-1 toEnum = primIntToFloat fromEnum = fromInteger . truncate -- may overflow enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo instance Enum Double where succ x = x+1 pred x = x-1 toEnum = primIntToDouble fromEnum = fromInteger . truncate -- may overflow enumFrom = numericEnumFrom enumFromThen = numericEnumFromThen enumFromTo = numericEnumFromTo enumFromThenTo = numericEnumFromThenTo instance Read Float where readsPrec p = readSigned readFloat instance Show Float where show = primShowFloat instance Read Double where readsPrec p = readSigned readFloat instance Show Double where show = primShowsDouble -------------------------------------------------------------- -- Ratio and Rational type -------------------------------------------------------------- data (Integral a) => Ratio a = !a :% !a deriving (Eq) type Rational = Ratio Integer (%) :: Integral a => a -> a -> Ratio a x % y = reduce (x * signum y) (abs y) reduce :: Integral a => a -> a -> Ratio a reduce x y | y == 0 = error "Ratio.%: zero denominator" | otherwise = (x `quot` d) :% (y `quot` d) where d = gcd x y numerator :: Integral a => Ratio a -> a numerator (x :% y) = x denominator :: Integral a => Ratio a -> a denominator (x :% y) = y instance Integral a => Ord (Ratio a) where compare (x:%y) (x':%y') = compare (x*y') (x'*y) instance Integral a => Num (Ratio a) where (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y') (x:%y) * (x':%y') = reduce (x*x') (y*y') negate (x :% y) = negate x :% y abs (x :% y) = abs x :% y signum (x :% y) = signum x :% 1 fromInteger x = fromInteger x :% 1 -- fromInt = intToRatio fromInt x = fromInt x :% 1 intToRatio :: Integral a => Int -> Ratio a -- TODO: optimise fromRational (intToRatio x) intToRatio x = fromInt x :% 1 instance Integral a => Real (Ratio a) where toRational (x:%y) = toInteger x :% toInteger y instance Integral a => Fractional (Ratio a) where (x:%y) / (x':%y') = (x*y') % (y*x') recip (x:%y) = y % x fromRational (x:%y) = fromInteger x :% fromInteger y fromDouble = doubleToRatio doubleToRatio :: Integral a => Double -> Ratio a -- TODO: optimies fromRational (doubleToRatio x) doubleToRatio x | n>=0 = (round (x / fromInteger pow) * fromInteger pow) % 1 | otherwise = fromRational (round (x * fromInteger denom) % denom) where (m,n) = decodeFloat x n_dec :: Integer n_dec = ceiling (logBase 10 (encodeFloat 1 n :: Double)) denom = 10 ^ (-n_dec) pow = 10 ^ n_dec instance Integral a => RealFrac (Ratio a) where properFraction (x:%y) = (fromIntegral q, r:%y) where (q,r) = quotRem x y instance Integral a => Enum (Ratio a) where succ x = x+1 pred x = x-1 toEnum = fromInt fromEnum = fromInteger . truncate -- may overflow enumFrom = numericEnumFrom enumFromTo = numericEnumFromTo enumFromThen = numericEnumFromThen enumFromThenTo = numericEnumFromThenTo instance (Read a, Integral a) => Read (Ratio a) where readsPrec p = readParen (p > 7) (\r -> [(x%y,u) | (x,s) <- readsPrec 8 r, ("%",t) <- lex s, (y,u) <- readsPrec 8 t ]) instance (Show a,Integral a) => Show (Ratio a) where showsPrec p (x:%y) = showParen (p > 7) (showsPrec 8 x . showString " % " . showsPrec 8 y) -------------------------------------------------------------- -- Some standard functions ------------------------------------------------------------- fst :: (a,b) -> a fst (x,_) = x snd :: (a,b) -> b snd (_,y) = y curry :: ((a,b) -> c) -> a -> b -> c curry f x y = f (x,y) uncurry :: (a -> b -> c) -> (a,b) -> c uncurry f p = f (fst p) (snd p) id :: a -> a id x = x const :: a -> b -> a const k _ = k (.) :: (b -> c) -> (a -> b) -> a -> c (f . g) x = f (g x) flip :: (a -> b -> c) -> b -> a -> c flip f x y = f y x ($) :: (a -> b) -> a -> b f $ x = f x until :: (a -> Bool) -> (a -> a) -> a -> a until p f x = if p x then x else until p f (f x) -------------------------------------------------------------- -- Standard list functions -------------------------------------------------------------- head :: [a] -> a head (x:_) = x last :: [a] -> a last [x] = x last (_:xs) = last xs tail :: [a] -> [a] tail (_:xs) = xs init :: [a] -> [a] init [x] = [] init (x:xs) = x : init xs null :: [a] -> Bool null [] = True null (_:_) = False (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) map :: (a -> b) -> [a] -> [b] map f xs = [ f x | x <- xs ] filter :: (a -> Bool) -> [a] -> [a] filter p xs = [ x | x <- xs, p x ] concat :: [[a]] -> [a] concat = foldr (++) [] length :: [a] -> Int length = foldl' (\n _ -> n + (1::Int)) (0::Int) (!!) :: [a] -> Int -> a xs !! n | n<0 = error "Prelude.!!: negative index" [] !! _ = error "Prelude.!!: index too large" (x:_) !! 0 = x (_:xs) !! n = xs !! (n-1) foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' f a [] = a foldl1 :: (a -> a -> a) -> [a] -> a foldl1 f (x:xs) = foldl f x xs scanl :: (a -> b -> a) -> a -> [b] -> [a] scanl f q xs = q : (case xs of [] -> [] x:xs -> scanl f (f q x) xs) scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 _ [] = [] scanl1 f (x:xs) = scanl f x xs foldr :: (a -> b -> b) -> b -> [a] -> b foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldr1 :: (a -> a -> a) -> [a] -> a foldr1 f [x] = x foldr1 f (x:xs) = f x (foldr1 f xs) scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr f q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 f [] = [] scanr1 f [x] = [x] scanr1 f (x:xs) = f x q : qs where qs@(q:_) = scanr1 f xs iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) repeat :: a -> [a] repeat x = xs where xs = x:xs replicate :: Int -> a -> [a] replicate n x = take n (repeat x) cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs = xs' where xs'=xs++xs' take :: Int -> [a] -> [a] take n _ | n <= 0 = [] take _ [] = [] take n (x:xs) = x : take (n-1) xs drop :: Int -> [a] -> [a] drop n xs | n <= 0 = xs drop _ [] = [] drop n (_:xs) = drop (n-1) xs splitAt :: Int -> [a] -> ([a], [a]) splitAt n xs | n <= 0 = ([],xs) splitAt _ [] = ([],[]) splitAt n (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile p [] = [] dropWhile p xs@(x:xs') | p x = dropWhile p xs' | otherwise = xs span, break :: (a -> Bool) -> [a] -> ([a],[a]) span p [] = ([],[]) span p xs@(x:xs') | p x = (x:ys, zs) | otherwise = ([],xs) where (ys,zs) = span p xs' break p = span (not . p) lines :: String -> [String] lines "" = [] lines s = let (l,s') = break ('\n'==) s in l : case s' of [] -> [] (_:s'') -> lines s'' words :: String -> [String] words s = case dropWhile isSpace s of "" -> [] s' -> w : words s'' where (w,s'') = break isSpace s' unlines :: [String] -> String unlines [] = [] unlines (l:ls) = l ++ '\n' : unlines ls unwords :: [String] -> String unwords [] = "" unwords [w] = w unwords (w:ws) = w ++ ' ' : unwords ws reverse :: [a] -> [a] reverse = foldl (flip (:)) [] and, or :: [Bool] -> Bool and = foldr (&&) True or = foldr (||) False any, all :: (a -> Bool) -> [a] -> Bool any p = or . map p all p = and . map p elem, notElem :: Eq a => a -> [a] -> Bool elem = any . (==) notElem = all . (/=) lookup :: Eq a => a -> [(a,b)] -> Maybe b lookup k [] = Nothing lookup k ((x,y):xys) | k==x = Just y | otherwise = lookup k xys sum, product :: Num a => [a] -> a sum = foldl' (+) 0 product = foldl' (*) 1 maximum, minimum :: Ord a => [a] -> a maximum = foldl1 max minimum = foldl1 min concatMap :: (a -> [b]) -> [a] -> [b] concatMap _ [] = [] concatMap f (x:xs) = f x ++ concatMap f xs zip :: [a] -> [b] -> [(a,b)] zip = zipWith (\a b -> (a,b)) zip3 :: [a] -> [b] -> [c] -> [(a,b,c)] zip3 = zipWith3 (\a b c -> (a,b,c)) zipWith :: (a->b->c) -> [a]->[b]->[c] zipWith z (a:as) (b:bs) = z a b : zipWith z as bs zipWith _ _ _ = [] zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d] zipWith3 z (a:as) (b:bs) (c:cs) = z a b c : zipWith3 z as bs cs zipWith3 _ _ _ _ = [] unzip :: [(a,b)] -> ([a],[b]) unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], []) unzip3 :: [(a,b,c)] -> ([a],[b],[c]) unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs)) ([],[],[]) -------------------------------------------------------------- -- PreludeText -------------------------------------------------------------- reads :: Read a => ReadS a reads = readsPrec 0 shows :: Show a => a -> ShowS shows = showsPrec 0 read :: Read a => String -> a read s = case [x | (x,t) <- reads s, ("","") <- lex t] of [x] -> x [] -> error "Prelude.read: no parse" _ -> error "Prelude.read: ambiguous parse" showChar :: Char -> ShowS showChar = (:) showString :: String -> ShowS showString = (++) showParen :: Bool -> ShowS -> ShowS showParen b p = if b then showChar '(' . p . showChar ')' else p showField :: Show a => String -> a -> ShowS showField m@(c:_) v | isAlpha c || c == '_' = showString m . showString " = " . shows v | otherwise = showChar '(' . showString m . showString ") = " . shows v readParen :: Bool -> ReadS a -> ReadS a readParen b g = if b then mandatory else optional where optional r = g r ++ mandatory r mandatory r = [(x,u) | ("(",s) <- lex r, (x,t) <- optional s, (")",u) <- lex t ] readField :: Read a => String -> ReadS a readField m s0 = [ r | (t, s1) <- readFieldName m s0, ("=",s2) <- lex s1, r <- reads s2 ] readFieldName :: String -> ReadS String readFieldName m@(c:_) s0 | isAlpha c || c == '_' = [ (f,s1) | (f,s1) <- lex s0, f == m ] | otherwise = [ (f,s3) | ("(",s1) <- lex s0, (f,s2) <- lex s1, f == m, (")",s3) <- lex s2 ] lex :: ReadS String lex "" = [("","")] lex (c:s) | isSpace c = lex (dropWhile isSpace s) lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s, -- head ch /= '\'' || not (null (tail ch)) ch /= "'" ] lex ('"':s) = [('"':str, t) | (str,t) <- lexString s] where lexString ('"':s) = [("\"",s)] lexString s = [(ch++str, u) | (ch,t) <- lexStrItem s, (str,u) <- lexString t ] lexStrItem ('\\':'&':s) = [("\\&",s)] lexStrItem ('\\':c:s) | isSpace c = [("",t) | '\\':t <- [dropWhile isSpace s]] lexStrItem s = lexLitChar s lex (c:s) | isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]] | isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]] -- '_' can be the start of a single char or a name/id. | c == '_' = case span isIdChar s of ([],_) -> [([c],s)] (nm,t) -> [((c:nm),t)] | isSingle c = [([c],s)] | isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s], (fe,t) <- lexFracExp s ] | otherwise = [] -- bad character where isSingle c = c `elem` ",;()[]{}_`" isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~" isIdChar c = isAlphaNum c || c `elem` "_'" lexFracExp ('.':c:cs) | isDigit c = [('.':ds++e,u) | (ds,t) <- lexDigits (c:cs), (e,u) <- lexExp t ] lexFracExp s = lexExp s lexExp (e:s) | e `elem` "eE" = [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-", (ds,u) <- lexDigits t] ++ [(e:ds,t) | (ds,t) <- lexDigits s] lexExp s = [("",s)] lexDigits :: ReadS String lexDigits = nonnull isDigit nonnull :: (Char -> Bool) -> ReadS String nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]] lexLitChar :: ReadS String lexLitChar "" = [] lexLitChar (c:s) | c /= '\\' = [([c],s)] | otherwise = map (prefix '\\') (lexEsc s) where lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)] lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)] -- Numeric escapes lexEsc ('o':s) = [prefix 'o' (span isOctDigit s)] lexEsc ('x':s) = [prefix 'x' (span isHexDigit s)] lexEsc s@(c:_) | isDigit c = [span isDigit s] | isUpper c = case [(mne,s') | (c, mne) <- table, ([],s') <- [lexmatch mne s]] of (pr:_) -> [pr] [] -> [] lexEsc _ = [] table = ('\DEL',"DEL") : asciiTab prefix c (t,s) = (c:t, s) isOctDigit c = c >= '0' && c <= '7' isHexDigit c = isDigit c || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f' lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a]) lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys lexmatch xs ys = (xs,ys) asciiTab = zip ['\NUL'..' '] (["NUL", "SOH", "STX", "ETX"]++[ "EOT", "ENQ", "ACK", "BEL"]++ [ "BS", "HT", "LF", "VT" ]++[ "FF", "CR", "SO", "SI"]++ [ "DLE", "DC1", "DC2", "DC3"]++[ "DC4", "NAK", "SYN", "ETB"]++ [ "CAN", "EM", "SUB", "ESC"]++[ "FS", "GS", "RS", "US"]++ [ "SP"]) readLitChar :: ReadS Char readLitChar ('\\':s) = readEsc s where readEsc ('a':s) = [('\a',s)] readEsc ('b':s) = [('\b',s)] readEsc ('f':s) = [('\f',s)] readEsc ('n':s) = [('\n',s)] readEsc ('r':s) = [('\r',s)] readEsc ('t':s) = [('\t',s)] readEsc ('v':s) = [('\v',s)] readEsc ('\\':s) = [('\\',s)] readEsc ('"':s) = [('"',s)] readEsc ('\'':s) = [('\'',s)] readEsc ('^':c:s) | c >= '@' && c <= '_' = [(toEnum (fromEnum c - fromEnum '@'), s)] readEsc s@(d:_) | isDigit d = [(toEnum n, t) | (n,t) <- readDec s] readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s] readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s] readEsc s@(c:_) | isUpper c = let table = ('\DEL',"DEL") : asciiTab in case [(c,s') | (c, mne) <- table, ([],s') <- [lexmatch mne s]] of (pr:_) -> [pr] [] -> [] readEsc _ = [] readLitChar (c:s) = [(c,s)] showLitChar :: Char -> ShowS showLitChar c | c > '\DEL' = showChar '\\' . protectEsc isDigit (shows (fromEnum c)) showLitChar '\DEL' = showString "\\DEL" showLitChar '\\' = showString "\\\\" showLitChar c | c >= ' ' = showChar c showLitChar '\a' = showString "\\a" showLitChar '\b' = showString "\\b" showLitChar '\f' = showString "\\f" showLitChar '\n' = showString "\\n" showLitChar '\r' = showString "\\r" showLitChar '\t' = showString "\\t" showLitChar '\v' = showString "\\v" showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO") showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c)) -- the composition with cont makes CoreToGrin break the GrinModeInvariant so we forget about protecting escapes for the moment protectEsc p f = f -- . cont where cont s@(c:_) | p c = "\\&" ++ s cont s = s -- Unsigned readers for various bases readDec, readOct, readHex :: Integral a => ReadS a readDec = readInt 10 isDigit (\ d -> fromEnum d - fromEnum_0) readOct = readInt 8 isOctDigit (\ d -> fromEnum d - fromEnum_0) readHex = readInt 16 isHexDigit hex where hex d = fromEnum d - (if isDigit d then fromEnum_0 else fromEnum (if isUpper d then 'A' else 'a') - 10) fromEnum_0 :: Int fromEnum_0 = fromEnum '0' -- readInt reads a string of digits using an arbitrary base. -- Leading minus signs must be handled elsewhere. readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a readInt radix isDig digToInt s = [(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r) | (ds,r) <- nonnull isDig s ] readSigned:: Real a => ReadS a -> ReadS a readSigned readPos = readParen False read' where read' r = read'' r ++ [(-x,t) | ("-",s) <- lex r, (x,t) <- read'' s] read'' r = [(n,s) | (str,s) <- lex r, (n,"") <- readPos str] -- This floating point reader uses a less restrictive syntax for floating -- point than the Haskell lexer. The `.' is optional. readFloat :: RealFrac a => ReadS a readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r, (k,t) <- readExp s] ++ [ (0/0, t) | ("NaN",t) <- lex r] ++ [ (1/0, t) | ("Infinity",t) <- lex r] where readFix r = [(read (ds++ds'), length ds', t) | (ds, d) <- lexDigits r , (ds',t) <- lexFrac d ] lexFrac ('.':s) = lexDigits s lexFrac s = [("",s)] readExp (e:s) | e `elem` "eE" = readExp' s readExp s = [(0::Int,s)] readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s] readExp' ('+':s) = readDec s readExp' s = readDec s ---------------------------------------------------------------- -- Monadic I/O implementation ---------------------------------------------------------------- instance Functor IO where fmap f x = x >>= (return . f) instance Monad IO where (>>=) = primbindIO return = primretIO fail s = ioError (userError s) -- Primitive ordering ops primCmpChar :: Char -> Char -> Ordering primCmpInteger :: Integer -> Integer -> Ordering primCmpFloat :: Float -> Float -> Ordering -- primitive rational operat primRationalToFloat :: Rational -> Float primRationalToDouble :: Rational -> Double
rodrigogribeiro/mptc
src/Libs/Base.hs
bsd-3-clause
50,296
5
17
19,171
18,159
9,786
8,373
-1
-1
main = 1e
roberth/uu-helium
test/parser/ExponentBad.hs
gpl-3.0
10
0
5
3
9
4
5
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudSearch.DeleteAnalysisScheme -- 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) -- -- Deletes an analysis scheme. For more information, see -- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-analysis-schemes.html Configuring Analysis Schemes> -- in the /Amazon CloudSearch Developer Guide/. -- -- /See:/ <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_DeleteAnalysisScheme.html AWS API Reference> for DeleteAnalysisScheme. module Network.AWS.CloudSearch.DeleteAnalysisScheme ( -- * Creating a Request deleteAnalysisScheme , DeleteAnalysisScheme -- * Request Lenses , dasDomainName , dasAnalysisSchemeName -- * Destructuring the Response , deleteAnalysisSchemeResponse , DeleteAnalysisSchemeResponse -- * Response Lenses , dasarsResponseStatus , dasarsAnalysisScheme ) where import Network.AWS.CloudSearch.Types import Network.AWS.CloudSearch.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Container for the parameters to the 'DeleteAnalysisScheme' operation. -- Specifies the name of the domain you want to update and the analysis -- scheme you want to delete. -- -- /See:/ 'deleteAnalysisScheme' smart constructor. data DeleteAnalysisScheme = DeleteAnalysisScheme' { _dasDomainName :: !Text , _dasAnalysisSchemeName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteAnalysisScheme' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dasDomainName' -- -- * 'dasAnalysisSchemeName' deleteAnalysisScheme :: Text -- ^ 'dasDomainName' -> Text -- ^ 'dasAnalysisSchemeName' -> DeleteAnalysisScheme deleteAnalysisScheme pDomainName_ pAnalysisSchemeName_ = DeleteAnalysisScheme' { _dasDomainName = pDomainName_ , _dasAnalysisSchemeName = pAnalysisSchemeName_ } -- | Undocumented member. dasDomainName :: Lens' DeleteAnalysisScheme Text dasDomainName = lens _dasDomainName (\ s a -> s{_dasDomainName = a}); -- | The name of the analysis scheme you want to delete. dasAnalysisSchemeName :: Lens' DeleteAnalysisScheme Text dasAnalysisSchemeName = lens _dasAnalysisSchemeName (\ s a -> s{_dasAnalysisSchemeName = a}); instance AWSRequest DeleteAnalysisScheme where type Rs DeleteAnalysisScheme = DeleteAnalysisSchemeResponse request = postQuery cloudSearch response = receiveXMLWrapper "DeleteAnalysisSchemeResult" (\ s h x -> DeleteAnalysisSchemeResponse' <$> (pure (fromEnum s)) <*> (x .@ "AnalysisScheme")) instance ToHeaders DeleteAnalysisScheme where toHeaders = const mempty instance ToPath DeleteAnalysisScheme where toPath = const "/" instance ToQuery DeleteAnalysisScheme where toQuery DeleteAnalysisScheme'{..} = mconcat ["Action" =: ("DeleteAnalysisScheme" :: ByteString), "Version" =: ("2013-01-01" :: ByteString), "DomainName" =: _dasDomainName, "AnalysisSchemeName" =: _dasAnalysisSchemeName] -- | The result of a 'DeleteAnalysisScheme' request. Contains the status of -- the deleted analysis scheme. -- -- /See:/ 'deleteAnalysisSchemeResponse' smart constructor. data DeleteAnalysisSchemeResponse = DeleteAnalysisSchemeResponse' { _dasarsResponseStatus :: !Int , _dasarsAnalysisScheme :: !AnalysisSchemeStatus } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteAnalysisSchemeResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dasarsResponseStatus' -- -- * 'dasarsAnalysisScheme' deleteAnalysisSchemeResponse :: Int -- ^ 'dasarsResponseStatus' -> AnalysisSchemeStatus -- ^ 'dasarsAnalysisScheme' -> DeleteAnalysisSchemeResponse deleteAnalysisSchemeResponse pResponseStatus_ pAnalysisScheme_ = DeleteAnalysisSchemeResponse' { _dasarsResponseStatus = pResponseStatus_ , _dasarsAnalysisScheme = pAnalysisScheme_ } -- | The response status code. dasarsResponseStatus :: Lens' DeleteAnalysisSchemeResponse Int dasarsResponseStatus = lens _dasarsResponseStatus (\ s a -> s{_dasarsResponseStatus = a}); -- | The status of the analysis scheme being deleted. dasarsAnalysisScheme :: Lens' DeleteAnalysisSchemeResponse AnalysisSchemeStatus dasarsAnalysisScheme = lens _dasarsAnalysisScheme (\ s a -> s{_dasarsAnalysisScheme = a});
fmapfmapfmap/amazonka
amazonka-cloudsearch/gen/Network/AWS/CloudSearch/DeleteAnalysisScheme.hs
mpl-2.0
5,263
0
14
978
625
378
247
83
1
-- | -- Scalpel is a web scraping library inspired by libraries like parsec and -- Perl's <http://search.cpan.org/~miyagawa/Web-Scraper-0.38/ Web::Scraper>. -- Scalpel builds on top of "Text.HTML.TagSoup" to provide a declarative and -- monadic interface. -- -- There are two general mechanisms provided by this library that are used to -- build web scrapers: Selectors and Scrapers. -- -- -- Selectors describe a location within an HTML DOM tree. The simplest selector, -- that can be written is a simple string value. For example, the selector -- @\"div\"@ matches every single div node in a DOM. Selectors can be combined -- using tag combinators. The '//' operator to define nested relationships -- within a DOM tree. For example, the selector @\"div\" \/\/ \"a\"@ matches all -- anchor tags nested arbitrarily deep within a div tag. -- -- In addition to describing the nested relationships between tags, selectors -- can also include predicates on the attributes of a tag. The '@:' operator -- creates a selector that matches a tag based on the name and various -- conditions on the tag's attributes. An attribute predicate is just a function -- that takes an attribute and returns a boolean indicating if the attribute -- matches a criteria. There are several attribute operators that can be used -- to generate common predicates. The '@=' operator creates a predicate that -- matches the name and value of an attribute exactly. For example, the selector -- @\"div\" \@: [\"id\" \@= \"article\"]@ matches div tags where the id -- attribute is equal to @\"article\"@. -- -- -- Scrapers are values that are parameterized over a selector and produce -- a value from an HTML DOM tree. The 'Scraper' type takes two type parameters. -- The first is the string like type that is used to store the text values -- within a DOM tree. Any string like type supported by "Text.StringLike" is -- valid. The second type is the type of value that the scraper produces. -- -- There are several scraper primitives that take selectors and extract content -- from the DOM. Each primitive defined by this library comes in two variants: -- singular and plural. The singular variants extract the first instance -- matching the given selector, while the plural variants match every instance. -- -- -- The following is an example that demonstrates most of the features provided -- by this library. Suppose you have the following hypothetical HTML located at -- @\"http://example.com/article.html\"@ and you would like to extract a list of -- all of the comments. -- -- > <html> -- > <body> -- > <div class='comments'> -- > <div class='comment container'> -- > <span class='comment author'>Sally</span> -- > <div class='comment text'>Woo hoo!</div> -- > </div> -- > <div class='comment container'> -- > <span class='comment author'>Bill</span> -- > <img class='comment image' src='http://example.com/cat.gif' /> -- > </div> -- > <div class='comment container'> -- > <span class='comment author'>Susan</span> -- > <div class='comment text'>WTF!?!</div> -- > </div> -- > </div> -- > </body> -- > </html> -- -- The following snippet defines a function, @allComments@, that will download -- the web page, and extract all of the comments into a list: -- -- > type Author = String -- > -- > data Comment -- > = TextComment Author String -- > | ImageComment Author URL -- > deriving (Show, Eq) -- > -- > allComments :: IO (Maybe [Comment]) -- > allComments = scrapeURL "http://example.com/article.html" comments -- > where -- > comments :: Scraper String [Comment] -- > comments = chroots ("div" @: [hasClass "container"]) comment -- > -- > comment :: Scraper String Comment -- > comment = textComment <|> imageComment -- > -- > textComment :: Scraper String Comment -- > textComment = do -- > author <- text $ "span" @: [hasClass "author"] -- > commentText <- text $ "div" @: [hasClass "text"] -- > return $ TextComment author commentText -- > -- > imageComment :: Scraper String Comment -- > imageComment = do -- > author <- text $ "span" @: [hasClass "author"] -- > imageURL <- attr "src" $ "img" @: [hasClass "image"] -- > return $ ImageComment author imageURL -- -- Complete examples can be found in the -- <https://github.com/fimad/scalpel/examples examples> folder in the scalpel -- git repository. module Text.HTML.Scalpel ( -- * Selectors Selector , Selectable (..) , AttributePredicate , AttributeName , TagName -- ** Wildcards , Any (..) -- ** Tag combinators , (//) -- ** Attribute predicates , (@:) , (@=) , (@=~) , hasClass -- ** Executing selectors , select -- * Scrapers , Scraper -- ** Primitives , attr , attrs , html , htmls , text , texts , chroot , chroots -- ** Executing scrapers , scrape , scrapeStringLike , URL , scrapeURL , scrapeURLWithOpts ) where import Text.HTML.Scalpel.Internal.Scrape import Text.HTML.Scalpel.Internal.Scrape.StringLike import Text.HTML.Scalpel.Internal.Scrape.URL import Text.HTML.Scalpel.Internal.Select import Text.HTML.Scalpel.Internal.Select.Combinators import Text.HTML.Scalpel.Internal.Select.Types
sulami/scalpel
src/Text/HTML/Scalpel.hs
apache-2.0
5,333
0
5
1,111
262
219
43
-1
-1
module L01.Validation.Tests where import Test.Framework import Test.Framework.Providers.QuickCheck2 (testProperty) import L01.Validation import Test.QuickCheck import Test.QuickCheck.Function instance Arbitrary a => Arbitrary (Validation a) where arbitrary = fmap (either Error Value) arbitrary main :: IO () main = defaultMain [test] test :: Test test = testGroup "Validation" [ testProperty "isError is not equal to isValue" prop_isError_isValue , testProperty "valueOr produces or isValue" prop_valueOr , testProperty "errorOr produces or isError" prop_errorOr , testProperty "mapValidation maps" prop_map ] prop_isError_isValue :: Validation Int -> Bool prop_isError_isValue x = isError x /= isValue x prop_valueOr :: Validation Int -> Int -> Bool prop_valueOr x n = isValue x || valueOr x n == n prop_errorOr :: Validation Err -> Err -> Bool prop_errorOr x e = isError x || errorOr x e == e prop_map :: Validation Int -> Fun Int Int -> Int -> Bool prop_map x (Fun _ f) n = f (valueOr x n) == valueOr (mapValidation f x) (f n)
juretta/course
test/src/L01/Validation/Tests.hs
bsd-3-clause
1,117
0
8
243
340
172
168
46
1
{-# LANGUAGE Haskell2010, CPP, Rank2Types, DeriveDataTypeable, StandaloneDeriving #-} {-# LINE 1 "lib/Data/Time/Clock/UTC.hs" #-} {-# OPTIONS -fno-warn-unused-imports #-} {-# LANGUAGE Trustworthy #-} -- #hide module Data.Time.Clock.UTC ( -- * UTC -- | UTC is time as measured by a clock, corrected to keep pace with the earth by adding or removing -- occasional seconds, known as \"leap seconds\". -- These corrections are not predictable and are announced with six month's notice. -- No table of these corrections is provided, as any program compiled with it would become -- out of date in six months. -- -- If you don't care about leap seconds, use UTCTime and NominalDiffTime for your clock calculations, -- and you'll be fine. UTCTime(..),NominalDiffTime ) where import Control.DeepSeq import Data.Time.Calendar.Days import Data.Time.Clock.Scale import Data.Fixed import Data.Typeable import Data.Data -- | This is the simplest representation of UTC. -- It consists of the day number, and a time offset from midnight. -- Note that if a day has a leap second added to it, it will have 86401 seconds. data UTCTime = UTCTime { -- | the day utctDay :: Day, -- | the time from midnight, 0 <= t < 86401s (because of leap-seconds) utctDayTime :: DiffTime } deriving (Data, Typeable) instance NFData UTCTime where rnf (UTCTime d t) = d `deepseq` t `deepseq` () instance Eq UTCTime where (UTCTime da ta) == (UTCTime db tb) = (da == db) && (ta == tb) instance Ord UTCTime where compare (UTCTime da ta) (UTCTime db tb) = case (compare da db) of EQ -> compare ta tb cmp -> cmp -- | This is a length of time, as measured by UTC. -- Conversion functions will treat it as seconds. -- It has a precision of 10^-12 s. -- It ignores leap-seconds, so it's not necessarily a fixed amount of clock time. -- For instance, 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC (+ 1 day), -- regardless of whether a leap-second intervened. newtype NominalDiffTime = MkNominalDiffTime Pico deriving (Eq,Ord ,Data, Typeable ) -- necessary because H98 doesn't have "cunning newtype" derivation instance NFData NominalDiffTime where -- FIXME: Data.Fixed had no NFData instances yet at time of writing rnf ndt = seq ndt () instance Enum NominalDiffTime where succ (MkNominalDiffTime a) = MkNominalDiffTime (succ a) pred (MkNominalDiffTime a) = MkNominalDiffTime (pred a) toEnum = MkNominalDiffTime . toEnum fromEnum (MkNominalDiffTime a) = fromEnum a enumFrom (MkNominalDiffTime a) = fmap MkNominalDiffTime (enumFrom a) enumFromThen (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromThen a b) enumFromTo (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromTo a b) enumFromThenTo (MkNominalDiffTime a) (MkNominalDiffTime b) (MkNominalDiffTime c) = fmap MkNominalDiffTime (enumFromThenTo a b c) instance Show NominalDiffTime where show (MkNominalDiffTime t) = (showFixed True t) ++ "s" -- necessary because H98 doesn't have "cunning newtype" derivation instance Num NominalDiffTime where (MkNominalDiffTime a) + (MkNominalDiffTime b) = MkNominalDiffTime (a + b) (MkNominalDiffTime a) - (MkNominalDiffTime b) = MkNominalDiffTime (a - b) (MkNominalDiffTime a) * (MkNominalDiffTime b) = MkNominalDiffTime (a * b) negate (MkNominalDiffTime a) = MkNominalDiffTime (negate a) abs (MkNominalDiffTime a) = MkNominalDiffTime (abs a) signum (MkNominalDiffTime a) = MkNominalDiffTime (signum a) fromInteger i = MkNominalDiffTime (fromInteger i) -- necessary because H98 doesn't have "cunning newtype" derivation instance Real NominalDiffTime where toRational (MkNominalDiffTime a) = toRational a -- necessary because H98 doesn't have "cunning newtype" derivation instance Fractional NominalDiffTime where (MkNominalDiffTime a) / (MkNominalDiffTime b) = MkNominalDiffTime (a / b) recip (MkNominalDiffTime a) = MkNominalDiffTime (recip a) fromRational r = MkNominalDiffTime (fromRational r) -- necessary because H98 doesn't have "cunning newtype" derivation instance RealFrac NominalDiffTime where properFraction (MkNominalDiffTime a) = (i,MkNominalDiffTime f) where (i,f) = properFraction a truncate (MkNominalDiffTime a) = truncate a round (MkNominalDiffTime a) = round a ceiling (MkNominalDiffTime a) = ceiling a floor (MkNominalDiffTime a) = floor a {-# RULES "realToFrac/DiffTime->NominalDiffTime" realToFrac = \ dt -> MkNominalDiffTime (realToFrac dt) "realToFrac/NominalDiffTime->DiffTime" realToFrac = \ (MkNominalDiffTime ps) -> realToFrac ps "realToFrac/NominalDiffTime->Pico" realToFrac = \ (MkNominalDiffTime ps) -> ps "realToFrac/Pico->NominalDiffTime" realToFrac = MkNominalDiffTime #-}
phischu/fragnix
tests/packages/scotty/Data.Time.Clock.UTC.hs
bsd-3-clause
4,906
0
9
953
991
517
474
66
0
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE CPP, UndecidableInstances, ParallelListComp #-} -- Undeciable instances only need for derived Show instance #include "fusion-phases.h" -- | Parallel array types and the PR class that works on the generic -- representation of array data. module Data.Array.Parallel.PArray.PData.Base ( -- * Parallel Array types. PArray(..) , length, takeData , PR (..) , PData(..), PDatas(..) , bpermutePR) where import Data.Array.Parallel.Pretty import GHC.Exts import SpecConstr () import Data.Vector (Vector) import Data.Array.Parallel.Base (Tag) import qualified Data.Array.Parallel.Unlifted as U import qualified Data.Vector as V import qualified Data.Typeable as T import Prelude hiding (length) -- PArray --------------------------------------------------------------------- -- | A parallel array consisting of a length field and some array data. -- IMPORTANT: -- The vectoriser requires the PArray data constructor to have this specific -- form, because it builds them explicitly. Specifically, the array length -- must be unboxed. -- -- TODO: Why do we need the NoSpecConstr annotation? -- {-# ANN type PArray NoSpecConstr #-} data PArray a = PArray Int# (PData a) deriving instance T.Typeable PArray -- | Take the length field of a `PArray`. {-# INLINE_PA length #-} length :: PArray a -> Int length (PArray n# _) = (I# n#) -- | Take the `PData` of a `PArray`. {-# INLINE_PA takeData #-} takeData :: PArray a -> PData a takeData (PArray _ d) = d -- Parallel array data -------------------------------------------------------- -- | A chunk of parallel array data with a linear index space. -- -- In contrast to a `PArray`, a `PData` may not have a fixed length, and its -- elements may have been converted to a generic representation. Whereas a -- `PArray` is the \"user view\" of an array, a `PData` is a type only -- used internally to the library. -- An example of an array with no length is PData Void. We can index this -- at an arbitrary position, and always get a 'void' element back. -- {-# ANN type PData NoSpecConstr #-} data family PData a -- | Several chunks of parallel array data. -- -- Although a `PArray` of atomic type such as `Int` only contains a -- single `PData` chunk, nested arrays may contain several, which we -- wrap up into a `PDatas`. {-# ANN type PDatas NoSpecConstr #-} data family PDatas a -- Put these here to break an import loop. data instance PData Int = PInt (U.Array Int) data instance PDatas Int = PInts (U.Arrays Int) -- PR ------------------------------------------------------------------------- -- | The PR (Parallel Representation) class holds primitive array operators that -- work on our generic representation of data. -- -- There are instances for all atomic types such as `Int` and `Double`, tuples, -- nested arrays `PData (PArray a)` and for the generic types we used to represent -- user level algebraic data, `Sum2` and `Wrap` and `Void`. All array data -- is converted to this fixed set of types. -- -- TODO: refactor to change PData Int to U.Array Int, -- there's not need to wrap an extra PData constructor around these arrays, -- and the type of bpermute is different than the others. class PR a where -- House Keeping ------------------------------ -- These methods are helpful for debugging, but we don't want their -- associated type classes as superclasses of PR. -- | (debugging) Check that an array has a well formed representation. -- This should only return `False` where there is a bug in the library. validPR :: PData a -> Bool -- | (debugging) Ensure an array is fully evaluted. nfPR :: PData a -> () -- | (debugging) Weak equality of contained elements. -- -- Returns `True` for functions of the same type. In the case of nested arrays, -- returns `True` if the array defines the same set of elements, but does not -- care about the exact form of the segement descriptors. similarPR :: a -> a -> Bool -- | (debugging) Check that an index is within an array. -- -- Arrays containing `Void` elements don't have a fixed length, and return -- `Void` for all indices. If the array does have a fixed length, and the -- flag is true, then we allow the index to be equal to this length, as -- well as less than it. coversPR :: Bool -> PData a -> Int -> Bool -- | (debugging) Pretty print the physical representation of an element. pprpPR :: a -> Doc -- | (debugging) Pretty print the physical representation of some array data. pprpDataPR :: PData a -> Doc -- | (debugging) Get the representation of this type. -- We don't use the Typeable class for this because the vectoriser -- won't handle the Typeable superclass on PR. typeRepPR :: a -> T.TypeRep -- | (debugging) Given a 'PData a' get the representation of the 'a' typeRepDataPR :: PData a -> T.TypeRep -- | (debugging) Given a 'PDatas a' get the representation of the 'a' typeRepDatasPR :: PDatas a -> T.TypeRep -- Constructors ------------------------------- -- | Produce an empty array with size zero. emptyPR :: PData a -- | O(n). Define an array of the given size, that maps all elements to the -- same value. -- -- We require the replication count to be > 0 so that it's easier to -- maintain the `validPR` invariants for nested arrays. replicatePR :: Int -> a -> PData a -- | O(sum lengths). Segmented replicate. -- -- Given a Segment Descriptor (Segd), replicate each each element in the -- array according to the length of the corrsponding segment. -- The array data must define at least as many elements as there are segments -- in the descriptor. -- TODO: This takes a whole Segd instead of just the lengths. If the Segd knew -- that there were no zero length segments then we could implement this -- more efficiently in the nested case case. If there are no zeros, then -- all psegs in the result are reachable from the vsegs, and we wouldn't -- need to pack them after the replicate. -- replicatesPR :: U.Segd -> PData a -> PData a -- | Append two arrays. appendPR :: PData a -> PData a -> PData a -- | Segmented append. -- -- The first descriptor defines the segmentation of the result, -- and the others define the segmentation of each source array. appendvsPR :: U.Segd -> U.VSegd -> PDatas a -> U.VSegd -> PDatas a -> PData a -- Projections -------------------------------- -- | O(1). Get the length of an array, if it has one. -- -- Applying this function to an array of `Void` will yield `error`, as -- these arrays have no fixed length. To check array bounds, use the -- `coversPR` method instead, as that is a total function. lengthPR :: PData a -> Int -- | O(1). Retrieve a single element from a single array. indexPR :: PData a -> Int -> a -- | O(1). Shared indexing. -- Retrieve several elements from several chunks of array data, -- given the chunkid and index in that chunk for each element. indexsPR :: PDatas a -> U.Array (Int, Int) -> PData a -- | O(1). Shared indexing indexvsPR :: PDatas a -> U.VSegd -> U.Array (Int, Int) -> PData a -- | O(slice len). Extract a slice of elements from an array, -- given the starting index and length of the slice. extractPR :: PData a -> Int -> Int -> PData a -- | O(sum seglens). Shared extract. -- Extract several slices from several source arrays. -- -- The Scattered Segment Descriptor (`SSegd`) describes where to get each -- slice, and all slices are concatenated together into the result. extractssPR :: PDatas a -> U.SSegd -> PData a -- | O(sum seglens). Shared extract. -- Extract several slices from several source arrays. -- TODO: we're refactoring the library so functions use the VSeg form directly, -- instead of going via a SSegd. extractvsPR :: PDatas a -> U.VSegd -> PData a extractvsPR pdatas vsegd = extractssPR pdatas (U.unsafeDemoteToSSegdOfVSegd vsegd) -- Pack and Combine --------------------------- -- | Select elements of an array that have their corresponding tag set to -- the given value. -- -- The data array must define at least as many elements as the length -- of the tags array. packByTagPR :: PData a -> U.Array Tag -> Tag -> PData a -- | Combine two arrays based on a selector. -- -- See the documentation for selectors in the dph-prim-seq library -- for how this works. combine2PR :: U.Sel2 -> PData a -> PData a -> PData a -- Conversions -------------------------------- -- | Convert a boxed vector to an array. fromVectorPR :: Vector a -> PData a -- | Convert an array to a boxed vector. toVectorPR :: PData a -> Vector a -- PDatas ------------------------------------- -- | O(1). Yield an empty collection of `PData`. emptydPR :: PDatas a -- | O(1). Yield a singleton collection of `PData`. singletondPR :: PData a -> PDatas a -- | O(1). Yield how many `PData` are in the collection. lengthdPR :: PDatas a -> Int -- | O(1). Lookup a `PData` from a collection. indexdPR :: PDatas a -> Int -> PData a -- | O(n). Append two collections of `PData`. appenddPR :: PDatas a -> PDatas a -> PDatas a -- | O(n). Convert a vector of `PData` to a `PDatas`. fromVectordPR :: V.Vector (PData a) -> PDatas a -- | O(n). Convert a `PDatas` to a vector of `PData`. toVectordPR :: PDatas a -> V.Vector (PData a) -- | O(len indices) Backwards permutation. -- Retrieve several elements from a single array. bpermutePR :: PR a => PData a -> U.Array Int -> PData a bpermutePR pdata ixs = indexsPR (singletondPR pdata) (U.zip (U.replicate (U.length ixs) 0) ixs) -- Pretty --------------------------------------------------------------------- instance PR a => PprPhysical (PData a) where pprp = pprpDataPR instance PR a => PprPhysical (PDatas a) where pprp pdatas = vcat $ [ int n <> colon <> text " " <> pprpDataPR pd | n <- [0..] | pd <- V.toList $ toVectordPR pdatas]
mainland/dph
dph-lifted-vseg/Data/Array/Parallel/PArray/PData/Base.hs
bsd-3-clause
10,584
1
12
2,652
1,232
704
528
-1
-1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Control/Applicative/Lift.hs" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {-# LANGUAGE AutoDeriveTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Applicative.Lift -- Copyright : (c) Ross Paterson 2010 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Adding a new kind of pure computation to an applicative functor. ----------------------------------------------------------------------------- module Control.Applicative.Lift ( -- * Lifting an applicative Lift(..), unLift, mapLift, elimLift, -- * Collecting errors Errors, runErrors, failure, eitherToErrors ) where import Data.Functor.Classes import Control.Applicative import Data.Foldable (Foldable(foldMap)) import Data.Functor.Constant import Data.Monoid (Monoid(..)) import Data.Traversable (Traversable(traverse)) -- | Applicative functor formed by adding pure computations to a given -- applicative functor. data Lift f a = Pure a | Other (f a) instance (Eq1 f) => Eq1 (Lift f) where liftEq eq (Pure x1) (Pure x2) = eq x1 x2 liftEq _ (Pure _) (Other _) = False liftEq _ (Other _) (Pure _) = False liftEq eq (Other y1) (Other y2) = liftEq eq y1 y2 {-# INLINE liftEq #-} instance (Ord1 f) => Ord1 (Lift f) where liftCompare comp (Pure x1) (Pure x2) = comp x1 x2 liftCompare _ (Pure _) (Other _) = LT liftCompare _ (Other _) (Pure _) = GT liftCompare comp (Other y1) (Other y2) = liftCompare comp y1 y2 {-# INLINE liftCompare #-} instance (Read1 f) => Read1 (Lift f) where liftReadsPrec rp rl = readsData $ readsUnaryWith rp "Pure" Pure `mappend` readsUnaryWith (liftReadsPrec rp rl) "Other" Other instance (Show1 f) => Show1 (Lift f) where liftShowsPrec sp _ d (Pure x) = showsUnaryWith sp "Pure" d x liftShowsPrec sp sl d (Other y) = showsUnaryWith (liftShowsPrec sp sl) "Other" d y instance (Eq1 f, Eq a) => Eq (Lift f a) where (==) = eq1 instance (Ord1 f, Ord a) => Ord (Lift f a) where compare = compare1 instance (Read1 f, Read a) => Read (Lift f a) where readsPrec = readsPrec1 instance (Show1 f, Show a) => Show (Lift f a) where showsPrec = showsPrec1 instance (Functor f) => Functor (Lift f) where fmap f (Pure x) = Pure (f x) fmap f (Other y) = Other (fmap f y) {-# INLINE fmap #-} instance (Foldable f) => Foldable (Lift f) where foldMap f (Pure x) = f x foldMap f (Other y) = foldMap f y {-# INLINE foldMap #-} instance (Traversable f) => Traversable (Lift f) where traverse f (Pure x) = Pure <$> f x traverse f (Other y) = Other <$> traverse f y {-# INLINE traverse #-} -- | A combination is 'Pure' only if both parts are. instance (Applicative f) => Applicative (Lift f) where pure = Pure {-# INLINE pure #-} Pure f <*> Pure x = Pure (f x) Pure f <*> Other y = Other (f <$> y) Other f <*> Pure x = Other (($ x) <$> f) Other f <*> Other y = Other (f <*> y) {-# INLINE (<*>) #-} -- | A combination is 'Pure' only either part is. instance (Alternative f) => Alternative (Lift f) where empty = Other empty {-# INLINE empty #-} Pure x <|> _ = Pure x Other _ <|> Pure y = Pure y Other x <|> Other y = Other (x <|> y) {-# INLINE (<|>) #-} -- | Projection to the other functor. unLift :: (Applicative f) => Lift f a -> f a unLift (Pure x) = pure x unLift (Other e) = e {-# INLINE unLift #-} -- | Apply a transformation to the other computation. mapLift :: (f a -> g a) -> Lift f a -> Lift g a mapLift _ (Pure x) = Pure x mapLift f (Other e) = Other (f e) {-# INLINE mapLift #-} -- | Eliminator for 'Lift'. -- -- * @'elimLift' f g . 'pure' = f@ -- -- * @'elimLift' f g . 'Other' = g@ -- elimLift :: (a -> r) -> (f a -> r) -> Lift f a -> r elimLift f _ (Pure x) = f x elimLift _ g (Other e) = g e {-# INLINE elimLift #-} -- | An applicative functor that collects a monoid (e.g. lists) of errors. -- A sequence of computations fails if any of its components do, but -- unlike monads made with 'ExceptT' from "Control.Monad.Trans.Except", -- these computations continue after an error, collecting all the errors. -- -- * @'pure' f '<*>' 'pure' x = 'pure' (f x)@ -- -- * @'pure' f '<*>' 'failure' e = 'failure' e@ -- -- * @'failure' e '<*>' 'pure' x = 'failure' e@ -- -- * @'failure' e1 '<*>' 'failure' e2 = 'failure' (e1 '<>' e2)@ -- type Errors e = Lift (Constant e) -- | Extractor for computations with accumulating errors. -- -- * @'runErrors' ('pure' x) = 'Right' x@ -- -- * @'runErrors' ('failure' e) = 'Left' e@ -- runErrors :: Errors e a -> Either e a runErrors (Other (Constant e)) = Left e runErrors (Pure x) = Right x {-# INLINE runErrors #-} -- | Report an error. failure :: e -> Errors e a failure e = Other (Constant e) {-# INLINE failure #-} -- | Convert from 'Either' to 'Errors' (inverse of 'runErrors'). eitherToErrors :: Either e a -> Errors e a eitherToErrors = either failure Pure
phischu/fragnix
tests/packages/scotty/Control.Applicative.Lift.hs
bsd-3-clause
5,157
0
9
1,188
1,542
810
732
94
1
-- Thanks to Bryan O'Sullivan for this test case. -- hexpat will spawn zillions of threads (which is seen as huge virtual memory -- usage in top). This is now fixed in 0.19.1. import Control.Concurrent import Control.Monad import qualified Data.ByteString as B import Text.XML.Expat.Tree import System.Environment main = do [path, threads, reads] <- getArgs let nthreads = read threads qs <- newQSem 0 replicateM_ nthreads $ do forkIO $ do replicateM_ (read reads) $ do bs <- B.readFile path case parse' defaultParseOptions bs of Left err -> print err Right p -> print (p :: UNode B.ByteString) signalQSem qs replicateM_ nthreads $ waitQSem qs putStrLn "done"
the-real-blackh/hexpat
test/hexpat-leak/Parse.hs
bsd-3-clause
727
0
22
173
194
93
101
19
2
{-# LANGUAGE FlexibleInstances, UndecidableInstances, GADTs #-} module Bind(Fresh(..),Freshen(..),Swap(..),Name,Perm ,Bind,bind ,swapM, swapsM, swapsMf ,M,runM ,unsafeUnBind,reset,name1,name2,name3,name4,name5,name2Int,integer2Name) where import Control.Monad.Fix(MonadFix(..)) import Monads class (Monad m, HasNext m) => Fresh m where fresh :: m Name class Freshen b where freshen :: Fresh m => b -> m (b,[(Name,Name)]) unbind :: (Fresh m,Swap c) => Bind b c -> m(b,c) unbind (B x y) = do { (x',perm) <- freshen x ; return(x',swaps perm y) } class Swap b where swap :: Name -> Name -> b -> b swap a b x = swaps [(a,b)] x swaps :: [(Name ,Name )] -> b -> b swaps [] x = x swaps ((a,b):ps) x = swaps ps (swap a b x) sw :: Eq a => a -> a -> a -> a sw x y s | x==s = y | y==s = x | True = s ------------------------------------------------------- instance Freshen Int where freshen n = return(n,[]) instance Freshen b => Freshen [b] where freshen xs = do { pairs <- mapM freshen xs ; return (map fst pairs,concat(map snd pairs))} instance (Freshen a,Freshen b) => Freshen (a,b) where freshen (x,y) = do { (x',p1) <- freshen x ; (y',p2) <- freshen y ; return((x',y'),p1++p2)} ----------------------------------------------- name1 = Nm 1 name2 = Nm 2 name3 = Nm 3 name4 = Nm 4 name5 = Nm 5 type Perm = [(Name,Name)] newtype Name = Nm Integer instance Show Name where show (Nm x) = "x" ++ (show x) instance Eq Name where (Nm x) == (Nm y) = x==y instance Ord Name where compare (Nm x) (Nm y) = compare x y instance Swap Name where swap (Nm a) (Nm b) (Nm x) = Nm(sw a b x) instance Freshen Name where freshen nm = do { x <- fresh; return(x,[(nm,x)]) } instance HasNext m => Fresh m where fresh = do { n <- nextInteger; return (Nm n) } name2Int (Nm x) = x integer2Name = Nm ---------------------------------------------- data Bind a b where B :: (Freshen a,Swap b) => a -> b -> Bind a b bind :: (Freshen a,Swap b) => a -> b -> Bind a b bind a b = B a b unsafeUnBind (B a b) = (a,b) instance (Freshen a,Swap a,Swap b) => Swap (Bind a b) where swaps perm (B x y) = B (swaps perm x) (swaps perm y) ------------------------------------------------------------ swapM :: (Monad m,Swap x) => Name -> Name -> m x -> m x swapM a b x = do { z <- x; return(swap a b z)} swapsM :: (Monad m,Swap x) => [(Name,Name)] -> m x -> m x swapsM xs x = do { z <- x; return(swaps xs z)} swapsMf xs f = \ x -> swapsM xs (f (swaps xs x)) instance Swap a => Swap (M a) where swaps xs comp = do { e <- comp; return(swaps xs e) } instance Swap a => Swap (IO a) where swaps xs comp = do { e <- comp; return(swaps xs e) } instance (Swap a,Swap b) => Swap (a,b) where swaps perm (x,y)= (swaps perm x,swaps perm y) instance (Swap a,Swap b,Swap c) => Swap (a,b,c) where swaps perm (x,y,z)= (swaps perm x,swaps perm y,swaps perm z) instance Swap Bool where swaps xs x = x instance (Swap a,Swap b) => Swap (a -> b) where swaps perm f = \ x -> swaps perm (f (swaps perm x)) instance Swap a => Swap [a] where swaps perm xs = map (swaps perm) xs instance Swap Int where swap x y n = n instance Swap Integer where swap x y n = n instance Swap a => Swap (Maybe a) where swaps [] x = x swaps cs Nothing = Nothing swaps cs (Just x) = Just(swaps cs x) instance Swap Char where swaps cs c = c instance (Swap a,Swap b) => Swap (Either a b) where swaps [] x = x swaps cs (Left x) = Left (swaps cs x) swaps cs (Right x) = Right (swaps cs x) -------------------------------------- newtype M x = M (Integer -> (x,Integer)) unM (M f) = f instance Monad M where return x = M (\ n -> (x,n)) (>>=) (M h) g = M f where f n = let (a,n2) = h n M k = g a in k n2 runM (M f) = fst(f 0) instance HasNext M where nextInteger = M h where h n = (n,n+1) resetNext x = M h where h n = ((),x) instance HasOutput M where outputString = error instance MonadFix M where mfix = undefined
cartazio/omega
src/Bind.hs
bsd-3-clause
4,137
0
12
1,093
2,203
1,152
1,051
109
1
{- main = 1; {-# ANN module ("HLint: ignore Use camelCase" :: String) #-} main = 1; {-# ANN module (1 + (2)) #-} -} module Comment00006 where
charleso/intellij-haskforce
tests/gold/parser/Comment00006.hs
apache-2.0
143
0
2
29
5
4
1
1
0
module Docs.AST where import qualified Data.Map as Map import qualified Elm.Compiler.Type as Type import qualified Reporting.Annotation as A -- FULL DOCUMENTATION data Docs t = Docs { comment :: String , aliases :: Map.Map String (A.Located Alias) , types :: Map.Map String (A.Located Union) , values :: Map.Map String (A.Located (Value t)) } type Centralized = Docs (Maybe Type.Type) type Checked = Docs (Type.Type) -- VALUE DOCUMENTATION data Alias = Alias { aliasComment :: Maybe String , aliasArgs :: [String] , aliasType :: Type.Type } data Union = Union { unionComment :: Maybe String , unionArgs :: [String] , unionCases :: [(String, [Type.Type])] } data Value t = Value { valueComment :: Maybe String , valueType :: t , valueAssocPrec :: Maybe (String,Int) }
JoeyEremondi/elm-summer-opt
src/Docs/AST.hs
bsd-3-clause
850
0
13
207
271
162
109
23
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 -} {-# LANGUAGE CPP #-} module IfaceSyn ( module IfaceType, IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..), IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec, IfaceExpr(..), IfaceAlt, IfaceLetBndr(..), IfaceBinding(..), IfaceConAlt(..), IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..), IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget, IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..), IfaceBang(..), IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..), IfaceAxBranch(..), IfaceTyConParent(..), -- Misc ifaceDeclImplicitBndrs, visibleIfConDecls, ifaceDeclFingerprints, -- Free Names freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst, -- Pretty printing pprIfaceExpr, pprIfaceDecl, ShowSub(..), ShowHowMuch(..) ) where #include "HsVersions.h" import IfaceType import PprCore() -- Printing DFunArgs import Demand import Class import NameSet import CoAxiom ( BranchIndex, Role ) import Name import CostCentre import Literal import ForeignCall import Annotations( AnnPayload, AnnTarget ) import BasicTypes import Outputable import FastString import Module import SrcLoc import Fingerprint import Binary import BooleanFormula ( BooleanFormula ) import HsBinds import TyCon ( Role (..), Injectivity(..) ) import StaticFlags (opt_PprStyle_Debug) import Util( filterOut, filterByList ) import InstEnv import DataCon (SrcStrictness(..), SrcUnpackedness(..)) import Control.Monad import System.IO.Unsafe import Data.Maybe (isJust) infixl 3 &&& {- ************************************************************************ * * Declarations * * ************************************************************************ -} type IfaceTopBndr = OccName -- It's convenient to have an OccName in the IfaceSyn, altough in each -- case the namespace is implied by the context. However, having an -- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints -- very convenient. -- -- We don't serialise the namespace onto the disk though; rather we -- drop it when serialising and add it back in when deserialising. data IfaceDecl = IfaceId { ifName :: IfaceTopBndr, ifType :: IfaceType, ifIdDetails :: IfaceIdDetails, ifIdInfo :: IfaceIdInfo } | IfaceData { ifName :: IfaceTopBndr, -- Type constructor ifCType :: Maybe CType, -- C type for CAPI FFI ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifCtxt :: IfaceContext, -- The "stupid theta" ifCons :: IfaceConDecls, -- Includes new/data/data family info ifRec :: RecFlag, -- Recursive or not? ifPromotable :: Bool, -- Promotable to kind level? ifGadtSyntax :: Bool, -- True <=> declared using -- GADT syntax ifParent :: IfaceTyConParent -- The axiom, for a newtype, -- or data/newtype family instance } | IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifSynKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifSynRhs :: IfaceType } | IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor ifTyVars :: [IfaceTvBndr], -- Type variables ifResVar :: Maybe IfLclName, -- Result variable name, used -- only for pretty-printing -- with --show-iface ifFamKind :: IfaceKind, -- Kind of the *rhs* (not of -- the tycon) ifFamFlav :: IfaceFamTyConFlav, ifFamInj :: Injectivity } -- injectivity information | IfaceClass { ifCtxt :: IfaceContext, -- Superclasses ifName :: IfaceTopBndr, -- Name of the class TyCon ifTyVars :: [IfaceTvBndr], -- Type variables ifRoles :: [Role], -- Roles ifFDs :: [FunDep FastString], -- Functional dependencies ifATs :: [IfaceAT], -- Associated type families ifSigs :: [IfaceClassOp], -- Method signatures ifMinDef :: BooleanFormula IfLclName, -- Minimal complete definition ifRec :: RecFlag -- Is newtype/datatype associated -- with the class recursive? } | IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name ifTyCon :: IfaceTyCon, -- LHS TyCon ifRole :: Role, -- Role of axiom ifAxBranches :: [IfaceAxBranch] -- Branches } | IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym ifPatIsInfix :: Bool, ifPatMatcher :: (IfExtName, Bool), ifPatBuilder :: Maybe (IfExtName, Bool), -- Everything below is redundant, -- but needed to implement pprIfaceDecl ifPatUnivTvs :: [IfaceTvBndr], ifPatExTvs :: [IfaceTvBndr], ifPatProvCtxt :: IfaceContext, ifPatReqCtxt :: IfaceContext, ifPatArgs :: [IfaceType], ifPatTy :: IfaceType } data IfaceTyConParent = IfNoParent | IfDataInstance IfExtName IfaceTyCon IfaceTcArgs data IfaceFamTyConFlav = IfaceOpenSynFamilyTyCon | IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch])) -- ^ Name of associated axiom and branches for pretty printing purposes, -- or 'Nothing' for an empty closed family without an axiom | IfaceAbstractClosedSynFamilyTyCon | IfaceBuiltInSynFamTyCon -- for pretty printing purposes only data IfaceClassOp = IfaceClassOp IfaceTopBndr DefMethSpec IfaceType -- Nothing => no default method -- Just False => ordinary polymorphic default method -- Just True => generic default method data IfaceAT = IfaceAT -- See Class.ClassATItem IfaceDecl -- The associated type declaration (Maybe IfaceType) -- Default associated type instance, if any -- This is just like CoAxBranch data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr] , ifaxbLHS :: IfaceTcArgs , ifaxbRoles :: [Role] , ifaxbRHS :: IfaceType , ifaxbIncomps :: [BranchIndex] } -- See Note [Storing compatibility] in CoAxiom data IfaceConDecls = IfAbstractTyCon Bool -- c.f TyCon.AbstractTyCon | IfDataFamTyCon -- Data family | IfDataTyCon [IfaceConDecl] -- Data type decls | IfNewTyCon IfaceConDecl -- Newtype decls data IfaceConDecl = IfCon { ifConOcc :: IfaceTopBndr, -- Constructor name ifConWrapper :: Bool, -- True <=> has a wrapper ifConInfix :: Bool, -- True <=> declared infix -- The universal type variables are precisely those -- of the type constructor of this data constructor -- This is *easy* to guarantee when creating the IfCon -- but it's not so easy for the original TyCon/DataCon -- So this guarantee holds for IfaceConDecl, but *not* for DataCon ifConExTvs :: [IfaceTvBndr], -- Existential tyvars ifConEqSpec :: IfaceEqSpec, -- Equality constraints ifConCtxt :: IfaceContext, -- Non-stupid context ifConArgTys :: [IfaceType], -- Arg types ifConFields :: [IfaceTopBndr], -- ...ditto... (field labels) ifConStricts :: [IfaceBang], -- Empty (meaning all lazy), -- or 1-1 corresp with arg tys -- See Note [Bangs on imported data constructors] in MkId ifConSrcStricts :: [IfaceSrcBang] } -- empty meaning no src stricts type IfaceEqSpec = [(IfLclName,IfaceType)] -- | This corresponds to an HsImplBang; that is, the final -- implementation decision about the data constructor arg data IfaceBang = IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion -- | This corresponds to HsSrcBang data IfaceSrcBang = IfSrcBang SrcUnpackedness SrcStrictness data IfaceClsInst = IfaceClsInst { ifInstCls :: IfExtName, -- See comments with ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst ifDFun :: IfExtName, -- The dfun ifOFlag :: OverlapFlag, -- Overlap flag ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv -- There's always a separate IfaceDecl for the DFun, which gives -- its IdInfo with its full type and version number. -- The instance declarations taken together have a version number, -- and we don't want that to wobble gratuitously -- If this instance decl is *used*, we'll record a usage on the dfun; -- and if the head does not change it won't be used if it wasn't before -- The ifFamInstTys field of IfaceFamInst contains a list of the rough -- match types data IfaceFamInst = IfaceFamInst { ifFamInstFam :: IfExtName -- Family name , ifFamInstTys :: [Maybe IfaceTyCon] -- See above , ifFamInstAxiom :: IfExtName -- The axiom , ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceRule = IfaceRule { ifRuleName :: RuleName, ifActivation :: Activation, ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars ifRuleHead :: IfExtName, -- Head of lhs ifRuleArgs :: [IfaceExpr], -- Args of LHS ifRuleRhs :: IfaceExpr, ifRuleAuto :: Bool, ifRuleOrph :: IsOrphan -- Just like IfaceClsInst } data IfaceAnnotation = IfaceAnnotation { ifAnnotatedTarget :: IfaceAnnTarget, ifAnnotatedValue :: AnnPayload } type IfaceAnnTarget = AnnTarget OccName -- Here's a tricky case: -- * Compile with -O module A, and B which imports A.f -- * Change function f in A, and recompile without -O -- * When we read in old A.hi we read in its IdInfo (as a thunk) -- (In earlier GHCs we used to drop IdInfo immediately on reading, -- but we do not do that now. Instead it's discarded when the -- ModIface is read into the various decl pools.) -- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *) -- and so gives a new version. data IfaceIdInfo = NoInfo -- When writing interface file without -O | HasInfo [IfaceInfoItem] -- Has info, and here it is data IfaceInfoItem = HsArity Arity | HsStrictness StrictSig | HsInline InlinePragma | HsUnfold Bool -- True <=> isStrongLoopBreaker is true IfaceUnfolding -- See Note [Expose recursive functions] | HsNoCafRefs -- NB: Specialisations and rules come in separately and are -- only later attached to the Id. Partial reason: some are orphans. data IfaceUnfolding = IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding -- Possibly could eliminate the Bool here, the information -- is also in the InlinePragma. | IfCompulsory IfaceExpr -- Only used for default methods, in fact | IfInlineRule Arity -- INLINE pragmas Bool -- OK to inline even if *un*-saturated Bool -- OK to inline even if context is boring IfaceExpr | IfDFunUnfold [IfaceBndr] [IfaceExpr] -- We only serialise the IdDetails of top-level Ids, and even then -- we only need a very limited selection. Notably, none of the -- implicit ones are needed here, because they are not put it -- interface files data IfaceIdDetails = IfVanillaId | IfRecSelId IfaceTyCon Bool | IfDFunId {- Note [Versioning of instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances] ************************************************************************ * * Functions over declarations * * ************************************************************************ -} visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl] visibleIfConDecls (IfAbstractTyCon {}) = [] visibleIfConDecls IfDataFamTyCon = [] visibleIfConDecls (IfDataTyCon cs) = cs visibleIfConDecls (IfNewTyCon c) = [c] ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName] -- *Excludes* the 'main' name, but *includes* the implicitly-bound names -- Deeply revolting, because it has to predict what gets bound, -- especially the question of whether there's a wrapper for a datacon -- See Note [Implicit TyThings] in HscTypes -- N.B. the set of names returned here *must* match the set of -- TyThings returned by HscTypes.implicitTyThings, in the sense that -- TyThing.getOccName should define a bijection between the two lists. -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop]) -- The order of the list does not matter. ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}} = [] -- Newtype ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ, ifCons = IfNewTyCon ( IfCon { ifConOcc = con_occ })}) = -- implicit newtype coercion (mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit -- data constructor and worker (newtypes don't have a wrapper) [con_occ, mkDataConWorkerOcc con_occ] ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ, ifCons = IfDataTyCon cons }) = -- for each data constructor in order, -- data constructor, worker, and (possibly) wrapper concatMap dc_occs cons where dc_occs con_decl | has_wrapper = [con_occ, work_occ, wrap_occ] | otherwise = [con_occ, work_occ] where con_occ = ifConOcc con_decl -- DataCon namespace wrap_occ = mkDataConWrapperOcc con_occ -- Id namespace work_occ = mkDataConWorkerOcc con_occ -- Id namespace has_wrapper = ifConWrapper con_decl -- This is the reason for -- having the ifConWrapper field! ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ, ifSigs = sigs, ifATs = ats }) = -- (possibly) newtype coercion co_occs ++ -- data constructor (DataCon namespace) -- data worker (Id namespace) -- no wrapper (class dictionaries never have a wrapper) [dc_occ, dcww_occ] ++ -- associated types [ifName at | IfaceAT at _ <- ats ] ++ -- superclass selectors [mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++ -- operation selectors [op | IfaceClassOp op _ _ <- sigs] where n_ctxt = length sc_ctxt n_sigs = length sigs co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ] | otherwise = [] dcww_occ = mkDataConWorkerOcc dc_occ dc_occ = mkClassDataConOcc cls_tc_occ is_newtype = n_sigs + n_ctxt == 1 -- Sigh ifaceDeclImplicitBndrs _ = [] -- ----------------------------------------------------------------------------- -- The fingerprints of an IfaceDecl -- We better give each name bound by the declaration a -- different fingerprint! So we calculate the fingerprint of -- each binder by combining the fingerprint of the whole -- declaration with the name of the binder. (#5614, #7215) ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)] ifaceDeclFingerprints hash decl = (ifName decl, hash) : [ (occ, computeFingerprint' (hash,occ)) | occ <- ifaceDeclImplicitBndrs decl ] where computeFingerprint' = unsafeDupablePerformIO . computeFingerprint (panic "ifaceDeclFingerprints") {- ************************************************************************ * * Expressions * * ************************************************************************ -} data IfaceExpr = IfaceLcl IfLclName | IfaceExt IfExtName | IfaceType IfaceType | IfaceCo IfaceCoercion | IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted | IfaceLam IfaceLamBndr IfaceExpr | IfaceApp IfaceExpr IfaceExpr | IfaceCase IfaceExpr IfLclName [IfaceAlt] | IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives] | IfaceLet IfaceBinding IfaceExpr | IfaceCast IfaceExpr IfaceCoercion | IfaceLit Literal | IfaceFCall ForeignCall IfaceType | IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E data IfaceTickish = IfaceHpcTick Module Int -- from HpcTick x | IfaceSCC CostCentre Bool Bool -- from ProfNote | IfaceSource RealSrcSpan String -- from SourceNote -- no breakpoints: we never export these into interface files type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr) -- Note: IfLclName, not IfaceBndr (and same with the case binder) -- We reconstruct the kind/type of the thing from the context -- thus saving bulk in interface files data IfaceConAlt = IfaceDefault | IfaceDataAlt IfExtName | IfaceLitAlt Literal data IfaceBinding = IfaceNonRec IfaceLetBndr IfaceExpr | IfaceRec [(IfaceLetBndr, IfaceExpr)] -- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too -- It's used for *non-top-level* let/rec binders -- See Note [IdInfo on nested let-bindings] data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo {- Note [Empty case alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In IfaceSyn an IfaceCase does not record the types of the alternatives, unlike CorSyn Case. But we need this type if the alternatives are empty. Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn. Note [Expose recursive functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For supercompilation we want to put *all* unfoldings in the interface file, even for functions that are recursive (or big). So we need to know when an unfolding belongs to a loop-breaker so that we can refrain from inlining it (except during supercompilation). Note [IdInfo on nested let-bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Occasionally we want to preserve IdInfo on nested let bindings. The one that came up was a NOINLINE pragma on a let-binding inside an INLINE function. The user (Duncan Coutts) really wanted the NOINLINE control to cross the separate compilation boundary. In general we retain all info that is left by CoreTidy.tidyLetBndr, since that is what is seen by importing module with --make ************************************************************************ * * Printing IfaceDecl * * ************************************************************************ -} pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc -- The TyCon might be local (just an OccName), or this might -- be a branch for an imported TyCon, so it would be an ExtName -- So it's easier to take an SDoc here pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs , ifaxbLHS = pat_tys , ifaxbRHS = rhs , ifaxbIncomps = incomps }) = hang (pprUserIfaceForAll tvs) 2 (hang pp_lhs 2 (equals <+> ppr rhs)) $+$ nest 2 maybe_incomps where pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys) maybe_incomps = ppUnless (null incomps) $ parens $ ptext (sLit "incompatible indices:") <+> ppr incomps instance Outputable IfaceAnnotation where ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value instance HasOccName IfaceClassOp where occName (IfaceClassOp n _ _) = n instance HasOccName IfaceConDecl where occName = ifConOcc instance HasOccName IfaceDecl where occName = ifName instance Outputable IfaceDecl where ppr = pprIfaceDecl showAll data ShowSub = ShowSub { ss_ppr_bndr :: OccName -> SDoc -- Pretty-printer for binders in IfaceDecl -- See Note [Printing IfaceDecl binders] , ss_how_much :: ShowHowMuch } data ShowHowMuch = ShowHeader -- Header information only, not rhs | ShowSome [OccName] -- [] <=> Print all sub-components -- (n:ns) <=> print sub-component 'n' with ShowSub=ns -- elide other sub-components to "..." -- May 14: the list is max 1 element long at the moment | ShowIface -- Everything including GHC-internal information (used in --show-iface) showAll :: ShowSub showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr } ppShowIface :: ShowSub -> SDoc -> SDoc ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc ppShowIface _ _ = Outputable.empty ppShowRhs :: ShowSub -> SDoc -> SDoc ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _ = Outputable.empty ppShowRhs _ doc = doc showSub :: HasOccName n => ShowSub -> n -> Bool showSub (ShowSub { ss_how_much = ShowHeader }) _ = False showSub (ShowSub { ss_how_much = ShowSome (n:_) }) thing = n == occName thing showSub (ShowSub { ss_how_much = _ }) _ = True {- Note [Printing IfaceDecl binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The binders in an IfaceDecl are just OccNames, so we don't know what module they come from. But when we pretty-print a TyThing by converting to an IfaceDecl (see PprTyThing), the TyThing may come from some other module so we really need the module qualifier. We solve this by passing in a pretty-printer for the binders. When printing an interface file (--show-iface), we want to print everything unqualified, so we can just print the OccName directly. -} ppr_trim :: [Maybe SDoc] -> [SDoc] -- Collapse a group of Nothings to a single "..." ppr_trim xs = snd (foldr go (False, []) xs) where go (Just doc) (_, so_far) = (False, doc : so_far) go Nothing (True, so_far) = (True, so_far) go Nothing (False, so_far) = (True, ptext (sLit "...") : so_far) isIfaceDataInstance :: IfaceTyConParent -> Bool isIfaceDataInstance IfNoParent = False isIfaceDataInstance _ = True pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc -- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi -- See Note [Pretty-printing TyThings] in PprTyThing pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype, ifCtxt = context, ifTyVars = tc_tyvars, ifRoles = roles, ifCons = condecls, ifParent = parent, ifRec = isrec, ifGadtSyntax = gadt, ifPromotable = is_prom }) | gadt_style = vcat [ pp_roles , pp_nd <+> pp_lhs <+> pp_where , nest 2 (vcat pp_cons) , nest 2 $ ppShowIface ss pp_extra ] | otherwise = vcat [ pp_roles , hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons) , nest 2 $ ppShowIface ss pp_extra ] where is_data_instance = isIfaceDataInstance parent gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons cons = visibleIfConDecls condecls pp_where = ppWhen (gadt_style && not (null cons)) $ ptext (sLit "where") pp_cons = ppr_trim (map show_con cons) :: [SDoc] pp_lhs = case parent of IfNoParent -> pprIfaceDeclHead context ss tycon tc_tyvars _ -> ptext (sLit "instance") <+> pprIfaceTyConParent parent pp_roles | is_data_instance = Outputable.empty | otherwise = pprRoles (== Representational) (pprPrefixIfDeclBndr ss tycon) tc_tyvars roles -- Don't display roles for data family instances (yet) -- See discussion on Trac #8672. add_bars [] = Outputable.empty add_bars (c:cs) = sep ((equals <+> c) : map (char '|' <+>) cs) ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc) show_con dc | ok_con dc = Just $ pprIfaceConDecl ss gadt_style mk_user_con_res_ty dc | otherwise = Nothing mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc) -- See Note [Result type of a data family GADT] mk_user_con_res_ty eq_spec | IfDataInstance _ tc tys <- parent = (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys))) | otherwise = (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst)) where gadt_subst = mkFsEnv eq_spec done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv) con_univ_tvs = filterOut done_univ_tv tc_tyvars ppr_tc_app gadt_subst dflags = pprPrefixIfDeclBndr ss tycon <+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv) | (tv,_kind) <- stripIfaceKindVars dflags tc_tyvars ] pp_nd = case condecls of IfAbstractTyCon d -> ptext (sLit "abstract") <> ppShowIface ss (parens (ppr d)) IfDataFamTyCon -> ptext (sLit "data family") IfDataTyCon _ -> ptext (sLit "data") IfNewTyCon _ -> ptext (sLit "newtype") pp_extra = vcat [pprCType ctype, pprRec isrec, pp_prom] pp_prom | is_prom = ptext (sLit "Promotable") | otherwise = Outputable.empty pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec , ifCtxt = context, ifName = clas , ifTyVars = tyvars, ifRoles = roles , ifFDs = fds }) = vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) tyvars roles , ptext (sLit "class") <+> pprIfaceDeclHead context ss clas tyvars <+> pprFundeps fds <+> pp_where , nest 2 (vcat [vcat asocs, vcat dsigs, pprec])] where pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (ptext (sLit "where")) asocs = ppr_trim $ map maybeShowAssoc ats dsigs = ppr_trim $ map maybeShowSig sigs pprec = ppShowIface ss (pprRec isrec) maybeShowAssoc :: IfaceAT -> Maybe SDoc maybeShowAssoc asc@(IfaceAT d _) | showSub ss d = Just $ pprIfaceAT ss asc | otherwise = Nothing maybeShowSig :: IfaceClassOp -> Maybe SDoc maybeShowSig sg | showSub ss sg = Just $ pprIfaceClassOp ss sg | otherwise = Nothing pprIfaceDecl ss (IfaceSynonym { ifName = tc , ifTyVars = tv , ifSynRhs = mono_ty }) = hang (ptext (sLit "type") <+> pprIfaceDeclHead [] ss tc tv <+> equals) 2 (sep [pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau]) where (tvs, theta, tau) = splitIfaceSigmaTy mono_ty pprIfaceDecl ss (IfaceFamily { ifName = tycon, ifTyVars = tyvars , ifFamFlav = rhs, ifFamKind = kind , ifResVar = res_var, ifFamInj = inj }) = vcat [ hang (text "type family" <+> pprIfaceDeclHead [] ss tycon tyvars) 2 (pp_inj res_var inj <+> ppShowRhs ss (pp_rhs rhs)) , ppShowRhs ss (nest 2 (pp_branches rhs)) ] where pp_inj Nothing _ = dcolon <+> ppr kind pp_inj (Just res) inj | Injective injectivity <- inj = hsep [ equals, ppr res, dcolon, ppr kind , pp_inj_cond res injectivity] | otherwise = hsep [ equals, ppr res, dcolon, ppr kind ] pp_inj_cond res inj = case filterByList inj tyvars of [] -> empty tvs -> hsep [text "|", ppr res, text "->", interppSP (map fst tvs)] pp_rhs IfaceOpenSynFamilyTyCon = ppShowIface ss (ptext (sLit "open")) pp_rhs IfaceAbstractClosedSynFamilyTyCon = ppShowIface ss (ptext (sLit "closed, abstract")) pp_rhs (IfaceClosedSynFamilyTyCon _) = ptext (sLit "where") pp_rhs IfaceBuiltInSynFamTyCon = ppShowIface ss (ptext (sLit "built-in")) pp_branches (IfaceClosedSynFamilyTyCon (Just (ax, brs))) = vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs) $$ ppShowIface ss (ptext (sLit "axiom") <+> ppr ax) pp_branches _ = Outputable.empty pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder, ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs, ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt, ifPatArgs = arg_tys, ifPatTy = pat_ty} ) = pprPatSynSig name is_bidirectional (pprUserIfaceForAll tvs) (pprIfaceContextMaybe prov_ctxt) (pprIfaceContextMaybe req_ctxt) (pprIfaceType ty) where is_bidirectional = isJust builder tvs = univ_tvs ++ ex_tvs ty = foldr IfaceFunTy pat_ty arg_tys pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty, ifIdDetails = details, ifIdInfo = info }) = vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon) 2 (pprIfaceSigmaType ty) , ppShowIface ss (ppr details) , ppShowIface ss (ppr info) ] pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon , ifAxBranches = branches }) = hang (ptext (sLit "axiom") <+> ppr name <> dcolon) 2 (vcat $ map (pprAxBranch (ppr tycon)) branches) pprCType :: Maybe CType -> SDoc pprCType Nothing = Outputable.empty pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType -- if, for each role, suppress_if role is True, then suppress the role -- output pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTvBndr] -> [Role] -> SDoc pprRoles suppress_if tyCon tyvars roles = sdocWithDynFlags $ \dflags -> let froles = suppressIfaceKinds dflags tyvars roles in ppUnless (all suppress_if roles || null froles) $ ptext (sLit "type role") <+> tyCon <+> hsep (map ppr froles) pprRec :: RecFlag -> SDoc pprRec NonRecursive = Outputable.empty pprRec Recursive = ptext (sLit "RecFlag: Recursive") pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = pprInfixVar (isSymOcc occ) (ppr_bndr occ) pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ = parenSymOcc occ (ppr_bndr occ) instance Outputable IfaceClassOp where ppr = pprIfaceClassOp showAll pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc pprIfaceClassOp ss (IfaceClassOp n dm ty) = hang opHdr 2 (pprIfaceSigmaType ty) where opHdr = pprPrefixIfDeclBndr ss n <+> ppShowIface ss (ppr dm) <+> dcolon instance Outputable IfaceAT where ppr = pprIfaceAT showAll pprIfaceAT :: ShowSub -> IfaceAT -> SDoc pprIfaceAT ss (IfaceAT d mb_def) = vcat [ pprIfaceDecl ss d , case mb_def of Nothing -> Outputable.empty Just rhs -> nest 2 $ ptext (sLit "Default:") <+> ppr rhs ] instance Outputable IfaceTyConParent where ppr p = pprIfaceTyConParent p pprIfaceTyConParent :: IfaceTyConParent -> SDoc pprIfaceTyConParent IfNoParent = Outputable.empty pprIfaceTyConParent (IfDataInstance _ tc tys) = sdocWithDynFlags $ \dflags -> let ftys = stripKindArgs dflags tys in pprIfaceTypeApp tc ftys pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName -> [IfaceTvBndr] -> SDoc pprIfaceDeclHead context ss tc_occ tv_bndrs = sdocWithDynFlags $ \ dflags -> sep [ pprIfaceContextArr context , pprPrefixIfDeclBndr ss tc_occ <+> pprIfaceTvBndrs (stripIfaceKindVars dflags tv_bndrs) ] isVanillaIfaceConDecl :: IfaceConDecl -> Bool isVanillaIfaceConDecl (IfCon { ifConExTvs = ex_tvs , ifConEqSpec = eq_spec , ifConCtxt = ctxt }) = (null ex_tvs) && (null eq_spec) && (null ctxt) pprIfaceConDecl :: ShowSub -> Bool -> (IfaceEqSpec -> ([IfaceTvBndr], SDoc)) -> IfaceConDecl -> SDoc pprIfaceConDecl ss gadt_style mk_user_con_res_ty (IfCon { ifConOcc = name, ifConInfix = is_infix, ifConExTvs = ex_tvs, ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys, ifConStricts = stricts, ifConFields = labels }) | gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty | otherwise = ppr_fields tys_w_strs where tys_w_strs :: [(IfaceBang, IfaceType)] tys_w_strs = zip stricts arg_tys pp_prefix_con = pprPrefixIfDeclBndr ss name (univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec ppr_ty = pprIfaceForAllPart (univ_tvs ++ ex_tvs) ctxt pp_tau -- A bit gruesome this, but we can't form the full con_tau, and ppr it, -- because we don't have a Name for the tycon, only an OccName pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of (t:ts) -> fsep (t : map (arrow <+>) ts) [] -> panic "pp_con_taus" ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_' ppr_bang IfStrict = char '!' ppr_bang IfUnpack = ptext (sLit "{-# UNPACK #-}") ppr_bang (IfUnpackCo co) = ptext (sLit "! {-# UNPACK #-}") <> pprParendIfaceCoercion co pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty pprBangTy (bang, ty) = ppr_bang bang <> ppr ty maybe_show_label (lbl,bty) | showSub ss lbl = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty) | otherwise = Nothing ppr_fields [ty1, ty2] | is_infix && null labels = sep [pprParendBangTy ty1, pprInfixIfDeclBndr ss name, pprParendBangTy ty2] ppr_fields fields | null labels = pp_prefix_con <+> sep (map pprParendBangTy fields) | otherwise = pp_prefix_con <+> (braces $ sep $ punctuate comma $ ppr_trim $ map maybe_show_label (zip labels fields)) instance Outputable IfaceRule where ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs, ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs }) = sep [hsep [pprRuleName name, ppr act, ptext (sLit "forall") <+> pprIfaceBndrs bndrs], nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args), ptext (sLit "=") <+> ppr rhs]) ] instance Outputable IfaceClsInst where ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag , ifInstCls = cls, ifInstTys = mb_tcs}) = hang (ptext (sLit "instance") <+> ppr flag <+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs)) 2 (equals <+> ppr dfun_id) instance Outputable IfaceFamInst where ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs , ifFamInstAxiom = tycon_ax}) = hang (ptext (sLit "family instance") <+> ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs) 2 (equals <+> ppr tycon_ax) ppr_rough :: Maybe IfaceTyCon -> SDoc ppr_rough Nothing = dot ppr_rough (Just tc) = ppr tc {- Note [Result type of a data family GADT] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family T a data instance T (p,q) where T1 :: T (Int, Maybe c) T2 :: T (Bool, q) The IfaceDecl actually looks like data TPr p q where T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q T2 :: forall p q. (p~Bool) => TPr p q To reconstruct the result types for T1 and T2 that we want to pretty print, we substitute the eq-spec [p->Int, q->Maybe c] in the arg pattern (p,q) to give T (Int, Maybe c) Remember that in IfaceSyn, the TyCon and DataCon share the same universal type variables. ----------------------------- Printing IfaceExpr ------------------------------------ -} instance Outputable IfaceExpr where ppr e = pprIfaceExpr noParens e noParens :: SDoc -> SDoc noParens pp = pp pprParendIfaceExpr :: IfaceExpr -> SDoc pprParendIfaceExpr = pprIfaceExpr parens -- | Pretty Print an IfaceExpre -- -- The first argument should be a function that adds parens in context that need -- an atomic value (e.g. function args) pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc pprIfaceExpr _ (IfaceLcl v) = ppr v pprIfaceExpr _ (IfaceExt v) = ppr v pprIfaceExpr _ (IfaceLit l) = ppr l pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty) pprIfaceExpr _ (IfaceType ty) = char '@' <+> pprParendIfaceType ty pprIfaceExpr _ (IfaceCo co) = text "@~" <+> pprParendIfaceCoercion co pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app []) pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (pprWithCommas ppr as) pprIfaceExpr add_par i@(IfaceLam _ _) = add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow, pprIfaceExpr noParens body]) where (bndrs,body) = collect [] i collect bs (IfaceLam b e) = collect (b:bs) e collect bs e = (reverse bs, e) pprIfaceExpr add_par (IfaceECase scrut ty) = add_par (sep [ ptext (sLit "case") <+> pprIfaceExpr noParens scrut , ptext (sLit "ret_ty") <+> pprParendIfaceType ty , ptext (sLit "of {}") ]) pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)]) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow, pprIfaceExpr noParens rhs <+> char '}']) pprIfaceExpr add_par (IfaceCase scrut bndr alts) = add_par (sep [ptext (sLit "case") <+> pprIfaceExpr noParens scrut <+> ptext (sLit "of") <+> ppr bndr <+> char '{', nest 2 (sep (map ppr_alt alts)) <+> char '}']) pprIfaceExpr _ (IfaceCast expr co) = sep [pprParendIfaceExpr expr, nest 2 (ptext (sLit "`cast`")), pprParendIfaceCoercion co] pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body) = add_par (sep [ptext (sLit "let {"), nest 2 (ppr_bind (b, rhs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body) = add_par (sep [ptext (sLit "letrec {"), nest 2 (sep (map ppr_bind pairs)), ptext (sLit "} in"), pprIfaceExpr noParens body]) pprIfaceExpr add_par (IfaceTick tickish e) = add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e) ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs, arrow <+> pprIfaceExpr noParens rhs] ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc ppr_con_bs con bs = ppr con <+> hsep (map ppr bs) ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc ppr_bind (IfLetBndr b ty info, rhs) = sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info), equals <+> pprIfaceExpr noParens rhs] ------------------ pprIfaceTickish :: IfaceTickish -> SDoc pprIfaceTickish (IfaceHpcTick m ix) = braces (text "tick" <+> ppr m <+> ppr ix) pprIfaceTickish (IfaceSCC cc tick scope) = braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope) pprIfaceTickish (IfaceSource src _names) = braces (pprUserRealSpan True src) ------------------ pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $ nest 2 (pprParendIfaceExpr arg) : args pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args) ------------------ instance Outputable IfaceConAlt where ppr IfaceDefault = text "DEFAULT" ppr (IfaceLitAlt l) = ppr l ppr (IfaceDataAlt d) = ppr d ------------------ instance Outputable IfaceIdDetails where ppr IfVanillaId = Outputable.empty ppr (IfRecSelId tc b) = ptext (sLit "RecSel") <+> ppr tc <+> if b then ptext (sLit "<naughty>") else Outputable.empty ppr IfDFunId = ptext (sLit "DFunId") instance Outputable IfaceIdInfo where ppr NoInfo = Outputable.empty ppr (HasInfo is) = ptext (sLit "{-") <+> pprWithCommas ppr is <+> ptext (sLit "-}") instance Outputable IfaceInfoItem where ppr (HsUnfold lb unf) = ptext (sLit "Unfolding") <> ppWhen lb (ptext (sLit "(loop-breaker)")) <> colon <+> ppr unf ppr (HsInline prag) = ptext (sLit "Inline:") <+> ppr prag ppr (HsArity arity) = ptext (sLit "Arity:") <+> int arity ppr (HsStrictness str) = ptext (sLit "Strictness:") <+> pprIfaceStrictSig str ppr HsNoCafRefs = ptext (sLit "HasNoCafRefs") instance Outputable IfaceUnfolding where ppr (IfCompulsory e) = ptext (sLit "<compulsory>") <+> parens (ppr e) ppr (IfCoreUnfold s e) = (if s then ptext (sLit "<stable>") else Outputable.empty) <+> parens (ppr e) ppr (IfInlineRule a uok bok e) = sep [ptext (sLit "InlineRule") <+> ppr (a,uok,bok), pprParendIfaceExpr e] ppr (IfDFunUnfold bs es) = hang (ptext (sLit "DFun:") <+> sep (map ppr bs) <> dot) 2 (sep (map pprParendIfaceExpr es)) {- ************************************************************************ * * Finding the Names in IfaceSyn * * ************************************************************************ This is used for dependency analysis in MkIface, so that we fingerprint a declaration before the things that depend on it. It is specific to interface-file fingerprinting in the sense that we don't collect *all* Names: for example, the DFun of an instance is recorded textually rather than by its fingerprint when fingerprinting the instance, so DFuns are not dependencies. -} freeNamesIfDecl :: IfaceDecl -> NameSet freeNamesIfDecl (IfaceId _s t d i) = freeNamesIfType t &&& freeNamesIfIdInfo i &&& freeNamesIfIdDetails d freeNamesIfDecl d@IfaceData{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfaceTyConParent (ifParent d) &&& freeNamesIfContext (ifCtxt d) &&& freeNamesIfConDecls (ifCons d) freeNamesIfDecl d@IfaceSynonym{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfType (ifSynRhs d) &&& freeNamesIfKind (ifSynKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceFamily{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfFamFlav (ifFamFlav d) &&& freeNamesIfKind (ifFamKind d) -- IA0_NOTE: because of promotion, we -- return names in the kind signature freeNamesIfDecl d@IfaceClass{} = freeNamesIfTvBndrs (ifTyVars d) &&& freeNamesIfContext (ifCtxt d) &&& fnList freeNamesIfAT (ifATs d) &&& fnList freeNamesIfClsSig (ifSigs d) freeNamesIfDecl d@IfaceAxiom{} = freeNamesIfTc (ifTyCon d) &&& fnList freeNamesIfAxBranch (ifAxBranches d) freeNamesIfDecl d@IfacePatSyn{} = unitNameSet (fst (ifPatMatcher d)) &&& maybe emptyNameSet (unitNameSet . fst) (ifPatBuilder d) &&& freeNamesIfTvBndrs (ifPatUnivTvs d) &&& freeNamesIfTvBndrs (ifPatExTvs d) &&& freeNamesIfContext (ifPatProvCtxt d) &&& freeNamesIfContext (ifPatReqCtxt d) &&& fnList freeNamesIfType (ifPatArgs d) &&& freeNamesIfType (ifPatTy d) freeNamesIfAxBranch :: IfaceAxBranch -> NameSet freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars , ifaxbLHS = lhs , ifaxbRHS = rhs }) = freeNamesIfTvBndrs tyvars &&& freeNamesIfTcArgs lhs &&& freeNamesIfType rhs freeNamesIfIdDetails :: IfaceIdDetails -> NameSet freeNamesIfIdDetails (IfRecSelId tc _) = freeNamesIfTc tc freeNamesIfIdDetails _ = emptyNameSet -- All other changes are handled via the version info on the tycon freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon (Just (ax, br))) = unitNameSet ax &&& fnList freeNamesIfAxBranch br freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon Nothing) = emptyNameSet freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet freeNamesIfContext :: IfaceContext -> NameSet freeNamesIfContext = fnList freeNamesIfType freeNamesIfAT :: IfaceAT -> NameSet freeNamesIfAT (IfaceAT decl mb_def) = freeNamesIfDecl decl &&& case mb_def of Nothing -> emptyNameSet Just rhs -> freeNamesIfType rhs freeNamesIfClsSig :: IfaceClassOp -> NameSet freeNamesIfClsSig (IfaceClassOp _n _dm ty) = freeNamesIfType ty freeNamesIfConDecls :: IfaceConDecls -> NameSet freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c freeNamesIfConDecls (IfNewTyCon c) = freeNamesIfConDecl c freeNamesIfConDecls _ = emptyNameSet freeNamesIfConDecl :: IfaceConDecl -> NameSet freeNamesIfConDecl c = freeNamesIfTvBndrs (ifConExTvs c) &&& freeNamesIfContext (ifConCtxt c) &&& fnList freeNamesIfType (ifConArgTys c) &&& fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints freeNamesIfKind :: IfaceType -> NameSet freeNamesIfKind = freeNamesIfType freeNamesIfTcArgs :: IfaceTcArgs -> NameSet freeNamesIfTcArgs (ITC_Type t ts) = freeNamesIfType t &&& freeNamesIfTcArgs ts freeNamesIfTcArgs (ITC_Kind k ks) = freeNamesIfKind k &&& freeNamesIfTcArgs ks freeNamesIfTcArgs ITC_Nil = emptyNameSet freeNamesIfType :: IfaceType -> NameSet freeNamesIfType (IfaceTyVar _) = emptyNameSet freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceTyConApp tc ts) = freeNamesIfTc tc &&& freeNamesIfTcArgs ts freeNamesIfType (IfaceTupleTy _ _ ts) = freeNamesIfTcArgs ts freeNamesIfType (IfaceLitTy _) = emptyNameSet freeNamesIfType (IfaceForAllTy tv t) = freeNamesIfTvBndr tv &&& freeNamesIfType t freeNamesIfType (IfaceFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfType (IfaceDFunTy s t) = freeNamesIfType s &&& freeNamesIfType t freeNamesIfCoercion :: IfaceCoercion -> NameSet freeNamesIfCoercion (IfaceReflCo _ t) = freeNamesIfType t freeNamesIfCoercion (IfaceFunCo _ c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceTyConAppCo _ tc cos) = freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceAppCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceForAllCo tv co) = freeNamesIfTvBndr tv &&& freeNamesIfCoercion co freeNamesIfCoercion (IfaceCoVarCo _) = emptyNameSet freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos) = unitNameSet ax &&& fnList freeNamesIfCoercion cos freeNamesIfCoercion (IfaceUnivCo _ _ t1 t2) = freeNamesIfType t1 &&& freeNamesIfType t2 freeNamesIfCoercion (IfaceSymCo c) = freeNamesIfCoercion c freeNamesIfCoercion (IfaceTransCo c1 c2) = freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2 freeNamesIfCoercion (IfaceNthCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceLRCo _ co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceInstCo co ty) = freeNamesIfCoercion co &&& freeNamesIfType ty freeNamesIfCoercion (IfaceSubCo co) = freeNamesIfCoercion co freeNamesIfCoercion (IfaceAxiomRuleCo _ax tys cos) -- the axiom is just a string, so we don't count it as a name. = fnList freeNamesIfType tys &&& fnList freeNamesIfCoercion cos freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet freeNamesIfTvBndrs = fnList freeNamesIfTvBndr freeNamesIfBndr :: IfaceBndr -> NameSet freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b freeNamesIfLetBndr :: IfaceLetBndr -> NameSet -- Remember IfaceLetBndr is used only for *nested* bindings -- The IdInfo can contain an unfolding (in the case of -- local INLINE pragmas), so look there too freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty &&& freeNamesIfIdInfo info freeNamesIfTvBndr :: IfaceTvBndr -> NameSet freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k -- kinds can have Names inside, because of promotion freeNamesIfIdBndr :: IfaceIdBndr -> NameSet freeNamesIfIdBndr = freeNamesIfTvBndr freeNamesIfIdInfo :: IfaceIdInfo -> NameSet freeNamesIfIdInfo NoInfo = emptyNameSet freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i freeNamesItem :: IfaceInfoItem -> NameSet freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u freeNamesItem _ = emptyNameSet freeNamesIfUnfold :: IfaceUnfolding -> NameSet freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e freeNamesIfUnfold (IfDFunUnfold bs es) = fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es freeNamesIfExpr :: IfaceExpr -> NameSet freeNamesIfExpr (IfaceExt v) = unitNameSet v freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty freeNamesIfExpr (IfaceCase s _ alts) = freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts where fn_alt (_con,_bs,r) = freeNamesIfExpr r -- Depend on the data constructors. Just one will do! -- Note [Tracking data constructors] fn_cons [] = emptyNameSet fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con fn_cons (_ : _ ) = emptyNameSet freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body freeNamesIfExpr (IfaceLet (IfaceRec as) x) = fnList fn_pair as &&& freeNamesIfExpr x where fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs freeNamesIfExpr _ = emptyNameSet freeNamesIfTc :: IfaceTyCon -> NameSet freeNamesIfTc tc = unitNameSet (ifaceTyConName tc) -- ToDo: shouldn't we include IfaceIntTc & co.? freeNamesIfRule :: IfaceRule -> NameSet freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f , ifRuleArgs = es, ifRuleRhs = rhs }) = unitNameSet f &&& fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es &&& freeNamesIfExpr rhs freeNamesIfFamInst :: IfaceFamInst -> NameSet freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName , ifFamInstAxiom = axName }) = unitNameSet famName &&& unitNameSet axName freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet freeNamesIfaceTyConParent IfNoParent = emptyNameSet freeNamesIfaceTyConParent (IfDataInstance ax tc tys) = unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfTcArgs tys -- helpers (&&&) :: NameSet -> NameSet -> NameSet (&&&) = unionNameSet fnList :: (a -> NameSet) -> [a] -> NameSet fnList f = foldr (&&&) emptyNameSet . map f {- Note [Tracking data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a case expression case e of { C a -> ...; ... } You might think that we don't need to include the datacon C in the free names, because its type will probably show up in the free names of 'e'. But in rare circumstances this may not happen. Here's the one that bit me: module DynFlags where import {-# SOURCE #-} Packages( PackageState ) data DynFlags = DF ... PackageState ... module Packages where import DynFlags data PackageState = PS ... lookupModule (df :: DynFlags) = case df of DF ...p... -> case p of PS ... -> ... Now, lookupModule depends on DynFlags, but the transitive dependency on the *locally-defined* type PackageState is not visible. We need to take account of the use of the data constructor PS in the pattern match. ************************************************************************ * * Binary instances * * ************************************************************************ -} instance Binary IfaceDecl where put_ bh (IfaceId name ty details idinfo) = do putByte bh 0 put_ bh (occNameFS name) put_ bh ty put_ bh details put_ bh idinfo put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 2 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do putByte bh 3 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh (IfaceFamily a1 a2 a3 a4 a5 a6) = do putByte bh 4 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7 a8 a9) = do putByte bh 5 put_ bh a1 put_ bh (occNameFS a2) put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh (IfaceAxiom a1 a2 a3 a4) = do putByte bh 6 put_ bh (occNameFS a1) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh (IfacePatSyn name a2 a3 a4 a5 a6 a7 a8 a9 a10) = do putByte bh 7 put_ bh (occNameFS name) put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do h <- getByte bh case h of 0 -> do name <- get bh ty <- get bh details <- get bh idinfo <- get bh occ <- return $! mkVarOccFS name return (IfaceId occ ty details idinfo) 1 -> error "Binary.get(TyClDecl): ForeignType" 2 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceData occ a2 a3 a4 a5 a6 a7 a8 a9 a10) 3 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceSynonym occ a2 a3 a4 a5) 4 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceFamily occ a2 a3 a4 a5 a6) 5 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh occ <- return $! mkClsOccFS a2 return (IfaceClass a1 occ a3 a4 a5 a6 a7 a8 a9) 6 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh occ <- return $! mkTcOccFS a1 return (IfaceAxiom occ a2 a3 a4) 7 -> do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh occ <- return $! mkDataOccFS a1 return (IfacePatSyn occ a2 a3 a4 a5 a6 a7 a8 a9 a10) _ -> panic (unwords ["Unknown IfaceDecl tag:", show h]) instance Binary IfaceFamTyConFlav where put_ bh IfaceOpenSynFamilyTyCon = putByte bh 0 put_ bh (IfaceClosedSynFamilyTyCon mb) = putByte bh 1 >> put_ bh mb put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 2 put_ _ IfaceBuiltInSynFamTyCon = pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty get bh = do { h <- getByte bh ; case h of 0 -> return IfaceOpenSynFamilyTyCon 1 -> do { mb <- get bh ; return (IfaceClosedSynFamilyTyCon mb) } _ -> return IfaceAbstractClosedSynFamilyTyCon } instance Binary IfaceClassOp where put_ bh (IfaceClassOp n def ty) = do put_ bh (occNameFS n) put_ bh def put_ bh ty get bh = do n <- get bh def <- get bh ty <- get bh occ <- return $! mkVarOccFS n return (IfaceClassOp occ def ty) instance Binary IfaceAT where put_ bh (IfaceAT dec defs) = do put_ bh dec put_ bh defs get bh = do dec <- get bh defs <- get bh return (IfaceAT dec defs) instance Binary IfaceAxBranch where put_ bh (IfaceAxBranch a1 a2 a3 a4 a5) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh return (IfaceAxBranch a1 a2 a3 a4 a5) instance Binary IfaceConDecls where put_ bh (IfAbstractTyCon d) = putByte bh 0 >> put_ bh d put_ bh IfDataFamTyCon = putByte bh 1 put_ bh (IfDataTyCon cs) = putByte bh 2 >> put_ bh cs put_ bh (IfNewTyCon c) = putByte bh 3 >> put_ bh c get bh = do h <- getByte bh case h of 0 -> liftM IfAbstractTyCon $ get bh 1 -> return IfDataFamTyCon 2 -> liftM IfDataTyCon $ get bh _ -> liftM IfNewTyCon $ get bh instance Binary IfaceConDecl where put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 put_ bh a9 put_ bh a10 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh a9 <- get bh a10 <- get bh return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) instance Binary IfaceBang where put_ bh IfNoBang = putByte bh 0 put_ bh IfStrict = putByte bh 1 put_ bh IfUnpack = putByte bh 2 put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co get bh = do h <- getByte bh case h of 0 -> do return IfNoBang 1 -> do return IfStrict 2 -> do return IfUnpack _ -> do { a <- get bh; return (IfUnpackCo a) } instance Binary IfaceSrcBang where put_ bh (IfSrcBang a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfSrcBang a1 a2) instance Binary IfaceClsInst where put_ bh (IfaceClsInst cls tys dfun flag orph) = do put_ bh cls put_ bh tys put_ bh dfun put_ bh flag put_ bh orph get bh = do cls <- get bh tys <- get bh dfun <- get bh flag <- get bh orph <- get bh return (IfaceClsInst cls tys dfun flag orph) instance Binary IfaceFamInst where put_ bh (IfaceFamInst fam tys name orph) = do put_ bh fam put_ bh tys put_ bh name put_ bh orph get bh = do fam <- get bh tys <- get bh name <- get bh orph <- get bh return (IfaceFamInst fam tys name orph) instance Binary IfaceRule where put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 put_ bh a6 put_ bh a7 put_ bh a8 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh a6 <- get bh a7 <- get bh a8 <- get bh return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) instance Binary IfaceAnnotation where put_ bh (IfaceAnnotation a1 a2) = do put_ bh a1 put_ bh a2 get bh = do a1 <- get bh a2 <- get bh return (IfaceAnnotation a1 a2) instance Binary IfaceIdDetails where put_ bh IfVanillaId = putByte bh 0 put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b put_ bh IfDFunId = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> return IfVanillaId 1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) } _ -> return IfDFunId instance Binary IfaceIdInfo where put_ bh NoInfo = putByte bh 0 put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut get bh = do h <- getByte bh case h of 0 -> return NoInfo _ -> liftM HasInfo $ lazyGet bh -- NB lazyGet instance Binary IfaceInfoItem where put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad put_ bh HsNoCafRefs = putByte bh 4 get bh = do h <- getByte bh case h of 0 -> liftM HsArity $ get bh 1 -> liftM HsStrictness $ get bh 2 -> do lb <- get bh ad <- get bh return (HsUnfold lb ad) 3 -> liftM HsInline $ get bh _ -> return HsNoCafRefs instance Binary IfaceUnfolding where put_ bh (IfCoreUnfold s e) = do putByte bh 0 put_ bh s put_ bh e put_ bh (IfInlineRule a b c d) = do putByte bh 1 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfDFunUnfold as bs) = do putByte bh 2 put_ bh as put_ bh bs put_ bh (IfCompulsory e) = do putByte bh 3 put_ bh e get bh = do h <- getByte bh case h of 0 -> do s <- get bh e <- get bh return (IfCoreUnfold s e) 1 -> do a <- get bh b <- get bh c <- get bh d <- get bh return (IfInlineRule a b c d) 2 -> do as <- get bh bs <- get bh return (IfDFunUnfold as bs) _ -> do e <- get bh return (IfCompulsory e) instance Binary IfaceExpr where put_ bh (IfaceLcl aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceType ab) = do putByte bh 1 put_ bh ab put_ bh (IfaceCo ab) = do putByte bh 2 put_ bh ab put_ bh (IfaceTuple ac ad) = do putByte bh 3 put_ bh ac put_ bh ad put_ bh (IfaceLam (ae, os) af) = do putByte bh 4 put_ bh ae put_ bh os put_ bh af put_ bh (IfaceApp ag ah) = do putByte bh 5 put_ bh ag put_ bh ah put_ bh (IfaceCase ai aj ak) = do putByte bh 6 put_ bh ai put_ bh aj put_ bh ak put_ bh (IfaceLet al am) = do putByte bh 7 put_ bh al put_ bh am put_ bh (IfaceTick an ao) = do putByte bh 8 put_ bh an put_ bh ao put_ bh (IfaceLit ap) = do putByte bh 9 put_ bh ap put_ bh (IfaceFCall as at) = do putByte bh 10 put_ bh as put_ bh at put_ bh (IfaceExt aa) = do putByte bh 11 put_ bh aa put_ bh (IfaceCast ie ico) = do putByte bh 12 put_ bh ie put_ bh ico put_ bh (IfaceECase a b) = do putByte bh 13 put_ bh a put_ bh b get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceLcl aa) 1 -> do ab <- get bh return (IfaceType ab) 2 -> do ab <- get bh return (IfaceCo ab) 3 -> do ac <- get bh ad <- get bh return (IfaceTuple ac ad) 4 -> do ae <- get bh os <- get bh af <- get bh return (IfaceLam (ae, os) af) 5 -> do ag <- get bh ah <- get bh return (IfaceApp ag ah) 6 -> do ai <- get bh aj <- get bh ak <- get bh return (IfaceCase ai aj ak) 7 -> do al <- get bh am <- get bh return (IfaceLet al am) 8 -> do an <- get bh ao <- get bh return (IfaceTick an ao) 9 -> do ap <- get bh return (IfaceLit ap) 10 -> do as <- get bh at <- get bh return (IfaceFCall as at) 11 -> do aa <- get bh return (IfaceExt aa) 12 -> do ie <- get bh ico <- get bh return (IfaceCast ie ico) 13 -> do a <- get bh b <- get bh return (IfaceECase a b) _ -> panic ("get IfaceExpr " ++ show h) instance Binary IfaceTickish where put_ bh (IfaceHpcTick m ix) = do putByte bh 0 put_ bh m put_ bh ix put_ bh (IfaceSCC cc tick push) = do putByte bh 1 put_ bh cc put_ bh tick put_ bh push put_ bh (IfaceSource src name) = do putByte bh 2 put_ bh (srcSpanFile src) put_ bh (srcSpanStartLine src) put_ bh (srcSpanStartCol src) put_ bh (srcSpanEndLine src) put_ bh (srcSpanEndCol src) put_ bh name get bh = do h <- getByte bh case h of 0 -> do m <- get bh ix <- get bh return (IfaceHpcTick m ix) 1 -> do cc <- get bh tick <- get bh push <- get bh return (IfaceSCC cc tick push) 2 -> do file <- get bh sl <- get bh sc <- get bh el <- get bh ec <- get bh let start = mkRealSrcLoc file sl sc end = mkRealSrcLoc file el ec name <- get bh return (IfaceSource (mkRealSrcSpan start end) name) _ -> panic ("get IfaceTickish " ++ show h) instance Binary IfaceConAlt where put_ bh IfaceDefault = putByte bh 0 put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> return IfaceDefault 1 -> liftM IfaceDataAlt $ get bh _ -> liftM IfaceLitAlt $ get bh instance Binary IfaceBinding where put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac get bh = do h <- getByte bh case h of 0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) } _ -> do { ac <- get bh; return (IfaceRec ac) } instance Binary IfaceLetBndr where put_ bh (IfLetBndr a b c) = do put_ bh a put_ bh b put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (IfLetBndr a b c) instance Binary IfaceTyConParent where put_ bh IfNoParent = putByte bh 0 put_ bh (IfDataInstance ax pr ty) = do putByte bh 1 put_ bh ax put_ bh pr put_ bh ty get bh = do h <- getByte bh case h of 0 -> return IfNoParent _ -> do ax <- get bh pr <- get bh ty <- get bh return $ IfDataInstance ax pr ty
wxwxwwxxx/ghc
compiler/iface/IfaceSyn.hs
bsd-3-clause
71,979
78
28
24,013
17,782
8,854
8,928
1,374
12
module A4 where import B4 import C4 import D4 main :: (Tree Int) -> Bool main t = isSameOrNot (sumSquares (fringe t)) ((sumSquares (B4.myFringe t)) + (sumSquares (C4.myFringe t)))
kmate/HaRe
old/testing/renaming/A4_AstOut.hs
bsd-3-clause
197
4
12
46
92
49
43
9
1
module SPARC.AddrMode ( AddrMode(..), addrOffset ) where import GhcPrelude import SPARC.Imm import SPARC.Base import Reg -- addressing modes ------------------------------------------------------------ -- | Represents a memory address in an instruction. -- Being a RISC machine, the SPARC addressing modes are very regular. -- data AddrMode = AddrRegReg Reg Reg -- addr = r1 + r2 | AddrRegImm Reg Imm -- addr = r1 + imm -- | Add an integer offset to the address in an AddrMode. -- addrOffset :: AddrMode -> Int -> Maybe AddrMode addrOffset addr off = case addr of AddrRegImm r (ImmInt n) | fits13Bits n2 -> Just (AddrRegImm r (ImmInt n2)) | otherwise -> Nothing where n2 = n + off AddrRegImm r (ImmInteger n) | fits13Bits n2 -> Just (AddrRegImm r (ImmInt (fromInteger n2))) | otherwise -> Nothing where n2 = n + toInteger off AddrRegReg r (RegReal (RealRegSingle 0)) | fits13Bits off -> Just (AddrRegImm r (ImmInt off)) | otherwise -> Nothing _ -> Nothing
ezyang/ghc
compiler/nativeGen/SPARC/AddrMode.hs
bsd-3-clause
1,120
0
15
324
289
146
143
25
4
{-# OPTIONS -fwarn-incomplete-patterns #-} -- Test for incomplete-pattern warnings -- None should cause a warning module ShouldCompile where -- These ones gave bogus warnings in 6.2 data D = D1 { f1 :: Int } | D2 -- Use pattern matching in the argument f :: D -> D f d1@(D1 {f1 = n}) = d1 { f1 = f1 d1 + n } -- Warning here f d = d -- Use case pattern matching g :: D -> D g d1 = case d1 of D1 { f1 = n } -> d1 { f1 = n + 1 } -- Warning here also D2 -> d1 -- These ones were from Neil Mitchell -- no warning ex1 x = ss where (_s:ss) = x -- no warning ex2 x = let (_s:ss) = x in ss -- Warning: Pattern match(es) are non-exhaustive -- In a case alternative: Patterns not matched: [] ex3 x = case x of ~(_s:ss) -> ss
urbanslug/ghc
testsuite/tests/deSugar/should_compile/ds059.hs
bsd-3-clause
778
0
10
227
220
124
96
14
2
{-# LANGUAGE OverloadedStrings #-} module Cirrus.Deploy (runDeploy) where import Cirrus.Encode (encode) import Control.Exception.Lens (catching_) import Control.Lens ((&), (?~), (.~)) import Control.Monad (void) import Data.ByteString.Lazy (toStrict) import Data.Text.Encoding (decodeUtf8) import Data.Text (Text) import Network.AWS import Network.AWS.CloudFormation import System.IO (stdout) import qualified Cirrus.Types as C (Stack(..)) create :: C.Stack -> CreateStack create s = createStack (C.stackName s) & csTemplateBody ?~ templateBody s update :: C.Stack -> UpdateStack update s = updateStack (C.stackName s) & usTemplateBody ?~ templateBody s templateBody :: C.Stack -> Text templateBody = decodeUtf8 . toStrict . encode . C.stackTemplate -- TODO return an Either? deploy :: C.Stack -> AWS () deploy s = catching_ _AlreadyExistsException (run create) (run update) where run f = void . send $ f s runDeploy :: C.Stack -> IO () runDeploy s = do env <- newEnv NorthVirginia Discover logger <- newLogger Debug stdout runResourceT . runAWS (env & envLogger .~ logger) $ deploy s
ags/cirrus
src/Cirrus/Deploy.hs
mit
1,101
0
12
167
388
211
177
27
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Protop.Logic.Builder ( M , evalM' , evalM , popM , lftM , objM , morM , prfM , lamSM , sgmSM , varM , lamM , appM , sgmM ) where import qualified Control.Monad.Identity as I import qualified Control.Monad.State as S import Protop.Logic.Simple newtype M m a = M { runM :: S.StateT Scope m a } deriving (Functor, Applicative, Monad, S.MonadState Scope) evalM' :: Monad m => M m a -> m a evalM' m = do (x, sc) <- S.runStateT (runM m) empty if sc == empty then return x else error "scope not empty" evalM :: M I.Identity a -> a evalM = I.runIdentity . evalM' varM :: Monad m => Sig -> M m Entity varM s = do sc <- S.get S.when (sc /= scope s) $ fail $ show s ++ " has scope " ++ show (scope s) ++ ", expecting scope " ++ show sc S.put $ cons s return $ var s popM :: Monad m => M m () popM = do sc <- S.get case headTail sc of Nothing -> fail "can't pop empty scope" Just (_, sc') -> S.put sc' lftM :: (Monad m, Liftable a, HasScope a, Show a) => a -> M m a lftM x = do sc <- S.get return $ lft' sc x objM :: Monad m => M m Sig objM = objS <$> S.get morM :: Monad m => Entity -> Entity -> M m Sig morM x y = morS <$> lftM x <*> lftM y prfM :: Monad m => Entity -> Entity -> M m Sig prfM f g = prfS <$> lftM f <*> lftM g lamSM :: Monad m => Sig -> M m Sig lamSM s = do s' <- lftM s popM return $ lamS s' sgmSM :: Monad m => Sig -> M m Sig sgmSM s = do s' <- lftM s popM return $ sgmS s' lamM :: Monad m => Entity -> M m Entity lamM e = do e' <- lftM e popM return $ lam e' appM :: Monad m => Entity -> Entity -> M m Entity appM e f = app <$> lftM e <*> lftM f sgmM :: Monad m => Sig -> Entity -> Entity -> M m Entity sgmM s e f = sgm <$> lftM s <*> lftM e <*> lftM f
brunjlar/protop
src/Protop/Logic/Builder.hs
mit
1,983
0
16
642
882
435
447
71
2
module LasmConverter where import Control.Monad.State import Data.Map hiding (map, foldr) import Prelude hiding (lookup) import Debug.Trace import AbsLasm import AbsJavalette --Environment monad data LEnv = Env Integer Integer Integer [Context] Context type EnvState = State LEnv data Pointer = Val Integer | Ref Integer deriving (Eq, Ord, Show) type Context = Map AbsLasm.Ident Pointer newEnv :: LEnv newEnv = Env 0 0 0 [empty] empty getFreshLabel :: EnvState Label getFreshLabel = do (Env l c t r s) <- get put (Env (l+1) c t r s) return (Label ("label" ++ (show l))) countStringRegs :: EnvState Integer countStringRegs = do (Env _ _ _ _ s) <- get return (fromIntegral(size s)) getReg :: AbsJavalette.Ident -> EnvState (Register, Bool) getReg i = do (Env _ _ _ rs _) <- get return (getReg' (cIdentL i) rs) getReg' :: AbsLasm.Ident -> [Context] -> (Register, Bool) getReg' i [] = error $ "[getReg] Register not found " ++ (show i) getReg' i (r:rs) = case (lookup i r) of Just reg -> case reg of Val x -> (Register ("reg" ++ (show x)), True) Ref x -> (Register ("reg" ++ (show x)), False) Nothing -> getReg' i rs openScope :: EnvState() openScope = do (Env l c t r s) <- get put (Env l c t (empty:r) s) closeScope :: EnvState() closeScope = do (Env l c t (_:rs) s) <- get put (Env l c t rs s) getFreshReg :: AbsJavalette.Ident -> Bool -> EnvState Register getFreshReg i byVal = do (Env l c t (r:rs) s) <- get put (Env l (c+1) t ((insert (cIdentL i) (createPointer (c+1) byVal) r):rs) s) return (Register ("reg" ++ (show (c+1)))) createPointer :: Integer -> Bool -> Pointer createPointer x byVal = case byVal of True -> Val x False -> Ref x getFreshTmpReg :: EnvState Register getFreshTmpReg = do (Env l c t r s) <- get put (Env l c (t+1) r s) return (Register ("tmp"++(show (t)))) getFreshString :: String -> EnvState Register getFreshString s = do (Env l c t r sc) <- get case (lookup (AbsLasm.Ident s) sc) of Just (Ref x) -> return (Register ("string" ++ (show x))) _ -> do cs <- countStringRegs put (Env l c t r (insert (AbsLasm.Ident s) (createPointer (cs+1) False) sc)) return (Register ("string" ++ (show (cs+1)))) getStrings :: EnvState Context getStrings = do (Env _ _ _ _ sc) <- get return (sc) --Converter cASTL :: Program -> LProgram cASTL (Program defs) = AbsLasm.Prog (defsL) where defsL = evalState (combineGlobals defs) newEnv combineGlobals :: [Def] -> EnvState [LTop] combineGlobals ds = do ds' <- cDefsL ds ss <- findStrings return (ss ++ ds') cDefsL :: [Def] -> EnvState [LTop] cDefsL [] = return [] cDefsL ((Def t i as (Block ss)):ds) = do openScope as' <- cArgsL as ss' <- (cStmsL ss) ds' <- cDefsL ds closeScope return ((AbsLasm.Fun (cTypeL t) (cIdentL i) as' ([SLabel (Label "entry")] ++ ss')):ds') cStmsL :: [Stm] -> EnvState [LStm] cStmsL [] = return [] cStmsL (s:ss) = case s of SRet _ -> cStmL s SVRet -> cStmL s _ -> do s' <- cStmL s ss' <- cStmsL ss return (s' ++ ss') cStmL :: Stm -> EnvState [LStm] cStmL s = case s of SEmpty -> return [] SBlock (Block ss) -> do openScope ss' <- cStmsL ss closeScope return ss' SDecl t is -> cDeclVarsL is (cTypeL t) SAss i e -> do (o, ss) <- cExpL e (addr, _) <- getReg i return (ss ++ [SStore o addr]) SRefAss i e1 e2 -> do (e1', ss) <- cExpL e1 (ptr, _) <- getReg i tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg (e2', ss') <- cExpL e2 return (ss ++ ss' ++ [SGEPtr tmp1 (TPtr(TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cExpTypeL e2))])) ptr [(Const (VInt 0)),(Const (VInt 1))], SLoad tmp2 (TPtr (AbsLasm.TArray (cExpTypeL e2))) tmp1, SGEPtr addr (TPtr (AbsLasm.TArray (cExpTypeL e2))) tmp2 [(Const (VInt 0)), e1'], SStore e2' addr]) SIncr i -> do (reg, byVal) <- getReg i case byVal of True -> return [SAdd reg AbsLasm.TInt (Var AbsLasm.TInt reg) (Const (VInt 1))] False -> do val <- getFreshTmpReg return [SLoad val AbsLasm.TInt reg, SAdd val AbsLasm.TInt (Var AbsLasm.TInt val) (Const (VInt 1))] SDecr i -> do (reg, byVal) <- getReg i case byVal of True -> return [SSub reg AbsLasm.TInt (Var AbsLasm.TInt reg) (Const (VInt 1))] False -> do val <- getFreshTmpReg return [SLoad val AbsLasm.TInt reg, SSub val AbsLasm.TInt (Var AbsLasm.TInt val) (Const (VInt 1))] SRet e -> do (o, ss) <- cExpL e return (ss ++ [SReturn (cExpTypeL e) o]) SVRet -> return [SVReturn] SIf e s1 -> case e of EType ETrue _ -> cStmL s1 EType EFalse _ -> return [] _ -> do true <- getFreshLabel false <- getFreshLabel (cmp, ss) <- cExpL e ss' <- cStmL s1 return (ss ++ [SBr (getRegister cmp) true false] ++ [SLabel (true)] ++ ss' ++ [SJmp (false)] ++ [SLabel (false)]) SIfElse e s1 s2 -> case e of EType ETrue _ -> cStmL s1 EType EFalse _ -> cStmL s2 _ -> do true <- getFreshLabel false <- getFreshLabel end <- getFreshLabel (cmp, ss) <- cExpL e ss1 <- cStmL s1 ss2 <- cStmL s2 return (ss ++ [SBr (getRegister cmp) true false] ++ [SLabel (true)] ++ ss1 ++ [SJmp (end)] ++ [SLabel (false)] ++ ss2 ++ [SJmp (end)] ++ [SLabel (end)]) SWhile e s1 -> case e of EType ETrue _ -> do into <- getFreshLabel ss1 <- cStmL s1 return ([SJmp (into)] ++ [SLabel (into)] ++ ss1 ++ [SJmp (into)]) EType EFalse _ -> return [] _ -> do into <- getFreshLabel test <- getFreshLabel out <- getFreshLabel (cmp, ss) <- cExpL e ss1 <- cStmL s1 return ([SJmp (into)] ++ [SLabel (into)] ++ ss1 ++ [SJmp (test)] ++ [SLabel (test)] ++ ss ++ [SBr (getRegister cmp) into out] ++ [SLabel (out)]) SFor t i e s -> do into <- getFreshLabel test <- getFreshLabel body <- getFreshLabel out <- getFreshLabel (ldarr, ss) <- cExpL e array <- getFreshTmpReg var <- getFreshReg i False j <- getFreshTmpReg len <- getFreshTmpReg tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg tmp3 <- getFreshTmpReg tmp4 <- getFreshTmpReg tmp5 <- getFreshTmpReg tmp6 <- getFreshTmpReg tmp7 <- getFreshTmpReg tmp8 <- getFreshTmpReg tmp9 <- getFreshTmpReg s' <- cStmL s return ([SJmp (into), SLabel (into), SAlloc j AbsLasm.TInt, SStore (Const (VInt 0)) j] ++ ss ++ [SAlloc array (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]), SStore ldarr array, SExtStruct len (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]) (getRegister ldarr) 0, SJmp (test), SLabel (test), SLoad tmp3 (AbsLasm.TInt) j, SCmp tmp4 BNeq AbsLasm.TInt (Var AbsLasm.TInt tmp3) (Var AbsLasm.TInt len), SBr tmp4 body out, SLabel (body), SGEPtr tmp5 (TPtr(TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray t')])) array [(Const (VInt 0)),(Const (VInt 1))], SLoad tmp6 (TPtr (AbsLasm.TArray t')) tmp5, SLoad tmp7 (AbsLasm.TInt) j, SGEPtr var (TPtr (AbsLasm.TArray t')) tmp6 [(Const (VInt 0)), (Var (AbsLasm.TInt) tmp7)]] ++ s' ++ [SLoad tmp8 (AbsLasm.TInt) j, SAdd tmp9 AbsLasm.TInt (Var AbsLasm.TInt tmp8) (Const (VInt 1)), SStore (Var AbsLasm.TInt tmp9) j, SJmp (test), SLabel (out)]) where t' = cTypeL t SExp e -> do (_, ss) <- cExpL e return ss cExpL :: Exp -> EnvState (Operand, [LStm]) cExpL et@(EType e t) = case e of EVar i -> do (reg, byVal) <- getReg i case byVal of True -> return ((Var (cTypeL t) reg), []) False -> do val <- getFreshTmpReg return ((Var (cTypeL t) val), [SLoad val (cTypeL t) reg]) EInt n -> return (Const (VInt n), []) EDbl d -> return (Const (VDbl d), []) ETrue -> return (Const (VBool 1), []) EFalse -> return (Const (VBool 0), []) EApp i es -> case t of AbsJavalette.TVoid -> do (os, ss) <- cAppArgsL es [] [] return (Const (VInt 0), ss ++ [SVCall (cIdentL i) os]) _ -> do (os, ss) <- cAppArgsL es [] [] reg <- getFreshTmpReg return (Var (cTypeL t) reg, ss ++ [SCall reg (cIdentL i) (cTypeL t) os]) EString s -> do reg <- getFreshString s return (Const (VString reg (fromIntegral (length s)+1)), []) ERef i e1 -> do (e1', ss) <- cExpL e1 (ptr, _) <- getReg i tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg val <- getFreshTmpReg return (Var (cTypeL t) val, ss ++ [SGEPtr tmp1 (TPtr(TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cTypeL t))])) ptr [(Const (VInt 0)),(Const (VInt 1))], SLoad tmp2 (TPtr (AbsLasm.TArray (cTypeL t))) tmp1, SGEPtr addr (TPtr (AbsLasm.TArray (cTypeL t))) tmp2 [(Const (VInt 0)), e1'], SLoad val (cTypeL t) addr]) ENew t'' e1 -> do (e1', ss) <- cExpL e1 tmp0 <- getFreshTmpReg tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg tmp3 <- getFreshTmpReg tmp4 <- getFreshTmpReg tmp5 <- getFreshTmpReg tmp6 <- getFreshTmpReg reg <- getFreshTmpReg return (Var t' reg, [SAlloc tmp0 t', SLoad tmp1 t' tmp0] ++ ss ++ [SCalloc tmp2 tmp3 (cTypeL t'') e1' tmp4, SInsStruct tmp6 t' tmp1 e1' 0, SInsStruct reg t' tmp6 (Var (TPtr (AbsLasm.TArray (cTypeL t''))) tmp4) 1]) where t' = cTypeL t EALen i -> do (addr, _) <- getReg i tmp <- getFreshTmpReg reg <- getFreshTmpReg return (Var (AbsLasm.TInt) reg, [SLoad tmp (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]) addr, SExtStruct reg (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray AbsLasm.TInt)]) tmp 0]) ENeg e1 -> do (e1', ss) <- cExpL e1 reg <- getFreshTmpReg return (case t of AbsJavalette.TInt -> ((Var (cTypeL t) reg), (ss ++ [SMul reg (cTypeL t) e1' (Const (VInt (-1)))])) AbsJavalette.TDbl -> ((Var (cTypeL t) reg), (ss ++ [SMul reg (cTypeL t) e1' (Const (VDbl (-1.0)))]))) ENot e1 -> do (e1', ss) <- cExpL e1 reg <- getFreshTmpReg return ((Var (cTypeL t) reg), (ss ++ [SXor reg (cTypeL t) e1' (Const (VInt (1)))])) EMul e1 op e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 reg <- getFreshTmpReg return (case op of OTimes -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SMul reg (cTypeL t) e1' e2'])) ODiv -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SDiv reg (cTypeL t) e1' e2'])) OMod -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SMod reg (cTypeL t) e1' e2']))) EAdd e1 op e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 reg <- getFreshTmpReg return (case op of OPlus -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SAdd reg (cTypeL t) e1' e2'])) OMinus -> ((Var (cTypeL t) reg), (ss ++ ss' ++ [SSub reg (cTypeL t) e1' e2']))) ERel e1 op e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 reg <- getFreshTmpReg return ((Var (cTypeL t) reg), (ss ++ ss' ++ [SCmp reg (cRelOpL op) (cExpTypeL e1) e1' e2'])) EAnd e1 e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg reg <- getFreshTmpReg true <- getFreshLabel false <- getFreshLabel end <- getFreshLabel return ((Var AbsLasm.TBool reg), ([SAlloc addr AbsLasm.TBool] ++ ss ++ [SCmp tmp1 BNeq AbsLasm.TBool e1' (Const (VBool 0))] ++ [SBr tmp1 true false, SLabel true] ++ ss' ++ [SAnd tmp2 AbsLasm.TBool e1' e2', SStore (Var AbsLasm.TBool tmp2) addr, SJmp end] ++ [SLabel false, SStore (Const (VBool 0)) addr, SJmp end] ++ [SLabel end, SLoad reg AbsLasm.TBool addr])) EOr e1 e2 -> do (e1', ss) <- cExpL e1 (e2', ss') <- cExpL e2 tmp1 <- getFreshTmpReg tmp2 <- getFreshTmpReg addr <- getFreshTmpReg reg <- getFreshTmpReg true <- getFreshLabel false <- getFreshLabel end <- getFreshLabel return ((Var AbsLasm.TBool reg), ([SAlloc addr AbsLasm.TBool] ++ ss ++ [SCmp tmp1 BNeq AbsLasm.TBool e1' (Const (VBool 1))] ++ [SBr tmp1 true false, SLabel true] ++ ss' ++ [SOr tmp2 AbsLasm.TBool e1' e2', SStore (Var AbsLasm.TBool tmp2) addr, SJmp end] ++ [SLabel false, SStore (Const (VBool 1)) addr, SJmp end] ++ [SLabel end, SLoad reg AbsLasm.TBool addr])) EType e t -> error $ "[cExpL] Should not try to convert a EType " ++ (show e) cAppArgsL :: [Exp] -> [Operand] -> [LStm] -> EnvState ([Operand], [LStm]) cAppArgsL [] os ss = return (os, ss) cAppArgsL (e:es) os ss = do (o, ss') <- cExpL e case o of Var (TStruct ts) r -> do tmp <- getFreshTmpReg cAppArgsL es (os++[Var (TPtr (TStruct ts)) tmp]) (ss++ss'++[SAlloc tmp (TStruct ts), SStore o tmp]) _ -> cAppArgsL es (os++[o]) (ss++ss') cDeclVarsL :: [Item] -> LType -> EnvState [LStm] cDeclVarsL [] _ = return [] cDeclVarsL (it:its) t = case it of INoInit i -> case t of AbsLasm.TInt -> do newreg <- getFreshReg i False ss <- (cDeclVarsL its t) return ([SAlloc newreg t, SStore (Const (VInt 0)) newreg] ++ ss) AbsLasm.TDbl -> do newreg <- getFreshReg i False ss <- (cDeclVarsL its t) return ([SAlloc newreg t, SStore (Const (VDbl 0.0)) newreg] ++ ss) AbsLasm.TArray t' -> do newreg <- getFreshReg i False ss <- (cDeclVarsL its t) return ([SAlloc newreg t] ++ ss) IInit i e -> do (o, ss) <- cExpL e newreg <- getFreshReg i False ss' <- (cDeclVarsL its t) return ([SAlloc newreg t] ++ ss ++ [SStore o newreg] ++ ss') cExpTypeL :: Exp -> LType cExpTypeL (EType _ t) = cTypeL t cExpTypeL e = error $ "[cExpTypeL] not an EType, instead: " ++ show e cArgsL :: [Arg] -> EnvState [LArg] cArgsL [] = return [] cArgsL ((AbsJavalette.Arg t i):as) = do (Register s) <- getFreshReg i byVal as' <- (cArgsL as) return ((AbsLasm.Arg t' (AbsLasm.Ident s)):as') where t' = case t of AbsJavalette.TArray t'' -> TPtr (TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cTypeL t''))]) _ -> cTypeL t byVal = case t of AbsJavalette.TArray _ -> False _ -> True cTypeL :: Type -> LType cTypeL t = case t of AbsJavalette.TInt -> AbsLasm.TInt AbsJavalette.TDbl -> AbsLasm.TDbl AbsJavalette.TBool -> AbsLasm.TBool AbsJavalette.TVoid -> AbsLasm.TVoid (AbsJavalette.TArray t') -> TStruct [AbsLasm.TInt, TPtr (AbsLasm.TArray (cTypeL t'))] cArrayTypeL :: Type -> LType cArrayTypeL t = case t of (AbsJavalette.TArray t') -> cTypeL t' _ -> error $ "[cTypeArray] Input type is not array but " ++ show t cRelOpL :: RelOp -> LBrType cRelOpL op = case op of OLt -> BLt OLeq -> BLEq OGt -> BGt OGeq -> BGEq OEq -> BEq ONEq -> BNeq cIdentL :: AbsJavalette.Ident -> AbsLasm.Ident cIdentL (AbsJavalette.Ident s) = AbsLasm.Ident s getRegister :: Operand -> Register getRegister (Var t reg) = reg getRegister op = error $ "[getRegister] Operand not register: " ++ (show op) findStrings :: EnvState [LTop] findStrings = do sc <- getStrings return (cGlobalsL (toList sc)) cGlobalsL :: [(AbsLasm.Ident, Pointer)]-> [LTop] cGlobalsL [] = [] cGlobalsL ((AbsLasm.Ident s, Ref x):ss) = (Global (Register ("string"++show x)) s):(cGlobalsL ss)
davidsundelius/JLC
src/LasmConverter.hs
mit
21,425
0
26
10,071
7,497
3,710
3,787
403
24
-- | A data type representing the game map at a particular frame, and functions that operate on it. module Hlt.GameMap where import qualified Data.Either as Either import qualified Data.Maybe as Maybe import qualified Data.Map as Map import Hlt.Entity -- | A GameMap contains the current frame of a Halite game. data GameMap = GameMap { myId :: PlayerId , width :: Int , height :: Int , allPlayers :: Map.Map PlayerId Player , allPlanets :: Map.Map PlanetId Planet } deriving (Show) -- | Return a list of all Planets. listAllPlanets :: GameMap -> [Planet] listAllPlanets g = Map.elems $ allPlanets g -- | Return a list of all Ships. listAllShips :: GameMap -> [Ship] listAllShips g = concat $ map (Map.elems . ships) (Map.elems $ allPlayers g) -- | Return a list of my Ships. listMyShips :: GameMap -> [Ship] listMyShips g = Map.elems $ ships $ Maybe.fromJust $ Map.lookup (myId g) (allPlayers g) -- | Checks if any of the given Entities are in between two Entities. entitiesBetweenList :: Entity a => Entity b => Entity c => [a] -> b -> c -> Bool entitiesBetweenList l e0 e1 = any (\e -> isSegmentCircleCollision e0 e1 e) $ filter (\e -> notEqual e e0 && notEqual e e1) l -- | Checks if there are any Entities between two Entities. entitiesBetween :: Entity a => Entity b => GameMap -> Bool -> a -> b -> Bool entitiesBetween g c a b = entitiesBetweenList (listAllPlanets g) a b || (c && entitiesBetweenList (listAllShips g) a b)
HaliteChallenge/Halite-II
airesources/Haskell/Hlt/GameMap.hs
mit
1,567
0
10
395
424
228
196
-1
-1
{- Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? -} euler19 = length $ filter (\d -> d `mod` 7 == 5) -- 1/1/1901 is Tuesday so 5 days after is Sunday $ [getDaysSince1901 y m | y <- [1901..2000], m <- [0..11]] getDaysSince1901 :: Int -> Int -> Int getDaysSince1901 year month = foldl (+) 0 $ [if leapYear y then 366 else 365 | y <- [1901..(year - 1)]] ++ (map (days) $ take month monthDays) where days = if leapYear year then fst else snd leapYear n = n `mod` 4 == 0 && (n `mod` 400 == 0 || n `mod` 100 /= 0) monthDays = [(31, 31), (29, 28), (31, 31), (30, 30), (31, 31), (30, 30), (31, 31), (31, 31), (30, 30), (31, 31), (30, 30), (31, 31) ]
RossMeikleham/Project-Euler-Haskell
19.hs
mit
1,266
0
13
372
341
200
141
11
3
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Sound.PortAudio.Base import Sound.PortAudio import qualified Sound.File.Sndfile as SF import qualified Sound.File.Sndfile.Buffer as BSF import qualified Sound.File.Sndfile.Buffer.Vector as VSF import Data.List (transpose) import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as MV import Control.Monad (foldM, foldM_, forM_, when, unless, zipWithM_) import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent (threadDelay, forkIO) import Text.Printf import Foreign.C.Types import Foreign.Storable import Foreign.ForeignPtr import Foreign.Marshal.Alloc import Foreign.Ptr import qualified UI.HSCurses.Curses as Curses (move, refresh, scrSize, endWin) import qualified UI.HSCurses.CursesHelper as CursesH (gotoTop, drawLine, start, end) import System.Environment (getArgs) import Transform ( kPointFFT ) data TimedBuffer = TimedBuffer { dataPoints :: V.Vector Float, timeStamp :: Double } framesPerBuffer :: Int framesPerBuffer = 300 type FFTPrintFunc = MVar [ Float ] -> IO () rawPrintFunc :: FFTPrintFunc rawPrintFunc mvar = do dta <- takeMVar mvar unless (null dta) $ do print dta rawPrintFunc mvar cursesRawPrintFunc :: FFTPrintFunc cursesRawPrintFunc mvar = CursesH.start >> workerFunc >> CursesH.end where workerFunc = do dta <- takeMVar mvar unless (null dta) $ do (maxRows, maxCols) <- Curses.scrSize let compressed = transpose $ take maxCols $ asciiDisplayRaw maxRows 5 (0, 25) (take maxCols dta) '*' asciiDisplayRaw :: Int -> Int -> (Float, Float) -> [Float] -> Char -> [String] asciiDisplayRaw height barWidth (x,y) points symbol = result where result = concatMap (\str -> replicate barWidth str) pure pure = map (\p -> let req = (func p) in (replicate (height - req) ' ') ++ (replicate req symbol)) points func pnt | pnt > y = height | pnt < x = 0 | otherwise = ceiling $ (realToFrac height) * (pnt - x) / spanning spanning = y - x len = length points displayBars :: Int -> [String] -> IO () displayBars width items = zipWithM_ (\row string -> Curses.move row 0 >> CursesH.drawLine width string) [0..] items displayBars (maxCols - 1) compressed >> Curses.refresh workerFunc processFourierData :: Chan TimedBuffer -> Int -> Int -> IO () processFourierData readChannel channels pointsFFT = do fourierDrawing <- newMVar (U.fromList []) toPrinter <- newEmptyMVar fftVec <- MV.new pointsFFT forkIO $ defaultPrintFunc toPrinter let workerFunc pos lastTime mutVec fftUpdate = do if pos == pointsFFT then do frozen <- U.freeze mutVec swapMVar fourierDrawing (kPointFFT frozen) workerFunc 0 lastTime mutVec True else do TimedBuffer pnts ts <- readChan readChannel if (V.null pnts) then (putMVar toPrinter [] >> putStrLn "Ending!") else do let numPoints = V.length pnts fftPrint = (ts - lastTime >= updateInterval && fftUpdate) slotsAvail = pointsFFT - pos toFourier = V.take slotsAvail pnts newFFTUpdate = if fftPrint then False else fftUpdate newTime = if fftPrint then ts else lastTime forM_ [0..(V.length toFourier - 1)] $ \i -> MV.unsafeWrite mutVec (pos + i) (toFourier V.! i) when fftPrint $ do drawData <- readMVar fourierDrawing putMVar toPrinter (U.toList drawData) workerFunc (pos + V.length toFourier) newTime mutVec newFFTUpdate workerFunc 0 0 fftVec False runFunc :: MVar (V.Vector Float) -> Chan TimedBuffer -> Int -> Int -> ForeignPtr CFloat -> Stream CFloat CFloat -> IO () runFunc fileData fourierChannel frames channels out strm = do pnts <- modifyMVar fileData (\vec -> let (x, y) = V.splitAt (fromIntegral frames * channels) vec in return (y, x)) if (V.null pnts) then (writeChan fourierChannel (TimedBuffer (V.fromList []) 0)) else do let totalLen = V.length pnts withForeignPtr out $ \p -> V.foldM_ (\i val -> pokeElemOff p i (realToFrac val) >> return (i + 1)) 0 pnts (Right (PaTime tme)) <- getStreamTime strm writeStream strm (fromIntegral $ totalLen `div` channels) out writeChan fourierChannel (TimedBuffer pnts (realToFrac tme)) runFunc fileData fourierChannel frames channels out strm withBlockingIO :: SF.Info -> MVar (V.Vector Float) -> IO (Either Error ()) withBlockingIO info fileData = do let channels = SF.channels info fourierChannel <- newChan forkIO $ processFourierData fourierChannel channels pointsPerTransform outInfo <- getDefaultOutputInfo case outInfo of Left err -> return $ Left err Right (devIndex, devInfo) -> do let outInfo = Just $ StreamParameters devIndex 2 (defaultHighOutputLatency devInfo) withStream Nothing outInfo (realToFrac $ SF.samplerate info) (Just framesPerBuffer) [ClipOff] Nothing Nothing $ \strm -> do allocaBytes (framesPerBuffer * channels) $ \out -> do out' <- newForeignPtr_ out startStream strm runFunc fileData fourierChannel framesPerBuffer channels out' strm stopStream strm return $ Right () updateInterval :: Double updateInterval = 0.5 pointsPerTransform :: Int pointsPerTransform = 1024 defaultPrintFunc :: FFTPrintFunc defaultPrintFunc = cursesRawPrintFunc main :: IO () main = do [inFile] <- getArgs (info, Just (x :: VSF.Buffer Float)) <- SF.readFile inFile let vecData = V.convert $ VSF.fromBuffer x channels = SF.channels info fileData <- newMVar vecData withPortAudio $ withBlockingIO info fileData return ()
sw17ch/portaudio
examples/Example3.hs
mit
6,545
5
27
2,043
1,892
975
917
-1
-1
import Samba import System.Process (createProcess, shell) import Control.Monad (when) main = do putStrLn $ unlines [ "################################################################" , "Instructions: " , "" , "Firstly, ensure your smb.conf have this section:" , "[homes]" , " comment = Home Directories" , " browseable = yes" , " writable = yes" , " read only = no" , " valid users = %S" , "" , "----------------------------------------------------------------" , "To use this program, just enter the names you want to add and the" , "whole process of adding a new user to the system and then to Samba" , "will be done for you. Also the passwords will be generated " , "automatically" , "" , "*Note: remember to restart Samba after changes" , "*Note: remember to add permision to a newSambaUser.bash" , "################################################################" ] createUser createUser :: IO () createUser = do putStrLn "Insert a username" user <- getLine when (user /= "") $ do let pass = dpass user putStrLn $ "The password of the user " ++ user ++ " will be " ++ pass putStrLn "Creating user..." callCommand $ "./newSambaUser.bash \"" ++ user ++ "\" \"" ++ pass ++ "\"" createUser callCommand = createProcess . shell
felipexpert/sambaHaskell
defineSambaUser.hs
mit
1,353
0
14
320
222
118
104
37
1
module Main where import Barcode import System.Environment import qualified Data.Vector as V import qualified Data.List as DL main :: IO () main = do -- get input arg [inFile, maxSnps'] <- getArgs >>= return . take 2 let maxSnps = read maxSnps' :: Int samples <- parseBarcode inFile let samples' = uniquify $ V.toList $ V.filter validBarcode samples putStrLn $ show $ DL.sort $ map (+1) $ take maxSnps $ chooseSnps samples' [0..23] -- :load Barcode -- samples <- parseBarcode "2013-test.csv" -- let samples' = uniquify $ V.toList $ V.filter validBarcode samples -- let ids = map (\x -> x - 1) [1, 9, 10, 11, 12, 14, 15, 18] -- putStrLn $ unlines $ reportDuplicates samples' ids -- let ids = map (\x -> x - 1) [19,15,6,4,3,20,5,12,8,13,14,22,18,17,7,16,10,11,21,2]
ndaniels/strain-assay-minimization
Main.hs
mit
788
0
12
153
170
92
78
12
1
------------- --LIBRARIES-- ------------- import Graphics.UI.WXCore import GUI_Player import GUI_Cpu ----------- --METHODS-- ----------- main :: IO() main = do putStrLn "Enter game mode (player or cpu): " gameMode <- getLine case gameMode of "player" -> run createPlayerWindow "cpu" -> run createCpuWindow otherwise -> skipCurrentEvent
BrunoAltadill/Bloxorz_2D
code/Main.hs
mit
372
0
10
79
78
41
37
11
3
#!/usr/bin/env runhaskell {-# LANGUAGE FlexibleInstances #-} import Control.Monad.Reader hiding (when) import Data.Decimal import qualified Data.List as L hiding (and) import DSL import FinancialArithmetic import Models import Graphics.EasyPlot ------------------------------------------------------------------------------ main = do let payments1 = [] let u1 = Contract "1" $ when (at $ 3 Months) (Give $ One $ 100 USD) let u2 = Contract "2" $ american (1 Month, 3 Months) (One $ 10 NZD) print $ u1 .+ u2 -- let timeline = map Model [0..11] -- print $ {- EXAMPLE 1: ------------------------------------------------------------ Over the timeframe of 12 months, get and compare performance figures for two contracts. First contract: Pay 100 NZD at the beginning of the third month, get 105 NZD at the end of the 10th month. Second contract: Pay 100 USD at the beginning of the third month, get 103 USD at the end of the 10th month. -} let c1 = Contract "C1" $ (when (at $ 2 Months) (Give $ One $ 100 NZD)) `And` (when (at $ 10 Months) (One $ 105 NZD)) let c2 = Contract "C2" $ And (when (at $ 2 Months) (Give $ One $ 100 USD)) (when (at $ 10 Months) (One $ 103 USD)) {- Information provided: Main currency Highest deposit rates for each month Lowest loan rates for each month Defined in Models.hs -} let m = m_nzakl_2015_baseline -- Schedule of payments let s1 = contractToSchedule m c1 let s2 = contractToSchedule m c2 -- Print actions for each period of the whole term print $ name c1 ++ ": " ++ (show s1) print $ name c2 ++ ": " ++ (show s2) {- Questions asked: * Calculate NPV, NFV for each contract * Calculate equivalent deposit rate for each contract -} let npv :: Contract -> Reader (Model, Time) Contract npv c = do (m, t) <- ask return $ npv' m t c print $ runReader (npv c1) (m, 1 Month)
AlexanderAA/haskell-contract-valuation
Examples.hs
mit
2,230
0
16
752
505
254
251
30
1
-- -- This code was created by Jeff Molofee '99 (ported to Haskell GHC 2005) -- module Main where import qualified Graphics.UI.GLFW as GLFW -- everything from here starts with gl or GL import Graphics.Rendering.OpenGL.Raw import Graphics.Rendering.GLU.Raw ( gluPerspective ) import Data.Bits ( (.|.) ) import System.Exit ( exitWith, ExitCode(..) ) import Control.Monad ( forever ) import Data.IORef ( IORef, newIORef, readIORef, writeIORef ) increment :: GLfloat increment = 1.5 initGL :: GLFW.Window -> IO () initGL win = do glShadeModel gl_SMOOTH -- enables smooth color shading glClearColor 0 0 0 0 -- Clear the background color to black glClearDepth 1 -- enables clearing of the depth buffer glEnable gl_DEPTH_TEST glDepthFunc gl_LEQUAL -- type of depth test glHint gl_PERSPECTIVE_CORRECTION_HINT gl_NICEST (w,h) <- GLFW.getFramebufferSize win resizeScene win w h resizeScene :: GLFW.WindowSizeCallback resizeScene win w 0 = resizeScene win w 1 -- prevent divide by zero resizeScene _ width height = do glViewport 0 0 (fromIntegral width) (fromIntegral height) glMatrixMode gl_PROJECTION glLoadIdentity gluPerspective 45 (fromIntegral width/fromIntegral height) 0.1 100 glMatrixMode gl_MODELVIEW glLoadIdentity glFlush drawScene :: IORef GLfloat -> IORef GLfloat -> GLFW.Window -> IO () drawScene rtri rquad _ = do -- clear the screen and the depth buffer glClear $ fromIntegral $ gl_COLOR_BUFFER_BIT .|. gl_DEPTH_BUFFER_BIT glLoadIdentity -- reset view glTranslatef (-1.5) 0 (-6.0) --Move left 1.5 Units and into the screen 6.0 rt <- readIORef rtri glRotatef rt 0 1 0 -- Rotate the triangle on the Y axis -- draw a triangle (in smooth coloring mode) glBegin gl_TRIANGLES -- start drawing a polygon glColor3f 1 0 0 -- set the color to Red glVertex3f 0 1 0 -- top glColor3f 0 1 0 -- set the color to Green glVertex3f 1 (-1) 0 -- bottom right glColor3f 0 0 1 -- set the color to Blue glVertex3f (-1) (-1) 0 -- bottom left glEnd glLoadIdentity glTranslatef 1.5 0 (-6) -- move right three units rq <- readIORef rquad glRotatef rq 1 0 0 -- rotate the quad on the x axis glColor3f 0.5 0.5 1 -- set color to a blue shade glBegin gl_QUADS -- start drawing a polygon (4 sided) glVertex3f (-1) 1 0 -- top left glVertex3f 1 1 0 -- top right glVertex3f 1 (-1) 0 -- bottom right glVertex3f (-1) (-1) 0 -- bottom left glEnd -- increase the rotation angle for the triangle writeIORef rtri $! rt + increment -- increase the rotation angle for the quad writeIORef rquad $! rq + increment glFlush shutdown :: GLFW.WindowCloseCallback shutdown win = do GLFW.destroyWindow win GLFW.terminate _ <- exitWith ExitSuccess return () keyPressed :: GLFW.KeyCallback keyPressed win GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win keyPressed _ _ _ _ _ = return () main :: IO () main = do True <- GLFW.init -- select type of display mode: -- Double buffer -- RGBA color -- Alpha components supported -- Depth buffer GLFW.defaultWindowHints -- open a window Just win <- GLFW.createWindow 800 600 "Lesson 4" Nothing Nothing GLFW.makeContextCurrent (Just win) -- register the function to do all our OpenGL drawing rt <- newIORef 0 rq <- newIORef 0 GLFW.setWindowRefreshCallback win (Just (drawScene rt rq)) -- register the funciton called when our window is resized GLFW.setFramebufferSizeCallback win (Just resizeScene) -- register the function called when the keyboard is pressed. GLFW.setKeyCallback win (Just keyPressed) GLFW.setWindowCloseCallback win (Just shutdown) -- initialize our window. initGL win -- start event processing engine forever $ do GLFW.pollEvents drawScene rt rq win GLFW.swapBuffers win
spetz911/progames
nehe-tuts-master/lesson04.hs
mit
3,972
0
11
950
973
474
499
86
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Network.Network ( Network(..) ) where import Network.Layer import Numeric.LinearAlgebra import System.Random -- | A network is class Network a where type Parameters :: * predict :: Vector Double -> a -> Vector Double createNetwork :: (RandomGen g) => RandomTransform -> g -> Parameters -> a
mckeankylej/hwRecog
Network/Network.hs
mit
490
0
10
122
95
55
40
13
0
module Data.IntSet.Data where import qualified Data.IntSet as I isetTo :: Int -> I.IntSet isetTo n = I.fromList [1..n] iset1 :: I.IntSet iset1 = isetTo 10 iset2 :: I.IntSet iset2 = isetTo 20 iset3 :: I.IntSet iset3 = isetTo 30 iset4 :: I.IntSet iset4 = isetTo 40 iset5 :: I.IntSet iset5 = isetTo 50
athanclark/sets
bench/Data/IntSet/Data.hs
mit
307
0
6
61
119
66
53
14
1
import Criterion.Main import Control.DeepSeq import qualified Data.Maybe as B import qualified MapMaybe as F main = do rnf ints `seq` return () defaultMain [ bgroup "simple" [ bench "base" $ nf (B.mapMaybe half) ints , bench "fold" $ nf (F.mapMaybe half) ints ] , bgroup "after map" [ bench "base" $ nf (B.mapMaybe half . map (+1)) ints , bench "fold" $ nf (F.mapMaybe half . map (+1)) ints ] , bgroup "after filter" [ bench "base" $ nf (B.mapMaybe half . filter seven) ints , bench "fold" $ nf (F.mapMaybe half . filter seven) ints ] , bgroup "before map" [ bench "base" $ nf (map (+1) . B.mapMaybe half) ints , bench "fold" $ nf (map (+1) . F.mapMaybe half) ints ] ] ints :: [Int] ints = [-2 .. 8000] half :: Int -> Maybe Int half n = if even n then Just $! div n 2 else Nothing seven :: Int -> Bool seven x = quot x 10 == 7
takano-akio/mapmaybe-benchmarks
main.hs
cc0-1.0
928
0
16
267
414
210
204
25
2